// 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. import CoreGraphics import CottonKit import Foundation import SwiftUI import XCTest @testable import CottonUI @MainActor final class LaunchHomeTests: XCTestCase { private var suite: String! private var defaults: UserDefaults! private var own: HeldDatabase! private var garden: HeldDatabase! private var attic: HeldDatabase! private var shed: HeldDatabase! override func setUp() async throws { 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) } override func tearDown() async throws { 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. private struct Window { let scene: DatabaseScene let home: HomeModel let databases: DatabasesModel let aims: Count } private func 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 in await home.prepare(shown: id, calls: calls) } let aims = Count() scene.aimed = { [home, calls = scene.calls] _ in aims.n += 1 home.turnToAsked() let asked = calls.id Task { @MainActor in await home.readAgainIfAskedElsewhere(shown: asked) } } return Window(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). private func launch(_ window: Window) -> Task { Task { @MainActor in let 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. private struct Frame: Equatable { let splash: Bool let fan: [String]? } /// The fan's cards in the core's order (`shell.fan`): by name, Home among them. private static func dealt(_ tools: [String]) -> [String] { (tools.filter { $0 != "home" } + ["home"]).sorted { $0.localizedStandardCompare($1) == .orderedAscending } } private func 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 = try SourceSweep.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.. Bool) async throws { let deadline = ContinuousClock.now + .seconds(10) while !done() { guard ContinuousClock.now < deadline else { XCTFail("never: \(what)") return } try await Task.sleep(for: .milliseconds(5)) } } private static func picture() throws -> CGImage { let context = try XCTUnwrap(CGContext( data: nil, width: 2, height: 2, bitsPerComponent: 8, bytesPerRow: 8, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)) return try XCTUnwrap(context.makeImage()) } /// A database's page as the core answers it, its tools in `order`. private static func home(_ order: [String]) -> String { TodayAnswerJSON.answer(arrangement: TodayAnswerJSON.arrangement(order)) } } /// A count a closure can add to. @MainActor private final class Count { 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. private final class LaunchCore: CottonCalling, @unchecked Sendable { private let lock = NSLock() private var _home: [String?: String] = [:] private var _refuse = false private var reads: [String?] = [] private var held: String?? private var waiting: CheckedContinuation? 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? in held = nil defer { waiting = nil } return waiting } resume?.resume() } func homeReads(_ database: String?) -> Int { lock.withLock { reads.filter { $0 == database }.count } } func callRaw(_ method: String, requestJSON: String) async throws -> 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) in let now = lock.withLock { () -> Bool in if held == nil { return true } waiting = done return false } 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)}"# } guard let 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. private final class GrowingHeld: DatabasesCalling, @unchecked Sendable { private let lock = NSLock() private var _held: [HeldDatabase] init(_ held: [HeldDatabase]) { _held = held } var held: [HeldDatabase] { get { lock.withLock { _held } } set { lock.withLock { _held = newValue } } } func databases() async throws -> [HeldDatabase] { held } func show(_ databaseId: String) async throws {} func hide(_ databaseId: String) async throws {} func create(name: String, toolkit: DatabaseToolkit) async throws -> HeldDatabase { throw CottonCallError(code: "refused", message: "No.") } }