Repository Public
1// SP Notes iOS2// File: Tests/ShellStateTests.swift3// Description: The 2.0 shell as logic: tabs with their own stacks, adaptation between tabs and columns (the place, the note and4// its block survive both ways), state restoration, routes applied to a window, the reachability of every 1.05// screen, the hosted sections (nothing shown until a screen is registered and the server offers it), the command6// palette (matching, ranking, keyboard selection, execution), the typed page kind and assistant sources by block.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import SwiftUI12import Testing13import SPNotesCore14@testable import SPNotes1516@MainActor17private func makeShell(_ registry: HostedSectionRegistry = HostedSectionRegistry()) -> ShellState { ShellState(sections: registry) }1819@MainActor20private func fakeSection(_ id: String = "graph", feature: String? = nil, layout: HostedSectionLayout = .wide, order: Int = 100) -> HostedSectionEntry {21 HostedSectionEntry(id: id, title: "Graphe \(id)", symbol: "point.3.connected.trianglepath.dotted", requiredFeature: feature, layout: layout, order: order) { _ in Text("section \(id)") }22}2324@Suite("Onglets et colonnes")25@MainActor26struct ShellAdaptationTests {27 @Test func eachTabKeepsItsOwnStack() {28 let shell = makeShell()29 #expect(shell.tab == .today && shell.path.isEmpty)30 shell.open(note: "a")31 #expect(shell.paths[.today] == [.note("a", isNew: false)])32 shell.tab = .notes33 #expect(shell.path == [.list(.smart(.all))], "Notes opens on the list of all notes, the library one step back")34 shell.open(source: .folder("f"))35 shell.tab = .more36 shell.path = [.tasks]37 // going back to a tab finds its stack where it was38 shell.tab = .today39 #expect(shell.path == [.note("a", isNew: false)])40 shell.tab = .notes41 #expect(shell.path == [.list(.smart(.all)), .list(.folder("f"))])42 shell.tab = .more43 #expect(shell.path == [.tasks])44 }4546 @Test func theSameNoteIsNotPushedTwice() {47 let shell = makeShell()48 shell.open(note: "a")49 shell.open(note: "a", blockId: "k1")50 #expect(shell.path == [.note("a", isNew: false)])51 #expect(shell.reveal(for: "a")?.blockId == "k1")52 let first = shell.reveal(for: "a")53 shell.open(note: "a", blockId: "k1")54 #expect(shell.reveal(for: "a") != first, "asking for the same block again is a new request")55 }5657 @Test func everyPlaceSurvivesCompactToRegularAndBack() {58 let places: [SidebarItem] = [.today, .tasks, .inbox, .search, .source(.smart(.all)), .source(.smart(.trash)), .source(.section("research")),59 .source(.folder("f")), .source(.tag("idée")), .hosted("graph")]60 for place in places {61 let shell = makeShell()62 shell.go(to: place)63 shell.open(note: "n", blockId: "k1")64 #expect(shell.location == place, "\(place) in tabs")65 #expect(shell.currentNote == "n")6667 shell.adapt(toCompact: false) // Split View widened, Stage Manager resize68 #expect(!shell.isCompact)69 #expect(shell.sidebar == place, "\(place) in columns")70 #expect(shell.selectedNote == "n")71 #expect(shell.reveal(for: "n")?.blockId == "k1", "the block to show survives the adaptation")7273 shell.adapt(toCompact: true) // Slide Over74 #expect(shell.location == place, "\(place) back in tabs")75 #expect(shell.currentNote == "n")76 #expect(shell.path.last == .note("n", isNew: false))77 #expect(shell.reveal(for: "n")?.blockId == "k1")78 // and once more without a note79 shell.close(note: "n")80 shell.adapt(toCompact: false)81 #expect(shell.sidebar == place && shell.selectedNote == nil)82 }83 }8485 @Test func thePlacesMapToTheExpectedTabs() {86 #expect(ShellState.compactPlace(for: .today).0 == .today)87 #expect(ShellState.compactPlace(for: .source(.smart(.favorites))).0 == .notes)88 #expect(ShellState.compactPlace(for: .search).0 == .search)89 #expect(ShellState.compactPlace(for: .tasks) == (.more, [.tasks]))90 #expect(ShellState.compactPlace(for: .inbox) == (.more, [.inbox]))91 #expect(ShellState.compactPlace(for: .hosted("graph")) == (.more, [.hosted("graph")]))92 #expect(ShellState.place(tab: .more, path: []) == nil, "the « Plus » list is not a place of the sidebar")93 #expect(ShellState.place(tab: .more, path: [.folders, .list(.folder("f")), .note("n", isNew: false)]) == .source(.folder("f")))94 }9596 @Test func aFreshWindowStartsAtTheDefaultPlaceOfItsLayout() {97 let phone = makeShell()98 #expect(phone.isCompact && phone.tab == .today)99 let pad = makeShell()100 pad.adapt(toCompact: false) // the first size class reading of an iPad window101 #expect(pad.sidebar == .source(.smart(.all)), "the iPad keeps its 1.0 landing list")102 #expect(pad.selectedNote == nil)103 }104105 @Test func leavingThePlusListForColumnsKeepsTheSidebarSelection() {106 let shell = makeShell()107 shell.tab = .more108 shell.adapt(toCompact: false)109 #expect(shell.sidebar == .source(.smart(.all)))110 }111112 @Test func aWindowIsRestoredInEitherLayout() {113 for key in ["today", "tasks", "inbox", "search", "smart:trash", "folder:f1", "tag:x", "hosted:graph"] {114 let place = SidebarItem(storageKey: key)115 #expect(place?.storageKey == key, "\(key) round-trips through @SceneStorage")116 let phone = makeShell()117 phone.restore(location: place, note: "n")118 #expect(phone.location == place && phone.currentNote == "n")119 let pad = makeShell()120 pad.adapt(toCompact: false)121 pad.restore(location: place, note: "n")122 #expect(pad.sidebar == place && pad.selectedNote == "n")123 // restored state then adapts like any other124 pad.adapt(toCompact: true)125 #expect(pad.location == place && pad.currentNote == "n")126 }127 // the keys written by 1.0 still restore128 #expect(SidebarItem(storageKey: "smart:all") == .source(.smart(.all)))129 #expect(SidebarItem(storageKey: "section:projects") == .source(.section("projects")))130 #expect(SidebarItem(storageKey: "hosted:") == nil)131 #expect(SidebarItem(storageKey: "nope") == nil)132 }133134 @Test func routesMoveAWindowToTheirDestination() {135 let registry = HostedSectionRegistry()136 registry.register(fakeSection("timeline"))137 let shell = makeShell(registry)138 shell.isPaletteOpen = true139 shell.sheet = .settings140 #expect(!ShellRouting.apply(.tasks, to: shell))141 #expect(shell.location == .tasks && shell.sheet == nil && !shell.isPaletteOpen, "a route closes what covers the window")142 ShellRouting.apply(.inbox, to: shell); #expect(shell.location == .inbox)143 ShellRouting.apply(.today, to: shell); #expect(shell.location == .today)144 ShellRouting.apply(.search("budget"), to: shell); #expect(shell.tab == .search && shell.searchQuery == "budget")145 ShellRouting.apply(.note("n", blockId: "k1"), to: shell)146 #expect(shell.currentNote == "n" && shell.reveal(for: "n")?.blockId == "k1")147 ShellRouting.apply(.section("timeline"), to: shell); #expect(shell.location == .hosted("timeline"))148 ShellRouting.apply(.today, to: shell)149 ShellRouting.apply(.section("unknown"), to: shell)150 #expect(shell.location == .today, "a section that does not exist is not navigated to")151 #expect(ShellRouting.apply(.newNote, to: shell), "the caller creates the note")152 #expect(shell.captureRequest == nil)153 ShellRouting.apply(.capture(kind: "audio"), to: shell)154 #expect(shell.captureRequest?.kind == "audio")155 let first = shell.captureRequest156 ShellRouting.apply(.capture(kind: "audio"), to: shell)157 #expect(shell.captureRequest != first, "two captures in a row are two requests")158 // the same routes in columns159 shell.adapt(toCompact: false)160 ShellRouting.apply(.tasks, to: shell); #expect(shell.sidebar == .tasks)161 ShellRouting.apply(.note("m", blockId: "b2"), to: shell); #expect(shell.selectedNote == "m" && shell.sidebar == .tasks)162 }163164 @Test func aNoteWindowOnlyTakesNotes() {165 let shell = makeShell()166 shell.tab = .notes167 shell.paths = [.notes: []]168 ShellRouting.handleInNoteWindow(.tasks, shell: shell)169 #expect(shell.path.isEmpty)170 shell.rootNote = "root"171 ShellRouting.handleInNoteWindow(.note("n", blockId: "k"), shell: shell)172 #expect(shell.path == [.note("n", isNew: false)] && shell.reveal(for: "n")?.blockId == "k")173 // its own note: back to the root of the window, at the block asked for — never a second copy of the editor174 ShellRouting.handleInNoteWindow(.note("root", blockId: "b9"), shell: shell)175 #expect(shell.path.isEmpty && shell.reveal(for: "root")?.blockId == "b9")176 }177}178179@Suite("Écrans de la 1.0 toujours accessibles")180@MainActor181struct ShellReachabilityTests {182 /// Everything a 1.0 iPhone user could reach from the home screen, and where it is now.183 @Test func every10ScreenIsOneOrTwoTapsFromATab() {184 let library = ShellEntries.library.flatMap { $0 }185 let more = ShellEntries.more(sections: HostedSectionRegistry()).flatMap { $0 }186 func pushes(_ entries: [ShellEntry]) -> [Destination] { entries.compactMap { if case .push(let destination) = $0.target { return destination } else { return nil } } }187 func sheets(_ entries: [ShellEntry]) -> [String] { entries.compactMap { if case .sheet(let name) = $0.target { return name } else { return nil } } }188189 // 1.0 home entries → « Notes » and « Plus »190 for required: Destination in [.list(.smart(.all)), .list(.smart(.favorites)), .folders, .tags] { #expect(pushes(library).contains(required), "\(required) in Notes") }191 for section in NoteSection.editable { #expect(pushes(library).contains(.list(.section(section))), "section \(section) in Notes") }192 for required: Destination in [.inbox, .folders, .tags, .list(.smart(.archived)), .list(.smart(.trash)), .tasks] { #expect(pushes(more).contains(required), "\(required) in Plus") }193 // settings and sync details (1.0: the gear and the sync indicator of the home screen — both still there on « Aujourd’hui »)194 #expect(Set(sheets(more)) == ["settings", "sync"])195 #expect(more.contains { $0.target == .palette })196 // the tabs themselves: home content, search197 #expect(ShellTab.destinations == [.today, .notes, .search, .more])198 #expect(ShellTab.allCases.map(\.title) == ["Aujourd’hui", "Notes", "Capture", "Recherche", "Plus"])199 // identifiers are unique (UI tests and VoiceOver rotor)200 let ids = (library + more).map(\.id)201 #expect(Set(ids).count == ids.count)202 }203204 @Test func everyDestinationHasAPlaceInBothLayouts() {205 // each list of 1.0 can be shown in columns (sidebar) and in tabs206 for list in SmartList.allCases {207 let shell = makeShell()208 shell.go(to: .source(.smart(list)))209 #expect(shell.path.last == .list(.smart(list)))210 shell.adapt(toCompact: false)211 #expect(shell.sidebar == .source(.smart(list)))212 }213 }214}215216@Suite("Sections hébergées")217@MainActor218struct HostedSectionTests {219 @Test func anEmptyRegistryShowsNothingAnywhere() {220 let registry = HostedSectionRegistry()221 #expect(registry.available.isEmpty)222 // sidebar model223 #expect(CommandRegistry.hostedPlaces(sections: registry).isEmpty)224 // « Plus »225 let more = ShellEntries.more(sections: registry).flatMap { $0 }226 #expect(!more.contains { if case .push(.hosted) = $0.target { return true } else { return false } })227 #expect(!more.contains { $0.id.hasPrefix("more-hosted") })228 // palette and ⌘1…9229 let commands = CommandRegistry.commands(sections: registry)230 #expect(!commands.contains { if case .go(.hosted) = $0.action { return true } else { return false } })231 #expect(!CommandRegistry.numberedPlaces(sections: registry).contains { if case .hosted = $0.item { return true } else { return false } })232 for word in ["Graphe", "Base de données", "Chronologie", "Canvas", "Santé"] {233 #expect(FuzzyMatch.rank(word, commands: commands).allSatisfy { !$0.id.contains("hosted") })234 }235 #expect(!registry.showsDatabases)236 }237238 @Test func aRegisteredSectionAppearsInTheSidebarPlusAndPalette() {239 let registry = HostedSectionRegistry()240 registry.register(fakeSection("graph"))241 #expect(registry.available.map(\.id) == ["graph"])242 #expect(CommandRegistry.hostedPlaces(sections: registry) == [ShellPlace(item: .hosted("graph"), title: "Graphe graph", symbol: "point.3.connected.trianglepath.dotted")])243 let more = ShellEntries.more(sections: registry).flatMap { $0 }244 #expect(more.contains { $0.id == "more-hosted-graph" && $0.target == .push(.hosted("graph")) })245 let commands = CommandRegistry.commands(sections: registry)246 let command = commands.first { $0.action == .go(.hosted("graph")) }247 #expect(command?.shortcut == "⌘6", "it takes the next number after the fixed places")248 #expect(FuzzyMatch.rank("graphe", commands: commands).first?.action == .go(.hosted("graph")))249 // and it can be navigated to and restored250 let shell = makeShell(registry)251 shell.go(to: .hosted("graph"))252 #expect(shell.tab == .more && shell.path == [.hosted("graph")])253 }254255 @Test func aSectionNeedingAServerFeatureWaitsForIt() {256 let registry = HostedSectionRegistry()257 registry.register(fakeSection("canvas", feature: ServerFeature.canvas))258 registry.register(fakeSection("research"))259 #expect(registry.available.map(\.id) == ["research"], "features unknown: the section is not offered")260 registry.update(features: ServerMeta(api: 2, version: "2.4.0", features: []))261 #expect(registry.available.map(\.id) == ["research"], "a 2.x server does not have it")262 registry.update(features: ServerMeta(api: 3, version: "3.0.0", features: [ServerFeature.canvas]))263 #expect(registry.available.map(\.id) == ["canvas", "research"])264 #expect(registry.section(id: "canvas") != nil)265 registry.unregister(id: "canvas")266 #expect(registry.section(id: "canvas") == nil)267 }268269 @Test func sectionsAreOrderedAndReplaceableById() {270 let registry = HostedSectionRegistry()271 registry.register(fakeSection("timeline", order: 30))272 registry.register(fakeSection("graph", order: 10))273 registry.register(fakeSection("health", order: 30))274 registry.register(fakeSection("graph", layout: .list, order: 20))275 #expect(registry.available.map(\.id) == ["graph", "timeline", "health"])276 #expect(registry.section(id: "graph")?.layout == .list)277 // more sections than numbers: ⌘1…9 stops at nine, the palette still lists them all278 for index in 0..<8 { registry.register(fakeSection("extra\(index)", order: 200 + index)) }279 #expect(CommandRegistry.numberedPlaces(sections: registry).count == 9)280 let commands = CommandRegistry.commands(sections: registry)281 #expect(commands.contains { $0.action == .go(.hosted("extra7")) && $0.shortcut == nil })282 }283284 @Test func theRouterNavigatesThroughTheShell() throws {285 let registry = HostedSectionRegistry()286 let shell = makeShell(registry)287 let router = ShellFeatureRouter(shell: shell, app: nil)288 var external: [URL] = []289 router.openExternal = { external.append($0) }290291 router.openPage(id: "p1", blockId: "k1")292 #expect(shell.currentNote == "p1" && shell.reveal(for: "p1")?.blockId == "k1")293 // a database keeps its 1.0 screen (the page: empty state + « Ouvrir sur le web ») until a database section exists294 router.openDatabase(id: "db1")295 #expect(shell.currentNote == "db1" && shell.pendingHostedItem == nil)296 registry.register(fakeSection(HostedSectionID.databases))297 router.openDatabase(id: "db2")298 #expect(shell.location == .hosted(HostedSectionID.databases))299 #expect(shell.pendingHostedItem == HostedItem(section: HostedSectionID.databases, id: "db2"))300 router.openCanvas(pageId: "c1")301 #expect(shell.currentNote == "c1", "no canvas section: the page opens")302 // links: ours navigate, the rest goes to the system — never a web view303 router.openURL(URL(string: "https://note.spboucher.ai/p/0b7f6c0e-3f0a-4d5e-9b0a-111111111111#k2")!)304 #expect(shell.currentNote == "0b7f6c0e-3f0a-4d5e-9b0a-111111111111")305 #expect(external.isEmpty)306 router.openURL(URL(string: "https://example.org/x")!)307 #expect(external == [URL(string: "https://example.org/x")!])308 router.presentError(RepositoryError.offline)309 #expect(router.lastError?.isEmpty == false)310 #expect(shell.toast?.message == router.lastError)311 }312}313314@Suite("Palette de commandes")315@MainActor316struct CommandPaletteTests {317 private var commands: [PaletteCommand] { CommandRegistry.commands(sections: HostedSectionRegistry()) }318319 @Test func matchingIgnoresCaseAndAccentsAndRanksPrefixesFirst() {320 #expect(FuzzyMatch.score("reglages", in: "Réglages") == 1000)321 #expect(FuzzyMatch.score("RÉG", in: "Réglages") ?? 0 > FuzzyMatch.score("gla", in: "Réglages") ?? 0)322 #expect(FuzzyMatch.score("note", in: "Nouvelle note") ?? 0 > FuzzyMatch.score("ote", in: "Nouvelle note") ?? 0, "the start of a word beats the middle of one")323 #expect(FuzzyMatch.score("nvn", in: "Nouvelle note") != nil, "letters in order match")324 #expect(FuzzyMatch.score("xyz", in: "Nouvelle note") == nil)325 #expect(FuzzyMatch.score("", in: "Tout") == 0)326 #expect(FuzzyMatch.score("a", in: "") == nil)327 }328329 @Test func filteringKeepsWhatMatchesBestFirst() {330 #expect(FuzzyMatch.rank("", commands: commands) == commands, "nothing typed: everything, in the registry order")331 #expect(FuzzyMatch.rank("tâches", commands: commands).first?.action == .go(.tasks))332 #expect(FuzzyMatch.rank("taches", commands: commands).first?.action == .go(.tasks))333 #expect(FuzzyMatch.rank("boite", commands: commands).first?.action == .go(.inbox))334 #expect(FuzzyMatch.rank("nouvelle n", commands: commands).first?.action == .newNote)335 #expect(FuzzyMatch.rank("synchro", commands: commands).first?.action == .sync, "a keyword finds a command")336 #expect(FuzzyMatch.rank("sombre", commands: commands).first?.action == .appearance(.dark))337 #expect(FuzzyMatch.rank("capt", commands: commands).first?.action == .capture)338 #expect(FuzzyMatch.rank("corb", commands: commands).first?.action == .go(.source(.smart(.trash))))339 #expect(FuzzyMatch.rank("zzzz", commands: commands).isEmpty)340 // a title match beats a keyword match341 let ranked = FuzzyMatch.rank("rech", commands: commands)342 #expect(ranked.prefix(2).contains { $0.action == .go(.search) })343 }344345 @Test func theRegistryCoversNavigationAndActions() {346 let actions = commands.map(\.action)347 for required: PaletteAction in [.go(.today), .go(.source(.smart(.all))), .go(.inbox), .go(.tasks), .go(.search), .go(.source(.smart(.archived))),348 .newNote, .capture, .newFolder, .sync, .settings, .syncDetails] {349 #expect(actions.contains(required), "\(required)")350 }351 #expect(commands.first { $0.action == .go(.today) }?.shortcut == "⌘1")352 #expect(commands.first { $0.action == .newNote }?.shortcut == "⌘N")353 #expect(Set(commands.map(\.id)).count == commands.count)354 // the appearance offered is never the current one355 #expect(!CommandRegistry.commands(sections: HostedSectionRegistry(), appearance: .dark).contains { $0.action == .appearance(.dark) })356 }357358 @Test func theModelFiltersSelectsAndFindsNotesByTitle() async {359 let model = CommandPaletteModel(commands: commands) { text in360 text.isEmpty ? [.note(id: "recent", title: "Note récente", subtitle: nil)] : (text.hasPrefix("bud") ? [.note(id: "n1", title: "Budget 2027", subtitle: nil)] : [])361 }362 await model.settle()363 #expect(model.results.count == 9 && model.results.last?.action == .openNote("recent"), "empty: the first commands, then recent notes")364 #expect(model.selection == 0)365366 model.query = "bud"367 await model.settle()368 #expect(model.results.contains { $0.action == .openNote("n1") }, "a note is found by its title")369 #expect(model.results.count <= CommandPaletteModel.limit)370371 model.query = "tâches"372 await model.settle()373 #expect(model.selected?.action == .go(.tasks), "Return runs the best match")374 // keyboard: ↓ ↑ wrap around the list375 model.query = "a"376 await model.settle()377 let count = model.results.count378 #expect(count > 2)379 model.move(1); #expect(model.selection == 1)380 model.move(-1); model.move(-1); #expect(model.selection == count - 1)381 model.move(1); #expect(model.selection == 0)382 model.query = "zzzz"383 await model.settle()384 #expect(model.results.isEmpty && model.selected == nil)385 model.move(1); #expect(model.selection == 0)386 }387388 @Test func runningACommandActsOnTheWindow() async throws {389 let app = try ShellFixtures.app()390 let shell = makeShell()391 let actions = ShellActions(app: app, shell: shell)392 actions.run(.go(.tasks)); #expect(shell.location == .tasks)393 actions.run(.go(.search)); #expect(shell.tab == .search)394 actions.run(.settings); #expect({ if case .settings? = shell.sheet { return true } else { return false } }())395 actions.run(.syncDetails); #expect({ if case .syncDetails? = shell.sheet { return true } else { return false } }())396 actions.run(.newFolder); #expect({ if case .newFolder? = shell.sheet { return true } else { return false } }())397 actions.run(.capture); #expect(shell.captureRequest != nil)398 let id = try await app.createNote(title: "Budget 2027")399 actions.run(.openNote(id)); #expect(shell.currentNote == id)400401 let before = UserDefaults.standard.string(forKey: "appearance")402 defer { UserDefaults.standard.set(before, forKey: "appearance") }403 actions.run(.appearance(.dark)); #expect(UserDefaults.standard.string(forKey: "appearance") == "dark")404405 actions.run(.newNote)406 for _ in 0..<200 where shell.currentNote == id { try await Task.sleep(for: .milliseconds(10)) }407 let created = try #require(shell.currentNote)408 #expect(created != id && shell.isFresh(created), "a new note is created and opened ready to type")409 #expect(!actions.canOpenCurrentNoteInWindow, "no window opener on a one-window device")410411 // the palette finds notes of the local store by title412 let search = CommandPaletteOverlay.noteSearch(store: app.store)413 #expect(await search("budget").contains { $0.action == .openNote(id) })414 #expect(await search("").contains { $0.isNote })415 }416417 @Test func theCaptureHookOpensQuickCaptureInTheModeAskedFor() async throws {418 let app = try ShellFixtures.app()419 let shell = makeShell()420 shell.requestCapture(kind: nil)421 CaptureHook.present(try #require(shell.captureRequest), app: app, shell: shell)422 #expect(shell.quickCapture?.mode == .text)423 shell.requestCapture(kind: "audio")424 CaptureHook.present(try #require(shell.captureRequest), app: app, shell: shell)425 #expect(shell.quickCapture?.mode == .audio)426 #expect(shell.currentNote == nil, "nothing is created before the user saves the capture")427 // `kind=tasks` starts a task list, as `spnotes://new?kind=tasks` does428 let other = makeShell()429 other.requestCapture(kind: "tasks")430 CaptureHook.present(try #require(other.captureRequest), app: app, shell: other)431 for _ in 0..<200 where other.currentNote == nil { try await Task.sleep(for: .milliseconds(10)) }432 let taskNote = try #require(other.currentNote)433 let page = try #require(try await app.store.page(id: taskNote))434 #expect(try NoteDocument(json: page.content).listKind(at: 0) == .task)435 }436}437438@Suite("Type de page et sources de l’assistant")439struct PageKindAndSourcesTests {440 @Test func pageKindsAreTypedOnce() {441 #expect(PageKind(type: "page") == .note)442 #expect(PageKind(type: "research") == .note)443 #expect(PageKind(type: "page", isFolder: true) == .folder)444 #expect(PageKind(type: "database") == .database)445 #expect(PageKind(type: "canvas") == .canvas)446 #expect(PageKind(type: "whiteboard9") == .other("whiteboard9"))447 #expect(PageKind.note.hasDocument && PageKind.other("x").hasDocument, "an unknown type is opened as a note, never dropped")448 #expect(!PageKind.database.hasDocument && !PageKind.canvas.hasDocument && !PageKind.folder.hasDocument)449 #expect(PageKind.note.isLinkable && PageKind.canvas.isLinkable && !PageKind.database.isLinkable && !PageKind.folder.isLinkable)450 }451452 @MainActor @Test func summariesExposeTheirKind() {453 #expect(ShellFixtures.summary("a").kind == .note)454 #expect(ShellFixtures.summary("b", folder: true).kind == .folder)455 #expect(ShellFixtures.summary("c", type: "database").kind == .database)456 // the link picker keeps its 1.0 rule through the typed kind457 let pages = [ShellFixtures.summary("a"), ShellFixtures.summary("c", type: "database"), ShellFixtures.summary("d", type: "canvas")]458 #expect(NoteLinkPicker.candidates(pages, excluding: "a").map(\.id) == ["d"])459 }460461 @Test func assistantSourcesKeepTheirBlocks() throws {462 let raw = RawJSON(data: Data(#"""463 {"sources":[{"n":1,"pageId":"a","title":"A","blockId":"k1","heading":"Intro"},{"n":2,"pageId":"a","title":"A","blockId":"k2"},464 {"n":3,"pageId":"a","title":"A","blockId":"k1"},{"n":4,"pageId":"b","title":"B"},{"n":5,"pageId":"b","title":"B"},{"n":6,"title":"sans page"}]}465 """#.utf8))466 let sources = AssistantSource.list(in: raw)467 #expect(sources.map(\.blockId) == ["k1", "k2", "k1", nil, nil])468 // two passages of the same note are two sources when their blocks differ; exact repeats are merged469 #expect(AssistantSource.uniqueAnchors(sources).map(\.n) == [1, 2, 4])470 #expect(Set(sources.map(\.id)).count == sources.count, "each row has its own identity")471 // what a tap routes to472 let first = try #require(AssistantSource.uniqueAnchors(sources).first)473 #expect(AppRoute.note(try #require(first.pageId), blockId: first.blockId) == .note("a", blockId: "k1"))474 }475476 @MainActor @Test func theChatModelReadsCitationsWithBlocksFromTheEvents() async throws {477 // the same fields `AssistantRepository.citations(of:)` exposes (`AIEvent` → `AISourceRef.blockId`)478 let fake = FakeBackend()479 defer { fake.shutdown() }480 let device = try FakeDevice(fake: fake)481 let event = aiEvent(#"{"type":"meta","sources":[{"n":1,"pageId":"a","title":"A","blockId":"k1"},{"n":2,"pageId":"a","title":"A","blockId":"k2"}]}"#)482 guard case .meta(let meta) = event else { Issue.record("not a meta event: \(event)"); return }483 let citations = device.repositories.assistant.citations(of: event)484 #expect(citations.map(\.blockId) == ["k1", "k2"])485 #expect(AssistantSource.list(in: meta.raw).map(\.blockId) == citations.map(\.blockId), "the app's sources and the Core's citations agree")486 await device.close()487 }488}489