Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Tests/CoreTests/PanelsDecodingTests.swift3// Description: Decoding of the contextual panel payloads (context, timeline, tree, lens list) captured from the development backend, tolerance to unknown and missing fields, endpoint requests.4import Foundation5import Testing6@testable import SPChatCore78@Suite struct PanelsDecodingTests {9 private func decode<T: Decodable>(_ type: T.Type, _ json: String) throws -> T { try JSONDecoder.api().decode(T.self, from: Data(json.utf8)) }1011 @Test func contextReport() throws {12 let r = try decode(ContextReport.self, PanelFixture.context)13 #expect(r.model?.id == "or:google/gemini-4-neon"); #expect(r.model?.displayName == "Gemini 4 Neon"); #expect(r.model?.contextWindow == 1_048_576); #expect(r.model?.status == "catalog")14 #expect(r.measured?.inputTokens == 895); #expect(r.measured?.outputTokens == 413); #expect(r.measured?.reasoningTokens == 322); #expect(r.measured?.cachedTokens == 0)15 #expect(r.measured?.source == "Rapporté par le fournisseur pour la dernière réponse"); #expect(r.measured?.at != nil)16 #expect(r.estimate?.nextRequestTokens == 1363); #expect(r.estimate?.percentOfContext == 0.1); #expect(r.estimate?.source?.hasPrefix("Estimation") == true)17 // 0.1 is a percentage of the window, not a fraction18 #expect(abs((r.estimate?.fraction ?? 0) - 0.001) < 1e-9)19 #expect(r.messages.count == 4); #expect(r.messages.user == 2); #expect(r.messages.assistant == 2)20 #expect(r.files.isEmpty); #expect(r.tools.enabled); #expect(r.tools.list.map(\.name) == ["web_search", "fetch_page", "python", "search_documents", "generate_image", "save_memory"])21 #expect(r.tools.list.first?.category == "web")22 #expect(abs((r.cost.conversationUsd ?? 0) - 0.009436) < 1e-9); #expect(r.cost.source?.contains("exact quand le fournisseur") == true); #expect(!r.streaming)23 }2425 @Test func contextReportOfAnEmptyConversationAndUnknownShapes() throws {26 // nothing measured yet, numbers as strings, a file with other field names, a tool sent as a bare string, an unreadable file27 let r = try decode(ContextReport.self, #"{"model":null,"measured":null,"estimate":{"nextRequestTokens":"120","percentOfContext":"150","source":"Estimation"},"messages":{"count":"0"},"files":[{"id":"att_1","name":"plan.pdf","mime":"application/pdf","size":2048,"tokens":"900"},42],"tools":{"enabled":false,"list":["python",{"name":"web_search"}]},"streaming":true,"future":{"a":1}}"#)28 #expect(r.model == nil); #expect(r.measured == nil); #expect(r.estimate?.nextRequestTokens == 120); #expect(r.estimate?.fraction == 1)29 #expect(r.files.count == 1); #expect(r.files.first?.filename == "plan.pdf"); #expect(r.files.first?.sizeBytes == 2048); #expect(r.files.first?.tokens == 900)30 #expect(r.tools.list.map(\.name) == ["python", "web_search"]); #expect(!r.tools.enabled); #expect(r.streaming); #expect(r.cost.conversationUsd == nil)31 // files and image count as sent for a dev conversation with two attachments; file events of its timeline32 let f = try decode(ContextReport.self, #"{"estimate":{"source":"Estimation (≈ 3,5 caractères par jeton, images non comptées)","nextRequestTokens":1328,"percentOfContext":0.1,"images":1},"files":[{"id":"att_kik30caiz0nk6xvu","filename":"csa-note.txt","mime":"text/plain","size_bytes":222,"page_count":null,"chars":222,"index_status":"indexed"},{"id":"att_2aurm3a9cx3cen1c","filename":"vision-test.png","mime":"image/png","size_bytes":2189,"page_count":null,"chars":null,"index_status":"skipped"}]}"#)33 #expect(f.files.map(\.filename) == ["csa-note.txt", "vision-test.png"]); #expect(f.files[0].sizeBytes == 222); #expect(f.files[0].chars == 222); #expect(f.files[1].chars == nil); #expect(f.files[1].indexStatus == "skipped"); #expect(f.estimate?.images == 1)34 let ev = try decode(ConversationTimeline.self, #"{"events":[{"at":"2026-11-17T18:59:20.001Z","type":"file","messageId":"msg_5kddrjnyno12wx6k","id":"att_kik30caiz0nk6xvu","name":"csa-note.txt","mime":"text/plain"}]}"#)35 #expect(ev.events[0].kind == .file); #expect(ev.events[0].filename == "csa-note.txt"); #expect(ev.events[0].recordId == "att_kik30caiz0nk6xvu"); #expect(ev.events[0].mime == "text/plain")36 let empty = try decode(ContextReport.self, "{}")37 #expect(empty.messages.count == 0); #expect(empty.estimate == nil); #expect(empty.files.isEmpty)38 }3940 @Test func timelineWithBranchModelSwitchAndVariants() throws {41 let t = try decode(ConversationTimeline.self, PanelFixture.timeline)42 #expect(t.conversation.title == "Comptage de 1 à 60"); #expect(t.note == "Chronologie reconstruite uniquement à partir des événements enregistrés.")43 #expect(t.events.map(\.type) == ["prompt", "response", "prompt", "response", "branch", "model_switch", "response"])44 #expect(t.events.map(\.index) == Array(0..<7)); #expect(t.events.map(\.kind) == [.prompt, .response, .prompt, .response, .branch, .modelSwitch, .response])45 let first = t.events[1]46 #expect(first.model == "claude-haiku-5-5"); #expect(first.usage?.input == 2237); #expect(first.usage?.cached == 2132); #expect(first.latencyMs == 725); #expect(first.ttftMs == 384)47 #expect(!first.isCostExact); #expect(first.citations == 0); #expect(first.active)48 let inactive = t.events[3]49 #expect(!inactive.active); #expect(inactive.variant == 1); #expect(inactive.variants == 2)50 let branch = t.events[4]51 #expect(branch.conversationId == "conv_ax86wojh31sghee7"); #expect(branch.title == "Variante courte"); #expect(branch.messageId == "msg_ady2mo6uy1e1ukp5"); #expect(branch.active, "a branch event carries no `active` flag: it is not a dimmed variant")52 #expect(t.events[5].from == "claude-haiku-5-5"); #expect(t.events[5].to == "or:google/gemini-4-neon")53 let last = t.events[6]54 #expect(last.isCostExact); #expect(last.costUsd == 0.00888); #expect(last.servedBy == "OpenRouter · Google"); #expect(last.variant == 2)55 #expect(last.at == ServerDate.parse("2026-11-19T14:40:11.114Z"))56 }5758 @Test func timelineToolArtifactAndUnknownTypes() throws {59 let t = try decode(ConversationTimeline.self, PanelFixture.timelineToolAndArtifact)60 #expect(t.events[1].citations == 6)61 let tool = t.events[2]62 #expect(tool.kind == .tool); #expect(tool.tool == "web_search"); #expect(tool.status == "ok"); #expect(tool.durationMs == 3178); #expect(tool.recordId == "tx_x7hwqhyze0rzb3c1")63 let art = t.events[3]64 #expect(art.kind == .artifact); #expect(art.artifactType == "python"); #expect(art.version == 1); #expect(art.title?.hasPrefix("Calcul") == true)65 // an event type this client does not know is kept, an entry that is not an object is skipped, the order is preserved66 let u = try decode(ConversationTimeline.self, #"{"events":[{"type":"prompt","at":"2026-11-19T10:00:00Z","messageId":"m1"},{"type":"hologram","at":"2026-11-19T10:00:05Z","messageId":"m2","preview":"Projection","id":7},"oops",{"type":"file","messageId":"m1","name":"plan.pdf","mime":"application/pdf","size":"2048"},{"type":"image","filename":"photo.png"},{"at":"pas une date"}]}"#)67 #expect(u.events.map(\.type) == ["prompt", "hologram", "file", "image", "unknown"]); #expect(u.events.map(\.index) == [0, 1, 2, 3, 4])68 #expect(u.events[1].kind == .unknown); #expect(u.events[1].preview == "Projection"); #expect(u.events[1].recordId == "7")69 #expect(u.events[2].filename == "plan.pdf"); #expect(u.events[2].sizeBytes == 2048); #expect(u.events[3].filename == "photo.png"); #expect(u.events[4].at == nil)70 #expect(u.note == nil); #expect(u.conversation.id == nil)71 }7273 @Test func treeFamilyAndVariants() throws {74 let t = try decode(ConversationTree.self, PanelFixture.tree)75 #expect(t.current == "conv_3nqb6uaejng8x5f2"); #expect(t.hasBranches); #expect(t.family.count == 2)76 #expect(t.family[0].isRoot); #expect(t.family[0].depth == 0); #expect(t.family[0].messageCount == 5); #expect(t.family[0].branchLabel == nil)77 #expect(t.family[1].parentId == "conv_3nqb6uaejng8x5f2"); #expect(t.family[1].depth == 1); #expect(t.family[1].branchLabel == "Variante courte"); #expect(t.family[1].branchMessageId == "msg_ady2mo6uy1e1ukp5")78 #expect(t.family[1].lastAt != nil)79 #expect(t.variants.count == 1)80 let g = t.variants[0]81 #expect(g.parentId == "msg_memnqrz1s9kt59hu"); #expect(g.role == "assistant"); #expect(g.options.map(\.active) == [false, true]); #expect(g.options.map(\.model) == ["claude-haiku-5-5", "or:google/gemini-4-neon"])82 // PostgreSQL timestamps with microseconds and an offset83 let expected = try #require(ServerDate.parse("2026-11-17T19:02:01.090Z")); let got = try #require(g.options[0].createdAt)84 #expect(abs(got.timeIntervalSince(expected)) < 0.001)85 let lone = try decode(ConversationTree.self, #"{"current":"c","family":[{"id":"c","title":"Seule","message_count":"2","depth":"0","branch_label":""},{"title":"sans id"}],"variants":[{"options":[{"id":"m1"},{"active":true}]}]}"#)86 #expect(!lone.hasBranches); #expect(lone.family.count == 1); #expect(lone.family[0].branchLabel == nil); #expect(lone.family[0].messageCount == 2)87 #expect(lone.variants[0].options.count == 1); #expect(lone.variants[0].role == "assistant")88 }8990 @Test func lensListAndCostBasis() throws {91 let empty = try decode(LensList.self, PanelFixture.lensListEmpty)92 #expect(empty.kinds.map(\.id) == ["summary", "explain", "keypoints", "table", "verify"]); #expect(empty.kinds.map(\.usesWeb) == [false, false, false, false, true]); #expect(empty.lenses.isEmpty)93 #expect(empty.label(for: "keypoints") == "Points importants"); #expect(empty.label(for: "inconnu") == "inconnu")94 let l = try decode(LensList.self, PanelFixture.lensList)95 let s = try #require(l.lenses.first)96 #expect(s.id == "lens_lkb7q8lk9whq0eg1"); #expect(s.lens == "summary"); #expect(s.modelId == "claude-haiku-5-5"); #expect(s.content == PanelFixture.lensContent)97 #expect(s.costUsd == 0.00008); #expect(!s.isCostExact, "no billed amount reported: the cost is an estimate"); #expect(s.createdAt != nil); #expect(s.status == "complete"); #expect(!s.isEmpty)98 // a billed amount inside usage makes the cost exact; unknown kinds and broken rows never fail the payload99 let x = try decode(LensList.self, #"{"kinds":[{"id":"haiku","usesWeb":true},{"label":"sans id"}],"lenses":[{"id":"l1","lens":"haiku","usage":{"input":1,"output":2,"costUsd":0.001},"cost_usd":"0.001","sources":[{"url":"https://www.example.org/a","title":"A","claim":"c"},{"title":"sans url"}]},{"lens":"sans id"}]}"#)100 #expect(x.kinds.count == 1); #expect(x.kinds[0].label == "haiku"); #expect(x.lenses.count == 1); #expect(x.lenses[0].isCostExact); #expect(x.lenses[0].costUsd == 0.001)101 #expect(x.lenses[0].sources.count == 1); #expect(x.lenses[0].sources[0].domain == "example.org")102 }103104 @Test func endpointsBuildTheDocumentedRequests() async throws {105 let t = MockTransport(); let api = makeClient(t)106 t.on("GET", "/api/conversations/conv_1/context", .json(200, PanelFixture.context)); t.on("GET", "/api/conversations/conv_1/timeline", .json(200, PanelFixture.timeline))107 t.on("GET", "/api/conversations/conv_1/tree", .json(200, PanelFixture.tree)); t.on("GET", "/api/lens", .json(200, PanelFixture.lensList)); t.on("DELETE", "/api/lens", .json(200, #"{"ok":true}"#))108 t.on("POST", "/api/lens", .sse(PanelFixture.lensRunFrames))109 #expect(try await api.conversationContext("conv_1", model: "or:google/gemini-4-neon").messages.count == 4)110 #expect(try await api.conversationTimeline("conv_1").events.count == 7)111 #expect(try await api.conversationTree("conv_1").family.count == 2)112 #expect(try await api.lenses(messageId: "msg_a").lenses.count == 1)113 try await api.deleteLens("lens_1")114 guard case .events = try await api.openLens(messageId: "msg_a", lens: "summary", modelId: "claude-haiku-5-5") else { Issue.record("expected an event stream"); return }115 let r = t.requests116 #expect(r[0].query == "model=or:google/gemini-4-neon"); #expect(r[3].query == "messageId=msg_a"); #expect(r[4].method == "DELETE"); #expect(r[4].query == "id=lens_1"); #expect(r[4].headers["Origin"] != nil)117 let raw = try #require(r[5].body); let body = try #require(JSONValue.parse(raw))118 #expect(body["messageId"]?.stringValue == "msg_a"); #expect(body["lens"]?.stringValue == "summary"); #expect(body["modelId"]?.stringValue == "claude-haiku-5-5"); #expect(r[5].headers["Accept"] == "text/event-stream")119 // a missing conversation is a server error, not a decoding crash120 t.on("GET", "/api/conversations/nope/context", .json(404, #"{"error":"Introuvable"}"#))121 await #expect(throws: APIError.self) { _ = try await api.conversationContext("nope") }122 }123}124