Repository Public
1// SP Notes Core2// File: Tests/SPNotesAPITests/NextRoutesRequestTests.swift3// Description: The exact requests the 3.0 routes send (method, path, query string, body, headers), checked against4// the stub server, which answers with the recorded fixtures so that each call is decoded end to end.5//6// Where no real answer exists (paid AI routes on a server we cannot call), the stub answer is written by7// hand: the codes come from API-NEXT §5 / API-NEXT-AI §9, the messages are placeholders, and such a test8// only proves the request shape and the code mapping.9//10// Author: Simon-Pierre Boucher11// Contact: contact@spboucher.ai12import Foundation13import XCTest14@testable import SPNotesAPI1516final class NextRoutesRequestTests: XCTestCase {17 private let page = "11111111-1111-4111-8111-111111111111"18 private let other = "22222222-2222-4222-8222-222222222222"1920 /// Answers every request with a recorded fixture (status and `x-existing` included).21 private func reply(_ group: String, _ name: String) throws {22 let fixture = try NextFixture.load(group, name)23 let headers = fixture.entry.headers.filter { $0.key == "x-existing" }24 StubServer.shared.reset { _ in StubReply(status: fixture.entry.status, headers: ["Content-Type": "application/json"].merging(headers) { $1 }, body: fixture.data) }25 }2627 private func last(file: StaticString = #filePath, line: UInt = #line) throws -> RecordedRequest {28 try XCTUnwrap(StubServer.shared.last, "no request was sent", file: file, line: line)29 }3031 private func items(_ request: RecordedRequest) -> [String: String] {32 let pairs = URLComponents(url: request.url, resolvingAgainstBaseURL: false)?.queryItems ?? []33 return Dictionary(pairs.map { ($0.name, $0.value ?? "") }, uniquingKeysWith: { a, _ in a })34 }3536 private func body(_ request: RecordedRequest) -> NSDictionary? { jsonObject(request.body) as? NSDictionary }3738 // MARK: graph3940 func testGraphViews() async throws {41 let (api, _, _) = TestEnv.api()42 try reply("graph", "graph-local")43 let local = try await api.graph(.local(pageId: page, depth: 2))44 XCTAssertEqual(local.view, GraphView.local)45 var request = try last()46 XCTAssertEqual(request.method, "GET")47 XCTAssertEqual(request.path, "/api/graph")48 XCTAssertEqual(items(request), ["view": "local", "pageId": page, "depth": "2"])49 XCTAssertNil(request.header("Origin"))5051 try reply("graph", "graph-timeline")52 let from = try XCTUnwrap(APIDate.parse("2026-11-01T00:00:00Z")), to = try XCTUnwrap(APIDate.parse("2027-01-01T00:00:00+00:00"))53 _ = try await api.graph(.timeline(from: from, to: to))54 request = try last()55 XCTAssertEqual(items(request), ["view": "timeline", "from": "2026-11-01T00:00:00.000Z", "to": "2027-01-01T00:00:00.000Z"])56 XCTAssertTrue(request.query?.contains("from=2026-11-01T00:00:00.000Z") ?? false)5758 try reply("graph", "graph-global")59 _ = try await api.graph(GraphQuery(view: GraphView.global, includeSuggestions: false, hideOrphans: true))60 XCTAssertEqual(items(try last()), ["view": "global", "suggestions": "0", "hideOrphans": "1"])61 _ = try await api.graph(GraphQuery(view: GraphView.global))62 XCTAssertEqual(try last().query, "view=global", "defaults are not sent")63 try reply("graph", "graph-project")64 _ = try await api.graph(.project(pageId: page))65 XCTAssertEqual(items(try last()), ["view": "project", "pageId": page])6667 // The 2.x form: no `view` at all.68 try reply("graph", "graph-legacy-page")69 let legacy = try await api.legacyGraph(pageID: page)70 XCTAssertNil(legacy.view)71 XCTAssertEqual(try last().query, "pageId=\(page)")72 try reply("graph", "graph-legacy")73 _ = try await api.legacyGraph()74 XCTAssertNil(try last().query)7576 try reply("graph", "graph-bad-view")77 let error = await captureAPIError { try await api.graph(GraphQuery(view: "galaxy")) }78 XCTAssertEqual(error?.code, APIError.NextCode.badView)79 }8081 func testRelationRoutes() async throws {82 let (api, _, _) = TestEnv.api()83 try reply("graph", "relation-create")84 let from = try XCTUnwrap(APIDate.parse("2026-01-01T00:00:00Z"))85 let draft = RelationDraft(id: other, fromId: page, toId: other, relType: RelationType.supports, note: "n", validFrom: from)86 let created = try await api.createRelation(draft, idempotencyKey: "spn-key-0001")87 XCTAssertFalse(created.existing)88 var request = try last()89 XCTAssertEqual(request.method, "POST")90 XCTAssertEqual(request.path, "/api/graph/relations")91 XCTAssertEqual(request.header("Origin"), "https://notes.test")92 XCTAssertEqual(request.header("Idempotency-Key"), "spn-key-0001")93 XCTAssertEqual(body(request), ["id": other, "fromId": page, "toId": other, "relType": "supports", "note": "n", "validFrom": "2026-01-01T00:00:00.000Z"],94 "unset fields are not sent")9596 try reply("graph", "relation-create-existing")97 let again = try await api.createRelation(draft)98 XCTAssertTrue(again.existing, "200 + x-existing")99 XCTAssertEqual(again.value, created.value)100101 try reply("graph", "relation-exists")102 let exists = await captureAPIError { try await api.createRelation(RelationDraft(fromId: page, toId: other, relType: RelationType.supports)) }103 XCTAssertEqual(exists?.existingRelation?.id, created.value.id)104 XCTAssertEqual(body(try last()), ["fromId": page, "toId": other, "relType": "supports"])105106 try reply("graph", "relations-list-include")107 let list = try await api.relations(RelationFilter(nodeId: page, status: DecisionStatus.accepted, relType: RelationType.cites, origin: KnowledgeOrigin.system,108 include: [RelationKind.cites, RelationKind.link]))109 XCTAssertFalse(list.isEmpty)110 request = try last()111 XCTAssertEqual(request.path, "/api/graph/relations")112 XCTAssertEqual(items(request), ["nodeId": page, "status": "accepted", "relType": "cites", "origin": "system", "include": "cites,link"])113 try reply("graph", "relations-list")114 _ = try await api.relations()115 XCTAssertNil(try last().query)116117 try reply("graph", "relation-get")118 _ = try await api.relation(id: other)119 XCTAssertEqual(try last().path, "/api/graph/relations/\(other)")120121 try reply("graph", "relation-patch")122 _ = try await api.updateRelation(id: other, RelationChanges(relType: RelationType.extends, note: .null, validTo: .null))123 request = try last()124 XCTAssertEqual(request.method, "PATCH")125 XCTAssertEqual(request.path, "/api/graph/relations/\(other)")126 XCTAssertEqual(request.bodyText, #"{"note":null,"relType":"extends","validTo":null}"#, "explicit nulls clear, absent keys are left alone")127 try reply("graph", "relation-patch-rejected")128 let rejected = try await api.updateRelation(id: other, RelationChanges(status: DecisionStatus.rejected, validFrom: .value(from)))129 XCTAssertEqual(rejected.status, DecisionStatus.rejected)130 XCTAssertEqual(try last().bodyText, #"{"status":"rejected","validFrom":"2026-01-01T00:00:00.000Z"}"#)131 XCTAssertTrue(RelationChanges().isEmpty)132133 try reply("graph", "relation-derived-edge")134 let derived = await captureAPIError { try await api.updateRelation(id: other, RelationChanges(note: .value("x"))) }135 XCTAssertEqual(derived?.isDerivedEdge, true)136137 try reply("graph", "relation-delete")138 let deleted = try await api.deleteRelation(id: other)139 XCTAssertTrue(deleted.ok)140 request = try last()141 XCTAssertEqual(request.method, "DELETE")142 XCTAssertEqual(request.path, "/api/graph/relations/\(other)")143 XCTAssertEqual(request.header("Origin"), "https://notes.test")144 XCTAssertTrue(request.body.isEmpty)145 }146147 func testConceptRoutes() async throws {148 let (api, _, _) = TestEnv.api()149 try reply("graph", "concept-create")150 let created = try await api.createConcept(ConceptDraft(id: other, name: "Fixture · hétéroscédasticité", description: "d", pageIds: [page]))151 XCTAssertFalse(created.existing)152 var request = try last()153 XCTAssertEqual(request.method, "POST")154 XCTAssertEqual(request.path, "/api/concepts")155 XCTAssertEqual(body(request), ["id": other, "name": "Fixture · hétéroscédasticité", "description": "d", "pageIds": [page]])156 try reply("graph", "concept-create-existing")157 let again = try await api.createConcept(ConceptDraft(id: other, name: "x"))158 XCTAssertTrue(again.existing)159 XCTAssertEqual(body(try last()), ["id": other, "name": "x"])160161 try reply("graph", "concept-exists")162 let exists = await captureAPIError { try await api.createConcept(ConceptDraft(name: "x")) }163 XCTAssertEqual(exists?.existingConcept?.id, created.value.id)164 try reply("graph", "concept-bad-page")165 let badPage = await captureAPIError { try await api.createConcept(ConceptDraft(name: "x", pageIds: [page])) }166 XCTAssertEqual(badPage?.unknownPageIDs?.count, 1)167168 try reply("graph", "concepts-list")169 _ = try await api.concepts()170 XCTAssertEqual(try last().path, "/api/concepts")171 XCTAssertNil(try last().query)172 try reply("graph", "concepts-list-page")173 _ = try await api.concepts(status: InsightStatus.all, pageID: page)174 XCTAssertEqual(items(try last()), ["status": "all", "pageId": page])175176 try reply("graph", "concept-get")177 let fetched = try await api.concept(id: other)178 XCTAssertEqual(fetched.pageLinks?.count, 2)179 XCTAssertEqual(try last().path, "/api/concepts/\(other)")180181 try reply("graph", "concept-patch")182 _ = try await api.updateConcept(id: other, ConceptChanges(description: "d2", addPages: [page], removePages: [other]))183 request = try last()184 XCTAssertEqual(request.method, "PATCH")185 XCTAssertEqual(request.path, "/api/concepts/\(other)")186 XCTAssertEqual(body(request), ["description": "d2", "addPages": [page], "removePages": [other]])187 try reply("graph", "concept-patch-page-links")188 _ = try await api.updateConcept(id: other, ConceptChanges(pageLinks: [ConceptPageDecision(pageId: page, status: DecisionStatus.rejected)]))189 XCTAssertEqual(try last().bodyText, #"{"pageLinks":[{"pageId":"\#(page)","status":"rejected"}]}"#)190191 // The collection form carries the id in the body.192 try reply("graph", "concept-patch-collection")193 let patched = try await api.patchConcepts(id: other, ConceptChanges(status: DecisionStatus.rejected))194 XCTAssertEqual(patched.status, DecisionStatus.rejected)195 request = try last()196 XCTAssertEqual(request.method, "PATCH")197 XCTAssertEqual(request.path, "/api/concepts")198 XCTAssertEqual(request.bodyText, #"{"id":"\#(other)","status":"rejected"}"#)199200 try reply("graph", "concept-delete")201 try await api.deleteConcept(id: other)202 XCTAssertEqual(try last().method, "DELETE")203 XCTAssertEqual(try last().path, "/api/concepts/\(other)")204 XCTAssertTrue(ConceptChanges().isEmpty)205 }206207 func testInsightRoutes() async throws {208 let (api, _, _) = TestEnv.api()209 try reply("graph", "insights")210 _ = try await api.graphInsights()211 XCTAssertEqual(try last().path, "/api/graph/insights")212 XCTAssertNil(try last().query)213 try reply("graph", "insights-no-intelligence")214 let bare = try await api.graphInsights(InsightQuery(status: InsightStatus.all, kind: InsightKind.duplicate, limit: 5, includeIntelligence: false))215 XCTAssertNil(bare.intelligence)216 XCTAssertEqual(items(try last()), ["status": "all", "kind": "duplicate", "limit": "5", "intelligence": "0"])217218 try reply("graph", "insights-run")219 let run = try await api.runGraphInsights(.deterministic)220 XCTAssertFalse(run.queued)221 var request = try last()222 XCTAssertEqual(request.method, "POST")223 XCTAssertEqual(request.path, "/api/graph/insights/run")224 XCTAssertEqual(request.bodyText, #"{"mode":"deterministic"}"#)225 try reply("graph", "insights-run-again")226 _ = try await api.runGraphInsights(InsightRunRequest(mode: InsightRunMode.deterministic, pageIds: [page], limit: 5))227 XCTAssertEqual(body(try last()), ["mode": "deterministic", "pageIds": [page], "limit": 5])228 _ = try await api.runGraphInsights(InsightRunRequest())229 XCTAssertEqual(try last().bodyText, "{}", "the body is required, even empty")230231 try reply("graph", "insight-dismiss")232 let decided = try await api.decideInsight(id: other, status: InsightStatus.dismissed)233 XCTAssertEqual(decided.status, InsightStatus.dismissed)234 request = try last()235 XCTAssertEqual(request.method, "PATCH")236 XCTAssertEqual(request.path, "/api/graph/insights/\(other)")237 XCTAssertEqual(request.bodyText, #"{"status":"dismissed"}"#)238 }239240 // MARK: journal, time machine241242 func testEventRoutes() async throws {243 let (api, _, _) = TestEnv.api()244 try reply("timeline", "events-page")245 let first = try await api.events(JournalQuery(pageId: page, limit: 3))246 XCTAssertEqual(first.events.count, 3)247 var request = try last()248 XCTAssertEqual(request.method, "GET")249 XCTAssertEqual(request.path, "/api/events")250 XCTAssertEqual(items(request), ["pageId": page, "limit": "3"])251252 // The opaque cursor is passed back as it is (base64url: no escaping needed, none applied twice).253 let cursor = try XCTUnwrap(first.nextCursor)254 try reply("timeline", "events-page-next")255 _ = try await api.events(JournalQuery(pageId: page, limit: 3, cursor: cursor))256 XCTAssertEqual(items(try last())["cursor"], cursor)257258 let from = try XCTUnwrap(APIDate.parse("2026-11-19T00:00:00Z")), to = try XCTUnwrap(APIDate.parse("2026-11-20T00:00:00Z"))259 try reply("timeline", "events-project-kinds")260 _ = try await api.events(JournalQuery(projectId: other, from: from, to: to, kinds: [EventKind.family("relation"), EventKind.family("task"), EventKind.pageRenamed], limit: 50))261 request = try last()262 XCTAssertEqual(items(request), ["projectId": other, "from": "2026-11-19T00:00:00.000Z", "to": "2026-11-20T00:00:00.000Z", "kinds": "relation.*,task.*,page.renamed", "limit": "50"])263 XCTAssertTrue(request.query?.contains("kinds=relation.*,task.*,page.renamed") ?? false, "families are sent literally: \(request.query ?? "")")264265 try reply("timeline", "events-workspace")266 _ = try await api.events()267 XCTAssertNil(try last().query)268269 try reply("timeline", "events-bad-kinds")270 let kinds = await captureAPIError { try await api.events(JournalQuery(kinds: ["unicorn.seen"])) }271 XCTAssertEqual(kinds?.validKinds?.count, 30)272 try reply("timeline", "events-bad-cursor")273 let bad = await captureAPIError { try await api.events(JournalQuery(cursor: "not-a-cursor")) }274 XCTAssertEqual(bad?.code, APIError.NextCode.badCursor)275 }276277 func testTimeMachineAndRestoreRoutes() async throws {278 let (api, _, _) = TestEnv.api()279 let at = try XCTUnwrap(APIDate.parse("2026-11-19T18:42:29.057Z"))280 try reply("timeline", "timemachine-page-middle")281 let snapshot = try await api.timeMachine(pageID: page, at: at)282 XCTAssertEqual(snapshot.pages.first?.source, TimeMachineSource.version)283 var request = try last()284 XCTAssertEqual(request.path, "/api/timemachine")285 XCTAssertEqual(items(request), ["at": "2026-11-19T18:42:29.057Z", "pageId": page], "content is left to the server default")286 try reply("timeline", "timemachine-page-no-content")287 _ = try await api.timeMachine(pageID: page, at: at, includeContent: false)288 XCTAssertEqual(items(try last())["content"], "0")289 try reply("timeline", "timemachine-project-content")290 _ = try await api.timeMachine(projectID: other, at: at, includeContent: true)291 XCTAssertEqual(items(try last()), ["at": "2026-11-19T18:42:29.057Z", "projectId": other, "content": "1"])292293 let entry = try XCTUnwrap(snapshot.pages.first?.versionId)294 try reply("timeline", "restore")295 let restored = try await api.restoreHistoryEntry(pageID: page, versionID: entry, baseVersion: 3, idempotencyKey: "spn-key-0002")296 XCTAssertEqual(restored.restored, 1)297 request = try last()298 XCTAssertEqual(request.method, "POST")299 XCTAssertEqual(request.path, "/api/pages/\(page)/versions/\(entry)/restore")300 XCTAssertEqual(request.bodyText, #"{"baseVersion":3}"#)301 XCTAssertEqual(request.header("Idempotency-Key"), "spn-key-0002")302 XCTAssertEqual(request.header("Origin"), "https://notes.test")303 try reply("timeline", "restore-by-number")304 _ = try await api.restoreHistoryEntry(pageID: page, versionID: "1")305 XCTAssertEqual(try last().path, "/api/pages/\(page)/versions/1/restore")306 XCTAssertEqual(try last().bodyText, "{}", "baseVersion is optional")307308 // 409: the standard page conflict, with the server copy.309 try reply("timeline", "restore-conflict")310 let conflict = await captureAPIError { try await api.restoreHistoryEntry(pageID: self.page, versionID: entry, baseVersion: 1) }311 guard case .conflict(let server, _)? = conflict else { return XCTFail("expected APIError.conflict, got \(String(describing: conflict))") }312 XCTAssertEqual(server.version, 3)313 }314315 // MARK: health, brief, query, zoom316317 func testKnowledgeRoutes() async throws {318 let (api, _, _) = TestEnv.api()319 try reply("knowledge", "health")320 _ = try await api.knowledgeHealth()321 XCTAssertEqual(try last().path, "/api/health/knowledge")322 XCTAssertNil(try last().query)323 try reply("knowledge", "health-inactive-1")324 _ = try await api.knowledgeHealth(inactiveDays: 1)325 XCTAssertEqual(try last().query, "inactiveDays=1")326327 try reply("knowledge", "brief")328 let brief = try await api.brief(timeZone: "America/Toronto")329 XCTAssertEqual(brief.timeZone, "America/Toronto")330 XCTAssertEqual(try last().path, "/api/brief")331 XCTAssertEqual(items(try last()), ["tz": "America/Toronto"])332 try reply("knowledge", "brief-default")333 _ = try await api.brief()334 XCTAssertNil(try last().query)335336 // The summary is only ever requested explicitly; its answer is the shape of `aiSummary` plus the cost.337 StubServer.shared.reset { _ in .json(#"{"ai":true,"text":"Résumé.","model":"m-1","at":"2026-11-19T18:32:01.974Z","costUsd":0.0001}"#) }338 let summary = try await api.summarizeBrief(timeZone: "Europe/Paris")339 XCTAssertEqual(summary.costUsd, 0.0001)340 var request = try last()341 XCTAssertEqual(request.method, "POST")342 XCTAssertEqual(request.path, "/api/brief/summary")343 XCTAssertEqual(request.bodyText, #"{"tz":"Europe/Paris"}"#)344 _ = try await api.summarizeBrief()345 XCTAssertEqual(try last().bodyText, "{}")346 StubServer.shared.reset { _ in .json(#"{"error":"The model returned nothing","code":"ai_empty"}"#, status: 502) }347 let empty = await captureAPIError { try await api.summarizeBrief() }348 XCTAssertEqual(empty?.code, APIError.NextCode.aiEmpty)349350 try reply("knowledge", "query-tasks")351 let result = try await api.query(.tasks(LiveQueryFilter(status: "all", parentId: page), limit: 10))352 XCTAssertEqual(result.total, 1)353 request = try last()354 XCTAssertEqual(request.method, "POST")355 XCTAssertEqual(request.path, "/api/query")356 XCTAssertEqual(request.header("Origin"), "https://notes.test", "a read, but a POST: it needs Origin")357 XCTAssertEqual(request.bodyText, #"{"filter":{"parentId":"\#(page)","status":"all"},"limit":10,"source":"tasks"}"#)358 try reply("knowledge", "query-database")359 _ = try await api.query(.database(page, viewId: other, text: "Engle"))360 XCTAssertEqual(body(try last()), ["source": "database", "databaseId": page, "viewId": other, "filter": ["text": "Engle"]])361 try reply("knowledge", "query-backlinks")362 _ = try await api.query(.backlinks(pageId: page))363 XCTAssertEqual(try last().bodyText, #"{"pageId":"\#(page)","source":"backlinks"}"#)364 try reply("knowledge", "query-pages")365 _ = try await api.query(.pages(LiveQueryFilter(tag: "t", section: "projects", text: "x", dueBefore: "2026-06-01", dueAfter: "2026-01-01"), limit: 5))366 XCTAssertEqual(body(try last()), ["source": "pages", "limit": 5, "filter": ["tag": "t", "section": "projects", "text": "x", "dueBefore": "2026-06-01", "dueAfter": "2026-01-01"]])367 try reply("knowledge", "query-references")368 _ = try await api.query(.references())369 XCTAssertEqual(try last().bodyText, #"{"source":"references"}"#)370371 try reply("knowledge", "zoom-2")372 let outline = try await api.pageZoom(pageID: page)373 XCTAssertEqual(outline.sections?.count, 3)374 XCTAssertEqual(try last().path, "/api/pages/\(page)/zoom")375 XCTAssertEqual(try last().query, "level=2")376 try reply("knowledge", "zoom-3")377 _ = try await api.pageZoom(pageID: page, level: 3)378 XCTAssertEqual(try last().query, "level=3")379 try reply("knowledge", "zoom-1")380 let unavailable = await captureAPIError { try await api.pageZoom(pageID: self.page, level: 1) }381 XCTAssertEqual(unavailable?.isRouteMissing, true)382 XCTAssertEqual(try last().query, "level=1")383384 try reply("knowledge", "tags")385 let tags = try await api.tags()386 XCTAssertTrue(tags.contains { $0.pages == 2 })387 }388389 // MARK: AI workstream (answers: the examples of its document)390391 func testSynopsisRoutes() async throws {392 let (api, _, _) = TestEnv.api()393 try reply("ai-doc", "zoom-ai-missing")394 let missing = try await api.pageSynopsis(pageID: page, cachedOnly: true)395 XCTAssertEqual(missing.status, SynopsisStatus.missing)396 var request = try last()397 XCTAssertEqual(request.method, "GET")398 XCTAssertEqual(request.path, "/api/pages/\(page)/zoom/ai")399 XCTAssertEqual(request.query, "cachedOnly=1")400 try reply("ai-doc", "zoom-ai-ready")401 _ = try await api.pageSynopsis(pageID: page, model: "openrouter:anthropic/claude-fable-5")402 XCTAssertEqual(items(try last()), ["model": "openrouter:anthropic/claude-fable-5"])403 _ = try await api.pageSynopsis(pageID: page)404 XCTAssertNil(try last().query)405 let regenerated = try await api.regeneratePageSynopsis(pageID: page, model: "claude-haiku-5-5")406 XCTAssertTrue(regenerated.ai)407 request = try last()408 XCTAssertEqual(request.method, "POST")409 XCTAssertEqual(request.path, "/api/pages/\(page)/zoom/ai")410 XCTAssertEqual(request.bodyText, #"{"model":"claude-haiku-5-5"}"#)411 _ = try await api.regeneratePageSynopsis(pageID: page)412 XCTAssertEqual(try last().bodyText, "{}")413414 // A server without the route: its HTML 404.415 let html = try NextFixture.load("ai", "zoom-ai-missing-route")416 StubServer.shared.reset { _ in StubReply(status: 404, headers: ["Content-Type": "text/html; charset=utf-8"], body: html.data) }417 let error = await captureAPIError { try await api.pageSynopsis(pageID: self.page, cachedOnly: true) }418 XCTAssertEqual(error?.isRouteMissing, true)419 }420421 func testModelCatalogRoute() async throws {422 let (api, _, _) = TestEnv.api()423 try reply("ai", "models")424 let catalog = try await api.aiModelCatalog()425 XCTAssertFalse(catalog.models.isEmpty)426 XCTAssertEqual(try last().path, "/api/ai/models")427 XCTAssertNil(try last().query)428 _ = try await api.aiModelCatalog(AIModelQuery(all: true, provider: "openrouter", creator: "anthropic", availableOnly: true, text: "claude 5", includeUnavailable: true))429 XCTAssertEqual(items(try last()), ["all": "1", "provider": "openrouter", "creator": "anthropic", "available": "1", "q": "claude 5", "unavailable": "1"])430 }431432 func testChatScopeAndActionBodies() async throws {433 let (api, _, _) = TestEnv.api()434 let sse: @Sendable ([String]) -> StubReply = { lines in435 StubReply(status: 200, headers: ["Content-Type": "text/event-stream"], body: Data((lines.map { "data: \($0)\n\n" }.joined() + "data: [DONE]\n\n").utf8))436 }437 let meta = String(decoding: try NextFixture.load("ai-doc", "chat-page-meta").data, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)438 let done = String(decoding: try NextFixture.load("ai-doc", "chat-page-done").data, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)439 StubServer.shared.reset { _ in sse([meta, #"{"type":"text","delta":"La"}"#, done]) }440 var events: [AIEvent] = []441 let chat = AIChatRequest(message: "Quelle est la pénalité ?", clientId: "client-0001", pageId: page, scope: AIChatScope.selection, projectId: other,442 selection: "Le texte choisi.", selectionBlockId: "XycxLnbyuq")443 for try await event in try await api.aiChat(chat) { events.append(event) }444 var request = try last()445 XCTAssertEqual(request.path, "/api/ai/chat")446 XCTAssertEqual(body(request), ["message": "Quelle est la pénalité ?", "clientId": "client-0001", "pageId": page, "scope": "selection", "projectId": other,447 "selection": "Le texte choisi.", "selectionBlockId": "XycxLnbyuq"])448 XCTAssertEqual(events.count, 3)449 guard case .meta(let first) = events[0], case .done(let lastEvent) = events[2] else { return XCTFail("meta … done expected") }450 XCTAssertEqual(first.scope, AIChatScope.page)451 XCTAssertEqual(first.sources.first?.anchor, AISourceAnchor.block)452 XCTAssertEqual(lastEvent.uncited, false)453454 // A 1.x request is unchanged on the wire: none of the 3.0 keys appears.455 StubServer.shared.reset { _ in sse([]) }456 for try await _ in try await api.aiChat(AIChatRequest(message: "hello", mode: .general)) {}457 XCTAssertEqual(try last().bodyText, #"{"message":"hello","mode":"general"}"#)458459 // The new action ids, with the page; `links` answers with one result event.460 let result = String(decoding: try NextFixture.load("ai-doc", "action-links-result").data, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)461 let linksDone = String(decoding: try NextFixture.load("ai-doc", "action-links-done").data, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)462 StubServer.shared.reset { _ in sse([#"{"type":"meta","model":"claude-haiku-5-5","provider":"anthropic","reason":"user selection","budgetNote":null}"#, result, linksDone]) }463 events = []464 for try await event in try await api.aiAction(AIActionCall(action: AIActionID.links, text: "Avant de signer.", pageId: page, model: "claude-haiku-5-5")) { events.append(event) }465 request = try last()466 XCTAssertEqual(request.method, "POST")467 XCTAssertEqual(request.path, "/api/ai/action")468 XCTAssertEqual(request.header("Accept"), "text/event-stream")469 XCTAssertEqual(request.bodyText, #"{"action":"links","model":"claude-haiku-5-5","pageId":"\#(page)","text":"Avant de signer."}"#)470 XCTAssertEqual(events.count, 3)471 XCTAssertEqual(events[1].linkSuggestions?.links.count, 2)472 guard case .done = events[2] else { return XCTFail("done expected") }473474 // A historical request can be tied to a page without touching AIActionRequest.475 StubServer.shared.reset { _ in sse([]) }476 for try await _ in try await api.aiAction(AIActionCall(AIActionRequest(action: .toTasks, text: "t", language: "fr"), pageId: page)) {}477 XCTAssertEqual(try last().bodyText, #"{"action":"to_tasks","language":"fr","pageId":"\#(page)","text":"t"}"#)478 // And the 1.x call still sends exactly what it sent.479 for try await _ in try await api.aiAction(AIActionRequest(action: .summarize, text: "t")) {}480 XCTAssertEqual(try last().bodyText, #"{"action":"summarize","text":"t"}"#)481482 StubServer.shared.reset { _ in .json(#"{"error":"Nothing to link","code":"no_text"}"#, status: 400) }483 let noText = await captureAPIError { try await api.aiAction(AIActionCall(action: AIActionID.links, text: "")) }484 XCTAssertEqual(noText?.code, APIError.AICode.noText)485 }486487 func testAudioRoutes() async throws {488 let (api, _, _) = TestEnv.api()489 try reply("ai-doc", "audio-transcribe-queued")490 let queued = try await api.transcribeAudio(attachmentID: other, summarize: true)491 XCTAssertEqual(queued.queued, true, "202 is a success")492 var request = try last()493 XCTAssertEqual(request.method, "POST")494 XCTAssertEqual(request.path, "/api/audio/\(other)/transcribe")495 XCTAssertEqual(request.bodyText, #"{"summarize":true}"#)496 _ = try await api.transcribeAudio(attachmentID: other, force: true)497 XCTAssertEqual(try last().bodyText, #"{"force":true}"#)498 _ = try await api.transcribeAudio(attachmentID: other)499 XCTAssertEqual(try last().bodyText, "{}")500501 try reply("ai-doc", "audio-done")502 let done = try await api.audioTranscription(attachmentID: other)503 XCTAssertTrue(done.isDone)504 request = try last()505 XCTAssertEqual(request.method, "GET")506 XCTAssertEqual(request.path, "/api/audio/\(other)")507508 StubServer.shared.reset { _ in .json(#"{"error":"Not an audio file","code":"not_audio"}"#, status: 415) }509 let notAudio = await captureAPIError { try await api.transcribeAudio(attachmentID: self.other) }510 XCTAssertEqual(notAudio?.code, APIError.AICode.notAudio)511 XCTAssertEqual(notAudio?.isBadRequest, true)512 StubServer.shared.reset { _ in .json(#"{"error":"No transcription engine","code":"not_configured"}"#, status: 503) }513 let unavailable = await captureAPIError { try await api.transcribeAudio(attachmentID: self.other) }514 XCTAssertEqual(unavailable?.isAIUnavailable, true)515 XCTAssertEqual(unavailable?.isRetryable, false)516 }517518 func testSmartDatabaseRoutes() async throws {519 let (api, _, _) = TestEnv.api()520 try reply("ai-doc", "database-ai-config")521 let config = try await api.databaseAIConfig(databaseID: page)522 XCTAssertEqual(config.properties.count, 1)523 XCTAssertEqual(try last().path, "/api/databases/\(page)/ai/config")524525 try reply("ai-doc", "database-ai-config-put")526 let saved = try await api.setDatabaseAIConfig(databaseID: page, propertyID: other, DatabaseAISettingsPatch(task: DatabaseAITask.classify, choices: ["A", "B"], model: .null, autoRun: true))527 XCTAssertEqual(saved.name, "Priorité IA")528 var request = try last()529 XCTAssertEqual(request.method, "PUT")530 XCTAssertEqual(request.path, "/api/databases/\(page)/ai/config")531 XCTAssertEqual(request.bodyText, #"{"ai":{"autoRun":true,"choices":["A","B"],"model":null,"task":"classify"},"propertyId":"\#(other)"}"#)532 _ = try await api.setDatabaseAIConfig(databaseID: page, propertyID: other, DatabaseAISettingsPatch(model: .value("claude-haiku-5-5"), managed: false))533 XCTAssertEqual(try last().bodyText, #"{"ai":{"managed":false,"model":"claude-haiku-5-5"},"propertyId":"\#(other)"}"#)534535 try reply("ai-doc", "database-ai-run-skipped")536 let run = try await api.runDatabaseAI(databaseID: page, propertyID: other, rowIDs: ["row-1"])537 XCTAssertEqual(run.skipped?.count, 1)538 request = try last()539 XCTAssertEqual(request.method, "POST")540 XCTAssertEqual(request.path, "/api/databases/\(page)/ai")541 XCTAssertEqual(request.bodyText, #"{"propertyId":"\#(other)","rowId":"row-1"}"#, "one row is sent as rowId")542 _ = try await api.runDatabaseAI(databaseID: page, propertyID: other, rowIDs: ["row-1", "row-2"], force: true)543 XCTAssertEqual(try last().bodyText, #"{"force":true,"propertyId":"\#(other)","rowIds":["row-1","row-2"]}"#)544545 try reply("ai-doc", "database-ai-runs")546 let log = try await api.databaseAIRuns(databaseID: page, DatabaseAIRunFilter(propertyId: other, rowId: "row-1", status: "done", limit: 20))547 XCTAssertEqual(log.count, 1)548 XCTAssertEqual(try last().path, "/api/databases/\(page)/ai/runs")549 XCTAssertEqual(items(try last()), ["propertyId": other, "rowId": "row-1", "status": "done", "limit": "20"])550 _ = try await api.databaseAIRuns(databaseID: page)551 XCTAssertNil(try last().query)552553 StubServer.shared.reset { _ in .json(#"{"error":"Not an AI property","code":"not_ai_property"}"#, status: 400) }554 let error = await captureAPIError { try await api.setDatabaseAIConfig(databaseID: self.page, propertyID: self.other, DatabaseAISettingsPatch(autoRun: true)) }555 XCTAssertEqual(error?.code, APIError.AICode.notAIProperty)556 }557}558