Repository Public License
1import Foundation2import NavigatorCore3@testable import Persistence // RestoredSession and SessionLaunchInfo have no public initialiser4import Testing5@testable import OrbitEngine67/// Deterministic generator for the equivalence test (SplitMix64).8struct SeededGenerator: RandomNumberGenerator {9 var state: UInt6410 mutating func next() -> UInt64 {11 state &+= 0x9E37_79B9_7F4A_7C1512 var z = state13 z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B914 z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB15 return z ^ (z >> 31)16 }17}1819/// A sleeper the test releases by hand: no real time in debounce tests.20final class ManualSleeper: @unchecked Sendable {21 private let lock = NSLock()22 private var waiting: [Int: CheckedContinuation<Void, any Error>] = [:]23 private var cancelled = Set<Int>()24 private var nextID = 025 private var durations: [Duration] = []2627 var requested: [Duration] { lock.withLock { durations } }28 var waitingCount: Int { lock.withLock { waiting.count } }2930 func sleep(_ duration: Duration) async throws {31 let id = lock.withLock { nextID += 1; durations.append(duration); return nextID }32 try await withTaskCancellationHandler {33 try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in34 let alreadyCancelled = lock.withLock { () -> Bool in35 if cancelled.contains(id) { return true }36 waiting[id] = continuation37 return false38 }39 if alreadyCancelled { continuation.resume(throwing: CancellationError()) }40 }41 } onCancel: {42 let continuation = lock.withLock { () -> CheckedContinuation<Void, any Error>? in43 cancelled.insert(id)44 return waiting.removeValue(forKey: id)45 }46 continuation?.resume(throwing: CancellationError())47 }48 }4950 /// Lets every pending sleep finish.51 func fire() {52 let pending = lock.withLock { () -> [CheckedContinuation<Void, any Error>] in53 defer { waiting.removeAll() }54 return Array(waiting.values)55 }56 for continuation in pending { continuation.resume() }57 }58}5960func eventually(_ condition: @Sendable () async throws -> Bool) async rethrows -> Bool {61 for _ in 0..<400 {62 if try await condition() { return true }63 try? await Task.sleep(for: .milliseconds(5))64 }65 return false66}6768struct SessionFixture {69 let database: NavigatorDatabase70 let profile: Profile71 let space: OrbitSpace72 let windows: [BrowserWindow]73 let groups: [TabGroup]7475 static func make(windowCount: Int = 2, saveWindows: Bool = true) async throws -> SessionFixture {76 let database = try await NavigatorDatabase.inMemory()77 let profile = Profile(name: "P", createdAt: Date(timeIntervalSince1970: 1))78 try await database.profiles.save(profile)79 let space = OrbitSpace(profileID: profile.id, name: "S", createdAt: Date(timeIntervalSince1970: 1), updatedAt: Date(timeIntervalSince1970: 1))80 try await database.spaces.save(space)81 let windows = (0..<windowCount).map { BrowserWindow(spaceID: space.id, order: $0) }82 if saveWindows { for window in windows { try await database.windows.save(window) } }83 return SessionFixture(database: database, profile: profile, space: space, windows: windows,84 groups: [TabGroup(spaceID: space.id, name: "G1"), TabGroup(spaceID: space.id, name: "G2")])85 }8687 func tab(_ window: Int = 0, title: String = "", order: Int = 0) -> Tab {88 Tab(windowID: windows[window].id, spaceID: space.id, title: title, order: order,89 createdAt: Date(timeIntervalSince1970: 10), lastActiveAt: Date(timeIntervalSince1970: 10))90 }91}9293func rowCount(_ database: NavigatorDatabase) async throws -> Int {94 try await database.sqlite.read { connection in95 let tables = try connection.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")96 .map { try $0.get("name", as: String.self) }97 return try tables.reduce(0) { total, table in98 total + (try connection.scalar("SELECT count(*) FROM \"\(table)\"", as: Int.self) ?? 0)99 }100 }101}102103@Suite struct SessionChangeCoalescerTests {104 let window = WindowID(), space = SpaceID()105 let date = Date(timeIntervalSince1970: 50)106107 private func tab(_ id: TabID = TabID(), title: String = "", group: TabGroupID? = nil, window other: WindowID? = nil) -> Tab {108 Tab(id: id, windowID: other ?? window, spaceID: space, groupID: group, title: title, createdAt: date, lastActiveAt: date)109 }110111 private func labels(_ changes: [SessionChange]) -> [String] { changes.map(SessionOrchestrator.label) }112113 @Test func repeatedTouchesKeepTheLastOne() {114 var coalescer = SessionChangeCoalescer()115 let id = TabID()116 for index in 0..<5 { coalescer.record(.touchTab(id: id, url: nil, title: "t\(index)", lastActiveAt: date)) }117 #expect(coalescer.count == 1 && coalescer.recordedCount == 5)118 guard case .touchTab(_, _, let title, _)? = coalescer.drain().first else { Issue.record("no touch"); return }119 #expect(title == "t4")120 #expect(coalescer.isEmpty && coalescer.recordedCount == 0)121 }122123 @Test func aFullSaveSupersedesEarlierPartialChanges() {124 var coalescer = SessionChangeCoalescer()125 let id = TabID()126 coalescer.record(.touchTab(id: id, url: nil, title: "a", lastActiveAt: date))127 coalescer.record(.setSessionState(id: id, state: Data([1])))128 coalescer.record(.closeTab(id: id, at: date))129 coalescer.record(.saveTab(tab(id, title: "full")))130 coalescer.record(.touchTab(id: id, url: nil, title: "after", lastActiveAt: date))131 #expect(labels(coalescer.drain()) == ["saveTab", "touchTab"])132 }133134 @Test func consecutiveSavesOfTheSameTabCollapse() {135 var coalescer = SessionChangeCoalescer()136 let id = TabID()137 coalescer.record(.saveTab(tab(id, title: "1")))138 coalescer.record(.saveWindow(BrowserWindow(id: window, spaceID: space)))139 coalescer.record(.saveTab(tab(id, title: "2")))140 let batch = coalescer.drain()141 #expect(labels(batch) == ["saveTab", "saveWindow"])142 guard case .saveTab(let saved) = batch[0] else { Issue.record("no save"); return }143 #expect(saved.title == "2")144 }145146 @Test func savesThatChangeOwnerAreNotMoved() {147 var coalescer = SessionChangeCoalescer()148 let id = TabID(), other = WindowID(), group = TabGroupID()149 coalescer.record(.saveTab(tab(id)))150 coalescer.record(.saveWindow(BrowserWindow(id: other, spaceID: space)))151 coalescer.record(.saveTab(tab(id, window: other))) // depends on the window saved just before152 coalescer.record(.saveGroup(TabGroup(id: group, spaceID: space, name: "G")))153 coalescer.record(.saveTab(tab(id, group: group, window: other))) // depends on the group154 #expect(labels(coalescer.drain()) == ["saveTab", "saveWindow", "saveTab", "saveGroup", "saveTab"])155 }156157 @Test func aReorderBetweenTwoSavesKeepsBoth() {158 var coalescer = SessionChangeCoalescer()159 let id = TabID()160 coalescer.record(.saveTab(tab(id)))161 coalescer.record(.reorderTabs(window: window, ids: [id]))162 coalescer.record(.saveTab(tab(id, title: "later order wins")))163 #expect(labels(coalescer.drain()) == ["saveTab", "reorderTabs", "saveTab"])164 }165166 @Test func reordersCollapseOnlyWhenTheNewListCoversTheOld() {167 let a = TabID(), b = TabID(), c = TabID()168 var coalescer = SessionChangeCoalescer()169 coalescer.record(.reorderTabs(window: window, ids: [a, b]))170 coalescer.record(.reorderTabs(window: window, ids: [b, a, c]))171 #expect(coalescer.count == 1)172 coalescer.record(.reorderTabs(window: window, ids: [c]))173 #expect(coalescer.count == 2)174 }175176 @Test func selectionsAndClosesCollapse() {177 var coalescer = SessionChangeCoalescer()178 let a = TabID(), b = TabID()179 coalescer.record(.selectTab(window: window, tab: a))180 coalescer.record(.selectTab(window: window, tab: b))181 coalescer.record(.closeTab(id: a, at: date))182 coalescer.record(.closeTab(id: a, at: date.addingTimeInterval(5)))183 coalescer.record(.closeWindow(id: window, at: date))184 coalescer.record(.closeWindow(id: window, at: date))185 let batch = coalescer.drain()186 #expect(labels(batch) == ["selectTab", "closeTab", "closeWindow"])187 guard case .selectTab(_, let selected) = batch[0], case .closeTab(_, let closedAt) = batch[1] else { Issue.record("shape"); return }188 #expect(selected == b && closedAt == date)189 }190191 @Test func deletesDropPendingPartialChangesButKeepSaves() {192 var coalescer = SessionChangeCoalescer()193 let id = TabID()194 coalescer.record(.saveTab(tab(id)))195 coalescer.record(.touchTab(id: id, url: nil, title: "x", lastActiveAt: date))196 coalescer.record(.deleteTab(id))197 coalescer.record(.deleteTab(id))198 coalescer.record(.selectTab(window: window, tab: nil))199 coalescer.record(.deleteWindow(window))200 #expect(labels(coalescer.drain()) == ["saveTab", "deleteTab", "deleteWindow"])201 }202203 /// The property that matters: a coalesced batch leaves storage exactly as the original sequence does.204 @Test func coalescingNeverChangesTheStoredResult() async throws {205 var generator = SeededGenerator(state: 2026_11_25)206 var totalRecorded = 0, totalApplied = 0207 for _ in 0..<120 {208 let sequential = try await SessionFixture.make(saveWindows: false)209 let batched = try await NavigatorDatabase.inMemory()210 try await batched.profiles.save(sequential.profile)211 try await batched.spaces.save(sequential.space)212213 let tabIDs = (0..<5).map { _ in TabID() }214 var windowsAlive = Set<Int>(), groupsAlive = Set<Int>(), tabWindow: [Int: Int] = [:]215 var changes: [SessionChange] = []216 for step in 0..<Int.random(in: 10...45, using: &generator) {217 let stamp = Date(timeIntervalSince1970: Double(1_000 + step))218 let t = Int.random(in: 0..<5, using: &generator), w = Int.random(in: 0..<2, using: &generator)219 let g = Int.random(in: 0..<2, using: &generator)220 switch Int.random(in: 0..<14, using: &generator) {221 case 0, 1:222 var window = sequential.windows[w]223 window.selectedTabID = Bool.random(using: &generator) ? tabIDs[t] : nil224 window.agentPanelWidth = Double(step)225 changes.append(.saveWindow(window)); windowsAlive.insert(w)226 case 2, 3, 4:227 guard windowsAlive.contains(w) else { continue }228 let group = groupsAlive.contains(g) && Bool.random(using: &generator) ? sequential.groups[g].id : nil229 changes.append(.saveTab(Tab(id: tabIDs[t], windowID: sequential.windows[w].id, spaceID: sequential.space.id,230 groupID: group, title: "save\(step)", order: Int.random(in: 0..<9, using: &generator),231 sessionState: Data([UInt8(step % 250)]), createdAt: stamp, lastActiveAt: stamp)))232 tabWindow[t] = w233 case 5:234 var group = sequential.groups[g]235 group.name = "g\(step)"236 changes.append(.saveGroup(group)); groupsAlive.insert(g)237 case 6, 7: changes.append(.touchTab(id: tabIDs[t], url: URL(string: "https://example.com/\(step)"), title: "touch\(step)", lastActiveAt: stamp))238 case 8: changes.append(.setSessionState(id: tabIDs[t], state: Bool.random(using: &generator) ? Data([UInt8(step % 250), 7]) : nil))239 case 9: changes.append(.selectTab(window: sequential.windows[w].id, tab: Bool.random(using: &generator) ? tabIDs[t] : nil))240 case 10: changes.append(.reorderTabs(window: sequential.windows[w].id, ids: tabIDs.shuffled(using: &generator).prefix(Int.random(in: 1...5, using: &generator)).map { $0 }))241 case 11: changes.append(Bool.random(using: &generator) ? .closeTab(id: tabIDs[t], at: stamp) : .closeWindow(id: sequential.windows[w].id, at: stamp))242 case 12:243 changes.append(.deleteTab(tabIDs[t])); tabWindow[t] = nil244 default:245 if Bool.random(using: &generator) {246 changes.append(.deleteWindow(sequential.windows[w].id)); windowsAlive.remove(w)247 for (tab, owner) in tabWindow where owner == w { tabWindow[tab] = nil }248 } else {249 changes.append(.deleteGroup(sequential.groups[g].id)); groupsAlive.remove(g)250 }251 }252 }253254 var coalescer = SessionChangeCoalescer()255 for change in changes {256 try await sequential.database.session.apply([change])257 coalescer.record(change)258 }259 let batch = coalescer.drain()260 #expect(batch.count <= changes.count)261 totalRecorded += changes.count; totalApplied += batch.count262 try await batched.session.apply(batch)263264 for id in tabIDs {265 #expect(try await sequential.database.tabs.tab(id) == batched.tabs.tab(id))266 }267 for window in sequential.windows {268 #expect(try await sequential.database.windows.window(window.id) == batched.windows.window(window.id))269 }270 for group in sequential.groups {271 #expect(try await sequential.database.tabGroups.group(group.id) == batched.tabGroups.group(group.id))272 }273 await sequential.database.close()274 await batched.close()275 }276 // The coalescer must actually coalesce on such sequences, or the test proves nothing useful.277 #expect(totalApplied < totalRecorded * 9 / 10)278 }279}280281@Suite struct SessionOrchestratorTests {282 @Test func changesAreWrittenOnlyAfterTheDebounce() async throws {283 let fixture = try await SessionFixture.make()284 let sleeper = ManualSleeper()285 let orchestrator = SessionOrchestrator(database: fixture.database, debounce: .milliseconds(400), sleep: sleeper.sleep)286 let tab = fixture.tab()287 await orchestrator.record(.saveTab(tab))288 for index in 0..<4 {289 await orchestrator.record(.touchTab(id: tab.id, url: URL(string: "https://example.com"), title: "title \(index)", lastActiveAt: tab.lastActiveAt))290 }291 #expect(await eventually { sleeper.waitingCount == 1 })292 #expect(try await fixture.database.tabs.tab(tab.id) == nil)293 #expect(await orchestrator.pendingCount == 2)294 #expect(sleeper.requested.allSatisfy { $0 <= .milliseconds(400) && $0 >= .zero })295 #expect(sleeper.requested.count == 5) // every change pushes the flush back296297 sleeper.fire()298 #expect(await eventually { await orchestrator.pendingCount == 0 })299 #expect(try await eventually { try await fixture.database.tabs.tab(tab.id)?.title == "title 3" })300 }301302 @Test func flushReportsWhatWasCoalesced() async throws {303 let fixture = try await SessionFixture.make()304 let orchestrator = SessionOrchestrator(database: fixture.database, sleep: ManualSleeper().sleep)305 let tab = fixture.tab()306 await orchestrator.record([.saveTab(tab), .selectTab(window: tab.windowID, tab: tab.id), .selectTab(window: tab.windowID, tab: nil),307 .selectTab(window: tab.windowID, tab: tab.id)])308 let report = await orchestrator.flush()309 #expect(report == SessionFlushReport(recorded: 4, applied: 2, failures: []))310 #expect(try await fixture.database.windows.window(tab.windowID)?.selectedTabID == tab.id)311 #expect(await orchestrator.flush() == .nothing)312 }313314 @Test func theObserverSeesAutomaticFlushes() async throws {315 let fixture = try await SessionFixture.make()316 let sleeper = ManualSleeper()317 let orchestrator = SessionOrchestrator(database: fixture.database, sleep: sleeper.sleep)318 let (stream, continuation) = AsyncStream<SessionFlushReport>.makeStream()319 await orchestrator.setFlushObserver { continuation.yield($0) }320 await orchestrator.record(.saveTab(fixture.tab()))321 #expect(await eventually { sleeper.waitingCount == 1 })322 sleeper.fire()323 var iterator = stream.makeAsyncIterator()324 #expect(await iterator.next() == SessionFlushReport(recorded: 1, applied: 1, failures: []))325 }326327 @Test func oneBadChangeDoesNotBlockTheOthers() async throws {328 let fixture = try await SessionFixture.make()329 let orchestrator = SessionOrchestrator(database: fixture.database, sleep: ManualSleeper().sleep)330 let good = fixture.tab(title: "good")331 let orphan = Tab(windowID: WindowID(), spaceID: fixture.space.id, title: "orphan")332 await orchestrator.record([.saveTab(good), .saveTab(orphan)])333 let report = await orchestrator.flush()334 #expect(report.applied == 1 && report.failures.count == 1)335 #expect(report.failures[0].hasPrefix("saveTab:"))336 #expect(!report.failures[0].contains("orphan")) // no page data in failure reports337 #expect(try await fixture.database.tabs.tab(good.id)?.title == "good")338 }339340 @Test func shutdownFlushesAndMarksTheSessionClean() async throws {341 let fixture = try await SessionFixture.make()342 _ = try await fixture.database.session.beginSession()343 #expect(try await !fixture.database.session.isMarkedClean())344 let orchestrator = SessionOrchestrator(database: fixture.database, sleep: ManualSleeper().sleep)345 let tab = fixture.tab()346 await orchestrator.record(.saveTab(tab))347 try await orchestrator.shutdown()348 #expect(try await fixture.database.session.isMarkedClean())349 #expect(try await fixture.database.tabs.tab(tab.id) != nil)350 }351352 @Test func ghostChangesNeverReachTheQueueOrTheDisk() async throws {353 let fixture = try await SessionFixture.make()354 let ghostProfile = ProfileID(), ghostSpace = SpaceID(), ghostWindow = WindowID()355 fixture.database.ghosts.declare(profile: ghostProfile, spaces: [ghostSpace], windows: [ghostWindow])356 let orchestrator = SessionOrchestrator(database: fixture.database, sleep: ManualSleeper().sleep)357 let before = try await rowCount(fixture.database)358359 let ghostTab = Tab(windowID: ghostWindow, spaceID: ghostSpace, url: URL(string: "https://private.example"), title: "secret")360 let ghostGroup = TabGroup(spaceID: ghostSpace, name: "secret group")361 let undeclared = TabID()362 await orchestrator.declareGhostTabs([undeclared])363 await orchestrator.record([364 .saveWindow(BrowserWindow(id: ghostWindow, spaceID: ghostSpace)), .saveTab(ghostTab), .saveGroup(ghostGroup),365 .touchTab(id: ghostTab.id, url: URL(string: "https://private.example/2"), title: "secret 2", lastActiveAt: .now),366 .setSessionState(id: ghostTab.id, state: Data([9])), .selectTab(window: ghostWindow, tab: ghostTab.id),367 .reorderTabs(window: ghostWindow, ids: [ghostTab.id]), .touchTab(id: undeclared, url: nil, title: "secret 3", lastActiveAt: .now),368 .closeTab(id: ghostTab.id, at: .now), .deleteGroup(ghostGroup.id), .deleteTab(ghostTab.id),369 .closeWindow(id: ghostWindow, at: .now), .deleteWindow(ghostWindow),370 ])371 #expect(await orchestrator.pendingCount == 0)372 #expect(await orchestrator.flush() == .nothing)373 #expect(try await rowCount(fixture.database) == before)374375 // A tab dragged from the private window into a normal one is saved like any other.376 var adopted = ghostTab377 adopted.windowID = fixture.windows[0].id; adopted.spaceID = fixture.space.id378 await orchestrator.record(.saveTab(adopted))379 #expect(await orchestrator.flush().applied == 1)380 }381}382383@Suite struct SessionRestorerTests {384 private func session(_ fixture: SessionFixture, windows: [BrowserWindow], tabs: [WindowID: [Tab]], spaces: [OrbitSpace]? = nil,385 clean: Bool = true) -> RestoredSession {386 RestoredSession(profiles: [fixture.profile], spaces: spaces ?? [fixture.space], groups: [], windows: windows,387 tabsByWindow: tabs, previousShutdownWasClean: clean)388 }389390 @Test func firstLaunchHasNothingToRestore() async throws {391 let fixture = try await SessionFixture.make(windowCount: 0)392 let model = SessionRestorer.launchModel(session: session(fixture, windows: [], tabs: [:]),393 launch: SessionLaunchInfo(isFirstLaunch: true, previousShutdownWasClean: true))394 #expect(model.mode == .firstLaunch && model.windows.isEmpty && model.defaultSpaceID == fixture.space.id)395 #expect(!model.requiresRestoreConfirmation)396 }397398 @Test func aCleanSessionIsRestoredAndOnlyVisibleTabsLoad() async throws {399 let fixture = try await SessionFixture.make()400 let a = fixture.tab(0, order: 0), b = fixture.tab(0, order: 1), c = fixture.tab(1)401 var first = fixture.windows[0], second = fixture.windows[1]402 first.selectedTabID = b.id403 second.selectedTabID = TabID() // points at a tab that no longer exists404 let model = SessionRestorer.launchModel(session: session(fixture, windows: [first, second], tabs: [first.id: [a, b], second.id: [c]]),405 launch: SessionLaunchInfo(isFirstLaunch: false, previousShutdownWasClean: true))406 #expect(model.mode == .restored && model.tabCount == 3 && model.windowsToClose.isEmpty)407 #expect(model.windows[0].tabsToLoad == [b.id])408 #expect(model.windows[1].window.selectedTabID == c.id && model.windows[1].tabsToLoad == [c.id])409 #expect(model.defaultSpaceID == fixture.space.id)410 }411412 @Test func afterACrashNothingLoadsUntilTheUserConfirms() async throws {413 let fixture = try await SessionFixture.make()414 let a = fixture.tab(0)415 var window = fixture.windows[0]416 window.selectedTabID = a.id417 let model = SessionRestorer.launchModel(session: session(fixture, windows: [window], tabs: [window.id: [a]], clean: false),418 launch: SessionLaunchInfo(isFirstLaunch: false, previousShutdownWasClean: false))419 #expect(model.mode == .crashRecovery && model.requiresRestoreConfirmation)420 #expect(model.windows.count == 1 && model.windows[0].tabsToLoad.isEmpty)421 let confirmed = SessionRestorer.confirmingRestore(model)422 #expect(confirmed.mode == .restored && confirmed.windows[0].tabsToLoad == [a.id])423 }424425 @Test func splitsAreValidatedAndTheirPanesLoad() async throws {426 let fixture = try await SessionFixture.make()427 let a = fixture.tab(0, order: 0), b = fixture.tab(0, order: 1), c = fixture.tab(0, order: 2)428 var window = fixture.windows[0]429 window.selectedTabID = a.id430 window.split = SplitLayout(panes: [a.id, TabID(), c.id], focusedPane: 2)431 let launch = SessionLaunchInfo(isFirstLaunch: false, previousShutdownWasClean: true)432 let model = SessionRestorer.launchModel(session: session(fixture, windows: [window], tabs: [window.id: [a, b, c]]), launch: launch)433 #expect(model.windows[0].window.split?.panes == [a.id, c.id])434 #expect(model.windows[0].tabsToLoad == [a.id, c.id] && model.windows[0].window.selectedTabID == c.id)435 // iPhone: no split at all.436 let phone = SessionRestorer.launchModel(session: session(fixture, windows: [window], tabs: [window.id: [a, b, c]]), launch: launch, paneLimit: 1)437 #expect(phone.windows[0].window.split == nil && phone.windows[0].tabsToLoad == [a.id])438 }439440 @Test func emptyWindowsAreClosedAndArchivedSpacesWait() async throws {441 let fixture = try await SessionFixture.make()442 var archived = OrbitSpace(profileID: fixture.profile.id, name: "Old", isArchived: true)443 archived.order = 5444 let archivedWindow = BrowserWindow(spaceID: archived.id)445 let archivedTab = Tab(windowID: archivedWindow.id, spaceID: archived.id)446 let kept = fixture.tab(1)447 let model = SessionRestorer.launchModel(448 session: session(fixture, windows: [fixture.windows[0], fixture.windows[1], archivedWindow],449 tabs: [fixture.windows[1].id: [kept], archivedWindow.id: [archivedTab]], spaces: [fixture.space, archived]),450 launch: SessionLaunchInfo(isFirstLaunch: false, previousShutdownWasClean: true))451 #expect(model.windows.map(\.id) == [fixture.windows[1].id])452 #expect(model.windowsToClose == [fixture.windows[0].id])453 }454455 @Test func aFreshStartKeepsThePreviousWindowsReopenable() async throws {456 let fixture = try await SessionFixture.make()457 let tab = fixture.tab(0)458 try await fixture.database.tabs.save(tab)459 _ = try await fixture.database.session.beginSession()460 try await fixture.database.session.markCleanShutdown()461462 let model = try await SessionRestorer.launch(database: fixture.database, policy: .startFresh)463 #expect(model.mode == .fresh && model.windows.isEmpty)464 #expect(Set(model.windowsToClose) == Set(fixture.windows.map(\.id)))465 #expect(try await fixture.database.windows.openWindows().isEmpty)466 #expect(try await fixture.database.windows.recentlyClosed().contains { $0.window.id == tab.windowID && $0.tabs.count == 1 })467 }468469 @Test func launchReadsStorageAndDetectsACrash() async throws {470 let fixture = try await SessionFixture.make()471 var window = fixture.windows[0]472 let tab = fixture.tab(0, title: "Kept")473 window.selectedTabID = tab.id474 try await fixture.database.session.apply([.saveWindow(window), .saveTab(tab)])475 _ = try await fixture.database.session.beginSession() // previous run starts… and never shuts down cleanly476477 let model = try await SessionRestorer.launch(database: fixture.database)478 #expect(model.mode == .crashRecovery)479 #expect(model.windows.map(\.id) == [window.id]) // the empty second window was dropped480 #expect(model.windows[0].tabs.map(\.title) == ["Kept"])481 #expect(model.windows[0].tabs.allSatisfy { $0.lifecycle == .dormant })482 }483}484