SPB Git

Repository Public

KnowledgeScreensTests.swift 18.3 KB 329 lines swift

1// SP Notes Core2// File: Tests/SPNotesFeaturesTests/KnowledgeScreensTests.swift3// Description: View models of the timeline, the time machine, knowledge health, the daily brief and the semantic zoom4//              against the fake backend: happy path, offline (cached copy with its date), server error, empty; restore5//              only after confirmation; AI summaries and synopses only on an explicit action.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import SPNotesAPI11import SPNotesStore12import SPNotesSync13import Testing14@testable import SPNotesFeatures15@testable import SPNotesFeaturesCatalog1617private let utc = TimeZone(identifier: "UTC")!1819@Suite("Knowledge: timeline")20@MainActor21struct KnowledgeTimelineTests {22    @Test("happy path: events grouped by day, newest first; paging appends without duplicates; machine and backfilled events are marked")23    func happy() async throws {24        let world = try await FeatureWorld()25        let router = FeatureRouterRecorder()26        let model = TimelineModel(repositories: world.repositories, router: router, timeZone: utc)27        await model.load()28        #expect(model.phase == .loaded)29        #expect(model.events.count == 8)30        #expect(model.canLoadMore)31        #expect(model.days.map(\.events.count) == [5, 3])32        #expect(model.days[0].events.first?.kind == EventKind.taskCompleted)33        #expect(model.dayTitle(model.days[0], now: FeatureSamples.now) == "Aujourd'hui")34        #expect(model.dayTitle(model.days[1], now: FeatureSamples.now) == "Hier")35        await model.loadMore()36        #expect(model.events.count == 12)37        #expect(!model.canLoadMore)38        #expect(model.days.count == 3)39        #expect(Set(model.events.map(\.id)).count == 12)40        #expect(model.events.filter(TimelineModel.isBackfilled).count == 2)41        #expect(model.events.filter(TimelineModel.isMachine).map(\.actor).sorted() == ["agent", "ai"])42        model.open(model.events[0])43        #expect(router.calls.count == 1)44    }4546    @Test("family filters are sent as families and can be cleared")47    func filters() async throws {48        let world = try await FeatureWorld()49        let model = TimelineModel(repositories: world.repositories, timeZone: utc)50        await model.toggle(family: "page")51        #expect(world.fake.requests.last { $0.path == "/api/events" }?.query.contains("page.") == true)52        #expect(!model.events.isEmpty && model.events.allSatisfy { $0.kind.hasPrefix("page.") })53        await model.toggle(family: "task")54        #expect(Set(model.events.map { $0.kind.split(separator: ".")[0] }) == ["page", "task"])55        await model.clearFamilies()56        #expect(model.families.isEmpty && model.events.count == 8)57    }5859    @Test("a page scope uses the recorded page journal and its cursor")60    func pageScope() async throws {61        let world = try await FeatureWorld()62        let model = TimelineModel(repositories: world.repositories, scope: .page(KnowledgeSamples.timePageId), timeZone: utc)63        await model.load()64        #expect(model.events.count == 3 && model.canLoadMore)65        await model.loadMore()66        #expect(model.events.count == 6)67    }6869    @Test("offline: the events already on the device with their date; load-more fails calmly; nothing cached → calm state")70    func offline() async throws {71        let world = try await FeatureWorld()72        let model = TimelineModel(repositories: world.repositories, timeZone: utc)73        await model.load()74        world.setOffline(true)75        let again = TimelineModel(repositories: world.repositories, timeZone: utc)76        await again.load()77        #expect(again.phase == .loaded)78        #expect(again.events.count == 8)79        #expect(again.freshness?.fromCache == true)80        #expect(!again.canLoadMore)81        await model.loadMore()82        #expect(model.actionFailure?.kind == .offline)83        #expect(model.events.count == 8)84        // Project scope cannot be evaluated offline.85        let project = TimelineModel(repositories: world.repositories, scope: .project(KnowledgeSamples.timeProjectId), timeZone: utc)86        await project.load()87        #expect(project.phase.failure?.kind == .notCached)88    }8990    @Test("server error and empty journal")91    func errorAndEmpty() async throws {92        let world = try await FeatureWorld(samples: false)93        let model = TimelineModel(repositories: world.repositories, timeZone: utc)94        world.fake.stub("GET", path: "^/api/events$", json: #"{"error":"Unknown kinds","code":"bad_kinds","kinds":["page.created"]}"#, status: 400)95        await model.load()96        #expect(model.phase.failure?.kind == .server)97        #expect(model.phase.failure?.code == "bad_kinds")98        world.fake.stub("GET", path: "^/api/events$", json: #"{"events":[],"nextCursor":null}"#)99        await model.load()100        #expect(model.phase == .loaded && model.events.isEmpty && model.days.isEmpty)101    }102}103104@Suite("Knowledge: time machine")105@MainActor106struct KnowledgeTimeMachineTests {107    @Test("honesty follows source / exact literally")108    func honesty() throws {109        func page(_ name: String) throws -> TimeMachinePage {110            try #require(try APIJSON.decoder().decode(TimeMachineSnapshot.self, from: Data(FeatureSamples.text("timeline", name).utf8)).pages.first)111        }112        let middle = try page("timemachine-page-middle"), now = try page("timemachine-page-now"), before = try page("timemachine-page-before")113        #expect(TimeMachineHonesty.level(middle) == .approximate)114        #expect(TimeMachineHonesty.text(middle).hasPrefix("Approximatif"))115        #expect(TimeMachineHonesty.level(now) == .exact)116        #expect(TimeMachineHonesty.level(before) == .absent)117        #expect(TimeMachineModel.canRestore(middle))118        #expect(!TimeMachineModel.canRestore(now))119        #expect(!TimeMachineModel.canRestore(before))120        var after = middle121        after.source = TimeMachineSource.versionAfter122        #expect(TimeMachineHonesty.level(after) == .approximate)123        #expect(TimeMachineHonesty.text(after).contains("après"))124        after.source = TimeMachineSource.none125        #expect(TimeMachineHonesty.level(after) == .unknown)126        #expect(TimeMachineModel.previewText(middle) == "Première version du texte.")127    }128129    @Test("happy path: the state at a date; restore needs a confirmation and passes the current version")130    func restore() async throws {131        let world = try await FeatureWorld()132        let model = TimeMachineModel(repositories: world.repositories, scope: .page(KnowledgeSamples.timePageId), date: KnowledgeSamples.timeMachineDate, now: { FeatureSamples.now.addingTimeInterval(86_400) })133        await model.load()134        #expect(model.phase == .loaded)135        let page = try #require(model.snapshot?.pages.first)136        #expect(model.snapshot?.relations.count == 2)137        model.requestRestore(page)138        #expect(model.pendingRestore?.id == page.id)139        #expect(world.fake.count("POST", "restore$") == 0)             // nothing before the confirmation140        model.cancelRestore()141        #expect(model.pendingRestore == nil)142        #expect(await model.confirmRestore() == false)143        model.requestRestore(page)144        #expect(await model.confirmRestore())145        #expect(world.fake.count("POST", "^/api/pages/\(page.id)/versions/\(page.versionId!)/restore$") == 1)146        #expect(model.lastRestore?.version == 4)147        #expect(model.pendingRestore == nil)148        // A conflict is explained as "changed elsewhere".149        world.fake.stub("POST", path: "restore$", json: FeatureSamples.text("timeline", "restore-conflict"), status: 409)150        model.requestRestore(page)151        #expect(await model.confirmRestore() == false)152        #expect(model.actionFailure?.kind == .stale)153    }154155    @Test("the scrubber maps fractions to dates inside the range")156    func scrubber() async throws {157        let world = try await FeatureWorld()158        let now = FeatureSamples.now159        let model = TimeMachineModel(repositories: world.repositories, scope: .project(KnowledgeSamples.timeProjectId), now: { now })160        #expect(model.fraction == 1)161        model.scrub(to: 0)162        #expect(model.date == now.addingTimeInterval(-90 * 86_400))163        model.scrub(to: 0.5)164        #expect(abs(model.fraction - 0.5) < 1e-9)165        model.scrub(to: 7)166        #expect(model.date == now)167        await model.setDate(now.addingTimeInterval(86_400 * 30))168        #expect(model.date == now)                                     // clamped to the range169        #expect(model.phase == .loaded)170        #expect(world.fake.requests.last { $0.path == "/api/timemachine" }?.query.contains("projectId=") == true)171    }172173    @Test("offline: a state already fetched comes from the cache; restore fails calmly; never fetched → not cached; workspace scope is refused")174    func offline() async throws {175        let world = try await FeatureWorld()176        let model = TimeMachineModel(repositories: world.repositories, scope: .page(KnowledgeSamples.timePageId), date: KnowledgeSamples.timeMachineDate)177        await model.load()178        world.setOffline(true)179        await model.load()180        #expect(model.phase == .loaded && model.snapshot != nil)181        model.requestRestore(try #require(model.snapshot?.pages.first))182        #expect(await model.confirmRestore() == false)183        #expect(model.actionFailure?.kind == .offline)184        await model.setDate(KnowledgeSamples.timeMachineDate.addingTimeInterval(-3600))185        #expect(model.phase.failure?.isOffline == true)186        let none = TimeMachineModel(repositories: world.repositories, scope: .workspace)187        await none.load()188        #expect(none.phase.failure != nil)189    }190191    @Test("server error")192    func serverError() async throws {193        let world = try await FeatureWorld(samples: false)194        world.fake.stub("GET", path: "^/api/timemachine$", json: #"{"error":"Not found","code":"not_found"}"#, status: 404)195        let model = TimeMachineModel(repositories: world.repositories, scope: .page(KnowledgeSamples.timePageId))196        await model.load()197        #expect(model.phase.failure?.kind == .notFound)198    }199}200201@Suite("Knowledge: health, brief, zoom")202@MainActor203struct KnowledgeReadModelTests {204    @Test("health: every section of the server's answer; items open their page at the block")205    func health() async throws {206        let world = try await FeatureWorld()207        let router = FeatureRouterRecorder()208        let model = KnowledgeHealthModel(repositories: world.repositories, router: router)209        await model.load()210        let health = try #require(model.health)211        #expect(model.phase == .loaded && !model.isHealthy)212        #expect(health.orphans.count == 5 && health.brokenLinks.count == 1 && health.missingReferences.count == 1 && health.potentialDuplicates.count == 2 && health.untitled.count == 1)213        #expect(model.ratio == 0)                                      // 11 issues for 9 pages: never negative214        let link = try #require(health.brokenLinks.items.first)215        model.open(pageId: link.pageId, blockId: link.blockId)216        #expect(router.calls == [.page(id: link.pageId, blockId: "o-uzSudOv_")])217        #expect(KnowledgeHealthModel.brokenLinkReason(link) == "La cible n'existe plus")218        world.setOffline(true)219        await model.load()220        #expect(model.phase == .loaded && model.freshness?.fromCache == true)221    }222223    @Test("health: offline with nothing cached, server error, healthy workspace")224    func healthFailures() async throws {225        let world = try await FeatureWorld(samples: false)226        let model = KnowledgeHealthModel(repositories: world.repositories)227        world.setOffline(true)228        await model.load()229        #expect(model.phase.failure?.kind == .notCached)230        world.setOffline(false)231        world.fake.stub("GET", path: "^/api/health/knowledge$", json: #"{"error":"boom","code":"internal"}"#, status: 500)232        await model.load()233        #expect(model.phase.failure?.kind == .server)234        let empty = #"{"count":0,"ids":[],"items":[]}"#235        world.fake.stub("GET", path: "^/api/health/knowledge$", json: #"{"computedAt":null,"inactiveDays":30,"score":{"pages":0,"issues":0},"orphans":\#(empty),"brokenLinks":\#(empty),"missingReferences":\#(empty),"potentialDuplicates":\#(empty),"untitled":\#(empty),"inactiveProjects":\#(empty),"openTasks":{"count":0,"overdue":0,"withoutDate":0,"ids":[],"items":[]}}"#)236        await model.load()237        #expect(model.phase == .loaded && model.isHealthy && model.ratio == 1)238    }239240    @Test("brief: the sections of the day; the AI summary is asked only by requestSummary()")241    func brief() async throws {242        let world = try await FeatureWorld()243        let router = FeatureRouterRecorder()244        let model = DailyBriefModel(repositories: world.repositories, router: router, timeZone: TimeZone(identifier: "America/Toronto")!)245        await model.load()246        let brief = try #require(model.brief)247        #expect(model.phase == .loaded && !model.isEmpty)248        #expect(brief.recentNotes.count == 7 && brief.activeProjects.count == 1 && model.taskCount == 2 && brief.unfiledCaptures.count == 1)249        #expect(model.summary == nil)250        #expect(world.fake.count("POST", "^/api/brief/summary$") == 0)251        #expect(world.fake.requests.last { $0.path == "/api/brief" }?.query.contains("America") == true)252        #expect(model.dayTitle.contains("19") && model.dayTitle.contains("novembre"))253        #expect(DailyBriefModel.due(brief.tasks.overdue[0])?.contains("15") == true)      // noon UTC = that calendar day254        model.open(task: brief.tasks.dueSoon[0])255        model.open(note: brief.recentNotes[0])256        #expect(router.calls == [.page(id: "730ee617-c8e0-4f8f-ad41-946976578691", blockId: "2nqTS3bPts"), .database(id: brief.recentNotes[0].id)])257        #expect(await model.requestSummary())258        #expect(model.summary?.ai == true && model.summary?.model == "exemple-catalogue")259        #expect(world.fake.count("POST", "^/api/brief/summary$") == 1)260        world.setOffline(true)261        await model.load()262        #expect(model.phase == .loaded && model.freshness?.fromCache == true)263        #expect(await model.requestSummary() == false)264        #expect(model.actionFailure?.kind == .offline)265        #expect(model.summary != nil)                                  // the summary on screen is kept266    }267268    @Test("brief: a stored summary is shown as AI; link suggestions and pages to revisit are decoded; errors; empty")269    func briefVariants() async throws {270        let world = try await FeatureWorld(samples: false)271        let model = DailyBriefModel(repositories: world.repositories)272        world.fake.stub("GET", path: "^/api/brief$", json: #"{"error":"Unknown time zone","code":"bad_request"}"#, status: 400)273        await model.load()274        #expect(model.phase.failure?.kind == .server)275        world.fake.stub("GET", path: "^/api/brief$", json: #"{"generatedAt":null,"date":"2026-11-19","timeZone":"UTC","recentNotes":[],"activeProjects":[],"tasks":{"overdue":[],"dueToday":[],"dueSoon":[]},"unfiledCaptures":{"count":0,"items":[]},"linkSuggestions":{"count":0,"items":[]},"toRevisit":[],"aiSummary":null}"#)276        await model.load()277        #expect(model.phase == .loaded && model.isEmpty)278        world.fake.stub("GET", path: "^/api/brief$", json: #"{"generatedAt":null,"date":"2026-11-19","timeZone":"UTC","recentNotes":[],"activeProjects":[],"tasks":{"overdue":[],"dueToday":[],"dueSoon":[]},"unfiledCaptures":{"count":0,"items":[]},"linkSuggestions":{"count":1,"items":[{"id":"e1","fromId":"a","toId":"b","fromTitle":"A","toTitle":"B","rationale":"Proches","ai":true}]},"toRevisit":[{"id":"p1","title":"Ancienne","icon":null}],"aiSummary":{"ai":true,"text":"Texte","model":"m","at":"2026-11-19T10:00:00.000Z"}}"#)279        await model.load()280        #expect(model.linkSuggestions.first?.rationale == "Proches")281        #expect(model.toRevisit.first?.title == "Ancienne")282        #expect(model.summary?.text == "Texte" && !model.isEmpty)283    }284285    @Test("zoom: the outline opens sections at their block; the synopsis is read from the cache only, generated on request")286    func zoom() async throws {287        let world = try await FeatureWorld()288        let router = FeatureRouterRecorder()289        let model = SemanticZoomModel(repositories: world.repositories, router: router, pageId: KnowledgeSamples.zoomPageId)290        await model.load()291        #expect(model.phase == .loaded && model.sections.count == 3)292        model.open(model.sections[1])293        #expect(router.calls == [.page(id: KnowledgeSamples.zoomPageId, blockId: "_spXf0Aair")])294        await model.setLevel(.synopsis)295        #expect(model.synopsisPhase == .loaded && !model.hasSynopsis)296        #expect(model.synopsis?.status == SynopsisStatus.missing)297        let asked = world.fake.requests.filter { $0.path.hasSuffix("/zoom/ai") }298        #expect(asked.count == 1 && asked[0].query.contains("cachedOnly=1"))          // nothing spent by looking299        #expect(await model.generateSynopsis())300        #expect(model.hasSynopsis && model.synopsis?.ai == true)301        #expect(world.fake.requests.filter { $0.path.hasSuffix("/zoom/ai") && !$0.query.contains("cachedOnly=1") }.count == 1)302        await model.setLevel(.full)303        #expect(model.phase == .loaded)304        world.setOffline(true)305        await model.setLevel(.outline)306        #expect(model.phase == .loaded && model.freshness?.fromCache == true)307        await model.setLevel(.synopsis)308        #expect(model.hasSynopsis)                                                     // the cached synopsis, still marked AI309    }310311    @Test("zoom: offline never fetched, generation offline, unknown page, empty outline")312    func zoomFailures() async throws {313        let world = try await FeatureWorld()314        world.setOffline(true)315        let model = SemanticZoomModel(repositories: world.repositories, pageId: KnowledgeSamples.zoomPageId, level: .synopsis)316        await model.load()317        #expect(model.phase.failure?.isOffline == true)318        #expect(await model.generateSynopsis() == false)319        #expect(model.actionFailure?.kind == .offline)320        world.setOffline(false)321        world.fake.stub("GET", path: "^/api/pages/[^/]+/zoom$", json: #"{"error":"Not found","code":"not_found"}"#, status: 404)322        await model.setLevel(.outline)323        #expect(model.phase.failure?.kind == .notFound)324        world.fake.stub("GET", path: "^/api/pages/[^/]+/zoom$", json: FeatureSamples.text("knowledge", "zoom-2-empty"))325        await model.load()326        #expect(model.phase == .loaded && model.sections.isEmpty)327    }328}329
Files main
Menu

Theme