// A cold launch on the phone is the splash — the logo on the paper — then// Home whole, at full, in one frame (295 B, walker294 on a real-sized// household of 13 databases: the splash's logo for 1.7 s, then bare paper// for up to a second, then a faded Home with the logo fading over it, its// fan in an order of its own and no Home, then Home; Home's card blinking out of// the fan while the caps' arc grew as the databases arrived).//// THE CAUSES. (1) The splash came down as Home's board APPEARED, not once it// was read, and faded over 250 ms over whatever stood under it: the ghost.// (2) The fan laid a plain view of the ground over the key window, above the// splash, and held it for at most 900 ms: the bare paper; and its wait// swallowed its own cancellation, so a fan rebuilt under it lifted it at// once. (3) The list arriving moved the shown id from nothing to the// personal database's and rebuilt the fan, and the board read the personal// database before the list named the one shown. (4) Every read of you made a new// face, which no print of Home's card matched, and the arc drew a card with no// print blank until it was printed again. (5) Every move of the held list// aimed the window again. The fix: the splash stands until the shown// database's Home read has come back and the fan stands whole under it// (`FanLaunchRule`), then goes in one frame (`SplashOverlay.cut`); nothing// else covers the window; the fan is keyed on the shown database, not the// raw id, and the board reads only once the list names it; Home keeps its face while its person, name and print do; a card// keeps its last print until the new one is drawn; a seed of a window// already aimed and pinned does nothing. Synthetic names and ids throughout.importCoreGraphicsimportCottonKitimportFoundationimportSwiftUIimport XCTest@testable importCottonUI@MainActorfinalclassLaunchHomeTests: XCTestCase {privatevar suite: String!privatevar defaults: UserDefaults!privatevar own: HeldDatabase!privatevar garden: HeldDatabase!privatevar attic: HeldDatabase!privatevar shed: HeldDatabase!overridefunc setUp() asyncthrows { suite = "LaunchHomeTests-\(UUID().uuidString)" defaults = UserDefaults(suiteName: suite)let run = UUID().uuidString.prefix(8) own = HeldDatabase(databaseId: "own-\(run)", name: "Personal", kind: .personal) garden = HeldDatabase(databaseId: "garden-\(run)", name: "Garden", kind: .shared) attic = HeldDatabase(databaseId: "attic-\(run)", name: "Attic", kind: .shared) shed = HeldDatabase(databaseId: "shed-\(run)", name: "Shed", kind: .shared) }overridefunc tearDown() asyncthrows { defaults.removePersistentDomain(forName: suite) }/// The window at a cold launch, wired as `WindowSession` wires one — but/// nothing read yet: the held list and Home are read after the first/// frame, as the window's own tasks read them.privatestructWindow {let scene: DatabaseScenelet home: HomeModellet databases: DatabasesModellet aims: Count }privatefunc window(_ core: LaunchCore, held: GrowingHeld, restored: String? = nil) -> Window {let databases = DatabasesModel(source: held, defaults: defaults)let scene = DatabaseScene(shownId: restored)let screens = DatabaseScopedCore(underlying: core, shown: scene.calls)let home = HomeModel(core: screens, unscoped: core, toasts: ToastCenter(scheduler: ManualToastScheduler())) home.askingDatabase = { [calls = scene.calls] in calls.id } scene.prepare = { [home] id, calls inawait home.prepare(shown: id, calls: calls) }let aims = Count() scene.aimed = { [home, calls = scene.calls] _ in aims.n += 1 home.turnToAsked()let asked = calls.idTask { @MainActor inawait home.readAgainIfAskedElsewhere(shown: asked) } }returnWindow(scene: scene, home: home, databases: databases, aims: aims) }/// What the window's views do at a launch, after the first frame: the/// held list read and the window seeded from it (`DatabaseSceneWiring`),/// and the board's read once the list names the shown database/// (`HomeBoard`: never before, and for that database).privatefunc launch(_ window: Window) -> Task<Void, Never> {Task { @MainActor inlet shown = await window.databases.refreshList()await window.scene.seed(from: window.databases)let named = window.home.shownDatabase(scene: window.scene, in: window.databases)if named.known { await window.home.readAgainIfAskedElsewhere(shown: named.database) }await window.databases.refreshAround(shown: shown) } }/// One frame of the launch as the person sees it: the splash, or Home's/// fan in its order.privatestructFrame: Equatable {let splash: Boollet fan: [String]? }/// The fan's cards in the core's order (`shell.fan`): by name, Home among them.privatestaticfunc dealt(_ tools: [String]) -> [String] { (tools.filter { $0 != "home" } + ["home"]).sorted { $0.localizedStandardCompare($1) == .orderedAscending } }privatefunc fan(_ window: Window) -> [String]? { window.home.drawnTiles(scene: window.scene, in: window.databases).map { Self.dealt($0.tools) } }// ── The splash ───────────────────────────────────────────────────────/// RULE: the splash stands until Home is read — the shown database's read has come back, its settled card's page drawn, every card in sight printed — and never past the boot's own ceiling (295 B).func testTheSplashStandsUntilHomeIsRead() {for read in [false, true] {for drawn in [false, true] {for printed in [false, true] { XCTAssertEqual(FanLaunchRule.stands(read: read, settledDrawn: drawn, printsInSight: printed), read && drawn && printed, "read \(read), drawn \(drawn), printed \(printed)") } } } XCTAssertEqual(FanLaunchRule.ceiling, .milliseconds(AUTH_INIT_FALLBACK_MS), "the boot's ceiling, never the fan's turn") }/// RULE: a read come back is not yet a fan laid out from it — the splash stands while the order the board draws is not the order the read holds; a read that brought no order lays out none (295 B, the launch walk: read true over a fan of Home and Tools, dealt again 0.2–2 s after the splash).func testTheSplashWaitsForTheFanLaidOutFromTheRead() { XCTAssertFalse(FanLaunchRule.laidOut(nil, from: ["goals", "mood"]), "the order not yet on the board") XCTAssertFalse(FanLaunchRule.laidOut(["notes"], from: ["goals", "mood"]), "another order on the board") XCTAssertTrue(FanLaunchRule.laidOut(["goals", "mood"], from: ["goals", "mood"])) XCTAssertTrue(FanLaunchRule.laidOut(nil, from: nil), "a refused read with nothing to lay out") }/// RULE: the splash goes in ONE transaction that animates nothing — no fade of its own and none a caller's change carries — so no frame shows it over a faded Home (295 B, walker294: a ghost Home under a fading logo).func testTheSplashGoesInOneFrame() throws {let cut = SplashOverlay.cut XCTAssertTrue(cut.disablesAnimations) XCTAssertNil(cut.animation)let root = trySourceSweep.mustRead("apps/cotton/Sources/CottonUI/Boot/RootView.swift", ownedBy: "rough")let code = SourceSweep.withoutComments(root)let start = try XCTUnwrap(code.range(of: "public struct SplashOverlay"))let end = try XCTUnwrap(code.range(of: "\n}\n", range: start.upperBound..<code.endIndex))let body = String(code[start.lowerBound..<end.lowerBound]) XCTAssertFalse(body.contains(".transition("), "the splash has no transition") XCTAssertFalse(body.contains(".animation("), "the splash animates nothing") XCTAssertTrue(body.contains("withTransaction(Self.cut)"), "it goes in the cut") }/// RULE: nothing but the splash covers the window at a launch — no source lays a view over a window (295 B, walker294: a view of the ground over the key window hid the splash's logo, bare paper for up to a second). The one view added to a window is the page painter's, which stands beyond the window's right edge (`PagePainter.origin`).func testNoViewCoversTheWindow() throws {let pattern = try NSRegularExpression(pattern: #"\bwindow\??\.addSubview\("#)var adding: [String] = []for (name, text) intrySourceSweep.swiftSources() {let code = SourceSweep.withoutComments(text)if pattern.firstMatch(in: code, range: NSRange(code.startIndex..., in: code)) != nil { adding.append(name) } } XCTAssertEqual(adding, ["CottonUI/Surfaces/Board/PagePictures.swift"], "only the page painter adds a view to a window") }// ── The launch, frame by frame ───────────────────────────────────────/// GUARD: between the splash's last frame and Home's first no frame is bare or another arrangement — the fan's first laid-out order is its settled order, across the held list arriving and more databases arriving after; Home's card is in every fan frame; databases arriving don't change the fan: the window is not aimed again and Home is not read again./// RULE: the fan is laid out once, under the splash, from Home's read; databases arriving after launch change the caps' arc only (295 B, walker294).func testTheFanIsLaidOutOnceAcrossALaunch() asyncthrows {let core = LaunchCore() core.home[nil] = Self.home(["goals", "journal", "mood", "notes"])let held = GrowingHeld([own, garden])let window = window(core, held: held) core.hold(nil) XCTAssertFalse(window.home.shownDatabase(scene: window.scene, in: window.databases).known,"before the held list is read, no database is named and the board reads nothing")let launching = launch(window)var seen: [Frame] = []var splash = truevar released = falsevar board: [String]?for step in0..<600 {if step == 60 { XCTAssertTrue(splash, "the splash stands while Home's read is out") core.release() released = true }if step == 300 {// Two databases arrive after the launch: the caps' arc grows. held.held = [own, garden, attic, shed] _ = await window.databases.refreshList()await window.scene.seed(from: window.databases) }// The board lays out the order its host handed it a step ago:// the read is seen a frame before its order arrives (`homeRead`).let model = window.home.drawnTiles(scene: window.scene, in: window.databases)?.toolslet read = window.home.readShown(scene: window.scene, in: window.databases) && FanLaunchRule.laidOut(board, from: model)if splash, FanLaunchRule.stands(read: read, settledDrawn: true, printsInSight: true) { XCTAssertTrue(released, "never before the read has come back") splash = false }let frame = Frame(splash: splash, fan: splash ? nil : board.map { Self.dealt($0) })if frame != seen.last { seen.append(frame) } board = modelawaitTask.yield() }await launching.value XCTAssertEqual(window.databases.held.count, 4)let home = seen.filter { !$0.splash } XCTAssertEqual(seen.first?.splash, true, "the launch opens on the splash") XCTAssertEqual(home.count, 1, "Home is one frame, laid out once: \(seen)") XCTAssertEqual(home.first?.fan, fan(window), "the fan's first laid-out order is its settled order")for each in home { XCTAssertTrue(each.fan?.contains("home") == true, "Home's card in every fan frame: \(each)") } XCTAssertEqual(seen.count, 2, "the splash, then Home — nothing between: \(seen)") XCTAssertEqual(core.homeReads(nil), 1, "Home read once: not again as databases arrived") XCTAssertEqual(window.aims.n, 1, "the window aimed once: databases arriving aim nothing") }/// RULE: a phone reopened on a shared database reads that database's Home, never the personal one's first — the board does not read before the held list names the database shown, and the calls' aim reads the one named (295 B).func testALaunchOntoARestoredDatabaseReadsItAlone() asyncthrows {let core = LaunchCore() core.home[nil] = Self.home(["notes"]) core.home[garden.databaseId] = Self.home(["goals", "mood"])let window = window(core, held: GrowingHeld([own, garden]), restored: garden.databaseId) XCTAssertFalse(window.home.readShown(scene: window.scene, in: window.databases))await launch(window).valuetryawait until("the read of the database shown has come back") { window.home.readShown(scene: window.scene, in: window.databases) } XCTAssertEqual(window.home.drawnTiles(scene: window.scene, in: window.databases)?.tools, ["goals", "mood"],"the database shown, from its own read") XCTAssertEqual(core.homeReads(nil), 0, "no read of the personal database") XCTAssertEqual(core.homeReads(garden.databaseId), 1, "one read of the database shown") }/// RULE: a refused read is a read come back — the splash comes down and the page says it could not read — never a splash held to the ceiling (295 B).func testARefusedReadStillTakesTheSplashDown() asyncthrows {let core = LaunchCore() core.refuse = truelet window = window(core, held: GrowingHeld([own]))await launch(window).valuetryawait until("the read of the database shown has come back") { window.home.readShown(scene: window.scene, in: window.databases) } XCTAssertTrue(window.home.bandUnreadable) }// ── Home ───────────────────────────────────────────────────────────────/// RULE: Home's card keeps its face while its person, name and print do — a read of you that names the same three draws nothing again, so the fan's print of Home's card still matches and Home never blinks out; another name, print or person, or a print not yet decoded, is read again (295 B, walker294).func testMeKeepsItsFaceAcrossReads() throws {let me = HomeRead() XCTAssertTrue(me.differs(name: "Example Person", print: "print-1", seed: "person-1"), "nothing held yet")let face = HomeFace(name: "Example Person", picture: trySelf.picture(), seed: "person-1") me.take(face, print: "print-1") XCTAssertNotEqual(face, HomeFace(name: "Example Person", picture: trySelf.picture(), seed: "person-1"),"a print decoded again is a new face") XCTAssertFalse(me.differs(name: "Example Person", print: "print-1", seed: "person-1"), "so the same is not taken again") XCTAssertTrue(me.differs(name: "Another Name", print: "print-1", seed: "person-1")) XCTAssertTrue(me.differs(name: "Example Person", print: "print-2", seed: "person-1")) XCTAssertTrue(me.differs(name: "Example Person", print: "print-1", seed: "person-2")) me.take(HomeFace(name: "Example Person", picture: nil, seed: "person-1"), print: "print-1") XCTAssertTrue(me.differs(name: "Example Person", print: "print-1", seed: "person-1"), "a print not decoded is tried again") me.take(HomeFace(name: "Example Person", picture: nil, seed: "person-1"), print: nil) XCTAssertFalse(me.differs(name: "Example Person", print: nil, seed: "person-1"), "no print: the initials stand") }// ── Fixtures ─────────────────────────────────────────────────────────/// Waits until `done` holds. The bound is a hang guard, not a timing: fifty/// yields were the wait once, and on a loaded CI Mac the read had not come/// back in fifty (swift-main #10212, 14 Nov 2026).privatefunc until(_ what: String, _ done: () -> Bool) asyncthrows {let deadline = ContinuousClock.now + .seconds(10)while !done() {guardContinuousClock.now < deadline else { XCTFail("never: \(what)")return }tryawaitTask.sleep(for: .milliseconds(5)) } }privatestaticfunc picture() throws -> CGImage {let context = try XCTUnwrap(CGContext( data: nil, width: 2, height: 2, bitsPerComponent: 8, bytesPerRow: 8, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))returntry XCTUnwrap(context.makeImage()) }/// A database's page as the core answers it, its tools in `order`.privatestaticfunc home(_ order: [String]) -> String {TodayAnswerJSON.answer(arrangement: TodayAnswerJSON.arrangement(order)) }}/// A count a closure can add to.@MainActorprivatefinalclassCount {var n = 0}/// A core that answers each database's `shell.today` from its own copy, by the/// `database` its calls name (none, the personal one), counts them, and can/// hold one database's read until released — a read that takes longer than/// a frame, as a real-sized Personal's does.privatefinalclassLaunchCore: CottonCalling, @unchecked Sendable {privatelet lock = NSLock()privatevar _home: [String?: String] = [:]privatevar _refuse = falseprivatevar reads: [String?] = []privatevar held: String??privatevar waiting: CheckedContinuation<Void, Never>?var home: [String?: String] { get { lock.withLock { _home } } set { lock.withLock { _home = newValue } } }var refuse: Bool { get { lock.withLock { _refuse } } set { lock.withLock { _refuse = newValue } } }func hold(_ database: String?) { lock.withLock { held = .some(database) } }func release() {let resume = lock.withLock { () -> CheckedContinuation<Void, Never>? in held = nildefer { waiting = nil }return waiting } resume?.resume() }func homeReads(_ database: String?) -> Int { lock.withLock { reads.filter { $0 == database }.count } }func callRaw(_ method: String, requestJSON: String) asyncthrows -> String {let request = (try? JSONDecoder().decode(JSONValue.self, from: Data(requestJSON.utf8))) ?? .object([:])let database = request.text("database")guard method == CottonMethod.shellToday else {return #"{"ok":false,"error":{"code":"unknown_method","message":"\#(method)"}}"# } lock.withLock { reads.append(database) }let holds = lock.withLock { held == .some(database) }if holds {await withCheckedContinuation { (done: CheckedContinuation<Void, Never>) inlet now = lock.withLock { () -> Boolinif held == nil { returntrue } waiting = donereturnfalse }if now { done.resume() } } }// A read that failed is still an answer: the core's line, and the band// says it could not read.if refuse {let failed = TodayAnswerJSON.answer( unreadable: true, failed: ["why": "unreadable", "line": "Home could not be read.", "keeps_trying": false])return #"{"ok":true,"data":\#(failed)}"# }guardlet answer = home[database] else { return #"{"ok":false,"error":{"code":"none","message":"none"}}"# }return #"{"ok":true,"data":\#(answer)}"# }func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {}func close() async {}}/// A held list that grows as copies arrive.privatefinalclassGrowingHeld: DatabasesCalling, @unchecked Sendable {privatelet lock = NSLock()privatevar _held: [HeldDatabase]init(_ held: [HeldDatabase]) { _held = held }var held: [HeldDatabase] { get { lock.withLock { _held } } set { lock.withLock { _held = newValue } } }func databases() asyncthrows -> [HeldDatabase] { held }func show(_ databaseId: String) asyncthrows {}func hide(_ databaseId: String) asyncthrows {}func create(name: String, toolkit: DatabaseToolkit) asyncthrows -> HeldDatabase {throwCottonCallError(code: "refused", message: "No.") }}