SPB Git

Repository Public

RepositoryOnlineTests.swift 30.1 KB 432 lines swift

1// SP Notes Core2// File: Tests/SPNotesSyncTests/RepositoryOnlineTests.swift3// Description: The repositories of the kinds that are written online and read offline (databases, relations, concepts,4//              references) and of the cached read models (health, brief, graph, zoom, query, journal), driven by the REAL5//              answers recorded from the scratch backend (Tests/SPNotesAPITests/Fixtures/next) served by the fake: the6//              answer of a write updates the local copy; offline a write throws `.offline` and queues nothing; a read7//              model comes back from the cache with its fetch date.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation12import SPNotesAPI13import SPNotesDocument14import SPNotesStore15import Testing16@testable import SPNotesSync17@testable import SPNotesTestSupport1819/// A recorded answer of the scratch backend (read from the source tree).20enum Recorded {21    static func text(_ group: String, _ name: String, file: String = #filePath) -> String {22        let root = URL(fileURLWithPath: file).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("SPNotesAPITests/Fixtures/next")23        return (try? String(contentsOf: root.appendingPathComponent(group).appendingPathComponent(name + ".json"), encoding: .utf8)) ?? "null"24    }25    static func json(_ group: String, _ name: String) -> JSONValue { (try? JSONValue(jsonString: text(group, name))) ?? .null }26}2728@Suite("Repositories: online writes, offline reads, cached read models (2.0)")29struct RepositoryOnlineTests {30    private func device() throws -> (World, Device, NotesRepositories) {31        let world = World(apiLevel: 3)32        let a = try world.device("A")33        return (world, a, NotesRepositories(store: a.store, api: a.api, engine: nil))34    }3536    @Test("databases: the server's answers fill the local copy; offline everything is readable and every write throws .offline without queueing")37    func databases() async throws {38        let (world, a, repos) = try device()39        let fake = world.fake40        let db = Recorded.json("databases", "db-get")41        let dbId = try #require(db["id"]?.stringValue), pageId = try #require(db["pageId"]?.stringValue)42        fake.stub("GET", path: "^/api/databases/[^/]+$", json: Recorded.text("databases", "db-get"))43        fake.stub("POST", path: "^/api/databases/[^/]+/query$", json: Recorded.text("databases", "query-all"))44        fake.stub("POST", path: "^/api/databases/[^/]+/rows$", json: Recorded.text("databases", "row-create"), status: 201)45        fake.stub("POST", path: "^/api/databases/[^/]+/properties$", json: Recorded.text("databases", "prop-create-number"), status: 201)46        fake.stub("POST", path: "^/api/databases/[^/]+/views$", json: Recorded.text("databases", "view-create"), status: 201)4748        // Opening by the host page id reads the definition and caches database, properties and views.49        let opened = try await repos.databases.refresh(id: pageId)50        #expect(opened.id == dbId && !opened.properties.isEmpty && !opened.views.isEmpty)51        let local = try #require(try await repos.databases.database(id: pageId), "found by host page id too")52        #expect(local.properties.map(\.id).sorted() == opened.properties.map(\.id).sorted())53        #expect(local.properties.first?.type == "title", "title first, then by position")54        #expect(local.views.map(\.id) == opened.views.map(\.id))55        #expect(try await repos.databases.list().map(\.id) == [dbId])5657        // Online writes: the answer lands in the local copy.58        let row = try await repos.databases.createRow(databaseId: dbId, DatabaseRowDraft(title: "Nouvelle ligne"))59        #expect(try await a.store.entity(kind: .databaseRow, id: row.id) != nil)60        let sent = try #require(fake.requests.last { $0.method == "POST" && $0.path.hasSuffix("/rows") })61        #expect(sent.status == 201)62        let property = try await repos.databases.createProperty(databaseId: dbId, DatabasePropertyDraft(name: "Année", type: "number"))63        #expect(try await a.store.databaseProperties(databaseId: property.databaseId).contains { $0.id == property.id })64        let view = try await repos.databases.createView(databaseId: dbId, DatabaseViewDraft(name: "Tableau", type: "board"))65        #expect(try await a.store.entity(kind: .databaseView, id: view.id) != nil)6667        // Online rows come from the server (computed values included).68        let online = try await repos.databases.rows(databaseId: dbId)69        #expect(online.source == .server && online.isExact && online.total == Recorded.json("databases", "query-all")["total"]?.intValue)7071        // Offline: reads work from the copy, writes fail with the typed error, nothing is queued.72        a.setOffline(true)73        let offline = try await repos.databases.rows(databaseId: dbId)74        #expect(offline.source == .local)75        #expect(offline.rows.map(\.id) == [row.id], "the rows the device holds")76        #expect(try await repos.databases.database(id: dbId) != nil)77        await #expect(throws: RepositoryError.offline) { try await repos.databases.createRow(databaseId: dbId, DatabaseRowDraft(title: "Hors ligne")) }78        await #expect(throws: RepositoryError.offline) { try await repos.databases.updateRow(databaseId: dbId, rowId: row.id, values: RawJSON(string: "{}")) }79        await #expect(throws: RepositoryError.offline) { try await repos.databases.deleteRows(databaseId: dbId, ids: [row.id]) }80        await #expect(throws: RepositoryError.offline) { try await repos.databases.createProperty(databaseId: dbId, DatabasePropertyDraft(name: "X", type: "text")) }81        await #expect(throws: RepositoryError.offline) { try await repos.databases.updateView(databaseId: dbId, viewId: view.id, DatabaseViewChanges()) }82        await #expect(throws: RepositoryError.offline) { try await repos.databases.refresh(id: dbId) }83        #expect(try await a.store.entityOpCount() == 0, "no silent queueing")84        #expect(try await a.store.dirtyEntities().isEmpty)85        #expect(try await a.store.entity(kind: .databaseRow, id: row.id) != nil, "a failed delete removes nothing locally")86        await world.closeAll()87    }8889    @Test("the recorded rows of a real database evaluate locally like the server answered (filter + sort of the recorded query)")90    func localEvaluationMatchesTheRecordedServerAnswer() async throws {91        let (world, a, repos) = try device()92        let fake = world.fake93        // The database, its properties and views as the feed delivers them, then its rows (stored values).94        let db = Recorded.json("databases", "db-get")95        let dbId = try #require(db["id"]?.stringValue)96        var bare = db.objectValue ?? [:]97        bare["properties"] = nil; bare["views"] = nil98        fake.webPutEntity(kind: "database", id: dbId, json: JSONValue.object(bare).canonicalString())99        for property in db["properties"]?.arrayValue ?? [] { fake.webPutEntity(kind: "database_property", id: property["id"]?.stringValue ?? "", json: property.canonicalString()) }100        for view in db["views"]?.arrayValue ?? [] { fake.webPutEntity(kind: "database_view", id: view["id"]?.stringValue ?? "", json: view.canonicalString()) }101        // The rows as the feed delivers them (stored values), put on the device by a sync of the entity feed.102        let all = Recorded.json("databases", "query-all")["rows"]?.arrayValue ?? []103        try #require(!all.isEmpty)104        for row in all {105            var object = row.objectValue ?? [:]106            object["databaseId"] = .string(dbId)107            fake.webPutEntity(kind: "database_row", id: object["id"]?.stringValue ?? "", json: JSONValue.object(object).canonicalString())108        }109        #expect(await a.sync() == .completed)110        let everything = try await repos.databases.evaluateLocally(databaseId: dbId, query: DatabaseViewQuery())111        #expect(everything.rows.map(\.id) == all.compactMap { $0["id"]?.stringValue }, "position order, like the server's unfiltered answer")112        // The recorded filtered + sorted query, replayed locally with the request that was sent.113        let index = (try? JSONValue(jsonString: Recorded.text("databases", "_index")))?.arrayValue ?? []114        let request = try #require(index.first { $0["name"]?.stringValue == "query-filter-sort" }?["request"])115        let query = DatabaseViewQuery(filter: DatabaseViewFilter(json: request["filter"]), sorts: DatabaseViewSort.list(json: request["sorts"]), search: request["search"]?.stringValue, limit: request["limit"]?.intValue, offset: request["offset"]?.intValue ?? 0)116        let local = try await repos.databases.evaluateLocally(databaseId: dbId, query: query)117        let expected = (Recorded.json("databases", "query-filter-sort")["rows"]?.arrayValue ?? []).compactMap { $0["id"]?.stringValue }118        #expect(local.isExact, "number, select and empty rules are evaluated on the device")119        #expect(local.rows.map(\.id) == expected, "same rows in the same order as the server answered")120        #expect(local.total == Recorded.json("databases", "query-filter-sort")["total"]?.intValue)121        await world.closeAll()122    }123124    @Test("relations and concepts: created online with a client id, cached, readable offline; offline writes throw; existing ones are typed")125    func graph() async throws {126        let (world, a, repos) = try device()127        let fake = world.fake128        fake.stub("POST", path: "^/api/graph/relations$", json: Recorded.text("graph", "relation-create"), status: 201)129        fake.stub("PATCH", path: "^/api/graph/relations/", json: Recorded.text("graph", "relation-patch-rejected"))130        fake.stub("POST", path: "^/api/concepts$", json: Recorded.text("graph", "concept-create"), status: 201)131        fake.stub("GET", path: "^/api/graph$", json: Recorded.text("graph", "graph-local"))132        fake.stub("GET", path: "^/api/graph/insights$", json: Recorded.text("graph", "insights"))133        let recorded = Recorded.json("graph", "relation-create")134        let from = try #require(recorded["fromId"]?.stringValue), to = try #require(recorded["toId"]?.stringValue)135136        let relation = try await repos.graph.createRelation(RelationDraft(fromId: from, toId: to, relType: RelationType.supports))137        #expect(relation.origin == KnowledgeOrigin.user && relation.status == DecisionStatus.accepted)138        #expect(try await repos.graph.localRelations(touching: from).map(\.id) == [relation.id])139        #expect(try await repos.graph.localBacklinks(pageId: to).map(\.id) == [relation.id])140        let rejected = try await repos.graph.reject(relationId: relation.id)141        #expect(rejected.status == DecisionStatus.rejected)142        #expect(try await repos.graph.localBacklinks(pageId: to).isEmpty, "a rejected relation is not a backlink")143        let concept = try await repos.graph.createConcept(name: "hétéroscédasticité")144        #expect(try await repos.graph.localConcepts().map(\.id) == [concept.id])145        let view = try await repos.graph.view(.local(pageId: from))146        #expect(view.source == .network && view.value.view == GraphView.local && !view.value.nodes.isEmpty)147        #expect(try await repos.graph.insights().value.counts != nil)148149        fake.stub("POST", path: "^/api/graph/relations$") { _ in .json(Recorded.text("graph", "relation-exists"), status: 409) }150        do { _ = try await repos.graph.createRelation(RelationDraft(fromId: from, toId: to, relType: RelationType.supports)); Issue.record("expected relation_exists") }151        catch let error as RepositoryError {152            #expect(error.code == APIError.NextCode.relationExists)153            if case .server(let api) = error { #expect(api.existingRelation?.id != nil) }154        }155156        a.setOffline(true)157        await #expect(throws: RepositoryError.offline) { try await repos.graph.createRelation(RelationDraft(fromId: from, toId: to, relType: RelationType.extends)) }158        await #expect(throws: RepositoryError.offline) { try await repos.graph.accept(relationId: relation.id) }159        await #expect(throws: RepositoryError.offline) { try await repos.graph.deleteRelation(id: relation.id) }160        await #expect(throws: RepositoryError.offline) { try await repos.graph.createConcept(name: "x") }161        #expect(try await a.store.entityOpCount() == 0)162        let cached = try await repos.graph.view(.local(pageId: from))163        #expect(cached.source == .cache && cached.value == view.value && cached.fetchedAt == view.fetchedAt || abs(cached.fetchedAt.timeIntervalSince(view.fetchedAt)) < 0.01)164        await #expect(throws: RepositoryError.notCached) { try await repos.graph.view(.project(pageId: from)) }165        #expect(try await repos.graph.localRelations(touching: from).count == 1)166        await world.closeAll()167    }168169    @Test("references: online writes update the library; citations resolve offline from the local copy")170    func research() async throws {171        let (world, a, repos) = try device()172        let fake = world.fake173        fake.stub("POST", path: "^/api/research/references$", json: Recorded.text("research", "ref-create"), status: 201)174        fake.stub("DELETE", path: "^/api/research/references", json: #"{"ok":true}"#)175        let reference = try await repos.research.create(ReferenceDraft(title: "Generalized autoregressive conditional heteroskedasticity"))176        #expect(try await repos.research.localReferences().map(\.id) == [reference.id])177        a.setOffline(true)178        let resolved = try await repos.research.resolve(ids: [reference.id, UUID().uuidString.lowercased()])179        #expect(Array(resolved.keys) == [reference.id], "offline: from the local copy; the unknown id is simply absent")180        await #expect(throws: RepositoryError.offline) { try await repos.research.create(ReferenceDraft(title: "x")) }181        await #expect(throws: RepositoryError.offline) { try await repos.research.delete(id: reference.id) }182        await #expect(throws: RepositoryError.offline) { try await repos.research.lookupDOI("10.1/x") }183        #expect(try await repos.research.localReferences().count == 1)184        #expect(try await a.store.entityOpCount() == 0)185        a.setOffline(false)186        try await repos.research.delete(id: reference.id)187        #expect(try await repos.research.localReferences().isEmpty)188        await world.closeAll()189    }190191    @Test("read models: health, brief, zoom, living blocks and the journal are served from the cache with their date when offline")192    func readModels() async throws {193        let (world, a, repos) = try device()194        let fake = world.fake195        fake.stub("GET", path: "^/api/health/knowledge$", json: Recorded.text("knowledge", "health"))196        fake.stub("GET", path: "^/api/brief$", json: Recorded.text("knowledge", "brief"))197        fake.stub("GET", path: "^/api/pages/[^/]+/zoom$") { request in request.query["level"] == "1" ? .error(501, code: "not_implemented") : .json(Recorded.text("knowledge", "zoom-2")) }198        fake.stub("POST", path: "^/api/query$", json: Recorded.text("knowledge", "query-tasks"))199        fake.stub("GET", path: "^/api/events$", json: Recorded.text("timeline", "events-page"))200        fake.stub("GET", path: "^/api/timemachine$", json: Recorded.text("timeline", "timemachine-page-middle"))201        let page = UUID().uuidString.lowercased()202203        let health = try await repos.knowledge.health()204        let brief = try await repos.knowledge.brief()205        let zoom = try await repos.knowledge.zoom(pageId: page)206        let rows = try await repos.knowledge.query(LiveQuery(source: LiveQuerySource.tasks, limit: 10))207        #expect(fake.requests.last { $0.path == "/api/brief" }?.query.contains("tz=") == true, "the brief is asked in the device's time zone")208        #expect(zoom.value.level == 2 && !(zoom.value.sections ?? []).isEmpty)209        do { _ = try await repos.knowledge.zoom(pageId: page, level: 1); Issue.record("expected unsupported") } catch let error as RepositoryError {210            guard case .unsupported = error else { Issue.record("unexpected \(error)"); return }211        }212        let journal = try await repos.timeline.events(JournalQuery(limit: 4))213        #expect(journal.source == .network && !journal.events.isEmpty)214        let recordedEvent = try #require(Recorded.json("timeline", "events-page")["events"]?.arrayValue?.first)215        let eventPage = recordedEvent["pageId"]?.stringValue216        let snapshot = try await repos.timeline.timeMachine(pageId: page, at: Date(timeIntervalSince1970: 1_795_000_000), policy: .networkFirst)217        #expect(!snapshot.value.pages.isEmpty)218219        a.setOffline(true)220        let offlineHealth = try await repos.knowledge.health()221        #expect(offlineHealth.source == .cache && offlineHealth.value == health.value && !offlineHealth.isStale(maxAge: Staleness.health))222        #expect(try await repos.knowledge.brief().value == brief.value)223        #expect(try await repos.knowledge.zoom(pageId: page).value == zoom.value)224        #expect(try await repos.knowledge.query(LiveQuery(source: LiveQuerySource.tasks, limit: 10)).value == rows.value)225        await #expect(throws: RepositoryError.notCached) { try await repos.knowledge.query(LiveQuery(source: LiveQuerySource.pages)) }226        let offlineJournal = try await repos.timeline.events(JournalQuery(limit: 4))227        #expect(offlineJournal.source == .cache && offlineJournal.nextCursor == nil && offlineJournal.fetchedAt != nil)228        #expect(offlineJournal.events.map(\.id) == journal.events.map(\.id), "newest first, from the local events table")229        #expect(try await repos.timeline.events(JournalQuery(pageId: eventPage, kinds: ["nothing.*"])).events.isEmpty)230        #expect(try await repos.timeline.events(JournalQuery(pageId: eventPage)).events.allSatisfy { $0.pageId == eventPage })231        await #expect(throws: RepositoryError.notCached) { try await repos.timeline.events(JournalQuery(projectId: page)) }232        #expect(try await repos.timeline.timeMachine(pageId: page, at: Date(timeIntervalSince1970: 1_795_000_000)).source == .cache)233        await #expect(throws: RepositoryError.offline) { try await repos.timeline.restore(pageId: page, versionId: "1") }234        await #expect(throws: RepositoryError.offline) { try await repos.knowledge.summarizeBrief() }235        await world.closeAll()236    }237238    @Test("assistant: scope travels in the request, citations carry the block to scroll to, the action list has the 3.0 ids, the catalogue gives creator / route / logo")239    func assistant() async throws {240        let (world, _, repos) = try device()241        let fake = world.fake242        let meta = Recorded.text("ai-doc", "chat-page-meta").replacingOccurrences(of: "\n", with: " ")243        let done = Recorded.text("ai-doc", "chat-page-done").replacingOccurrences(of: "\n", with: " ")244        let bodies = Bodies()245        fake.stub("POST", path: "^/api/ai/chat$") { request in246            bodies.set(request.body)247            return FakeBackend.StubResponse(status: 200, body: Data("data: \(meta)\n\ndata: {\"type\":\"text\",\"delta\":\"La\"}\n\ndata: \(done)\n\ndata: [DONE]\n\n".utf8), headers: ["Content-Type": "text/event-stream"])248        }249        var citations: [AssistantCitation] = []250        var text = ""251        for try await event in try await repos.assistant.ask("Quelle est la pénalité ?", scope: AIChatScope.page, pageId: "2eea0ded-b5b8-4abe-b560-75345504be80") {252            if case .text(let delta) = event { text += delta }253            if case .done = event { citations = repos.assistant.citations(of: event) }254        }255        #expect(text == "La")256        #expect(citations.count == 1 && citations[0].n == 1 && citations[0].blockId == "XycxLnbyuq" && citations[0].anchor == AISourceAnchor.block)257        let sent = try JSONValue(data: bodies.last)258        #expect(sent["scope"]?.stringValue == "page" && sent["pageId"]?.stringValue == "2eea0ded-b5b8-4abe-b560-75345504be80" && sent["clientId"]?.stringValue?.isEmpty == false)259260        let actions = repos.assistant.actions()261        #expect(actions.filter(\.isNew).map(\.id) == ["coherence", "questions", "synthesis", "structure", "links"])262        #expect(actions.first { $0.id == "links" }?.returnsData == true && actions.count == AIActionKind.allCases.count + 5)263264        fake.stub("GET", path: "^/api/ai/models$", json: #"{"models":[\#(Recorded.text("ai-doc", "model-openrouter"))],"providers":\#(Recorded.text("ai-doc", "models-providers")),"creators":\#(Recorded.text("ai-doc", "models-creators-first-two")),"hiddenUnavailable":479}"#)265        let catalogue = try await repos.assistant.models(policy: .networkFirst)266        let model = try #require(catalogue.value.models.first)267        #expect(model.creator == "anthropic" && model.route == "openrouter" && model.logo == "/model-logos/anthropic.svg" && model.available == false)268        #expect(await repos.assistant.logoURL(model.logo ?? "")?.path == "/model-logos/anthropic.svg")269        #expect(try await repos.assistant.models().source == .cache, "cached for a day")270        await world.closeAll()271    }272273    private final class Bodies: @unchecked Sendable {274        private let lock = NSLock()275        private var data = Data()276        func set(_ value: Data) { lock.withLock { data = value } }277        var last: Data { lock.withLock { data } }278    }279280    @Test("audio: upload, request, poll until done; a server without the voice routes is .unsupported")281    func audio() async throws {282        let (world, a, repos) = try device()283        let fake = world.fake284        let page = fake.webCreatePage(title: "Réunion")285        let file = a.directory.appendingPathComponent("memo.m4a")286        try Data(repeating: 7, count: 2048).write(to: file)287        // No voice routes on this server (the fake answers its plain 404, a real one its HTML page).288        fake.stub(path: "^/api/audio/") { _ in FakeBackend.StubResponse(status: 404, body: Data("<html>not found</html>".utf8), headers: ["Content-Type": "text/html"]) }289        let id = try await repos.audio.upload(fileURL: file, pageId: page)290        #expect(fake.attachment(id)?.bytes.count == 2048)291        await #expect(throws: RepositoryError.unsupported(feature: "voice")) { try await repos.audio.transcribe(attachmentId: id) }292293        fake.clearStubs()294        let polls = Bodies()295        fake.stub("POST", path: "^/api/audio/[^/]+/transcribe$", json: Recorded.text("ai-doc", "audio-transcribe-queued"), status: 202)296        fake.stub("GET", path: "^/api/audio/[^/]+$") { _ in297            polls.set(polls.last + [1])298            return polls.last.count < 3 ? .json(Recorded.text("ai-doc", "audio-transcribe-queued")) : .json(Recorded.text("ai-doc", "audio-done"))299        }300        let queued = try await repos.audio.transcribe(attachmentId: id, summarize: true)301        #expect(queued.status == TranscriptionStatus.pending && queued.queued == true)302        let finished = try await repos.audio.waitForTranscription(attachmentId: id, interval: .milliseconds(5))303        #expect(finished.status == TranscriptionStatus.done && polls.last.count == 3)304        let attributes = repos.audio.nodeAttributes(from: finished)305        #expect(attributes.transcript.count == 2 && attributes.engine == "openai:whisper-1" && attributes.status == "done")306        #expect(finished.summary?.decisions?.isEmpty == false)307        a.setOffline(true)308        await #expect(throws: RepositoryError.offline) { try await repos.audio.status(attachmentId: id) }309        await world.closeAll()310    }311312    @Test("inbox: capture and triage online with undo; offline they throw; the list is cached")313    func inbox() async throws {314        let (world, a, repos) = try device()315        let fake = world.fake316        fake.stub("POST", path: "^/api/capture$", json: Recorded.text("inbox", "capture-note"), status: 201)317        fake.stub("GET", path: "^/api/inbox$", json: Recorded.text("inbox", "inbox-list"))318        fake.stub("POST", path: "^/api/inbox/undo$", json: Recorded.text("inbox", "undo"))319        fake.stub("POST", path: "^/api/inbox/[0-9a-f-]{36}$", json: Recorded.text("inbox", "triage-keep"))320        let captured = try await repos.inbox.capture(CaptureDraft(kind: CaptureKindName.note, text: "Idée"))321        #expect(fake.requests.last { $0.path == "/api/capture" }?.idempotencyKey != nil)322        let items = try await repos.inbox.items()323        #expect(!items.value.isEmpty)324        let triaged = try await repos.inbox.triage(id: captured.id, .keep(section: .notes))325        let action = try #require(triaged.actionId)326        #expect(try await repos.inbox.undo(actionId: action).ok)327        _ = try await repos.inbox.items()328        a.setOffline(true)329        #expect(try await repos.inbox.items().source == .cache)330        await #expect(throws: RepositoryError.offline) { try await repos.inbox.capture(CaptureDraft(kind: CaptureKindName.note, text: "x")) }331        await #expect(throws: RepositoryError.offline) { try await repos.inbox.triage(id: captured.id, .archive) }332        await world.closeAll()333    }334}335336@Suite("Repositories: additions made with SPNotesFeatures (2.0)")337struct RepositoryFeatureAdditionsTests {338    private func device(features: [String]? = nil) throws -> (World, Device, NotesRepositories) {339        let world = World(apiLevel: 3)340        let a = try world.device("A")341        return (world, a, NotesRepositories(store: a.store, api: a.api, engine: nil))342    }343344    static let projection = """345    {"model":"text-embedding-3-small","computedAt":"2026-11-19T12:00:00.000Z","cached":false,"explained":[0.4,0.2],346     "stats":{"pages":2,"embedded":2,"shown":2,"links":1,"truncated":false},347     "points":[{"id":"p1","title":"A","x":-0.5,"y":0.25,"cluster":0},{"id":"p2","title":"B","x":0.5,"y":-0.25,"cluster":0}],348     "clusters":[{"id":0,"x":0,"y":0,"r":0.6,"size":2,"label":"taux"}],349     "links":[{"id":"l1","source":"p1","target":"p2","kind":"link"}]}350    """351352    @Test("constellation: never asked unless /api/meta lists the feature; decoded and cached when it does")353    func constellation() async throws {354        let (world, _, repos) = try device()355        let fake = world.fake356        fake.stub("GET", path: "^/api/graph/constellation", json: Self.projection)357        // unknown features: no request at all358        await #expect(throws: RepositoryError.unsupported(feature: ServerFeature.constellation)) { _ = try await repos.graph.constellation() }359        // a server that does not list it: no request either360        _ = try await repos.context.refreshFeatures()361        await #expect(throws: RepositoryError.unsupported(feature: ServerFeature.constellation)) { _ = try await repos.graph.constellation() }362        #expect(fake.count("GET", "^/api/graph/constellation") == 0)363        // a server that lists it364        fake.stub("GET", path: "^/api/meta", json: #"{"api":3,"version":"3.0.0","features":["entities","graph-v2","constellation"]}"#)365        _ = try await repos.context.refreshFeatures()366        let online = try await repos.graph.constellation()367        #expect(online.source == .network)368        #expect(online.value.points.count == 2)369        #expect(online.value.clusters.first?.label == "taux")370        fake.setOffline(true)371        let cached = try await repos.graph.constellation()372        #expect(cached.source == .cache)373        #expect(cached.value == online.value)374    }375376    @Test("journal: the page title of the server travels with the event; offline it is read from the device's page")377    func eventPageTitles() async throws {378        let (world, a, repos) = try device()379        let fake = world.fake380        let pageId = try await a.create("Titre local")381        fake.stub("GET", path: "^/api/events", json: """382        {"events":[{"id":"e1","at":"2026-11-19T12:00:00.000Z","kind":"page.edited","pageId":"\(pageId)","pageTitle":"Titre du serveur","pageIcon":"📈",383                    "entityKind":null,"entityId":null,"actor":"user","device":"Mac","summary":"Modifiée","data":{}}],"nextCursor":null}384        """)385        let online = try await repos.timeline.events()386        #expect(online.events.first?.pageTitle == "Titre du serveur")387        #expect(online.events.first?.pageIcon == "📈")388        fake.setOffline(true)389        let offline = try await repos.timeline.events()390        #expect(offline.source == .cache)391        #expect(offline.events.first?.id == "e1")392        #expect(offline.events.first?.pageTitle == "Titre local")393    }394395    @Test("a stored AI message source keeps its citation number")396    func messageSourceNumber() throws {397        let source = try APIJSON.decoder().decode(AIMessageSource.self, from: Data(#"{"n":2,"chunkId":"c","pageId":"p","blockId":"b","title":"T","excerpt":"e","score":0.5}"#.utf8))398        #expect(source.n == 2)399        #expect(try APIJSON.decoder().decode(AIMessageSource.self, from: Data(#"{"pageId":"p"}"#.utf8)).n == nil)400    }401402    @Test("database rows from the server: inside each group the rows keep the server's order (the view's sorts), not the position order")403    func groupsKeepServerOrder() async throws {404        let (world, _, repos) = try device()405        let fake = world.fake406        let db = Recorded.json("databases", "db-get")407        let dbId = try #require(db["id"]?.stringValue)408        fake.stub("GET", path: "^/api/databases/[^/]+$", json: Recorded.text("databases", "db-get"))409        // the server's order, reversed from the recorded one: positions no longer agree with it410        var answer = Recorded.json("databases", "query-all")411        let recorded = answer["rows"]?.arrayValue ?? []412        try #require(recorded.count >= 2)413        let reversed = Array(recorded.reversed())414        guard case .object(var object) = answer else { Issue.record("unexpected fixture"); return }415        object["rows"] = .array(reversed)416        answer = .object(object)417        fake.stub("POST", path: "^/api/databases/[^/]+/query$", json: answer.canonicalString())418        _ = try await repos.databases.refresh(id: dbId)419        let result = try await repos.databases.rows(databaseId: dbId)   // the default view is a board grouped by a property420        #expect(result.source == .server)421        let serverOrder = reversed.compactMap { $0["id"]?.stringValue }422        #expect(result.rows.map(\.id) == serverOrder)423        let groups = try #require(result.groups, "the default view groups")424        #expect(groups.flatMap(\.rows).count == serverOrder.count)425        for group in groups {426            let indexes = group.rows.compactMap { serverOrder.firstIndex(of: $0.id) }427            #expect(indexes == indexes.sorted(), "group \(group.label)")428        }429        #expect(groups.contains { $0.rows.count >= 2 }, "at least one group has several rows, or the test proves nothing")430    }431}432
Files main
Menu

Theme