SPB Git

Repository Public

NextTests.swift 32.2 KB 339 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/AppTests/NextTests.swift3// Description: Hosted tests of SP Notes 2.0 on real components: tasks offline then synchronised (in-memory backend of SPNotesTestSupport), refused operations surfaced, inbox triage and undo, routes and deep links to a block, per-window state, backlinks, quick capture, command registry, Spotlight and due-date notifications (recorded, never sent to the system), search scopes, and offscreen screenshots of the new screens.4import XCTest5import SwiftUI6import SPNotesDocument7import SPNotesStore8import SPNotesAPI9import SPNotesSync10import SPNotesEditor11import SPNotesTestSupport12@testable import SPNotes1314final class RecordingSpotlight: SpotlightIndexing, @unchecked Sendable {15    private let lock = NSLock(); private var entries: [String: SpotlightEntry] = [:]16    var indexed: [String: SpotlightEntry] { lock.withLock { entries } }17    func index(_ new: [SpotlightEntry]) async { lock.withLock { for e in new { entries[e.id] = e } } }18    func remove(ids: [String]) async { lock.withLock { for id in ids { entries[id] = nil } } }19    func removeAll() async { lock.withLock { entries = [:] } }20}21final class RecordingReminders: ReminderScheduling, @unchecked Sendable {22    private let lock = NSLock(); private var list: [TaskReminder] = []23    var scheduled: [TaskReminder] { lock.withLock { list } }24    func authorized(requesting: Bool) async -> Bool { true }25    func replaceAll(_ reminders: [TaskReminder]) async { lock.withLock { list = reminders } }26}2728/// A second device on the same account: what the server holds, read through the real API client.29func web(_ fake: FakeBackend) -> NotesAPI { NotesAPI(client: HTTPClient(configuration: APIConfiguration(baseURL: fake.baseURL, userAgent: "web"), tokenStore: InMemoryTokenStore(token: fake.issueToken()), sessionConfiguration: FakeBackend.sessionConfiguration())) }3031@MainActor func fakeBench(offline: Bool = false, apiLevel: Int? = nil) async -> (Bench, FakeBackend) {32    let fake = FakeBackend(apiLevel: apiLevel)33    Bench.fake = (fake.baseURL, fake.issueToken(), FakeBackend.sessionConfiguration()); defer { Bench.fake = nil }34    let b = await Bench(server: true, offline: offline)35    return (b, fake)36}3738final class TasksAndInboxTests: XCTestCase {39    @MainActor func testTasksAreCreatedOfflineThenSynchronisedAndCompletedBothWays() async throws {40        let (b, fake) = await fakeBench(offline: true); defer { b.cleanup(); fake.shutdown() }41        XCTAssertEqual(b.env.account.phase, .signedIn)42        // one cycle online first, so that the server features (tasks with client ids) are known43        b.env.connectivity.forcedOffline = false; let first = await b.env.syncMonitor.run(); XCTAssertEqual(first, .completed)44        b.env.connectivity.forcedOffline = true; fake.setOffline(true)   // no route to the server at all45        // offline: the task exists at once on this Mac, with its due day and priority46        let id = try must(await b.env.tasks.add("Envoyer le chapitre 3", dueDay: "2026-11-21", priority: .high))47        _ = await b.env.tasks.add("Relire l'introduction")48        XCTAssertEqual(b.env.tasks.tasks.map(\.title), ["Envoyer le chapitre 3", "Relire l'introduction"], "sorted: due first"); XCTAssertEqual(b.env.tasks.openCount, 2)49        XCTAssertEqual(b.env.tasks.pendingIds.count, 2, "both wait in the outbox")50        await b.env.sync.refreshCounts(); try await Task.sleep(for: .milliseconds(700))   // the outbox tried by itself and found no network51        XCTAssertEqual(b.env.syncMonitor.summary, .offline(pending: b.env.syncMonitor.status.pending)); XCTAssertGreaterThanOrEqual(b.env.syncMonitor.status.pending, 2)52        let t = try must(b.env.tasks.tasks.first); XCTAssertEqual(t.priority, "high")53        XCTAssertEqual(TasksModel.bucket(t, now: ISO8601DateFormatter().date(from: "2026-11-19T15:00:00Z")!), .week)54        XCTAssertEqual(TasksModel.bucket(t, now: ISO8601DateFormatter().date(from: "2026-11-23T15:00:00Z")!), .overdue)55        // completed offline, still nothing on the server56        await b.env.tasks.setDone(t, true)57        XCTAssertNil(fake.taskTitle(id), "nothing reached the server")58        // network back: one cycle sends everything, the outbox is empty, the server has the same tasks under the same ids59        b.env.connectivity.forcedOffline = false; fake.setOffline(false)60        let outcome = await b.env.syncMonitor.run(); XCTAssertEqual(outcome, .completed)61        await b.env.tasks.load()62        XCTAssertTrue(b.env.tasks.pendingIds.isEmpty); XCTAssertTrue(b.env.tasks.rejected.isEmpty)63        let server = try await web(fake).tasks(includeDone: true)64        XCTAssertEqual(Set(server.map(\.title)), ["Envoyer le chapitre 3", "Relire l'introduction"]); XCTAssertEqual(server.first { $0.id == id }?.status, "done")65        // a task created and one completed on the web arrive on this Mac66        let web = fake.webCreateTask(title: "Du web", priority: "low"); fake.webUpdateTask(try must(server.first { $0.id != id }?.id), status: "done")67        _ = await b.env.syncMonitor.run(); b.env.tasks.filter = .all; await b.env.tasks.load()68        XCTAssertEqual(b.env.tasks.tasks.first { $0.id == web }?.title, "Du web"); XCTAssertEqual(b.env.tasks.tasks.filter { $0.status == "done" }.count, 2)69        XCTAssertEqual(b.env.tasks.openCount, 1)70        // the due-date notifications follow the open tasks (recorded: the notification centre is never called by tests)71        let later = try must(await b.env.tasks.add("Soutenance", dueDay: TaskLevel.dayString(Date().addingTimeInterval(3 * 86_400))))72        await b.env.platform.flushReminders()73        let scheduled = b.reminders.scheduled; XCTAssertEqual(scheduled.map(\.taskId), [later]); XCTAssertEqual(Calendar.current.component(.hour, from: try must(scheduled.first).fireDate), 9)74        await b.env.tasks.setDone(try must(b.env.tasks.tasks.first { $0.id == later }), true); await b.env.platform.flushReminders()75        let after = b.reminders.scheduled; XCTAssertTrue(after.isEmpty, "a completed task is no longer announced")76    }7778    @MainActor func testAnOperationTheServerRefusesIsKeptAndShownWithRetryAndDiscard() async throws {79        let (b, fake) = await fakeBench(); defer { b.cleanup(); fake.shutdown() }80        _ = await b.env.syncMonitor.run()81        fake.inject(.status(400, code: "bad_request"), method: "POST", path: "^/api/tasks", count: 50)82        _ = await b.env.tasks.add("Refusée par le serveur")83        _ = await b.env.syncMonitor.run(); await b.env.tasks.load()84        XCTAssertEqual(b.env.tasks.rejected.count, 1, "kept with its payload, not dropped"); XCTAssertEqual(b.env.syncMonitor.status.rejected, 1)85        XCTAssertEqual(b.env.syncMonitor.attention.map(\.kind), [.rejected]); XCTAssertTrue(b.env.syncMonitor.attention[0].title.contains("refusée"))86        XCTAssertEqual(b.env.syncMonitor.summary, .attention(1), "the sync status says something needs the owner")87        XCTAssertEqual(b.env.tasks.tasks.map(\.title), ["Refusée par le serveur"], "the task is still on this Mac")88        await b.env.tasks.discard(try must(b.env.tasks.rejected.first))89        XCTAssertTrue(b.env.tasks.rejected.isEmpty); await b.env.syncMonitor.refresh(); try await Task.sleep(for: .milliseconds(150))90        XCTAssertTrue(b.env.syncMonitor.attention.isEmpty)91    }9293    @MainActor func testAServerWithoutTaskSyncIsSaidPlainly() async throws {94        let (b, fake) = await fakeBench(apiLevel: 2); defer { b.cleanup(); fake.shutdown() }95        _ = await b.env.syncMonitor.run()96        let id = await b.env.tasks.add("Sur un serveur 2.x")97        if id == nil { XCTAssertTrue(b.env.tasks.unsupported); XCTAssertTrue(b.env.toasts.current?.isError ?? false) }   // refused before anything is queued98        else { XCTAssertFalse(b.env.tasks.unsupported) }                                                               // features not known yet: queued, the engine decides99    }100101    @MainActor func testInboxTriageFilesConvertsArchivesDeletesAndEachCanBeUndone() async throws {102        let (b, fake) = await fakeBench(offline: true); defer { b.cleanup(); fake.shutdown() }103        b.env.connectivity.forcedOffline = false; _ = await b.env.syncMonitor.run(); b.env.connectivity.forcedOffline = true; fake.setOffline(true)104        // captures land in the inbox (quick capture and the Services menu), offline105        let capture = QuickCapture(env: b.env)106        let a = try must(await capture.capture(text: "Idée de figure\nComparer 1 min et 5 min\nhttps://example.org/papier", source: "test"))107        let c = try must(await capture.capture(text: "Appeler le comité"))108        let d = try must(await capture.capture(text: "Lien à garder")), e = try must(await capture.capture(text: "Brouillon inutile"))109        await b.env.inbox.load()110        XCTAssertEqual(Set(b.env.inbox.items.map(\.id)), [a, c, d, e]); try await Task.sleep(for: .milliseconds(250)); XCTAssertEqual(b.env.library.counts.inbox, 4)111        let page = try must(try await b.env.store.page(id: a)); XCTAssertNotNil(page.inboxAt); XCTAssertEqual(page.title, "Idée de figure")112        let doc = try NoteDocument(json: page.content); XCTAssertTrue(doc.markdown().contains("[https://example.org/papier](https://example.org/papier)"), "a bare link is a real link"); XCTAssertTrue(doc.schemaViolations().isEmpty)113        // file → out of the inbox, in the chosen space114        let filed = await b.env.inbox.triage(a, .file(section: "research", parentId: nil)); XCTAssertTrue(filed)115        var p = try must(try await b.env.store.page(id: a)); XCTAssertNil(p.inboxAt); XCTAssertEqual(p.section, "research")116        XCTAssertEqual(b.env.toasts.current?.action?.title, "Annuler", "the toast offers the undo")117        let undone = await b.env.inbox.undo(); XCTAssertTrue(undone)118        p = try must(try await b.env.store.page(id: a)); XCTAssertEqual(p.inboxAt?.timeIntervalSince1970 ?? 0, page.inboxAt?.timeIntervalSince1970 ?? 1, accuracy: 0.002, "back with its capture date"); XCTAssertEqual(p.section, page.section)119        // convert to a task → a task linked to the page, through the task outbox120        _ = await b.env.inbox.triage(c, .task)121        var tasks = try await b.env.repositories.tasks.list(.open); XCTAssertEqual(tasks.map(\.title), ["Appeler le comité"]); XCTAssertEqual(tasks.first?.pageId, c)122        _ = await b.env.inbox.undo(); tasks = try await b.env.repositories.tasks.list(.open); XCTAssertTrue(tasks.isEmpty); let back = try must(try await b.env.store.page(id: c)); XCTAssertNotNil(back.inboxAt)123        _ = await b.env.inbox.triage(c, .task)124        // archive and delete125        _ = await b.env.inbox.triage(d, .archive); let archived = try must(try await b.env.store.page(id: d)); XCTAssertTrue(archived.archived); XCTAssertNil(archived.inboxAt)126        _ = await b.env.inbox.triage(e, .trash); let trashed = try must(try await b.env.store.page(id: e)); XCTAssertNotNil(trashed.deletedAt)127        _ = await b.env.inbox.undo(); let restored = try must(try await b.env.store.page(id: e)); XCTAssertNil(restored.deletedAt); XCTAssertNotNil(restored.inboxAt)128        await b.env.inbox.load(); XCTAssertEqual(Set(b.env.inbox.items.map(\.id)), [a, e])129        // network back: the captures, their triage and the task reach the server130        b.env.connectivity.forcedOffline = false; fake.setOffline(false); let outcome = await b.env.syncMonitor.run(); XCTAssertEqual(outcome, .completed)131        let serverTasks = try await web(fake).tasks(includeDone: true); XCTAssertEqual(serverTasks.map(\.title), ["Appeler le comité"])132        let serverPage = try await web(fake).page(id: d); XCTAssertTrue(serverPage.page.archived)133        XCTAssertEqual(b.env.syncMonitor.status.pending, 0)134    }135}136137final class ShellTests: XCTestCase {138    @MainActor func testDeepLinksCarryAPageAndABlockAndOldLinksStillWork() throws {139        let id = "6A006B40-D91B-4EB4-93CB-0E644363FEEB"140        XCTAssertEqual(DeepLink(URL(string: "spnotes://page/\(id)?block=p000000003")!), .page(Route(pageId: id.lowercased(), blockId: "p000000003")))141        XCTAssertEqual(DeepLink(URL(string: "spnotes://note/\(id)")!), .page(Route(pageId: id.lowercased())), "1.x link")142        XCTAssertEqual(DeepLink(URL(string: "spnotes://p/\(id)")!), .note(id.lowercased()), "1.x short form")143        XCTAssertEqual(DeepLink(URL(string: "spnotes://note/\(id)#abc_DEF-12")!), .page(Route(pageId: id, blockId: "abc_DEF-12")))144        XCTAssertEqual(DeepLink(URL(string: "spnotes://page/\(id)?block=%3Cscript%3E")!), .page(Route(pageId: id)), "a block id that is not one is ignored; the page still opens")145        XCTAssertEqual(DeepLink(URL(string: "spnotes://new?text=bonjour")!), .new(text: "bonjour"))146        XCTAssertEqual(DeepLink(URL(string: "spnotes://go/tasks")!), .destination(.tasks))147        XCTAssertNil(DeepLink(URL(string: "spnotes://page/not-a-uuid")!)); XCTAssertNil(DeepLink(URL(string: "spnotes://delete/\(id)")!)); XCTAssertNil(DeepLink(URL(string: "https://note.spboucher.ai/p/\(id)")!))148        XCTAssertEqual(DeepLink(Route(pageId: id, blockId: "p000000003").url), .page(Route(pageId: id, blockId: "p000000003")), "a route round-trips through its URL")149        for item in [SidebarItem.list(.favorites), .section("research"), .folder(id), .tag("thèse"), .unsynced] { XCTAssertEqual(SidebarItem(stored: item.stored), item) }150    }151152    @MainActor func testARouteOpensTheNoteAtItsBlockAndEachWindowKeepsItsOwnPlace() async throws {153        let b = await Bench(server: false); defer { b.cleanup() }154        let target = try must(await b.env.library.newNote(title: "Cible", content: try NoteDocument(json: Data(#"{"type":"doc","content":[{"type":"paragraph","attrs":{"id":"aaaaaaaaa1"},"content":[{"type":"text","text":"premier"}]},{"type":"heading","attrs":{"level":2,"id":"hhhhhhhhh2"},"content":[{"type":"text","text":"Section visée"}]},{"type":"paragraph","attrs":{"id":"aaaaaaaaa3"},"content":[{"type":"text","text":"suite"}]}]}"#.utf8))))155        let other = try must(await b.env.library.newNote(title: "Autre", tags: ["thèse"]))156        let w1 = WindowModel(env: b.env), w2 = WindowModel(env: b.env)157        await w1.library.start(); await w2.library.start()158        // per-window sidebar selection, search and destination (they were shared by every window in 1.x)159        w1.library.selection = .tag("thèse"); w1.library.query = "Autre"; w1.destination = .tasks160        try await Task.sleep(for: .milliseconds(350))161        XCTAssertEqual(w2.library.selection, .list(.all)); XCTAssertEqual(w2.library.query, ""); XCTAssertEqual(w2.destination, .notes)162        XCTAssertEqual(w1.library.notes.map(\.id), [other]); XCTAssertEqual(Set(w2.library.notes.map(\.id)), [target, other]); XCTAssertEqual(b.env.library.selection, .list(.all))163        // a route (deep link, task, search result, citation) brings the window back to the notes, on the block164        w1.openPage(id: target, blockId: "hhhhhhhhh2")165        XCTAssertEqual(w1.destination, .notes); XCTAssertEqual(w1.pendingBlock, "hhhhhhhhh2")166        try await Task.sleep(for: .milliseconds(500))167        let s = try must(w1.session); XCTAssertEqual(s.id, target); XCTAssertNil(w1.pendingBlock)168        let v = s.editor.textView169        XCTAssertEqual(v.selectedRange().location, (v.storage.string as NSString).range(of: "Section visée").location, "the caret is on the block")170        XCTAssertTrue(v.layer?.sublayers?.contains { $0.name == "sp.flash" } ?? false, "and the block is flashed")171        XCTAssertNil(w2.session, "the other window did not move")172        // a block that no longer exists: the note opens, and the owner is told173        w2.open(Route(pageId: target, blockId: "disparu000")); try await Task.sleep(for: .milliseconds(500))174        XCTAssertEqual(w2.session?.id, target); XCTAssertEqual(b.env.toasts.current?.text, "Ce bloc n'existe plus dans la note.")175        // the hosting layer lists only the screens that exist; the others are not shown anywhere176        let shown = Destination.features.filter { b.env.features.isAvailable($0, env: b.env) }177        XCTAssertEqual(shown, [.inbox, .tasks, .search])178        for d in shown { XCTAssertNotNil(b.env.features.screen(for: d, env: b.env, window: w1), "\(d)") }179        for d in [Destination.today, .databases, .graph, .timeline, .health, .canvas, .ask] { XCTAssertNil(b.env.features.screen(for: d, env: b.env, window: w1)); XCTAssertFalse(AppCommandCatalog.commands(env: b.env, window: w1).contains { $0.id == "go." + d.rawValue }) }180    }181182    @MainActor func testBacklinksAndOutgoingLinksAreReadLocally() async throws {183        let b = await Bench(server: false); defer { b.cleanup() }184        let hub = try must(await b.env.library.newNote(title: "Méthode"))185        let mention = #"{"type":"doc","content":[{"type":"paragraph","attrs":{"id":"zzzzzzzzz1"},"content":[{"type":"text","text":"rien ici"}]},{"type":"paragraph","attrs":{"id":"zzzzzzzzz2"},"content":[{"type":"text","text":"Voir "},{"type":"mention","attrs":{"id":"\#(hub)","label":"Méthode"}}]}]}"#186        let a = try must(await b.env.library.newNote(title: "Résultats", content: try NoteDocument(json: Data(mention.utf8))))187        let ref = #"{"type":"doc","content":[{"type":"blockRef","attrs":{"id":"rrrrrrrrr1","pageId":"\#(hub)","blockId":null,"mode":"embed"}}]}"#188        let c = try must(await b.env.library.newNote(title: "Synthèse", content: try NoteDocument(json: Data(ref.utf8))))189        _ = try must(await b.env.library.newNote(title: "Sans rapport"))190        let incoming = await NoteLinks.incoming(pageId: hub, env: b.env)191        XCTAssertEqual(Set(incoming.map(\.pageId)), [a, c]); XCTAssertEqual(incoming.first { $0.pageId == a }?.blockId, "zzzzzzzzz2", "the backlink lands on the block that mentions the page")192        let out = await NoteLinks.outgoing(of: try NoteDocument(json: Data(mention.utf8)), pageId: a, env: b.env)193        XCTAssertEqual(out.map(\.pageId), [hub]); XCTAssertEqual(out.first?.title, "Méthode")194        // a trashed note is no longer a backlink195        await b.env.library.trash([c]); let fewer = await NoteLinks.incoming(pageId: hub, env: b.env); XCTAssertEqual(fewer.map(\.pageId), [a])196        // the block reference card resolves from the local store, and says when the target is gone197        let found = await EditorLookup.resolve(pageId: a, blockId: "zzzzzzzzz2", env: b.env); XCTAssertEqual(found, .resolved(pageTitle: "Résultats", text: "Voir @Méthode"))198        let lost = await EditorLookup.resolve(pageId: a, blockId: "inconnu", env: b.env); XCTAssertEqual(lost, .missing)199        let gone = await EditorLookup.resolve(pageId: c, blockId: nil, env: b.env); XCTAssertEqual(gone, .missing, "a note in the trash is not a valid target")200        XCTAssertEqual(ReferencableBlock.list(try NoteDocument(json: Data(mention.utf8))).map(\.id), ["zzzzzzzzz1", "zzzzzzzzz2"])201    }202203    @MainActor func testTheCommandCenterHasOneRegistryForEverything() async throws {204        let b = await Bench(server: false); defer { b.cleanup() }205        let id = try must(await b.env.library.newNote(title: "Note")); let w = WindowModel(env: b.env); w.open(id); try await Task.sleep(for: .milliseconds(250))206        let all = AppCommandCatalog.commands(env: b.env, window: w)207        XCTAssertEqual(Set(all.map(\.id)).count, all.count, "ids are unique")208        for needed in ["go.tasks", "go.inbox", "go.search", "new", "quick", "f.h1", "f.callout.decision", "f.task", "i.mermaid", "i.chart", "i.runcode", "i.query", "i.pdf", "i.audio", "i.blockref", "i.citation", "i.bibliography", "i.canvas", "i.drawing", "i.toggle", "i.footnote", "sync", "settings", "export.markdown"] { XCTAssertTrue(all.contains { $0.id == needed }, needed) }209        // the one registry (SPNotesFeatures) holds them; its matcher ignores accents and case210        b.env.featureServices.registerWindowCommands(env: b.env, window: w)211        let registry = b.env.featureServices.registry212        XCTAssertEqual(Set(registry.commands.map(\.id)), Set(all.map(\.id)))213        XCTAssertEqual(registry.ranked("taches").first?.item.id, "go.tasks"); XCTAssertTrue(registry.ranked("diagramme mermaid").contains { $0.item.id == "i.mermaid" }); XCTAssertTrue(registry.ranked("zzzzqqq").isEmpty)214        b.env.featureServices.registerWindowCommands(env: b.env, window: w); XCTAssertEqual(registry.commands.count, all.count, "registering again replaces, never duplicates")215        // a command acts on the window it was built for216        all.first { $0.id == "go.tasks" }?.run(); XCTAssertEqual(w.destination, .tasks)217        XCTAssertFalse(AppCommandCatalog.commands(env: b.env, window: w).contains { $0.group == .format }, "no formatting command outside the editor")218        w.destination = .notes; AppCommandCatalog.commands(env: b.env, window: w).first { $0.id == "i.chart" }?.run(); XCTAssertEqual(w.session?.editor.document().lines.first { $0.type == "chart" }?.type, "chart")219        XCTAssertEqual(w.session?.editor.activeAtom?.node.type, "chart", "the new block opens its sheet")220        // the insert menu, the toolbar and the « / » menu come from the same list221        let insertions = EditorInsertions.all(window: w, env: b.env); XCTAssertEqual(Set(insertions.map(\.id)).count, insertions.count)222        let slash = Set(NoteTextView.builtinSlashItems().map(\.id)); for i in insertions where i.builtin { XCTAssertTrue(slash.contains(i.id), "\(i.id) is in the editor's own menu") }223        XCTAssertEqual(HotKeyShortcut.default.display, "⌃⌥⌘N"); XCTAssertTrue(HotKeyShortcut.default.isValid); XCTAssertFalse(HotKeyShortcut(keyCode: 0, carbonModifiers: 512, display: "⇧A").isValid, "a bare or shifted key is refused")224    }225226    @MainActor func testSpotlightFollowsTheLibraryAndIsEmptiedOnDemand() async throws {227        let b = await Bench(server: false); defer { b.cleanup() }228        let a = try must(await b.env.library.newNote(title: "Volatilité réalisée", tags: ["thèse"])), c = try must(await b.env.library.newNote(title: "Recette"))229        let s = await b.session(a); b.type(s, "Estimateur à noyau sur données à une minute."); await s.saveNow(reason: nil)230        try await Task.sleep(for: .milliseconds(300)); await b.env.platform.flushIndex()231        var indexed = b.spotlight.indexed232        XCTAssertEqual(Set(indexed.keys), [a, c]); XCTAssertEqual(indexed[a]?.title, "Volatilité réalisée"); XCTAssertEqual(indexed[a]?.tags, ["thèse"]); XCTAssertTrue(indexed[a]?.excerpt.contains("noyau") ?? false)233        XCTAssertEqual(indexed[a]?.item.attributeSet.contentURL, Route(pageId: a).url, "Spotlight links back to the note")234        await b.env.library.trash([c]); try await Task.sleep(for: .milliseconds(200)); await b.env.platform.flushIndex()235        indexed = b.spotlight.indexed; XCTAssertEqual(Set(indexed.keys), [a], "a note in the trash leaves the index")236        await b.env.library.purge([c]); await b.env.library.restore([c])237        // the setting: off empties the index and stops feeding it; on rebuilds it238        b.env.preferences.spotlightIndexing = false; await b.env.platform.clearIndex()239        _ = await b.env.library.newNote(title: "Pas indexée"); try await Task.sleep(for: .milliseconds(200)); await b.env.platform.flushIndex()240        indexed = b.spotlight.indexed; XCTAssertTrue(indexed.isEmpty)241        b.env.preferences.spotlightIndexing = true; await b.env.platform.reindexAll(); indexed = b.spotlight.indexed; XCTAssertEqual(indexed.count, 2)242        // sign-out with local erase leaves nothing behind243        await b.env.account.signOut(eraseLocal: true); indexed = b.spotlight.indexed; XCTAssertTrue(indexed.isEmpty)244    }245246    @MainActor func testRemindersArePlannedForOpenFutureTasksOnly() throws {247        func task(_ id: String, _ due: String?, status: String = "todo") throws -> TaskItem {248            try APIJSON.decoder().decode(TaskItem.self, from: Data(#"{"id":"\#(id)","title":"T \#(id)","status":"\#(status)","priority":"medium","createdAt":"2026-11-01T10:00:00.000Z","updatedAt":"2026-11-01T10:00:00.000Z"\#(due.map { #","dueAt":"\#($0)""# } ?? "")}"#.utf8))249        }250        let now = ISO8601DateFormatter().date(from: "2026-11-19T15:00:00Z")!251        let plan = TaskReminder.plan([try task("a", "2026-11-21T12:00:00.000Z"), try task("b", "2026-11-10T12:00:00.000Z"), try task("c", "2026-11-22T12:00:00.000Z", status: "done"), try task("d", nil), try task("e", "2026-11-20T18:30:00.000Z")], now: now)252        XCTAssertEqual(plan.map(\.taskId), ["e", "a"], "past, done and undated tasks are not announced")253        let day = Calendar.current.dateComponents([.year, .month, .day, .hour], from: plan[1].fireDate)254        XCTAssertEqual([day.year, day.month, day.day, day.hour], [2026, 11, 21, 9], "a bare day is announced at 9:00 that day, whatever the time zone")255        XCTAssertEqual(plan[0].fireDate, ISO8601DateFormatter().date(from: "2026-11-20T18:30:00Z"), "a task with a time is announced at that time")256        XCTAssertEqual(SearchModel.scope(signedIn: true, reachable: true, semantic: false), .serverLexical, "the paid semantic ranking is never the default")257        XCTAssertEqual(SearchModel.scope(signedIn: true, reachable: true, semantic: true), .hybrid); XCTAssertEqual(SearchModel.scope(signedIn: false, reachable: true, semantic: true), .localOnly); XCTAssertEqual(SearchModel.scope(signedIn: true, reachable: false, semantic: true), .localOnly)258    }259260    @MainActor func testQuickCaptureGoesToTheInboxANoteOrTheEndOfAChosenNote() async throws {261        let b = await Bench(server: false); defer { b.cleanup() }262        let m = QuickNoteModel(env: b.env); m.begin()263        // smart paste: a link goes on its own line, text is appended, a file becomes an attachment264        m.text = "Lecture du jour"; m.append("https://example.org/a"); m.append("à lire avant lundi")265        XCTAssertEqual(m.text, "Lecture du jour\nhttps://example.org/a\nà lire avant lundi")266        let file = b.dir.appendingPathComponent("données.csv"); try "a,b\n1,2\n".write(to: file, atomically: true, encoding: .utf8); m.files = [file]267        let id = try must(await m.save()); XCTAssertTrue(m.isEmpty); XCTAssertEqual(m.savedCount, 1, "the save pulse fires once")268        let page = try must(try await b.env.store.page(id: id)); XCTAssertNotNil(page.inboxAt, "the default target is the inbox"); XCTAssertEqual(page.title, "Lecture du jour")269        let doc = try NoteDocument(json: page.content); XCTAssertEqual(Array(doc.lines.map(\.type).prefix(3)), ["paragraph", "paragraph", "fileBlock"]); XCTAssertEqual(doc.attachmentReferences().count, 1)270        // the 1.x behaviour is one setting away271        b.env.preferences.quickNoteTarget = .notes; m.text = "Note ordinaire"; let plain = try must(await m.save()); let p2 = try must(try await b.env.store.page(id: plain)); XCTAssertNil(p2.inboxAt)272        // appended to a chosen note, as one undoable edit of that note273        m.appendTo = try must(try await b.env.store.summary(id: plain)); m.text = "ajout en fin de note"; let same = await m.save(); XCTAssertEqual(same, plain)274        let text = await b.text(plain); XCTAssertTrue(text.hasSuffix("ajout en fin de note")); XCTAssertEqual(m.lastSaved, "Ajouté à la note")275        // nothing empty is ever created276        m.appendTo = nil; m.text = "   \n "; let none = await m.save(); XCTAssertNil(none)277    }278}279280/// Offscreen pictures of the screens (never on screen, never key). Written to SPNOTES_SHOT_DIR when it is set.281final class ScreenshotTests: XCTestCase {282    @MainActor func testScreensRenderInBothAppearances() async throws {283        let (b, fake) = await fakeBench(); defer { b.cleanup(); fake.shutdown() }284        _ = await b.env.syncMonitor.run()285        let day = { (n: Int) in TaskLevel.dayString(Date().addingTimeInterval(Double(n) * 86_400)) }286        _ = await b.env.tasks.add("Envoyer le chapitre 3 au directeur", dueDay: day(0), priority: .high); _ = await b.env.tasks.add("Relire la revue de littérature", dueDay: day(2)); _ = await b.env.tasks.add("Mettre à jour le graphique de volatilité", dueDay: day(-1), priority: .high)287        _ = await b.env.tasks.add("Réserver la salle de soutenance", dueDay: day(12), priority: .low); _ = await b.env.tasks.add("Trier la bibliographie")288        let done = try must(await b.env.tasks.add("Installer SP Notes 2.0")); b.env.tasks.filter = .all; await b.env.tasks.load(); await b.env.tasks.setDone(try must(b.env.tasks.tasks.first { $0.id == done }), true)289        _ = await QuickCapture(env: b.env).capture(text: "Idée : comparer la volatilité réalisée à 1 min et à 5 min\nÀ creuser avec les données FirstRate, voir aussi le papier de 2018.")290        _ = await QuickCapture(env: b.env).capture(text: "Article à lire\nhttps://example.org/realized-kernels")291        _ = await QuickCapture(env: b.env).capture(text: "Appeler le comité pour la date de dépôt")292        await b.env.inbox.load()293        let w = WindowModel(env: b.env)294        for dark in [false, true] {295            let size = CGSize(width: 900, height: 640)296            func wrap<V: View>(_ v: V) -> some View { v.environment(b.env).environment(w).preferredColorScheme(dark ? .dark : .light) }297            XCTAssertGreaterThan(renderOffscreen(wrap(TasksScreen(model: b.env.tasks, router: w)), size: size, dark: dark, name: "tasks").distinctColors, 12)298            XCTAssertGreaterThan(renderOffscreen(wrap(InboxScreen(model: b.env.inbox, router: w)), size: size, dark: dark, name: "inbox").distinctColors, 12)299            XCTAssertGreaterThan(renderOffscreen(wrap(WelcomeView {}), size: size, dark: dark, name: "sign-in").distinctColors, 12)300            XCTAssertGreaterThan(renderOffscreen(wrap(SettingsView()), size: CGSize(width: 600, height: 620), dark: dark, name: "settings").distinctColors, 8)301            XCTAssertGreaterThan(renderOffscreen(wrap(StoreFailureView(error: .migrationFailed(from: 1, to: 2, reason: "disk full", backupURL: b.env.storeURL.appendingPathExtension("backup-v1")))), size: size, dark: dark, name: "store-failure").distinctColors, 8)302        }303    }304}305306/// Against the integration build of the 3.0 backend (Scripts/integration-test.sh --server → M4M64c:8486, scratch database; never production).307final class NextServerTests: XCTestCase {308    @MainActor func testTasksCreatedOfflineReachTheIntegrationServerAndComeBack() async throws {309        try XCTSkipUnless(Bench.serverURL != nil && Bench.token != nil, "needs the integration server (Scripts/integration-test.sh --server)")310        let b = await Bench(server: true); defer { b.cleanup() }311        let first = await b.env.syncMonitor.run(); XCTAssertEqual(first, .completed)312        let features = await b.env.repositories.features()313        XCTAssertEqual(features?.api, 3, "the integration server announces API 3"); XCTAssertTrue(features?.has(ServerFeature.tasksV2) ?? false)314        let marker = "macOS 2.0 \(UUID().uuidString.prefix(8))"315        // offline: a task and a capture converted to a task316        b.env.connectivity.forcedOffline = true317        let id = try must(await b.env.tasks.add("\(marker) tâche", dueDay: "2026-12-01", priority: .high))318        let capture = try must(await QuickCapture(env: b.env).capture(text: "\(marker) capture"))319        let converted = await b.env.inbox.triage(capture, .task); XCTAssertTrue(converted)320        // back online: everything reaches the server under the same ids321        b.env.connectivity.forcedOffline = false322        let outcome = await b.env.syncMonitor.run(); XCTAssertEqual(outcome, .completed)323        await b.env.tasks.load(); XCTAssertTrue(b.env.tasks.rejected.isEmpty, "\(b.env.tasks.rejected)")324        let other = b.otherDevice()325        let server = try await other.tasks(includeDone: true, pageId: nil).filter { $0.title.hasPrefix(marker) }326        XCTAssertEqual(Set(server.map(\.title)), ["\(marker) tâche", "\(marker) capture"]); XCTAssertEqual(server.first { $0.id == id }?.priority, "high")327        XCTAssertEqual(server.first { $0.id != id }?.pageId, capture, "the converted capture is linked to its page")328        let page = try await other.page(id: capture); XCTAssertEqual(page.page.title, "\(marker) capture")329        // completed on this Mac → done on the server; cleaned up afterwards330        await b.env.tasks.setDone(try must(b.env.tasks.tasks.first { $0.id == id }), true)331        _ = await b.env.syncMonitor.run()332        let done = try await other.tasks(includeDone: true, pageId: nil).first { $0.id == id }; XCTAssertEqual(done?.status, "done")333        b.env.tasks.filter = .all; await b.env.tasks.load()334        for t in b.env.tasks.tasks where t.title.hasPrefix(marker) { await b.env.tasks.delete(t) }335        await b.env.library.trash([capture]); _ = await b.env.syncMonitor.run()336        let left = try await other.tasks(includeDone: true, pageId: nil).filter { $0.title.hasPrefix(marker) }; XCTAssertTrue(left.isEmpty)337    }338}339
Files main
Menu

Theme