Repository Public License
1import Foundation2import NavigatorCore3import Testing4@testable import Persistence56@Suite struct StoreRoundTripTests {7 @Test func profilesAndSpaces() async throws {8 let fixture = try await Fixture.make()9 let database = fixture.database10 #expect(try await database.profiles.profile(fixture.profile.id) == fixture.profile)1112 var work = Profile(name: "Work", tint: .ember, createdAt: day(1))13 try await database.profiles.save(work)14 work.name = "Work (renamed)"15 try await database.profiles.save(work)16 #expect(try await database.profiles.all() == [fixture.profile, work])1718 var research = OrbitSpace(profileID: work.id, name: "Research", symbol: "orix.atom", tint: .nebula, order: 1,19 ring: 2, angle: 1.25, isArchived: false,20 focus: FocusSettings(isEnabled: true, timerSeconds: 1_500, hidesTabStrip: false, hidesSidebar: true),21 createdAt: day(1), updatedAt: day(1))22 let inbox = OrbitSpace(profileID: work.id, name: "Inbox", order: 0, createdAt: day(1), updatedAt: day(1))23 try await database.spaces.save(research)24 try await database.spaces.save(inbox)25 #expect(try await database.spaces.space(research.id) == research)26 #expect(try await database.spaces.spaces(profile: work.id).map(\.name) == ["Inbox", "Research"])2728 try await database.spaces.reorder([research.id, inbox.id])29 #expect(try await database.spaces.spaces(profile: work.id).map(\.name) == ["Research", "Inbox"])30 try await database.spaces.setArchived(inbox.id, true, at: day(2))31 #expect(try await database.spaces.spaces(profile: work.id, includeArchived: false).map(\.name) == ["Research"])3233 research.focus.timerSeconds = nil34 research.updatedAt = day(3)35 research.order = 036 try await database.spaces.save(research)37 #expect(try await database.spaces.space(research.id) == research)3839 // Deleting the profile takes its spaces with it and leaves the other profile alone.40 try await database.profiles.delete(work.id)41 #expect(try await database.spaces.spaces().map(\.id) == [fixture.space.id])42 #expect(try await database.profiles.profile(work.id) == nil)43 // A space cannot be created for a profile that is not stored.44 await #expect(throws: PersistenceError.ownerNotPersisted(owner: "profile", id: work.id.string)) {45 try await database.spaces.save(inbox)46 }47 }4849 @Test func windowsTabsAndGroups() async throws {50 let fixture = try await Fixture.make()51 let database = fixture.database52 var window = BrowserWindow(spaceID: fixture.space.id, frame: WindowFrame(x: 10, y: 20, width: 1_280, height: 800),53 tabLayout: .grid, isSidebarCollapsed: true, isAgentPanelOpen: true,54 agentPanelWidth: 420, isFullScreen: false, order: 0)55 try await database.windows.save(window)5657 let group = TabGroup(spaceID: fixture.space.id, name: "Reading", tint: .auroraMint, isCollapsed: true, order: 0)58 try await database.tabGroups.save(group)59 #expect(try await database.tabGroups.group(group.id) == group)60 #expect(try await database.tabGroups.groups(space: fixture.space.id) == [group])6162 let parent = Tab(windowID: window.id, spaceID: fixture.space.id, url: url("https://swift.org/"), title: "Swift",63 faviconURL: url("https://swift.org/favicon.ico"), isPinned: true, isMuted: true, order: 5,64 lifecycle: .live, sessionState: Data([1, 2, 3, 0, 255]), zoom: 1.25, userAgentMode: .desktop,65 isReaderActive: true, createdAt: day(), lastActiveAt: day(1))66 let child = Tab(windowID: window.id, spaceID: fixture.space.id, parentID: parent.id, groupID: group.id,67 url: url("https://swift.org/blog/"), title: "Blog", order: 1, createdAt: day(), lastActiveAt: day())68 let blank = Tab(windowID: window.id, spaceID: fixture.space.id, order: 0, createdAt: day(), lastActiveAt: day())69 // The child is listed before its parent: the deferred foreign key allows any order inside a batch.70 try await database.tabs.save([child, blank, parent])7172 #expect(try await database.tabs.tab(parent.id) == parent)73 #expect(try await database.tabs.tab(child.id) == child)74 #expect(try await database.tabs.tab(blank.id) == blank)75 // Pinned first, then by order.76 #expect(try await database.tabs.tabs(window: window.id).map(\.id) == [parent.id, blank.id, child.id])77 #expect(try await database.tabs.pinnedTabs(space: fixture.space.id).map(\.id) == [parent.id])78 #expect(try await database.tabs.tabs(group: group.id).map(\.id) == [child.id])79 #expect(try await database.tabs.children(of: parent.id).map(\.id) == [child.id])8081 try await database.tabs.reorder(window: window.id, [child.id, blank.id])82 #expect(try await database.tabs.tabs(window: window.id).map(\.id) == [parent.id, child.id, blank.id])83 try await database.tabs.setPinned(parent.id, false)84 try await database.tabs.setGroup(blank.id, group.id)85 #expect(try await database.tabs.tabs(group: group.id).map(\.id) == [child.id, blank.id])8687 window.selectedTabID = child.id88 window.split = SplitLayout(axis: .vertical, panes: [parent.id, child.id], fractions: [1, 3], focusedPane: 1)89 try await database.windows.save(window)90 let stored = try #require(try await database.windows.window(window.id))91 #expect(stored == window)92 #expect(stored.split?.fractions == [0.25, 0.75])9394 // Deleting the group keeps its tabs; deleting the parent keeps the child.95 try await database.tabGroups.delete(group.id)96 #expect(try await database.tabs.tab(child.id)?.groupID == nil)97 try await database.tabs.delete(parent.id)98 #expect(try await database.tabs.tab(child.id)?.parentID == nil)99100 // Moving a tab to a window of another space changes its space.101 let otherSpace = OrbitSpace(profileID: fixture.profile.id, name: "Other", createdAt: day(), updatedAt: day())102 try await database.spaces.save(otherSpace)103 let otherWindow = BrowserWindow(spaceID: otherSpace.id, order: 1)104 try await database.windows.save(otherWindow)105 try await database.tabs.move(child.id, to: otherWindow.id, order: 0)106 let moved = try #require(try await database.tabs.tab(child.id))107 #expect(moved.windowID == otherWindow.id)108 #expect(moved.spaceID == otherSpace.id)109 #expect(try await database.windows.openWindows().map(\.id) == [window.id, otherWindow.id])110 #expect(try await database.windows.openWindows(space: otherSpace.id).map(\.id) == [otherWindow.id])111112 try await database.windows.delete(window.id)113 #expect(try await database.tabs.tab(blank.id) == nil)114 }115116 @Test func downloads() async throws {117 let fixture = try await Fixture.make()118 let store = fixture.database.downloads119 var download = Download(profileID: fixture.profile.id, sourceURL: url("https://example.com/file.zip"),120 originURL: url("https://example.com/"), filename: "file.zip",121 destinationPath: "/Users/me/Downloads/file.zip", mimeType: "application/zip",122 bytesReceived: 10, totalBytes: 5_000_000_000, state: .running,123 resumeData: Data([9, 8, 7]), startedAt: day())124 try await store.save(download)125 #expect(try await store.download(download.id) == download)126 #expect(try await store.interrupted().map(\.id) == [download.id])127128 try await store.updateProgress(download.id, bytesReceived: 2_500_000_000, totalBytes: 5_000_000_000)129 #expect(try await store.download(download.id)?.fractionCompleted == 0.5)130131 download.state = .failed132 download.errorDescription = "The network connection was lost."133 download.finishedAt = day(1)134 download.bytesReceived = 2_500_000_000135 try await store.save(download)136 #expect(try await store.download(download.id) == download)137 #expect(try await store.interrupted().isEmpty)138139 let second = Download(profileID: fixture.profile.id, sourceURL: url("https://example.com/b.pdf"),140 filename: "b.pdf", state: .pending, startedAt: day(2))141 try await store.save(second)142 #expect(try await store.downloads(profile: fixture.profile.id).map(\.id) == [second.id, download.id])143 #expect(try await store.downloads(profile: fixture.profile.id, states: [.failed]).map(\.id) == [download.id])144 #expect(try await store.clearInactive(profile: fixture.profile.id) == 1)145 #expect(try await store.downloads(profile: fixture.profile.id).map(\.id) == [second.id])146 try await store.delete(second.id)147 #expect(try await store.download(second.id) == nil)148 }149150 @Test func permissionsHonourOriginKindAndExpiry() async throws {151 let fixture = try await Fixture.make()152 let store = fixture.database.permissions153 let profile = fixture.profile.id154 let origin = try #require(WebOrigin(url: url("https://meet.example.com/room/1")))155 let otherPort = WebOrigin(scheme: "https", host: "meet.example.com", port: 8443)156 let now = day(10)157158 // Nothing stored: ask.159 #expect(try await store.verdict(profile: profile, origin: origin, kind: .camera, at: now) == .ask)160161 let allow = PermissionDecision(profileID: profile, origin: origin, kind: .camera, verdict: .allow,162 decidedAt: day(9), expiresAt: day(11))163 try await store.set(allow)164 #expect(try await store.decision(profile: profile, origin: origin, kind: .camera, at: now) == allow)165 // Another kind, another port, another profile: not covered.166 #expect(try await store.verdict(profile: profile, origin: origin, kind: .microphone, at: now) == .ask)167 #expect(try await store.verdict(profile: profile, origin: otherPort, kind: .camera, at: now) == .ask)168 let otherProfile = Profile(name: "Other", createdAt: day())169 try await fixture.database.profiles.save(otherProfile)170 #expect(try await store.verdict(profile: otherProfile.id, origin: origin, kind: .camera, at: now) == .ask)171172 // Expired: back to ask, exactly at the expiry instant too.173 #expect(try await store.verdict(profile: profile, origin: origin, kind: .camera, at: day(11)) == .ask)174 #expect(try await store.decision(profile: profile, origin: origin, kind: .camera, at: day(12)) == nil)175176 // A new decision for the same origin and kind replaces the old one.177 let deny = PermissionDecision(profileID: profile, origin: origin, kind: .camera, verdict: .deny, decidedAt: day(10))178 try await store.set(deny)179 #expect(try await store.decisions(profile: profile) == [deny])180 #expect(try await store.verdict(profile: profile, origin: origin, kind: .camera, at: day(400)) == .deny)181182 let temporary = PermissionDecision(profileID: profile, origin: otherPort, kind: .location, verdict: .allow,183 decidedAt: day(10), expiresAt: day(10.5))184 try await store.set(temporary)185 #expect(try await store.decisions(profile: profile, origin: otherPort) == [temporary])186 #expect(try await store.decisions(profile: profile, activeAt: day(11)) == [deny])187 #expect(try await store.purgeExpired(at: day(11)) == 1)188 #expect(try await store.decisions(profile: profile) == [deny])189 #expect(try await store.removeAll(profile: profile, origin: origin) == 1)190 #expect(try await store.decisions(profile: profile).isEmpty)191 }192193 @Test func archivesAndSnapshots() async throws {194 let fixture = try await Fixture.make()195 let database = fixture.database196 let page = url("https://example.com/article")197 let archive = Archive(profileID: fixture.profile.id, url: page, title: "Article", format: .webArchive,198 relativePath: "2026/article.webarchive", byteSize: 123_456, contentHash: "sha256:abc",199 isComplete: false, missing: ["video on cdn.example.com", "cross-origin frame"],200 capturedAt: day())201 try await database.archives.save(archive)202 #expect(try await database.archives.archive(archive.id) == archive)203 #expect(try await database.archives.archives(profile: fixture.profile.id, url: page) == [archive])204 #expect(try await database.archives.archives(profile: fixture.profile.id, url: url("https://nope.example/")).isEmpty)205206 let first = PageSnapshot(profileID: fixture.profile.id, url: page, title: "Article", text: "Version one",207 archiveID: archive.id, takenAt: day())208 let second = PageSnapshot(profileID: fixture.profile.id, url: page, title: "Article", text: "Version two — édité",209 takenAt: day(1))210 try await database.snapshots.save(first)211 try await database.snapshots.save(second)212 #expect(try await database.snapshots.snapshots(profile: fixture.profile.id, url: page) == [second, first])213 #expect(try await database.snapshots.snapshot(first.id) == first)214215 // Deleting the archive returns it (for file removal) and unlinks the snapshot without deleting it.216 #expect(try await database.archives.delete(archive.id) == archive)217 #expect(try await database.snapshots.snapshot(first.id)?.archiveID == nil)218 try await database.snapshots.delete(second.id)219 #expect(try await database.snapshots.snapshots(profile: fixture.profile.id).map(\.id) == [first.id])220 }221222 @Test func notesCanvasesAgentRunsAndWorkflows() async throws {223 let fixture = try await Fixture.make()224 let database = fixture.database225226 var note = Note(spaceID: fixture.space.id, url: url("https://example.com/a"), title: "Idea", body: "100% sure_thing",227 quote: "a highlighted “quote”", tint: .solar, createdAt: day(), updatedAt: day())228 let loose = Note(body: "No space, no URL", createdAt: day(), updatedAt: day(1))229 try await database.notes.save(note)230 try await database.notes.save(loose)231 #expect(try await database.notes.note(note.id) == note)232 #expect(try await database.notes.notes() == [loose, note])233 #expect(try await database.notes.notes(space: fixture.space.id) == [note])234 #expect(try await database.notes.notes(url: url("https://example.com/a")) == [note])235 // LIKE wildcards in user text are literal.236 #expect(try await database.notes.search("100%") == [note])237 #expect(try await database.notes.search("sure_thing") == [note])238 #expect(try await database.notes.search("%").map(\.id) == [note.id])239 #expect(try await database.notes.search("_").map(\.id) == [note.id])240 note.body = "Edited"241 note.tint = nil242 note.updatedAt = day(2)243 try await database.notes.save(note)244 #expect(try await database.notes.note(note.id) == note)245246 let cardA = CanvasCard(content: .page(url: url("https://example.com/"), title: "Example"), origin: CanvasPoint(x: 10, y: 20))247 let cardB = CanvasCard(content: .pdf(relativePath: "papers/a.pdf", page: 3), origin: CanvasPoint(x: -5.5, y: 0),248 size: CanvasSize(width: 400, height: 520), tint: .rose, zIndex: 4)249 let cardC = CanvasCard(content: .note(text: "multi\nline"), origin: .zero)250 let cardD = CanvasCard(content: .image(relativePath: "img/x.png"), origin: .zero)251 var canvas = CanvasDocument(spaceID: fixture.space.id, title: "Board", cards: [cardA, cardB, cardC, cardD],252 connections: [CanvasConnection(from: cardA.id, to: cardB.id, label: "cites")],253 viewport: CanvasViewport(center: CanvasPoint(x: 100, y: -40), scale: 0.5),254 createdAt: day(), updatedAt: day())255 try await database.canvases.save(canvas)256 #expect(try await database.canvases.document(canvas.id) == canvas)257 canvas.cards.removeLast()258 canvas.updatedAt = day(1)259 try await database.canvases.save(canvas)260 #expect(try await database.canvases.documents(space: fixture.space.id) == [canvas])261262 var run = AgentRun(spaceID: fixture.space.id, goal: "Compare two laptops", providerID: "anthropic", model: "claude",263 status: .awaitingConfirmation,264 steps: [AgentStep(id: 1, kind: .thought, status: .done, summary: "Plan", startedAt: second(1), finishedAt: second(2)),265 AgentStep(id: 2, kind: .toolCall, status: .running, tool: "browser.navigate",266 summary: "Open page", detail: "{\"url\":\"https://example.com\"}", startedAt: second(3))],267 citations: [Citation(id: 1, url: url("https://example.com/"), title: "Example", accessedAt: second(4), excerpt: "…")],268 usage: TokenUsage(inputTokens: 1_200, outputTokens: 340, estimatedCostUSD: 0.0123),269 budget: AgentBudget(maxSteps: 12, maxDurationSeconds: 90, maxTokens: 50_000, maxCostUSD: nil,270 allowedDomains: ["example.com"]),271 startedAt: second(0))272 try await database.agentRuns.save(run)273 #expect(try await database.agentRuns.run(run.id) == run)274 #expect(try await database.agentRuns.unfinished().map(\.id) == [run.id])275 run.status = .completed276 run.answer = "The second one."277 run.finishedAt = second(60)278 try await database.agentRuns.save(run)279 #expect(try await database.agentRuns.runs(space: fixture.space.id) == [run])280 #expect(try await database.agentRuns.unfinished().isEmpty)281282 var workflow = Workflow(name: "Morning", source: "open \"https://news.example.com\"\nwait 2s", languageVersion: 1,283 createdAt: day(), updatedAt: day())284 try await database.workflows.save(workflow)285 try await database.workflows.markRun(workflow.id, at: day(1))286 workflow.lastRunAt = day(1)287 #expect(try await database.workflows.workflow(workflow.id) == workflow)288 #expect(try await database.workflows.all() == [workflow])289290 // Deleting the space keeps notes, canvases and runs, unlinked.291 try await database.spaces.delete(fixture.space.id)292 #expect(try await database.notes.note(note.id)?.spaceID == nil)293 #expect(try await database.canvases.document(canvas.id)?.spaceID == nil)294 #expect(try await database.agentRuns.run(run.id)?.spaceID == nil)295296 try await database.notes.delete(note.id)297 try await database.canvases.delete(canvas.id)298 try await database.agentRuns.delete(run.id)299 try await database.workflows.delete(workflow.id)300 #expect(try await database.notes.notes() == [loose])301 #expect(try await database.canvases.documents().isEmpty)302 #expect(try await database.agentRuns.runs().isEmpty)303 #expect(try await database.workflows.all().isEmpty)304 }305306 @Test func syncRecordsKeepTombstonesAndAMonotonicVersion() async throws {307 let fixture = try await Fixture.make()308 let sync = fixture.database.sync309 #expect(try await sync.localVersion() == 0)310311 let created = try await sync.recordChange(entity: .bookmark, entityID: "b-1", deviceID: "mac", payloadHash: "h1", at: day())312 let other = try await sync.recordChange(entity: .note, entityID: "n-1", deviceID: "mac", at: day())313 let updated = try await sync.recordChange(entity: .bookmark, entityID: "b-1", deviceID: "mac", payloadHash: "h2", at: day(1))314 #expect([created.version, other.version, updated.version] == [1, 2, 3])315 // One record per entity: the id is stable across changes.316 #expect(updated.id == created.id)317 #expect(updated.payloadHash == "h2")318 #expect(try await sync.changes(since: 0).map(\.entityID) == ["n-1", "b-1"])319 #expect(try await sync.changes(since: 2).map(\.entityID) == ["b-1"])320321 let tombstone = try await sync.recordDeletion(entity: .bookmark, entityID: "b-1", deviceID: "mac", at: day(2))322 #expect(tombstone.version == 4)323 #expect(tombstone.deletedAt == day(2))324 #expect(tombstone.payloadHash == nil)325 #expect(try await sync.tombstones() == [tombstone])326 #expect(try await sync.record(entity: .bookmark, entityID: "b-1") == tombstone)327328 // A remote record far ahead lifts the local counter past it.329 let remote = SyncRecord(entity: .workflow, entityID: "w-1", version: 100, deviceID: "iphone", modifiedAt: day(3))330 #expect(try await sync.applyRemote(remote) == true)331 #expect(try await sync.localVersion() > 100)332 let afterRemote = try await sync.recordChange(entity: .space, entityID: "s-1", deviceID: "mac", at: day(3))333 #expect(afterRemote.version > 100)334335 // An older remote record loses against the local one; a newer one wins and can resurrect.336 let stale = SyncRecord(entity: .bookmark, entityID: "b-1", version: 2, deviceID: "iphone", modifiedAt: day(1), payloadHash: "old")337 #expect(try await sync.applyRemote(stale) == false)338 #expect(try await sync.record(entity: .bookmark, entityID: "b-1")?.deletedAt == day(2))339 let newer = SyncRecord(entity: .bookmark, entityID: "b-1", version: 500, deviceID: "iphone", modifiedAt: day(4), payloadHash: "new")340 #expect(try await sync.applyRemote(newer) == true)341 let resurrected = try #require(try await sync.record(entity: .bookmark, entityID: "b-1"))342 #expect(resurrected.deletedAt == nil)343 #expect(resurrected.version == 500)344 #expect(resurrected.deviceID == "iphone")345346 // Versions never repeat or go back, whatever happened before.347 var last = try await sync.localVersion()348 for index in 0..<20 {349 let record = try await sync.recordChange(entity: .note, entityID: "n-\(index)", deviceID: "mac")350 #expect(record.version > last)351 last = record.version352 }353354 let dead = try await sync.recordDeletion(entity: .note, entityID: "n-0", deviceID: "mac", at: day(5))355 #expect(try await sync.purgeTombstones(olderThan: day(5)) == 0)356 #expect(try await sync.purgeTombstones(olderThan: day(6)) == 1)357 #expect(try await sync.record(entity: .note, entityID: "n-0") == nil)358 #expect(try await sync.localVersion() == dead.version)359 }360361 @Test func typedSettings() async throws {362 struct Appearance: Codable, Sendable, Equatable { var theme: String; var density: Int }363 let fixture = try await Fixture.make()364 let settings = fixture.database.settings365 let engine = SettingKey<String>("search.engine", default: "duckduckgo")366 let blockTrackers = SettingKey<Bool>("privacy.block_trackers", default: true)367 let zoom = SettingKey<Double>("page.default_zoom", default: 1.0)368 let appearance = SettingKey<Appearance>("ui.appearance", default: Appearance(theme: "lunar", density: 1))369 let pinned = SettingKey<[String]?>("ui.pinned", default: nil)370371 // Defaults when nothing is stored.372 #expect(try await settings.value(engine) == "duckduckgo")373 #expect(try await settings.value(blockTrackers) == true)374 #expect(try await settings.value(appearance) == Appearance(theme: "lunar", density: 1))375 #expect(try await settings.isSet(engine.name) == false)376377 try await settings.set(engine, to: "kagi")378 try await settings.set(blockTrackers, to: false)379 try await settings.set(zoom, to: 1.5)380 try await settings.set(appearance, to: Appearance(theme: "solar", density: 2))381 try await settings.set(pinned, to: ["a", "b"])382 #expect(try await settings.value(engine) == "kagi")383 #expect(try await settings.value(blockTrackers) == false)384 #expect(try await settings.value(zoom) == 1.5)385 #expect(try await settings.value(appearance) == Appearance(theme: "solar", density: 2))386 #expect(try await settings.value(pinned) == ["a", "b"])387 #expect(try await settings.allRaw()["search.engine"] == "\"kagi\"")388389 // A stored value of another type falls back to the default instead of throwing.390 #expect(try await settings.value(SettingKey<Int>("search.engine", default: 7)) == 7)391392 try await settings.remove(engine.name)393 #expect(try await settings.value(engine) == "duckduckgo")394 #expect(try await settings.allRaw().count == 4)395 }396}397