Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Tests/SessionTests.swift4// Description: Integration tests against a scripted server: session cookie handling, sending, streaming, reconnection, offline outbox, sync.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import Foundation11import Testing12@testable import SPChat1314@Suite(.serialized) @MainActor struct HTTPClientTests {15 @Test func sendsTheSessionCookieAndOriginAndStoresARotatedToken() async throws {16 let host = "http-rotate.test"17 StubProtocol.install(host: host) { req, _ in18 req.url?.path == "/api/auth/reauth/verify"19 ? .json(#"{"ok":true}"#, headers: ["Set-Cookie": "__Host-csa_session=NEWTOKEN_NEWTOKEN_NEWTOKEN_NEWTOKEN_NEWTOK_ab; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=2592000"])20 : .json(#"{"conversations":[]}"#)21 }22 let tokens = MemorySessionTokenStore("OLDTOKEN")23 let http = HTTPClient(configuration: AppConfiguration(baseURL: URL(string: "https://\(host)")!, userAgent: "UA"), tokens: tokens, protocolClasses: [StubProtocol.self])24 _ = try await http.data(.get("/api/conversations"))25 let first = try #require(StubProtocol.requests(host: host).last)26 #expect(first.value(forHTTPHeaderField: "Cookie") == "__Host-csa_session=OLDTOKEN")27 #expect(first.value(forHTTPHeaderField: "Origin") == "https://\(host)")28 _ = try await http.data(.json("POST", "/api/auth/reauth/verify"))29 #expect(tokens.load() == "NEWTOKEN_NEWTOKEN_NEWTOKEN_NEWTOKEN_NEWTOK_ab") // rotation persisted30 _ = try await http.data(.get("/api/conversations"))31 #expect(StubProtocol.requests(host: host).last?.value(forHTTPHeaderField: "Cookie") == "__Host-csa_session=NEWTOKEN_NEWTOKEN_NEWTOKEN_NEWTOKEN_NEWTOK_ab")32 }3334 @Test func ceremonyCookiesStayInMemoryAndAreSentBack() async throws {35 let host = "http-ceremony.test"36 StubProtocol.install(host: host) { req, _ in37 req.url?.path == "/api/auth/login/options" ? .json(#"{"options":{"challenge":"AAAA"}}"#, headers: ["Set-Cookie": "__Host-csa_ceremony=CEREMONY123; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=300"]) : .json(#"{"ok":true}"#, headers: ["Set-Cookie": "__Host-csa_ceremony=; Path=/; Max-Age=0"])38 }39 let tokens = MemorySessionTokenStore(nil)40 let http = HTTPClient(configuration: AppConfiguration(baseURL: URL(string: "https://\(host)")!, userAgent: "UA"), tokens: tokens, protocolClasses: [StubProtocol.self])41 _ = try await http.data(.json("POST", "/api/auth/login/options"))42 _ = try await http.data(.json("POST", "/api/auth/login/verify"))43 #expect(StubProtocol.requests(host: host).last?.value(forHTTPHeaderField: "Cookie") == "__Host-csa_ceremony=CEREMONY123")44 _ = try await http.data(.get("/api/health"))45 #expect(StubProtocol.requests(host: host).last?.value(forHTTPHeaderField: "Cookie") == nil) // consumed, and never persisted46 #expect(tokens.load() == nil)47 }4849 @Test func aLockedAnswerClearsTheSessionAndNotifiesOnce() async throws {50 let host = "http-locked.test"51 StubProtocol.install(host: host) { _, _ in .json(#"{"error":"Session requise","code":"locked"}"#, status: 401, headers: ["x-csa-locked": "1"]) }52 let tokens = MemorySessionTokenStore("TOKEN")53 let http = HTTPClient(configuration: AppConfiguration(baseURL: URL(string: "https://\(host)")!, userAgent: "UA"), tokens: tokens, protocolClasses: [StubProtocol.self])54 let lost = NSLockBox(0)55 await http.setSessionLostHandler { lost.withLock { $0 += 1 } }56 for _ in 0..<2 {57 await #expect(throws: APIError.locked) { _ = try await http.data(.get("/api/conversations")) }58 }59 #expect(tokens.load() == nil && lost.withLock { $0 } == 1)60 #expect(await http.hasSession == false)61 }6263 @Test func aSensitiveOperationIsReplayedOnceAfterReauthentication() async throws {64 let host = "http-reauth.test"65 let calls = NSLockBox(0)66 StubProtocol.install(host: host) { _, _ in67 calls.withLock { $0 += 1 } ; return calls.withLock { $0 } == 1 ? .json(#"{"error":"Confirme avec ta clé d'accès pour continuer","code":"reauth_required"}"#, status: 403) : .json(#"{"codes":["a","b"]}"#)68 }69 let http = HTTPClient(configuration: AppConfiguration(baseURL: URL(string: "https://\(host)")!, userAgent: "UA"), tokens: MemorySessionTokenStore("T"), protocolClasses: [StubProtocol.self])70 let prompts = NSLockBox(0)71 await http.setReauthHandler { prompts.withLock { $0 += 1 } }72 let codes = try await ChatAPI(http: http).rotateRecoveryCodes()73 #expect(codes == ["a", "b"] && prompts.withLock { $0 } == 1 && calls.withLock { $0 } == 2)74 }7576 @Test func transportFailuresAreNetworkErrorsNotCrashes() async {77 let host = "http-offline.test"78 StubProtocol.install(host: host) { _, _ in .offline() }79 let http = HTTPClient(configuration: AppConfiguration(baseURL: URL(string: "https://\(host)")!, userAgent: "UA"), tokens: MemorySessionTokenStore("T"), protocolClasses: [StubProtocol.self])80 do { _ = try await http.data(.get("/api/models")); Issue.record("should throw") }81 catch { #expect((error as? APIError)?.kind == .network) }82 }83}8485@Suite(.serialized) @MainActor struct ChatSessionTests {86 /// Routes of a tiny fake backend. `chat` answers POST /api/chat; `detail` answers GET /api/conversations/:id.87 private func install(host: String, chat: @escaping @Sendable (Int, [String: JSONValue]) -> StubProtocol.Response, stream: (@Sendable (Int, URLRequest) -> StubProtocol.Response)? = nil, detail: @escaping @Sendable (Int) -> StubProtocol.Response) {88 let chatCalls = NSLockBox(0), detailCalls = NSLockBox(0), streamCalls = NSLockBox(0)89 StubProtocol.install(host: host) { req, body in90 let path = req.url?.path ?? ""91 if path == "/api/chat" || path.hasPrefix("/api/chat/re") || path == "/api/chat/edit" {92 let n = chatCalls.withLock { $0 += 1; return $0 }93 let json = (body.flatMap { try? JSONDecoder().decode([String: JSONValue].self, from: $0) }) ?? [:]94 return chat(n, json)95 }96 if path == "/api/chat/stream" { let n = streamCalls.withLock { $0 += 1; return $0 }; return stream?(n, req) ?? .json(#"{"error":"gone","code":"run_gone"}"#, status: 410) }97 if path == "/api/chat/cancel" { return .json(#"{"ok":true,"cancelled":true}"#) }98 if path.hasPrefix("/api/conversations/") { return detail(detailCalls.withLock { $0 += 1; return $0 }) }99 if path == "/api/conversations" { return .json(#"{"conversations":[\#(Fixtures.conversationJSON())]}"#) }100 if path == "/api/drafts" { return .json(#"{"draft":null}"#) }101 return .json("{}")102 }103 }104 private let finalDetail = Fixtures.detailJSON(messages: [Fixtures.messageJSON(id: "msg_user1", role: "user", text: "Bonjour"), Fixtures.messageJSON(id: "msg_asst1", role: "assistant", text: "Salut à toi !", parent: "msg_user1")])105106 @Test func sendingStreamsTheAnswerAndEndsWithTheServerState() async throws {107 let host = "chat-send.test"108 let final = finalDetail109 install(host: host, chat: { _, _ in .sse(SSE.run(deltas: ["Sal", "ut ", "à toi", " !"]), delay: 0.02) }, detail: { _ in .json(final) })110 let env = TestEnv.make(host: host)111 let session = env.newSession()112 session.composerText = "Bonjour"113 #expect(session.canSend)114 session.sendComposer(options: SendOptions(modelId: "claude-haiku-5-5", routingMode: .manual))115 // the optimistic bubble is local; nothing claims the server has it yet116 #expect(session.messages.count == 1 && session.messages[0].id.hasPrefix("tmp_") && session.phase == .sending && session.composerText.isEmpty)117 #expect(await TestEnv.wait { session.phase == .streaming })118 #expect(await TestEnv.wait { session.phase == .idle })119 #expect(session.conversationId == "conv_test1")120 #expect(session.messages.map(\.id) == ["msg_user1", "msg_asst1"] && session.messages[1].text == "Salut à toi !" && session.messages[1].status == .complete)121 // the request carried the idempotency key, the text and the model122 let post = try #require(StubProtocol.requests(host: host).first { $0.url?.path == "/api/chat" })123 #expect(post.value(forHTTPHeaderField: "Accept") == "text/event-stream" && post.httpMethod == "POST")124 // the conversation is now readable offline125 var cachedCount = 0126 for _ in 0..<100 where cachedCount != 2 { cachedCount = await env.store.detail("conv_test1")?.detail.messages.count ?? 0; if cachedCount != 2 { try await Task.sleep(for: .milliseconds(20)) } }127 #expect(cachedCount == 2)128 #expect(env.session(for: "conv_test1") === session) // the draft session became the conversation's session129 }130131 @Test func aDroppedConnectionReattachesWithTheLastIndexAndDuplicatesNothing() async throws {132 let host = "chat-drop.test"133 let all = SSE.run(deltas: ["Un ", "deux ", "trois ", "quatre"])134 let final = Fixtures.detailJSON(messages: [Fixtures.messageJSON(id: "msg_user1", role: "user", text: "Compte"), Fixtures.messageJSON(id: "msg_asst1", role: "assistant", text: "Un deux trois quatre", parent: "msg_user1")])135 let afters = NSLockBox<[String]>([])136 install(host: host, chat: { _, _ in .sse(Array(all.prefix(6)), delay: 0.02, drop: true) }, // retry, run, conversation, start, "Un ", "deux " then the socket dies137 stream: { _, req in138 let after = URLComponents(url: req.url!, resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == "after" }?.value ?? "?"139 afters.withLock { $0.append(after) }140 return .sse(Array(all.dropFirst(1)), delay: 0.01) // the server replays the whole run: the client must skip what it has141 }, detail: { _ in .json(final) })142 let env = TestEnv.make(host: host)143 let session = env.newSession()144 session.composerText = "Compte"145 session.sendComposer(options: SendOptions())146 #expect(await TestEnv.wait(timeout: 8) { session.phase == .idle && session.messages.count == 2 })147 #expect(afters.withLock { $0 } == ["4"]) // run=0 conversation=1 start=2 "Un "=3 "deux "=4148 #expect(session.messages[1].text == "Un deux trois quatre")149 #expect(StubProtocol.requests(host: host).filter { $0.url?.path == "/api/chat" }.count == 1) // never re-posted150 }151152 @Test func offlineMessagesWaitInTheOutboxAndAreSentOnceWithTheSameKey() async throws {153 let host = "chat-offline.test"154 let online = NSLockBox(false)155 let keys = NSLockBox<[String]>([])156 let final = finalDetail157 install(host: host, chat: { _, body in158 guard online.withLock({ $0 }) else { return .offline() }159 keys.withLock { $0.append(body["clientRequestId"]?.stringValue ?? "") }160 return .sse(SSE.run(created: false, deltas: ["Salut à toi !"]))161 }, detail: { _ in .json(final) })162 let env = TestEnv.make(host: host)163 env.auth.debugMarkSignedIn()164 env.network.simulate(online: false)165 let session = env.session(for: "conv_test1")166 await session.load()167 let before = session.messages.count168 session.composerText = "Message écrit hors ligne"169 session.sendComposer(options: SendOptions())170 #expect(await TestEnv.wait { session.phase == .idle })171 // not shown as a sent message: it sits in the outbox, persisted172 #expect(session.messages.count == before && session.pending.count == 1 && session.pending.first?.text == "Message écrit hors ligne")173 let queued = await env.store.outbox()174 #expect(queued.count == 1 && queued.first?.conversationId == "conv_test1")175 #expect(session.warning?.contains("Hors ligne") == true)176177 // the network returns: the outbox is flushed with the SAME idempotency key178 online.withLock { $0 = true }179 env.network.simulate(online: true)180 await env.flushOutbox()181 #expect(await TestEnv.wait { session.phase == .idle && session.pending.isEmpty })182 #expect(keys.withLock { $0 } == queued.map(\.id))183 #expect(await env.store.outbox().isEmpty && env.outboxCount == 0)184 #expect(session.messages.last?.text == "Salut à toi !")185 }186187 @Test func aRefusedSendGivesTheTextBackToTheComposer() async {188 let host = "chat-refused.test"189 let final = finalDetail190 install(host: host, chat: { _, _ in .json(#"{"error":"Limite quotidienne atteinte (10.00 $ / 10 $).","code":"budget"}"#, status: 402) }, detail: { _ in .json(final) })191 let env = TestEnv.make(host: host)192 let session = env.session(for: "conv_test1")193 await session.load()194 session.composerText = "Texte à ne pas perdre"195 session.sendComposer(options: SendOptions())196 #expect(await TestEnv.wait { session.phase == .idle })197 #expect(session.composerText == "Texte à ne pas perdre" && session.error?.contains("Limite quotidienne") == true)198 #expect(session.messages.count == 2 && session.pending.isEmpty) // no ghost bubble, nothing queued199 }200201 @Test func stopCancelsOnTheServerAndMarksTheAnswerStopped() async {202 let host = "chat-stop.test"203 let slow = SSE.run(deltas: Array(repeating: "mot ", count: 200), end: false)204 let final = Fixtures.detailJSON(messages: [Fixtures.messageJSON(id: "msg_user1", role: "user", text: "Long"), Fixtures.messageJSON(id: "msg_asst1", role: "assistant", text: "mot mot", parent: "msg_user1", status: "cancelled")])205 install(host: host, chat: { _, _ in .sse(slow, delay: 0.03) }, detail: { _ in .json(final) })206 let env = TestEnv.make(host: host)207 env.network.simulate(online: true)208 let session = env.newSession()209 session.composerText = "Long"210 session.sendComposer(options: SendOptions())211 #expect(await TestEnv.wait { session.messages.last?.role == .assistant && session.messages.last?.text.isEmpty == false })212 session.stop()213 #expect(session.phase == .idle && session.messages.last?.status == .cancelled)214 #expect(await TestEnv.wait { StubProtocol.requests(host: host).contains { $0.url?.path == "/api/chat/cancel" } })215 #expect(await TestEnv.wait(timeout: 3) { session.allMessages.last?.status == .cancelled })216 }217218 @Test func aConversationAlreadyDownloadedIsReadableWhenTheServerIsUnreachable() async throws {219 let host = "chat-cache.test"220 let final = finalDetail221 let reachable = NSLockBox(true)222 install(host: host, chat: { _, _ in .offline() }, detail: { _ in reachable.withLock { $0 } ? .json(final) : .offline() })223 let env = TestEnv.make(host: host)224 let first = env.session(for: "conv_test1")225 await first.load()226 #expect(first.messages.count == 2 && !first.isShowingCache)227 // a fresh session object (as after an app restart), server down228 reachable.withLock { $0 = false }229 let again = ChatSession(conversationId: "conv_test1", dependencies: ChatSessionDependencies(api: env.api, store: env.store, isOnline: { false }, waitUntilOnline: {}, conversationsChanged: {}, sessionAdopted: { _, _ in }, turnFinished: { _, _, _ in }))230 await again.load()231 #expect(again.messages.map(\.text) == ["Bonjour", "Salut à toi !"] && again.isShowingCache && again.loadError == nil)232 }233234 @Test func aRunStillAliveOnTheServerIsFollowedWhenTheConversationOpens() async {235 let host = "chat-liverun.test"236 let live = Fixtures.detailJSON(messages: [Fixtures.messageJSON(id: "msg_user1", role: "user", text: "Bonjour"), Fixtures.messageJSON(id: "msg_asst1", role: "assistant", text: "Sal", parent: "msg_user1", status: "streaming")], liveRun: "run_abc")237 let final = finalDetail238 install(host: host, chat: { _, _ in .offline() }, stream: { _, _ in .sse(Array(SSE.run(created: false, deltas: ["Salut ", "à toi !"]).dropFirst(1)), delay: 0.02) }, detail: { n in .json(n == 1 ? live : final) })239 let env = TestEnv.make(host: host)240 let session = env.session(for: "conv_test1")241 await session.load()242 #expect(await TestEnv.wait { session.phase == .idle && session.messages.last?.status == .complete })243 #expect(session.messages.count == 2 && session.messages[1].text == "Salut à toi !")244 }245246 @Test func signOutWipesEveryLocalTrace() async throws {247 let host = "chat-signout.test"248 let final = finalDetail249 install(host: host, chat: { _, _ in .offline() }, detail: { _ in .json(final) })250 let env = TestEnv.make(host: host)251 env.auth.debugMarkSignedIn()252 await env.conversations.refresh()253 await env.session(for: "conv_test1").load()254 await env.store.enqueue(OutboxItem(id: "req_cccccccccccccccc", conversationId: nil, projectId: nil, text: "x", attachments: [], options: SendOptions(), createdAt: Date(), lastError: nil))255 env.preferences.modelId = "claude-haiku-5-5"256 #expect(env.conversations.active.count == 1)257 await env.auth.signOut()258 #expect(env.auth.phase == .signedOut && env.conversations.active.isEmpty && env.router.current == nil && env.preferences.modelId == nil)259 let c = await env.store.counts()260 #expect(c.conversations == 0 && c.details == 0 && c.outbox == 0)261 #expect(await env.http.hasSession == false)262 #expect(StubProtocol.requests(host: host).contains { $0.url?.path == "/api/auth/logout" })263 }264265 @Test func deepLinksOpenConversationsAndRejectForgedIds() async {266 let host = "chat-links.test"267 let final = finalDetail268 install(host: host, chat: { _, _ in .offline() }, detail: { _ in .json(final) })269 let signedOut = TestEnv.make(host: host, token: nil)270 signedOut.handle(url: URL(string: "spchat://c/conv_test1")!)271 #expect(signedOut.router.current == nil) // ignored while signed out272 let env = TestEnv.make(host: host)273 env.handle(url: URL(string: "spchat://c/conv_test1")!)274 #expect(env.router.current?.conversationId == "conv_test1")275 env.handle(url: URL(string: "spchat://new?text=Bonjour%20toi")!)276 #expect(env.router.current?.conversationId == nil && env.router.current?.composerText == "Bonjour toi")277 env.handle(url: URL(string: "https://\(host)/c/conv_test1")!)278 #expect(env.router.current?.conversationId == "conv_test1")279 let before = env.router.current280 env.handle(url: URL(string: "spchat://c/..%2F..%2Fapi%2Fowner")!)281 env.handle(url: URL(string: "https://evil.example/c/conv_test1")!)282 #expect(env.router.current === before)283 env.handle(url: URL(string: "spchat://search")!)284 #expect(env.router.sheet == .search)285 }286287 @Test func aLongConversationLoadsAndStreamsWithoutQuadraticWork() async {288 let host = "chat-long.test"289 let msgs = (0..<600).map { i in Fixtures.messageJSON(id: "m\(i)", role: i % 2 == 0 ? "user" : "assistant", text: "Message numéro \(i) avec un peu de **markdown** et `du code`.", parent: i == 0 ? nil : "m\(i - 1)") }290 let detail = Fixtures.detailJSON(messages: msgs)291 install(host: host, chat: { _, _ in .sse(SSE.run(created: false, deltas: Array(repeating: "jeton ", count: 400)), delay: 0) }, detail: { _ in .json(detail) })292 let env = TestEnv.make(host: host)293 let session = env.session(for: "conv_test1")294 let t0 = ContinuousClock.now295 await session.load()296 #expect(session.messages.count == 600)297 session.composerText = "Encore"298 session.sendComposer(options: SendOptions())299 #expect(await TestEnv.wait(timeout: 10) { session.phase == .idle })300 // 600 messages decoded + cached twice and 400 deltas applied: far below a second of CPU on the main actor301 #expect(ContinuousClock.now - t0 < .seconds(6))302 // coalescing: 400 token events must not produce 400 UI publications303 #expect(session.revision < 120)304 }305}306