Cotton code
1852 lines · 100.1 KB · SwiftRaw
// The app's root: the splash, the gate, and the ONE platform branch.//// Design P6: ONE path rooted on Home, every surface opened over it, back// popping toward it. `Route` is the path type, so navigation is// `navigator.push(route)` and a deep link is `Route.deepLink(url)` — there is no// string in the middle and no router to configure.//// **One host over that one path**: `Boot/StackHost.swift`. The Mac's columns// host went with the Mac client (architect, 20 Oct 2026), so `hosts` below no// longer branches; everything this view hands the stack — the navigator, the// alarms, the toasts, the taps, the route deps, the shake sheet — wraps it.//// 4b lands the shell and a placeholder Home. 4d–4h fill `destination(for:)`,// which is deliberately TOTAL over `Route` with a placeholder arm rather than a// crash: a deep link or a notification may name a screen this build has not drawn// yet, and the honest answer is a page that says so, not a hang.//// **This view owns the ONE subscription.** `cotton_subscribe` takes a single// handler and a second call replaces the first, so a model that subscribed for// itself would silently unhook whichever came before it — which is what left// the join's own events going to nobody. So the app subscribes once, here, and// hands every `ClientEvent` to every model — boot, sync and home among them;// each one decides what is its.import CottonFacesimport CottonKitimport CottonValuesimport CottonVoiceimport SwiftUI/// The windows the app has open, for what the app does to every one of them:/// an event goes to each window's Home, and what moved the screens moves each/// window's answers. Held weakly — a closed Mac window is simply gone.@MainActorfinal class OpenWindows {    private struct Entry { weak var window: WindowSession? }    private var openWindows: [Entry] = []    func add(_ window: WindowSession) {        openWindows.removeAll { $0.window == nil }        openWindows.append(Entry(window: window))    }    var live: [WindowSession] { openWindows.compactMap(\.window) }    /// The first window: where a share or a notification tap lands.    var lead: WindowSession? { live.first }}/// What the APP has one of, whatever the number of windows: the gate, the/// sync loop, the held databases, the reminder and alarm passes,/// the share intake, capture. The phone's `RootView`/// makes one for itself; the Mac's host makes one and hands it to every/// window, so a second window is not a second sync loop (Cotton note/// 9e51c505: "More than one window is allowed. Each window is on its own/// database").@MainActor@Observablepublic final class AppSession {    @ObservationIgnored let core: any CottonCalling    @ObservationIgnored private let rawCore: any CottonCalling    /// Why writes are refused right now, if they are — the one fact    /// `GatedCore` reads on every `write`. Copied off `boot.readOnly` on    /// every gate transition.    @ObservationIgnored let writeGate: WriteGate    @ObservationIgnored let keyStore: any DeviceKeyStore    /// "Re-key this device": the successor key's slot beside `keyStore`, and    /// the app's way to open the core again on the promoted key.    @ObservationIgnored let rekey: DeviceRekey    /// This device's vault key, published at launch. Its own seam rather than a    /// line here, so what happens when the Keychain says no is decided in one    /// place for the launch and for every Reveal.    @ObservationIgnored let vault = VaultAccess()    @ObservationIgnored let boot: BootModel    @ObservationIgnored let sync: SyncModel    /// The recurring-todo pass. It must run on the first ready screen and on    /// every foreground after, whatever screen is up.    @ObservationIgnored let recurrences: RecurrenceMaterializer    /// The alarm reconciler. Here rather than on the Alarms screen: a    /// permission changed in Settings becomes visible on FOREGROUND, whatever    /// screen is up, and that is also when a one-shot that rang while the app    /// was away is noticed and switched off.    @ObservationIgnored let alarms: AlarmSyncModel    /// The databases this device holds — ONE list for the app, put in every    /// window's environment (`Surfaces/Databases/DatabasesModel.swift`).    @ObservationIgnored let databases: DatabasesModel    /// Notifications: the two tap tables, the reminder pass and the token.    @ObservationIgnored let notifications: NotificationsModel    /// Every terminal this app is listening to, handed down the environment:    /// a session's Terminal tab is a PUSHED screen, and a pushed screen is    /// never on the fan-out — `cotton_subscribe` takes one handler.    @ObservationIgnored let terminals = TerminalBus()    /// The share sheet's far side. It draws nothing either: the extension wrote    /// a mailbox entry in a process with no core, and this is the process that    /// has one. What it decides is a ROUTE, handed to the first window's taps.    @ObservationIgnored let shares: ShareIntake    /// The chat export a share-sheet arrival is carrying, until the import    /// screen takes it.    @ObservationIgnored let chatExports: ChatExportHandoff    /// A knock from the share extension, owed until the gate says the file is    /// open (`Boot/ShareArrivals.swift`).    @ObservationIgnored let shareArrivals = ShareArrivals()    /// Cotton Keys' passkey drain, mirror and identity store; nil in every    /// other app (`Boot/KeysPasskeys.swift`).    @ObservationIgnored private(set) var passkeys: KeysPasskeys?    /// Cotton Keys' Credential Exchange import (passkeys handed over by the    /// Passwords app); nil in every other app (`Boot/KeysImport.swift`).    @ObservationIgnored private(set) var keysImport: KeysImport?    /// The unlock window's card and its open windows (`Boot/UnlockAsks.swift`):    /// in every app, shown where the core answers one.    let unlockAsks: UnlockAsks    /// An assistant's ask to act as the owner (send mail, change a forward, invite guests), over the app (`asks.card`).    let assistantAsks: AssistantAsks    /// F: a recovery under way for this person, with Stop it, at the top of every app (`recovery.screen stop`).    let recoveryStop: RecoveryStop    /// The data key sealed tables open with, kept in the Keychain and asked    /// for by the core's line while missing (`Boot/SealedKeys.swift`).    let sealedKeys: SealedKeys    /// A new device asking to sign in to this person's Cotton, typed and    /// approved here (`Boot/SignInAsks.swift`): in every app, while connected.    let signInAsks: SignInAsks    /// Capture, composed ONCE per identity: the service the thoughts dock    /// writes through and the chip drain beside it. Built when the gate says    /// `.ready` and the boot read has named the workspace — never by a screen,    /// because `PendingLinks`' key is what keeps one person's chips off    /// another's file. Rebuilt if the pair changes (a first launch learns the    /// owner's id a beat after the workspace).    private(set) var capture: CaptureContext?    @ObservationIgnored let openWindows: OpenWindows    /// The owner's personal object this app backs up to, when its manifest    /// names one (Cotton): a phone holding its credential connects at every    /// launch before the gate's first read; any other stands on its own local    /// database, and Backup signs in (`Join/PersonalObject.swift`).    let personal: PersonalObject?    public init(        core rawCore: any CottonCalling,        keyStore: any DeviceKeyStore = KeychainDeviceKeyStore(),        successorKeyStore: any DeviceKeyStore = KeychainDeviceKeyStore(account: DeviceKey.successorAccount),        reopen: (@MainActor () async -> Void)? = nil,        boot: BootModel? = nil    ) {        // EVERY model below is handed the gated core, so a refused phone's        // writes are turned away in one place (`CottonKit/WriteGate.swift`)        // rather than checked by seventy-five callers. Reads, the sync and the        // stream pass straight through.        let gate = WriteGate()        let core: any CottonCalling = GatedCore(over: rawCore, gate: gate)        self.core = core        self.rawCore = rawCore        writeGate = gate        personal = PersonalObject.of(FlavourManifest.current, core: rawCore)        self.keyStore = keyStore        rekey = DeviceRekey(core: rawCore, current: keyStore, successor: successorKeyStore, reopen: reopen)        let openWindows = OpenWindows()        self.openWindows = openWindows        let chatExports = ChatExportHandoff()        self.chatExports = chatExports        self.boot = boot ?? BootModel(core: core)        let sync = SyncModel(core: core)        self.sync = sync        // The ONE invalidation hook: what moved the screens moves the cache —        // every window's.        sync.invalidating = { families in            for window in openWindows.live { window.answers.invalidate(families: families) }        }        let held = DatabasesModel(            source: CoreDatabases(core: core, deviceName: ThisPhone.deviceName()),            invites: CoreInvites(core: core),            members: CoreMembers(core: core),            readOwnerName: { try await core.callJSON(CottonMethod.readAccount).text("ownerName") },            readSyncs: { try await core.call(CottonMethod.readSyncStatus, as: SyncStatusRead.self).syncs }        )        databases = held        recurrences = RecurrenceMaterializer(core: core)        alarms = AlarmSyncModel(core: core)        // Every held database's reminders, each reconciled for its own        // (`ReminderDatabases`); nil until the held list is read, so no        // database's reminders are judged gone by a list merely empty.        let reminders = NotificationsModel(            core: core,            preferences: CoreNotificationPreferences(core: core),            databases: { held.held.isEmpty ? nil : held.held.filter { !$0.isPersonal }.map(\.databaseId) },            delivered: { await DeliveredPushes.read() },            reminds: ReminderApps.keeps)        notifications = reminders        shares = ShareIntake(            core: core,            // What this app files a PDF as: a book in Cotton Books, a            // document in Cotton (`ShareShelf`).            shelf: ShareShelf.ofThisApp(),            // Through the first window's `taps` rather than straight onto a            // stack: a share drained on a cold launch reaches the app long            // before the gate resolves, and it has to have somewhere to land.            navigate: { landing in                Task { @MainActor in                    guard let window = openWindows.lead else { return }                    // A chat export rides beside its route: the import                    // screen takes it when it is hosted.                    if landing.route == .messagesImport { chatExports.hold(landing.staged) }                    // A record of a deck tool the fan stands on opens on its                    // deck, at its card (`Navigator.fanBrings`): a book                    // shared in, or added from Books' Add a file, is its new                    // card, never a page over the deck; the first of many (a                    // Goodreads library, several books) on the tool's whole                    // view, Books' All.                    if case .tableRecord(let table, let id) = landing.route,                       window.navigator.fanBrings?(table, id, landing.many) == true { return }                    window.taps.arrive(landing.route)                }            },            // NO default on the seam, deliberately (`PendingLinkTrouble`'s            // rule): a dropped share has to go somewhere a person can find            // it. Both places, now that 4l's seam exists — Bugsink for the            // build in somebody's pocket, the console for the one on a            // desk.            report: { trouble in                Reporting.report(                    Report(                        kind: .unreadableAnswer,                        message: trouble.what,                        context: ["route": trouble.route]                    )                )                Log.write("share intake: \(trouble.route) — \(trouble.what)")                // AND the person, when the trouble carries a sentence for                // them. A drop that only reached Bugsink is a drop nobody                // in the room was told about: the walk of 15 Sep 2026                // shared a voice note, watched it not arrive, and got no                // word anywhere on the phone.                if let said = trouble.say {                    Task { @MainActor in openWindows.lead?.toasts.show(said, tone: .error) }                }            },            // What a share did that has no screen to open: a package's            // records, across tables, said in one line.            tell: { said in                Task { @MainActor in openWindows.lead?.toasts.show(said, tone: .success) }            }        )        unlockAsks = UnlockAsks(core: core, say: { said, tone in openWindows.lead?.toasts.show(said, tone: tone) })        assistantAsks = AssistantAsks(core: core, say: { said, tone in openWindows.lead?.toasts.show(said, tone: tone) })        recoveryStop = RecoveryStop(core: core)        sealedKeys = SealedKeys(core: core, say: { said, tone in openWindows.lead?.toasts.show(said, tone: tone) })        signInAsks = SignInAsks(core: core, say: { said, tone in openWindows.lead?.toasts.show(said, tone: tone) })        if KeysPasskeys.applies {            passkeys = KeysPasskeys(core: core, say: { said in openWindows.lead?.toasts.show(said, tone: .notice) })        }        if KeysImport.applies {            keysImport = KeysImport(core: core, say: { said in openWindows.lead?.toasts.show(said, tone: .notice, window: 8) })        }    }    /// One more window over this app: its own path, its own shown database,    /// its own answers. `taps` is the buffer its routes arrive in — the Mac's    /// delegate hands its own to the first window, because a deep link can    /// arrive before any window exists (`CottonHost/DeepLinkInbox.swift`).    public func window(taps: PendingTaps? = nil) -> WindowSession {        let window = WindowSession(            core: core, rawCore: rawCore, gate: writeGate, sync: sync, databases: databases,            taps: taps ?? PendingTaps())        openWindows.add(window)        return window    }    /// Build (or rebuild) the capture context for the identity the gate holds.    ///    /// Idempotent on the same pair, so the three callers — ready, and the two    /// identity fields changing — never mint a second service for one person.    /// `nil` with no workspace: nothing may be captured into a file the phone    /// has not been told about, and the dock stays unmounted rather than    /// writing under an empty key.    func composeCapture() {        guard case .ready = boot.screen, let workspaceId = boot.workspaceId else {            capture = nil            return        }        // The owner's id may lag the workspace by one boot read; until it        // arrives the workspace stands in for it, and the pair is rebuilt the        // moment the real one lands (see the property's note).        let userId = boot.ownerId ?? workspaceId        if let current = capture, current.userId == userId, current.workspaceId == workspaceId {            return        }        capture = CaptureContext(            userId: userId,            workspaceId: workspaceId,            core: core,            // NO default on the seam (`PendingLinkTrouble`'s rule): a chip            // that could not be applied has to go somewhere a person can find            // it — Bugsink for the build in a pocket, the console for the one            // on a desk.            report: { trouble in                Reporting.report(                    Report(                        kind: .unreadableAnswer,                        message: trouble.what,                        context: ["route": trouble.route]                    )                )                Log.write("pending links: \(trouble.route) — \(trouble.what)")            }        )    }}/// What ONE window has of its own: the path, the database it shows, the core/// that names that database on every call, Home's read, the receipt strip and/// the session's answers. The phone has one; a Mac window each.@MainActorpublic final class WindowSession {    /// The stack's path, as the value every screen reaches through the    /// environment (`Boot/Navigator.swift`).    let navigator = Navigator()    /// One receipt strip per window (design P8): a second centre in one    /// window would mean two toasts on screen at once, each unaware of the    /// other's undo.    let toasts: ToastCenter    let taps: PendingTaps    /// The session's last answers, so a screen the person returns to draws at    /// once (`Scaffold/AnswerCache.swift`). Emptied when the database is left    /// or the window turns to another, and dropped family by family by the    /// same `data` events that re-read the mounted screens.    let answers = AnswerCache()    /// One ledger for every routed Settings list and page in this window.    let settingsTableStores = SettingsTableStores()    /// The database this window shows. Born here because a link arriving in    /// this window is placed here, before its route opens. There is no    /// app-wide shown database.    let scene: DatabaseScene    /// The app's core, naming this window's shown database on every call.    let screens: any CottonCalling    /// The converted tools' verbs and definitions: the core's, for every    /// table (`AppTables.core`).    let databaseTables: DatabaseTableCatalog    /// The theme the shown database wears (`Theme/ThemeModel.swift`).    let themes: ThemeModel    let home: HomeModel    private let databases: DatabasesModel    init(        core: any CottonCalling, rawCore: any CottonCalling, gate: WriteGate, sync: SyncModel,        databases: DatabasesModel, taps: PendingTaps    ) {        self.taps = taps        self.databases = databases        let toasts = ToastCenter()        self.toasts = toasts        let scene = DatabaseScene()        self.scene = scene        // THE SCREENS' core names the database this window shows on every        // call (`DatabaseScopedCore`): the board, the lists and pages and        // every pushed screen read and write the SHOWN database. Everything        // that is the device's own — boot, sync, notifications, the share        // intake, capture — stays on the personal one.        let screens: any CottonCalling = GatedCore(            over: DatabaseScopedCore(underlying: rawCore, shown: scene.calls), gate: gate)        self.screens = screens        themes = ThemeModel(themes: CoreThemes(core: screens))        databaseTables = DatabaseTableCatalog { database in            let scoped = DatabaseScopedCore(underlying: core, database: database)            let records = CoreRecords(core: scoped)            return DatabaseTableCatalog.Source(tables: .core(records, writer: ScreenWriter(core: scoped))) { reload in                if reload { try await records.refreshCatalog() }                return try await records.tableDefinitions()            }        }        // Home reads through the window's calls, and a switch's read before        // it turns through the core under them (`HomeModel.prepare`).        home = HomeModel(core: screens, unscoped: core, toasts: toasts)        // What Home's read is asked of: the window's calls, so an answer is        // drawn only under the database it was read for.        home.askingDatabase = { [calls = scene.calls] in calls.id }        // A switch reads the new database's kept Home — its arrangement, its        // Today and its sync line — from the phone's own copy before anything        // of the window moves; the old Home stands meanwhile (295 A).        scene.prepare = { [home] id, calls in await home.prepare(shown: id, calls: calls) }        // Aimed at a database (a launch's seed, a switch): Home turns to it in        // the same step as the shown id moves, so the frame that shows it        // draws its kept answer; and reads it now if its answer was read for        // another. A cold launch onto a restored database read Home before        // the calls named it, and nothing read again until the next sync pull        // — the fan stood on Me and Tools (readpool, 16 Oct 2026).        scene.aimed = { [databaseTables, home, calls = scene.calls] _ in            databaseTables.point(at: calls.id)            home.turnToAsked()            let asked = calls.id            Task { @MainActor in await home.readAgainIfAskedElsewhere(shown: asked) }        }    }    /// The database this window shows, for the host's window list.    public var shownDatabaseId: String? { scene.shownId }    /// What a menu command names so only this window acts on it: the    /// `object` of the notification (`cottonNewThought`, `cottonShake`, …).    public var commandTarget: AnyObject { navigator }    /// Turn this window to `id`. A window that has not read the held list yet    /// opens on it once it has.    public func show(_ id: String) async {        if databases.database(id) != nil {            await scene.show(id, in: databases)        } else {            scene.shownId = id        }    }    /// The window closed for good: its database is no longer held open by it.    public func closed() async {        await scene.leave(in: databases)    }}extension Notification {    /// Whether a menu command is this window's: one posted with no object is    /// everybody's (the phone's shake), one naming a window is that window's.    func isFor(_ navigator: Navigator) -> Bool {        object == nil || (object as AnyObject) === navigator    }}public struct RootView: View {    @State private var session: AppSession    @State private var window: WindowSession    /// Whether this window runs what the APP does once: the subscription, the    /// gate's start, and every pass a gate change or a foreground owes. The    /// phone's one window does; on the Mac the first window does and a second    /// one only draws.    private let leads: Bool    /// A shake, or the Home card: what was on screen when the person asked to    /// report it, held until the sheet has sent or been dismissed. The picture    /// is taken HERE, before the sheet is up, or the sheet would be in it.    @State private var shakeStaged: ShakeStaged?    /// The shake as the paper sheet reads it: never set in an app with a look    /// of its own, which raises the report in that look (`LookReportRaise`).    private var paperReport: Binding<ShakeStaged?> {        Binding(get: { appLook == nil ? shakeStaged : nil }, set: { shakeStaged = $0 })    }    /// The cap switcher's project on the phone: held here, above the stack,    /// so the board and every list and page pushed over it read the same one    /// (`StackHost`'s `\.currentProject`). The Mac holds its own in    /// `MacWindowState`.    @State private var boardProject: String?    #if os(iOS)        /// Each database's page pictures, kept over a switch (`StalePages`).        @State private var stalePages = StalePages()    #endif    /// Who you are (`read.you`, the personal database's), over the    /// rebuild: a switch draws Me's head and card at once (`HomeRead`).    @State private var meRead = HomeRead()    /// Cotton Vault's screens, for Cotton Keys alone (`VaultLook.applies`):    /// made once the boot is ready, drawn where every other app's board stands.    @State private var vaultApp: VaultAppHolder?    /// Cotton Health's screens, for Cotton Health alone (`HealthModel.applies`),    /// made and drawn the same way.    @State private var healthApp: HealthAppHolder?    /// The look this app's own screens and the shell's pieces inside it wear    /// (Vault's or Health's); nil for every app drawn on paper.    private var appLook: VaultLook? {        #if os(iOS)        // Notes', Story's and Days' own looks (`AppLook`): there from the first frame.        if let own = VaultLook.standingApp { return own }        #endif        return vaultApp?.look ?? healthApp?.look    }    /// Whether the notifications have been started this launch    /// (`startOnFile`): once, on the first moment there is a file.    @State private var startedOnFile = false    /// The core's "Join this Circle?" for a Circle link just opened (`circle.invite.open`'s `ask`): a link alone    /// never joins (AUDIT E, owner approved 28 Nov 2026), only its Join does.    @State private var circleAsk: JSONValue?    @Environment(\.scenePhase) private var scenePhase    @Environment(\.colorScheme) private var colorScheme    /// Whether the shell's cards are laid above the app in a stack (an app    /// with a look of its own: Story, Days, Words, Comms, Vault, Health)    /// rather than in the top inset paper apps measure. Fixed for the    /// flavour, so the app's tree never changes shape under it.    private var cardsPushTheApp: Bool {        #if os(iOS)        VaultLook.drawsALook || VaultLook.standingApp != nil        #else        false        #endif    }    @Environment(\.opensCallLink) private var opensCallLink    private var boot: BootModel { session.boot }    private var sync: SyncModel { session.sync }    private var recurrences: RecurrenceMaterializer { session.recurrences }    private var alarms: AlarmSyncModel { session.alarms }    private var databases: DatabasesModel { session.databases }    private var notifications: NotificationsModel { session.notifications }    private var terminals: TerminalBus { session.terminals }    private var shares: ShareIntake { session.shares }    private var chatExports: ChatExportHandoff { session.chatExports }    private var shareArrivals: ShareArrivals { session.shareArrivals }    private var capture: CaptureContext? { session.capture }    private var core: any CottonCalling { session.core }    private var writeGate: WriteGate { session.writeGate }    private var keyStore: any DeviceKeyStore { session.keyStore }    private var vault: VaultAccess { session.vault }    private var navigator: Navigator { window.navigator }    private var bootReady: Bool { if case .ready = boot.screen { true } else { false } }    /// Start the notifications — they read the open file    /// (`reminders.reconcile`) — once, the first moment the boot gate is    /// `.ready`: at launch when the    /// file is already there, or when a first open's Start has made it. Run    /// right after `boot.start()` whatever the gate said, a fresh Rigby read    /// before `workspace.startLocal` and listed five "unreadable" failures    /// (architect's row C2, 22 Oct 2026).    private func startOnFile() async {        guard bootReady, !startedOnFile else { return }        startedOnFile = true        await notifications.start(taps: taps)    }    private var toasts: ToastCenter { window.toasts }    private var taps: PendingTaps { window.taps }    private var answers: AnswerCache { window.answers }    private var windowDatabase: DatabaseScene { window.scene }    private var screens: any CottonCalling { window.screens }    private var home: HomeModel { window.home }    private var tables: AppTables { window.databaseTables.tables }    /// The phone's root: one app, one window, made together.    ///    /// `taps` is an ARGUMENT since the Mac took deep links: the phone builds    /// its own and nothing else needs it — `onOpenURL` fires on this view, so    /// the buffer can be born with the view.    public init(        core rawCore: any CottonCalling,        keyStore: any DeviceKeyStore = KeychainDeviceKeyStore(),        reopen: (@MainActor () async -> Void)? = nil,        boot: BootModel? = nil,        taps: PendingTaps? = nil    ) {        let session = AppSession(core: rawCore, keyStore: keyStore, reopen: reopen, boot: boot)        self.init(session: session, window: session.window(taps: taps), leads: true)    }    /// One window over an app the HOST made — the Mac, where a window is one    /// of several. `leads` is true for exactly one of them.    public init(session: AppSession, window: WindowSession, leads: Bool) {        _session = State(initialValue: session)        _window = State(initialValue: window)        self.leads = leads    }    private func refreshToolPackages(reload: Bool = false) async {        await window.databaseTables.refresh(database: windowDatabase.calls.id, reload: reload)    }    public var body: some View {        ZStack {            content                // The cards' "Send a report" link (phone diagnostics part 3).                .environment(\.gateReport, GateReport(send: { [boot] in await boot.sendReport() }))            // Painted OVER everything and gone in one frame once somebody            // takes it down. The gate paints nothing while it waits, so this            // is what the person is actually looking at for the whole of the            // boot — and, on the phone, until Home is read (`FanLaunch`).            SplashOverlay()        }        #if os(iOS)        // An app with a look of its own raises the report in a panel of that look        // (`Feedback/LookReport.swift`), under the window's receipt so what became of it is said over the screen.        .modifier(LookReportRaise(staged: $shakeStaged, look: appLook, core: core, answers: answers))        #endif        // The window's one receipt overlay, inside the app's look so the line is drawn in it; the stack's overlay        // beneath it stays quiet (`receiptsHungAbove`), and only a sheet draws its own.        .cottonToasts(toasts)        // Cotton Vault's look over every piece the shell draws inside it (the        // receipt, the unlock card, the sign-in approval), and its appearance.        .environment(\.vaultLook, appLook)        #if os(iOS)        // Settings › Account's recovery code in Words, Days, Story and Comms (`Chrome/RecoveryAccountPart.swift`).        .environment(\.recoveryKeys, session.sealedKeys.recovery)        #endif        // Words, Days, Story and Comms draw the shell's passing lines in their own toast (`AppToast`).        .environment(\.appToast, AppToast.standing)        .preferredColorScheme(vaultApp?.scheme)        #if os(iOS)        .task {            // From the first frame: the look is the kit's own (`vault.look`            // reads no database), so the boot's gate stands in it too.            if HealthModel.applies, healthApp == nil {                let health = HealthModel(core: core, toasts: toasts)                healthApp = HealthAppHolder(model: health)                await health.readLook()                return            }            guard VaultLook.applies, vaultApp == nil else { return }            let model = VaultModel(core: core, toasts: toasts, unlockAsks: session.unlockAsks, signInAsks: session.signInAsks)            model.recovery = session.sealedKeys.recovery            vaultApp = VaultAppHolder(model: model)        }        #endif        // A slip, a message or a row with several acts lifts over the whole        // WINDOW: the status-bar and home-indicator strips dim with the page,        // the dial and the record button; only the lifted thing and its list        // stay bright (architect, 04:15 IST 18 Oct 2026, after Instagram's hold).        .liftsActs()        #if os(iOS)        // A cold launch's timeline starts as the window first shows        // (`SwitchClock.launching`): Home's read and the splash's going are        // measured from here.        .onAppear { SwitchClock.launching() }        #endif        // ONE watcher on the window, for every row in the app: a press has to        // tell a tap from a drag, and it must read the finger rather than claim        // it (`Chrome/Pressable.swift`).        .cottonWatchesTheFinger()        .task {            // What the app starts ONCE: a second window finds it all running.            guard leads else { return }            #if os(iOS)            // The films kept on this phone: the background sessions iOS            // carried while the app was gone, what lands on them written            // through the core, every film with Keep everything on            // (`FilmKeeper`); and the film player's core (`FilmPlayback`).            FilmKeeper.shared.attach(core: core, say: { [toasts] said in toasts.show(said, tone: .error) },                                     tell: { [toasts] said in toasts.show(said) })            FilmPlayback.attach(core: core) { [toasts] said in toasts.show(said, tone: .error) }            // The podcast episodes kept on this phone, the same way            // (`EpisodeKeeper`); and the one audio player's core (`PodcastPlayback`).            EpisodeKeeper.shared.attach(core: core) { [toasts] said in toasts.show(said, tone: .error) }            // The books kept on this phone (`BookKeeper`): every book being            // read is kept here.            BookKeeper.shared.attach(core: core) { [toasts] said in toasts.show(said, tone: .error) }            // The songs kept on this phone (`SongKeeper`), every one with Keep            // everything on.            SongKeeper.shared.attach(core: core, say: { [toasts] said in toasts.show(said, tone: .error) },                                     tell: { [toasts] said in toasts.show(said) })            // The music player's core (`MusicPlayback`).            MusicPlayback.shared.attach(core: core) { [toasts] said in toasts.show(said, tone: .error) }            #endif            // An album's Find details.            MusicLookup.shared.attach(core: core, say: { [toasts] said in toasts.show(said, tone: .error) },                                      tell: { [toasts] said in toasts.show(said) })            // A list's Set picture from Photos.            ListPicture.shared.attach(core: core, say: { [toasts] said in toasts.show(said, tone: .error) },                                      tell: { [toasts] said in toasts.show(said) })            // A library's Export library: its open bundle, zipped and shared.            LibraryExport.shared.attach(core: core, say: { [toasts] said in toasts.show(said, tone: .error) },                                        tell: { [toasts] said in toasts.show(said) })            // The ONE subscriber, before anything asks the core a question —            // so the first event of a bootstrap cannot land before            // there is somebody to hear it. Buffered events are replayed on            // subscribe, so nothing emitted before this is lost either.            await subscribeOnce()            LaunchMarks.mark("subscribed")            // Before the gate's first question, for the same reason the            // subscriber is: a cold-start tap reaches the app long before            // `read.boot` answers, and it has to have somewhere to land. The            // route it resolves to goes into `taps`, which holds it until the            // stack exists.            //            // The token forget is armed here too — on BOTH paths that stop            // this phone being a device of that server's, so a phone that            // comes back is not silenced by its own stale note.            boot.beforeLeaving = { [notifications] in                await notifications.forgetToken()            }            // The two one-time Keychain sweeps, once a launch and off the main            // path: provider keys and code-hosting tokens an old build left in            // this phone's Keychain, which nothing reads now that both live in            // `cotton_secrets`.            Task.detached(priority: .background) {                await ByokLegacyKeychain.forget()                await CodeHostingLegacyKeychain.forget()            }            // **THE GATE FIRST.** It used to run LAST, behind            // `notifications.start` — which awaited a token registration, an            // HTTP PUT with a sixty-second ceiling. `CottonCore` is an actor            // and answers ONE call at a time, so the boot read queued behind a            // network round trip and then ran its own clock down from a            // standing start. The registration does not gate the screen; the            // boot read is the only thing the person is waiting for, so it            // goes first and the registration follows.            //            // **A cold-start tap is not lost by this.** `NotificationBridge`            // HOLDS every tap until somebody attaches and replays them in            // order, so the tap that launched the app lands the moment            // `notifications.start` runs — one boot read later, and still long            // before there is a stack to push it onto.            // Import the local switches before the ready gate can draw a            // native device page; neither a page nor delivery invents defaults.            await notifications.preparePreferences()            // THE PERSONAL OBJECT, before the gate reads: a signed-in phone's            // copy is connected (no network once it has one), so the file the            // gate opens syncs with the object from its first pass; a phone            // holding no credential stands on its own local database, which            // the core opens — or, with none yet, starts at the gate's first ask.            if let personal = session.personal {                personal.beforeRemove = { [boot, openWindows = session.openWindows] in                    boot.waitForReplacement()                    for window in openWindows.live {                        window.navigator.resetForDatabaseChange()                        window.scene.reset()                        window.databaseTables.point(at: nil)                        window.answers.clear()                    }                }                personal.say = { [openWindows = session.openWindows] line, failed in                    if failed { _ = openWindows.lead?.toasts.show(line, tone: .error, window: ToastWindow.untilTap) }                    else { _ = openWindows.lead?.toasts.show(line, tone: .notice) }                }                personal.reread = { [boot, sync, databases, recurrences, openWindows = session.openWindows, sealedKeys = session.sealedKeys] change in                    switch change {                    case .removed:                        // The core starts a fresh local database at this ask.                        await boot.retry()                    case .changed:                        await boot.refreshCopy()                    }                    await databases.refreshList()                    for window in openWindows.live { await window.scene.seed(from: databases) }                    await recurrences.copyReplaced()                    sync.copyReplaced()                    for window in openWindows.live { await window.home.copyReplaced() }                    // The keys are read again: a copy replaced (signed out, the account deleted) stands on another                    // database, and what was offered for the last one goes (DELETE_ACCOUNT.md).                    await sealedKeys.read()                }                LaunchMarks.mark("personal-asked")                await personal.launch()                #if COTTON_DEV                await personal.walkSignIn()                #endif                LaunchMarks.mark("personal-connected")            }            await boot.start()            LaunchMarks.mark("gate-answered")            // Only once there IS a file: a first open that lands on Start has            // none until `workspace.startLocal` makes it, and these reads            // came back "unreadable" before it (`startOnFile`).            await startOnFile()            // A share taken while the app was not running: the extension left            // it in the mailbox and this is the first moment anything can act            // on it. AFTER the gate, because a drain that navigates needs a            // workspace to navigate INTO — `useReaderIntake.ts:71`'s            // `if (!workspaceId) return`, said with the gate's own answer.            //            // Through `shareArrivals`, like every other drain in this file:            // ONE drain per foreground, whichever trigger asks first            // (`Boot/ShareArrivals.swift`).            if case .ready = boot.screen, shareArrivals.takeDrain() { _ = await shares.drain() }            // Cotton Keys: what its passkey provider wrote while Keys was shut.            if case .ready = boot.screen { session.passkeys?.run(presence: true) }            // An assistant's unlock request waiting since the app was shut.            if case .ready = boot.screen { await session.unlockAsks.read() }            if case .ready = boot.screen { await session.assistantAsks.read() }            if case .ready = boot.screen { await session.recoveryStop.read() }            // The data key of sealed tables: handed back from the Keychain before the pass that opens them.            if case .ready = boot.screen { await session.sealedKeys.read() }            // THE VAULT KEY, published. Last, and deliberately: it is            // background work nobody is waiting for, it writes one row through            // the ordinary outbox, and it must not sit in front of the boot            // read that the person IS waiting for.            //            // **It never prompts.** Minting writes a Keychain item behind an            // access control without evaluating it, and the PUBLIC half is            // cached beside it — so a launch publishes without drawing a Face            // ID sheet, and the first prompt the person ever sees is the one in            // front of their first reveal (`CottonKit/VaultKeyring.swift`).            //            // Only with a file open: publishing writes a row, and a phone that            // has not joined has nowhere to write it.            if case .ready = boot.screen { await vault.publish(through: ScreenWriter(core: core)) }            // A re-key the app was closed in the middle of: a successor whose            // row went live is promoted now (`DeviceRekey.resumeAtLaunch`).            if case .ready = boot.screen { await session.rekey.resumeAtLaunch() }        }        // A timed walk of pages, asked at launch (`PageWalk`): its own task,        // never behind the launch's permission prompts.        .task(id: bootReady) { if bootReady { await PageWalk.run(navigator) } }        // A link shared by the walk (`ShareWalk`, a development build): read        // through the share extension's reader into the mailbox, then knocked        // as the extension knocks.        .task(id: bootReady) {            guard bootReady, await ShareWalk.share() else { return }            shareArrivals.arrived()            drainSharesIfOwed()        }        // Cotton Keys: an import asked before the file opened runs now.        .task(id: bootReady) { if bootReady { session.keysImport?.opened(land: { navigator.popToRoot() }) } }        // Cotton Keys: after each sync pass, a passkey row made on another        // device is mirrored into this phone's keychain and told to iOS.        .onChange(of: sync.lastPullAt) { _, _ in session.passkeys?.run(presence: false) }        // An unlock request (or a window's end) arrives with a sync pass.        .onChange(of: sync.lastPullAt) { _, _ in if bootReady { Task { await session.unlockAsks.read() } } }        .onChange(of: sync.lastPullAt) { _, _ in if bootReady { Task { await session.assistantAsks.read() } } }        .onChange(of: sync.lastPullAt) { _, _ in if bootReady { Task { await session.recoveryStop.read() } } }        // A data key a pass let the core take (a vault opened, a key minted) is kept; a missing one is asked for.        .onChange(of: sync.lastPullAt) { _, _ in if bootReady { Task { await session.sealedKeys.read() } } }        // The shell's cards stand above the app and push it down, compact at        // the largest text (`Boot/ShellCardsAbove.swift`).        .shellCardsAbove(pushes: cardsPushTheApp, ground: appLook?.colour("background", colorScheme)) {            if bootReady {                VStack(spacing: 0) {                    SealedKeyBanner(keys: session.sealedKeys)                    SignInAskBanner(asks: session.signInAsks)                    #if os(iOS)                    // Cotton Vault's unlock request stands here, pushing the screen down.                    VaultUnlockStanding(asks: session.unlockAsks)                    #endif                }                // The inset stands outside the look given above: the cards read it here.                .environment(\.vaultLook, appLook)            }        }        // A new device asking to sign in: read at the core's pace while the file is open.        .task(id: bootReady) { if bootReady { await session.signInAsks.watch() } }        #if COTTON_DEV && os(iOS)        // DEVELOPER TOOL: a simulator's airplane mode (`Developer/DevNetworkCut.swift`).        .task(id: bootReady) { if bootReady { DevNetworkCut.listen(core) } }        #endif        #if COTTON_DEV        // DEVELOPER TOOL: `-shell-toast-seed YES` says the approval's line for the invented Walk Mac once the file is        // open, standing until a tap, so a still shot shows where the shell's passing line is drawn. No server.        .task(id: bootReady) {            guard bootReady, ProcessInfo.processInfo.arguments.contains("-shell-toast-seed") else { return }            let name = ShellLines.line("unlock", "approval.seed_name")            toasts.show(ShellLines.line("signin", "waiting.approved", ["name": name]), tone: .success, window: ToastWindow.untilTap)        }        #endif        // Modal to a tree reader while the unlock card stands: the deck, the        // fan and every tile stack under it leave the tree, as under a lifted        // card.        // (Cotton Vault's card stands above its screen instead, and covers nothing.)        .coveredUnread(bootReady && session.unlockAsks.raised && !VaultLook.drawsALook)        .coversTheTileStacks(bootReady && session.unlockAsks.raised && !VaultLook.drawsALook)        // And to a finger: nothing under the card takes a touch, so a tap on        // the veil never reaches the fan's tiles or the deck beneath it.        .allowsHitTesting(!(bootReady && session.unlockAsks.raised && !VaultLook.drawsALook))        // The unlock card over the window while a request waits, and the        // open windows' End now (`Boot/UnlockAsks.swift`).        .overlay { if bootReady { UnlockAsksLayer(asks: session.unlockAsks, look: appLook) } }        // An assistant's ask stands once no unlock card does (one card at a time).        .overlay { if bootReady, !session.unlockAsks.raised { AssistantAskLayer(asks: session.assistantAsks) } }        .overlay(alignment: .top) { if bootReady { RecoveryStopBanner(stop: session.recoveryStop) } }        // GETTING-IN.md: this device waits for another of the person's to say yes: the page over the app, by itself,        // until Do this later (the slim line in the cards above brings it back) or the key is here.        .overlay { if bootReady, session.sealedKeys.page != nil, !session.sealedKeys.later { GettingInPage(keys: session.sealedKeys).environment(\.vaultLook, appLook) } }        .onChange(of: navigator.stack) { _, now in            // Every report carries the screen the person was on, and the ring            // shows how they got there.            let route = now.last?.path ?? "/"            Reporting.noteRoute(route)            Log.write("route \(route)")            #if COTTON_DEV && os(iOS)            DevFrames.shared.place = route            #endif        }        #if COTTON_DEV && os(iOS)        // DEVELOPER TOOL: the frame meter, only when the launch asked for it        // (`Developer/DevFrames.swift`).        .task { DevFrames.shared.startIfAsked() }        #endif        #if COTTON_DEV        // DEVELOPER TOOL: the build, the schema and (when asked) the timings,        // in every screen's corner (`Developer/DevCorner.swift`) — down in        // the safe area under Home's record button, never beside or under it.        // `-dev-corner-hidden YES` leaves it out, for the store's screenshots taken on a dev build.        .overlay(alignment: .bottomTrailing) {            if !UserDefaults.standard.bool(forKey: "dev-corner-hidden") {                DevCorner().environment(\.cottonCore, core).ignoresSafeArea(.container, edges: .bottom)            }        }        #endif        .onReceive(NotificationCenter.default.publisher(for: .cottonShake)) { note in            // Shake to report (`Feedback/ShakeReport.swift`). Only with a file            // open — the verb writes a row — and only one sheet at a time, in            // the window the report was asked from.            guard note.isFor(navigator), shakeStaged == nil, case .ready = boot.screen else { return }            Log.write("shake")            // The route as it was at the shake; the picture is the window            // server's answer, which is asynchronous on the Mac.            let route = navigator.top?.path ?? "/"            Task { @MainActor in                let snapshot = await ScreenSnapshot.take()                guard shakeStaged == nil else { return }                shakeStaged = ShakeStaged(snapshot: snapshot, route: route)            }        }        #if COTTON_DEV        // DEVELOPER TOOL: `-report-sheet-open YES` shakes once the file is open,        // for the report's own UI tests (a simulator's test has no shake to send).        .task(id: bootReady) {            guard bootReady, leads, ReportSeed.asked() else { return }            try? await Task.sleep(for: .seconds(1))            NotificationCenter.default.post(name: .cottonShake, object: nil)        }        #endif        .onReceive(NotificationCenter.default.publisher(for: .cottonReportProblem)) { note in            // The Feedback tool's "Report a problem": the same sheet, without            // a picture — a screenshot of the Feedback list is never the            // screen that looked wrong.            guard note.isFor(navigator), shakeStaged == nil, case .ready = boot.screen else { return }            shakeStaged = ShakeStaged(snapshot: nil, route: navigator.top?.path ?? "/")        }        // Paper apps' sheet; an app with a look of its own raises `LookReportRaise` instead.        .cottonCard(item: paperReport, detents: [.tall]) { staged in            // `unwired`: the sheet reads nothing, so there is nothing to re-read.            Hosted(unwired: { core, toasts in                ShakeReportModel(                    writer: ScreenWriter(core: core), toasts: toasts, staged: staged,                    hints: { await VoiceBias.hints(core: core) })            }) { model in                ShakeReportSheet(model: model) {                    shakeStaged = nil                }            }            // A sheet is its own presentation: it does NOT inherit what the            // body publishes beneath this modifier. `Hosted` reads the open            // database and the `ToastCenter` — the centre by type, which SwiftUI            // traps on when it is absent, so every shake crashed the app, and a            // missing database drew "No database" instead of the report. Both            // are published again here, and the sheet's own refusal toast draws            // over the sheet that is still open.            .environment(\.cottonCore, core)            .cottonToasts(toasts)            // And the session's answers, for the same reason as the core.            .environment(\.cottonAnswers, answers)        }        .onChange(of: boot.screen) { _, screen in            // The gate went back to waiting: a tap arriving now is HELD again            // rather than pushed onto a stack that is no longer there.            // Each window's own part first; what the app owes once follows,            // from the window that leads.            if screen == .door {                navigator.resetForDatabaseChange()                windowDatabase.reset()                if leads { databases.resetAfterLeaving() }                boardProject = nil            }            switch screen {            case .ready:                Task { await refreshToolPackages() }                guard leads else { break }                // The core is open: a shake report kept on this phone goes now.                Task { await FeedbackOutbox.flush(core: core) }                // A first open that started on Start has its file now.                Task { await startOnFile() }                // A knock that landed during the boot read — which is the                // ORDINARY case, because opening the app is what the extension                // just did — is paid here, the first moment a drain has a file                // to navigate into.                drainSharesIfOwed()                // The file is open: give every template what the planner says                // it is owed, before the person looks at their todos.                Task { await recurrences.run() }                // And fill in the city of anybody who has a zone and never had                // a city — Cotton's own act, shown on their page as an                // ordinary city. Not under a banner: the core refuses writes                // there, and this pass has nobody to tell.                if !boot.holdsDrains { Task { try? await core.fillPersonCities() } }                // And make the device's alarms match the file's.                Task { await alarms.run() }                // And the capture service, now that the identity is known —                // then the chips waiting on records that landed while the app                // was away.                composeCapture()                if !boot.holdsDrains { Task { await capture?.drain() } }            default:                taps.close()                answers.clear()            }            guard leads else { return }            sync.note(boot.standingRefusal)            // And the write gate: held with the refusal's own sentence while            // the app is reading under a banner, let go otherwise.            writeGate.hold(boot.readOnly.map { CottonStrings.readOnlyWriteRefused($0.title) })            // And START THE CONNECTION on the transition that means there is a            // file to sync. The decision is the model's (`bootScreenChanged`),            // not this closure's; before it existed a cold-launched app pulled            // nothing and held no socket until it had been backgrounded once.            Task { await sync.bootScreenChanged(to: screen) }        }        // Where this phone stands with its personal object is the boot's        // answer too (`shell.home`): the Backup card reads the same one.        .onChange(of: boot.home) { _, answer in            if let answer { session.personal?.take(answer) }        }        .onChange(of: boot.readOnly) { _, refusal in            // A refusal that arrives BEHIND an open app — the loop's own stop,            // a re-hydrate the server refused — changes no screen, so the            // screen's `onChange` above never fires for it. The gate and the            // sync model are held off this fact directly, the moment it            // moves, in either direction.            guard leads else { return }            writeGate.hold(refusal.map { CottonStrings.readOnlyWriteRefused($0.title) })            sync.note(boot.standingRefusal)        }        // THIS WINDOW TURNED TO ANOTHER DATABASE: nothing read off the last        // one may draw over it. The pushed screens close and the session's        // answers go. Home turned with the calls (`DatabaseScene.aimed`), on        // the answer the switch read before it turned; a turn that aimed        // nothing (a window reset) turns it here. The hosts are rebuilt on the        // same key (`stack`), so no list or page keeps the last database's        // rows, and the rebuilt board reads as it shows (`HomeBoard`).        .onChange(of: shownKey) { _, _ in            #if os(iOS)                SwitchClock.mark("shown", windowDatabase.shownId)            #endif            navigator.popToRoot()            answers.clear()            home.turnToAsked()        }        // A cap long-pressed on the Databases screen: its page or its sync        // page (Spec 10.2), opened AFTER the pick's switch has closed the last        // database's screens — a task runs after the update whose `shownKey`        // change pops to the root, so the switch cannot close what it opened.        .task(id: windowDatabase.picks) {            guard let asked = windowDatabase.pageAsked else { return }            windowDatabase.pageAsked = nil            navigator.open(asked)        }        .onChange(of: scenePhase, initial: true) { was, phase in            // The app's foreground and background, once.            guard leads else { return }            Task {                switch phase {                case .active:                    #if os(iOS)                        SyncHold.end()                    #endif                    await sync.foreground()                    // `initial: true` runs this closure AT MOUNT, where `was`                    // and `phase` are the same value — a cold launch never gets                    // an `.active` EDGE, which is how the connection came to be                    // started by nothing at all. Only the connection is wanted                    // there: everything below has its own first run in `.task`                    // or on the gate's `.ready`, and doing it twice on a cold                    // start is the queue this pass spent the boot read's five                    // seconds in.                    guard was != phase else { return }                    // A card for your Claude put aside (a tap outside, a pull) is raised again now the app is opened.                    session.unlockAsks.raiseAgain()                    // A shake report kept while there was no connection goes                    // now (`feedback.flush`; only logged).                    await FeedbackOutbox.flush(core: core)                    // Expo drained on foreground too (`_layout.tsx:277`): a                    // capture filed on the server while the phone was in a                    // pocket has its chips applied the moment it comes back.                    // UNDER A BANNER NOTHING IS DRAINED (`BootModel.holdsDrains`):                    // the core refuses every write, and a mailbox entry                    // refused is one reported as a fault and lost.                    if !boot.holdsDrains { await capture?.drain() }                    // Throttled to five minutes inside the model, so switching                    // apps every few seconds does not run the planner every                    // few seconds.                    await recurrences.run()                    // One query when nobody is owed a city, which is almost                    // always; the failure is swallowed for the materialiser's                    // reason — nobody asked for this pass.                    if !boot.holdsDrains { _ = try? await core.fillPersonCities() }                    await alarms.run()                    // Clips: what was copied in another app since, kept into                    // the personal database (`Clips/PhoneClipboard.swift`).                    #if os(iOS)                        if !boot.holdsDrains { await PhoneClipboard.shared.foreground(personal: { CoreRecords(core: core) }, thisDevice: { try? await core.callJSON(CottonMethod.readDevices).text("thisDevice") }) }                    #endif                    // ONE drain per foreground: if the knock that brought the                    // app forward already took this one, it is not taken again                    // (`Boot/ShareArrivals.swift`).                    if case .ready = boot.screen, !boot.holdsDrains, shareArrivals.takeDrain() {                        _ = await shares.drain()                    }                    // Cotton Keys: its provider's entries, at every foreground.                    if case .ready = boot.screen, !boot.holdsDrains { session.passkeys?.run(presence: true) }                    // An assistant's unlock request, at every foreground.                    if case .ready = boot.screen, !boot.holdsDrains { await session.unlockAsks.read() }                    if case .ready = boot.screen, !boot.holdsDrains { await session.assistantAsks.read() }                    // Re-read the permission (the person can change it in                    // Settings while the app is away), offer the token again                    // (APNs rotates them, and the row's `last_seen_at` is how                    // the server tells a live install from an abandoned one)                    // and reconcile.                    await notifications.foreground()                case .background:                    #if os(iOS)                        let left = SyncHold.begin {                            Task { await sync.background(budgetMs: 0) }                        }                        await sync.background(budgetMs: left)                    #else                        await sync.background()                    #endif                    // The phone catches up while it is away: ask iOS for the                    // short periodic slice and the long one it runs while the                    // phone charges. iOS decides when (`BackgroundCatchUp`).                    BackgroundCatchUp.shared.appWentAway()                    // THE FOREGROUND IS OVER, so the next one gets its own                    // share drain. Counted on the way OUT rather than on the                    // way in, because `onOpenURL` and the `.active` edge are                    // not ordered against each other — `ShareArrivals` says why                    // that matters.                    shareArrivals.wentAway()                default: break                }            }        }        // THE PHONE'S entry point only. This fires for a SwiftUI `App` scene;        // on the Mac this view is hosted inside an `NSHostingView` and it never        // fires at all — with no warning and nothing in the log. The Mac's URLs        // come in at `NSApplicationDelegate.application(_:open:)` and reach the        // same `taps` through `CottonHost/DeepLinkInbox.swift`, which is why        // `taps` can be handed in rather than born here.        #if os(iOS)        // Cotton Keys: the Passwords app's Credential Exchange handover, its        // token held until the file is open (`Boot/KeysImport.swift`).        .onContinueUserActivity(KeysImport.activityType) { activity in            session.keysImport?.receive(activity, land: { navigator.popToRoot() })        }        #endif        .alert(            circleAsk?["title"]?.string ?? "",            isPresented: Binding(get: { circleAsk != nil }, set: { if !$0 { circleAsk = nil } }),            presenting: circleAsk        ) { ask in            Button(ask["join"]?["title"]?.string ?? "") {                circleAsk = nil                guard let method = ask["join"]?["call"]?["method"]?.string, let request = ask["join"]?["call"]?["request"] else { return }                let core = self.core                Task {                    do {                        let answer = try await core.callJSON(method, request)                        if let said = answer["said"]?.string { toasts.show(said, tone: .success) }                        if let refused = answer["error"]?.string { toasts.show(refused, tone: .error) }                        if let out = answer["signedOut"]?["message"]?.string { toasts.show(out, tone: .notice) }                    } catch {                        toasts.show(error.localizedDescription, tone: .error)                    }                }            }            .accessibilityIdentifier("circle-invite-join")            Button(ask["cancel"]?.string ?? "", role: .cancel) { circleAsk = nil }                .accessibilityIdentifier("circle-invite-cancel")        } message: { ask in            Text(ask["line"]?.string ?? "")        }        .onOpenURL { url in            // A link handed to Sites is held for Sites' own screens (`SitesLinkInbox`), never a route here.            if SitesLinkInbox.shared.hold(url) { return }            // THE SHARE EXTENSION'S KNOCK IS NOT NAVIGATION. It says a new            // entry is in the mailbox, and the DRAIN is what decides where the            // app goes — because the drain is the only thing holding the            // staged file. Pushing the URL's own route here as well would open            // the import screen twice, and the bare one would be on top.            // `Boot/ShareArrivals.swift` has the whole of this reasoning.            if ShareOpen.isShareArrival(url) {                shareArrivals.arrived()                drainSharesIfOwed()                return            }            // A COTTON PACKAGE the system opened this app with — AirDropped,            // or tapped in Files. Staged like a share and imported by the            // drain's package branch, which tells the person what came in.            if PackageOpen.isPackage(url) {                openPackage(url)                return            }            #if os(iOS)            // An audio file opened into Comms (Files, a share sheet's Open in): a recording of it, its page opened            // (CONTRACT.md "Recordings", Import).            if ChatRecorder.opens(url) {                let core = self.core                Task {                    let came = await ChatRecorder.shared.bring(url, core: core)                    if let refused = came.refused { toasts.show(refused, tone: .error) }                    if let said = came.said { toasts.show(said) }                    if let meeting = came.meeting { ChatRecorder.shared.saved = meeting }                }                return            }            // A Circle invitation (`https://<sign-in host>/c/<code>#<secret>`): only Comms and Contacts carry the            // applinks entitlement for it (scripts/ios-spec-gate.ts CIRCLE_LINK_TARGETS). The whole link goes to the            // core, which redeems it from this person's own object; its words are said as they come.            if url.scheme == "https", url.path.hasPrefix("/c/"), let fragment = url.fragment, !fragment.isEmpty {                let core = self.core                Task {                    do {                        let answer = try await core.callJSON("circle.invite.open", JSONValue.object(["link": .string(url.absoluteString)]))                        // A link alone only asks: the core's question, and only its Join redeems.                        if let ask = answer["ask"], ask["title"]?.string != nil { circleAsk = ask; return }                        if let said = answer["said"]?.string { toasts.show(said, tone: .success) }                        if let refused = answer["error"]?.string { toasts.show(refused, tone: .error) }                        // Signed out: the core's words say to sign in first; the same link works after.                        if let out = answer["signedOut"]?["message"]?.string { toasts.show(out, tone: .notice) }                    } catch {                        toasts.show(error.localizedDescription, tone: .error)                    }                }                return            }            // A script file (Fountain, Final Draft, PDF, text), in Cotton Story: a new story from it.            if StoryFountainOpen.opens(url) {                let core = self.core                Task {                    let came = await StoryFountainOpen.bring(url, core: core) { said, done in                        toasts.show(said, tone: done ? .success : .error)                    }                    // The printed script's check rides along, for Story's home to show.                    NotificationCenter.default.post(name: StoryFountainOpen.broughtIn, object: came?.check)                }                return            }            #endif            // A call link, in the app that places calls (Cotton Calling).            if let opensCallLink, opensCallLink(url) { return }            guard let link = DeepLinks.link(url) else {                toasts.show(DeepLinks.opensNothing(url), tone: .error)                return            }            taps.arrive(link)        }        // After Delete account: what the core said stands in a card until Close (store pass, 24 Nov 2026).        #if os(iOS)        .cottonCard(isPresented: Binding(get: { session.personal?.deletedSaid != nil },                                         set: { if !$0 { session.personal?.deletedSaid = nil } })) {            AccountDeletedCard(said: session.personal?.deletedSaid ?? "")        }        #endif        // The window's cards: what a screen outside any page opens — the        // shake's report, the databases, capture's projects — stands here,        // over the whole window (`CardLayer`).        .cardLayers()    }    /// A gate's way out, sent to the boot.    private func gateWay(_ way: String) {        Task {            switch way {            case "retry": await boot.retry()            case "sign_out": await boot.leave()            case "reset_key": await boot.resetKey(store: keyStore)            case "erase": await boot.erase(store: keyStore)            default: break            }        }    }    /// The gate's screens. Nothing stands in front of them: Cotton works    /// before anyone signs in, and signing in is Settings › Backup's act.    @ViewBuilder private var content: some View {        switch boot.screen {        #if os(iOS)        case .waiting where appLook != nil:            // Inside Cotton Vault the first frame is its name on the flat            // ground (SHAPES "Decided" 12), the same as the launch.            VaultLaunchName().environment(\.vault, appLook ?? .blank)        case .gate(let gate) where appLook != nil:            // Its name while the gate waits, else the core's words and ways            // out on Vault's ground.            VaultGateScreen(gate: gate, look: appLook ?? .blank) { way in gateWay(way) }                .task(id: gate.code) {                    if boot.mustErase { await boot.erase(store: keyStore) }                }        #endif        case .waiting:            // NOTHING, on purpose: the splash is up and an interstitial spinner            // between it and the first screen is exactly what the boot seam            // exists to prevent.            Color.clear        case .door:            // A business app opens on its business's shell — a tile for each            // view its object lets this phone read, and Me: the phone holds            // no copy and founds none (`CustomerShell`). Every other app has            // its own database started by the core before it gets here.            if let manifest = FlavourManifest.current, let business = CustomerShell.opens(manifest) {                CustomerShell(manifest: manifest, client: BusinessClient(core: core, address: business))            }        case .gate(let gate):            // Every slip the core answered: its words, its ways out.            GateScreen(gate: gate) { way in gateWay(way) }            // **The owner already answered, so nothing is asked.** A            // revocation marked `erase` runs the erase once the wall paints.            .task(id: gate.code) {                if boot.mustErase { await boot.erase(store: keyStore) }            }        case .ready:            // The app — and, on a phone the server has refused, the refusal            // as a banner above it rather than a wall in front of it            // (`Boot/ReadOnlyBanner.swift`). `nil` draws nothing.            stack.readOnlyBanner(boot.readOnly)                // The gate's own sentence, for a page that says why a fact                // lifts with no editor on this device.                .environment(\.writeRefusal, boot.readOnly.map { CottonStrings.readOnlyWriteRefused($0.title) })        }    }    /// Subscribe once and fan every event out to every model.    private func subscribeOnce() async {        // Bound to locals rather than captured through `self`: the handler is        // `@Sendable` and crosses to the core's own thread, and the three        // models are `@MainActor` classes (implicitly `Sendable`) while a View        // struct is not.        let boot = boot        let sync = sync        let openWindows = session.openWindows        // The alarms model is on this fan-out for a reason the review named: a        // reconcile that runs only after a write made ON the Alarms screen        // leaves an alarm that arrived by sync, or was set by a tool, waiting        // for the next foreground. It reads the `data` event's own table list.        let alarms = alarms        let held = session.databases        let notifications = notifications        let terminals = terminals        let personal = session.personal        // The device's dictation language model reads its corpus from this        // core and recompiles when names or the person's lines move.        VoiceModelKeeper.shared.attach(core)        // The voice models this phone holds, joined with the core's catalogue.        Task { await VoiceModelStore.current.attach(core) }        await core.subscribe { event in            // THE TERMINAL FRAMES FIRST, and before `ClientEvent.from`, which            // knows the `client` and `data` kinds and drops everything else —            // a `terminal.data` frame read through it would be dropped as an            // unknown kind. The bus routes a frame to the session watching it            // and ignores every other kind itself.            Task { @MainActor in terminals.receive(event) }            guard let client = ClientEvent.from(event) else { return }            Task { @MainActor in                if case .personalSignedOut(let code) = client, let personal { Task { await personal.signedOut(code: code) } }                if case .personalDeleted(let line) = client, let personal { Task { await personal.deletedElsewhere(line: line) } }                if case .personalAdoptEnded = client, let personal { Task { await personal.followAdopt() } }                boot.receive(client)                held.receive(client)                sync.receive(client)                // Home too, and for the reason `home.tsx:13-17` states: every                // figure on that page comes from the tool that mutates it, so a                // tool's own invalidation is the only thing keeping the glance                // honest. Without this, a capture filed from a screen pushed                // over Home leaves Home's Asked of you and Done for you stale until somebody                // pulls to refresh.                for window in openWindows.live { window.home.receive(client) }                alarms.receive(client)                // And the reminder engine, for the reason                // `useNotificationEngine` watched the whole query cache: a todo                // given an hour, an event moved or a birthday named all change                // what should be scheduled, and nothing else would notice.                // Debounced there, not here.                notifications.receive(client)                VoiceModelKeeper.shared.receive(client)            }        }    }    /// **The one host** (design spec §5.2): the phone's stack. The Mac's    /// columns went with the Mac client (architect, 20 Oct 2026). No SCREEN    /// branches on a platform: the guard is `ScreenPlatformSweepTests`.    @ViewBuilder private var hosts: some View {        #if os(iOS)        if SecretsRoot.applies {            // Cotton Secrets in the Plum look: Unlock, then Secrets, People and            // You as text tabs; no fan and no board (`Secrets/SecretsRoot.swift`).            Group {                if let vaultApp {                    // Signing in or out (You's Account) changes what every Secrets place answers: read again.                    SecretsRoot(model: vaultApp.model)                        .onChange(of: session.personal?.stand) { _, _ in vaultApp.model.changed() }                } else { Plum.ground.ignoresSafeArea() }            }            .databaseScene(windowDatabase)        } else if InkStoryRoot.applies {            // Cotton Story in the Ink look: its own screens, opening on the            // script last worked on; no fan and no board (`Story/Ink`).            InkStoryRoot(core: core)                .databaseScene(windowDatabase)        } else if NotesRoot.applies {            // Cotton Notes in its own look: the list, the side page and the            // note; no fan and no board (`Notes/`).            NotesRoot(core: core)                .databaseScene(windowDatabase)        } else if CinemasRoot.applies {            // Cotton Cinemas as a streaming app: Home, Search and You on a            // bottom bar, always dark; no fan and no board (`Cinemas/`).            CinemasRoot(core: core, shares: shares)                .databaseScene(windowDatabase)        } else if PostRoot.applies {            // Cotton Post in the Stamp look: Mail, Senders, Files and You, the            // side page that pushes; no fan and no board (`Post/`).            PostRoot(core: core)        } else if SitesRoot.applies {            // Cotton Sites in Cranberry: the list, a site open with its bar and the thread, search and the chooser;            // its own screens, no fan and no board (`Sites/`).            SitesRoot(core: core)                .databaseScene(windowDatabase)        } else if ContactsRoot.applies {            // Cotton Contacts: every person, organisation and assistant (`Contacts/`); its own screens, no fan and no            // board.            ContactsRoot(core: core)                .databaseScene(windowDatabase)        } else if AlbumsRoot.applies {            // Cotton Albums: Albums, Tidy, People and You; every photo looked at on this phone (`Albums/`); its own            // screens, no fan and no board.            AlbumsRoot(core: core)                .databaseScene(windowDatabase)        } else if DataRoot.applies {            // Cotton Data in Stone: Tables, Lately, Search and You as text tabs, every table and row of the database,            // read only; its own screens, no fan and no board (`DataApp/`).            DataRoot(core: core)                .databaseScene(windowDatabase)        } else if DaysRoot.applies {            // Cotton Days in the Blue pen look: Days and Sometime, its own            // screens; no fan and no board (`Days/`).            DaysRoot(core: core)                .databaseScene(windowDatabase)        } else if ChatRoot.applies {            // Cotton Chat in the Warm look: sign-in first, then Chats, Calls            // and You on a floating pill; no fan and no board (`Chat/`).            ChatRoot(core: core)                .databaseScene(windowDatabase)        } else if HealthModel.applies {            // Cotton Health: Labs, Body, Reports and Settings on a bottom bar,            // in the core's look; no fan and no board (`HealthApp/HealthRoot.swift`).            Group {                if let healthApp { HealthRoot(model: healthApp.model) } else { Color.clear }            }            .databaseScene(windowDatabase)        } else {            StackHost(navigator: navigator, deps: routeDeps, project: boardProject) { homeScreen }                .databaseScene(windowDatabase)        }        #else        StackHost(navigator: navigator, deps: routeDeps, project: boardProject) { homeScreen }            .databaseScene(windowDatabase)        #endif    }    /// The board, as the phone's stack roots it — the same `HomeBoard` the    /// Mac's window draws, over the same read. Built here rather than inside    /// `StackHost` because every argument below is `RootView`'s own state.    private var homeScreen: some View {        HomeBoard(home: home,            databaseName: windowDatabase.shown(in: databases)?.name ?? boot.serverName,            personal: windowDatabase.shown(in: databases)?.kind != .shared,            project: $boardProject)    }    /// What this window's screens are keyed on: the shown project database,    /// or one constant for the personal one — which is also what a window    /// shows before it has chosen, so the first seed rebuilds nothing.    private var shownKey: String {        windowDatabase.shown(in: databases).flatMap { $0.isPersonal ? nil : $0.databaseId } ?? "personal"    }    @ViewBuilder private var stack: some View {        hosts        .id(shownKey)        .environment(meRead)        #if os(iOS)        // The fan's prints and each database's page pictures, over the        // rebuild (`StalePages`).        .environment(stalePages)        // The launch's splash stands over the stack until Home is read and        // stands whole (`FanLaunch`), never past the boot's ceiling — and        // goes at once for a screen opened over Home at launch (a link, a        // notification, capture): that screen is what is seen, not the fan.        .task { await FanLaunch.waitOutCeiling() }        .onChange(of: !navigator.path.isEmpty || navigator.capture != nil, initial: true) { _, over in            if over { FanLaunch.stand() }        }        #endif        // The one full-screen viewer: a picture, a film or a document opened        // anywhere below opens here, over the whole stack, with everything        // the stack is handed below.        .hostsViewer()        #if os(iOS)        // The one book reader (`BookReaderScreen`).        .hostsReader()        #endif        // The path, for every screen below: `navigator.push(route)` opens,        // `dismiss()` closes. And the alarm reconciler, for the one screen        // that shows it.        .environment(navigator)        // The share sheet's intake, which a deck's "+" doors hand the files        // they choose to (`DeckDoors`).        .environment(\.shareIntake, shares)        .environment(\.rekeyThisDevice, { [rekey = session.rekey] in await rekey.start() })        // This device's Sign in, Sign out and Erase, from its card wherever        // it is opened (`PersonalSessionFlows`); the sign-in sheet they raise.        // Its Share ink hands the ink the phone kept to the share sheet.        .environment(\.nativeKeptFlow, { [personal = session.personal, shares] request in            // A film's, a season's, a series' and an episode's Keep on phone            // and Remove download (`FilmKeeper`).            #if os(iOS)            switch request.flow {            // A book's Add file: its EPUB or PDF chosen in the system's            // picker, staged as a share is and taken through the share            // sheet's book branch into that book.            case .addBookFile:                guard let picked = await SystemFilePicker.pick(BookFileTypes.all) else { return false }                guard let url = picked.first else { return true }                await shares.intake(stageForIntake([url], at: CottonDate.format(Date())), intoBook: request.origin.id)                return true            case .keepFilm: return await FilmKeeper.shared.keep(table: request.origin.table, id: request.origin.id)            case .removeFilmDownload: return await FilmKeeper.shared.remove(table: request.origin.table, id: request.origin.id)            // A podcast episode's, the same way (`EpisodeKeeper`).            case .keepEpisode: return await EpisodeKeeper.shared.keep(table: request.origin.table, id: request.origin.id)            case .removeEpisodeDownload: return await EpisodeKeeper.shared.remove(table: request.origin.table, id: request.origin.id)            // A book's, the same way (`BookKeeper`).            case .keepBook: return await BookKeeper.shared.keep(table: request.origin.table, id: request.origin.id)            case .removeBookDownload: return await BookKeeper.shared.remove(table: request.origin.table, id: request.origin.id)            // A song's and an album's, the same way (`SongKeeper`).            case .keepSong, .keepAlbum: return await SongKeeper.shared.keep(table: request.origin.table, id: request.origin.id)            case .removeSongDownload, .removeAlbumDownload: return await SongKeeper.shared.remove(table: request.origin.table, id: request.origin.id)            default: break            }            #endif            guard request.flow.session else { return false }            if request.flow == .shareInk { return await InkCapture.share() }            return await PersonalSessionFlows.run(request, personal: personal)        })        .modifier(PersonalSheets(personal: session.personal))        // A link still arriving (held or being placed): Home reads nothing        // under the screen it is about to open (`BoardCover`).        .environment(taps)        .environment(alarms)        // The terminal frames, for the one screen that draws them.        .environment(terminals)        // The strip floats over the WHOLE stack rather than over one screen:        // a receipt for a decision taken on `/decide/memory` has to survive the        // pop that decision may cause.        .cottonToasts(toasts)        // Handed down rather than fanned out: a pushed screen is not alive        // when `subscribe` fires, so the screens with a `noticed(_:)` seam        // watch `sync.revision` instead, and 4g's thirty-one hosts take the        // same fact through `.rereading { … }` — this view cannot know which        // of them is on screen, and that is the stack's question rather than        // the subscription's. See `SyncModel`'s own note for why the counter        // and not the list, and `Sync/DataEventReread.swift` for the modifier.        .environment(\.cottonSync, sync)        // The databases this device holds, for every window's scene, the        // centre cap and the Databases screen.        .environment(databases)        // The pairing, for the one act that ends it: leaving the personal        // database (`KeptFlow.leaveDatabase`).        .environment(boot)        // The personal object's session, for Settings' Backup and Cotton        // server cards and the empty deck of a tool only the server fills.        .environment(session.personal)        // And every list and page reads again when a sync or an assistant's        // write lands: the core's `data` event moves `sync.revision`, and a        // surface keyed on `recordsRevision` reads in place (`RecordListModel        // .refresh`). The Mac's windows add their own inputs' bumps to it.        .environment(\.recordsRevision, sync.revision)        // And the core itself, for `Hosted` — the one reader that builds a        // pushed screen's model. `Scaffold/CottonCoreKey.swift` says why it is        // optional and why this is the only place it is set.        .environment(\.cottonCore, screens)        .environment(window.settingsTableStores)        // And the session's last answers, for `Hosted` too — the one reader        // that seeds a pushed screen's model before its first frame.        .environment(\.cottonAnswers, answers)        // And the notifications model, for the one screen that spends the one        // prompt — the todo that gets an hour. Handed down for `cottonSync`'s        // reason: a pushed screen is not alive when the root wires itself up.        .environment(\.cottonNotifications, notifications)        // And capture — the thoughts dock's service and drain. Optional in the        // environment on purpose: a screen mounted with none draws no bar.        .environment(\.cottonCapture, capture)        // And the OS's permissions, behind one seam (`Capabilities/`).        .environment(\.cottonCapabilities, SystemCapabilityAuthority())        // And the converted tools' lists and pages: the record verbs, the        // table definitions and the titles link columns show.        .environment(\.records, tables.records)        .task(id: windowDatabase.shownId) { await refreshToolPackages() }        .onReceive(NotificationCenter.default.publisher(for: .toolPackagesChanged)) { _ in            Task { await refreshToolPackages() }        }        .environment(\.tableDefinitions, tables.definitions)        .environment(\.linkTitles, tables.linkTitles)        // And the database's theme: every face below reads its skin from it.        // Read again on a switch and whenever a write lands — a theme row        // syncs like any other row.        .themed(window.themes.theme)        .environment(window.themes)        .task(id: windowDatabase.shownId) { await window.themes.refresh() }        .onChange(of: sync.revision) { _, _ in Task { await window.themes.refresh() } }        // And the app's own words (`ShellLines`): the shown database's `lines`        // rows, read on a switch and again whenever a sync lands.        .task(id: windowDatabase.shownId) {            await ShellLines.refresh(window.screens)            CountLines.shared.use(window.screens)        }        .onChange(of: sync.revision) { _, _ in            Task { await ShellLines.refresh(window.screens) }            CountLines.shared.use(window.screens)        }        // The identity can arrive in two beats (the workspace with the file,        // the owner's id with the cached `/v1/me`); the context follows it.        .onChange(of: boot.ownerId) { _, _ in if leads { composeCapture() } }        .onChange(of: boot.workspaceId) { _, _ in if leads { composeCapture() } }        // A fold that named the capture table is the moment a chip's record        // may have landed. `revision`, not `invalidated`, for `SyncModel`'s        // reason: two folds carrying the same tables would wake this once.        .onChange(of: sync.toolPackagesRevision) { _, _ in            Task { await refreshToolPackages(reload: true) }        }        .onChange(of: sync.revision) { _, _ in            guard leads, sync.invalidated.contains(.core) else { return }            Task { await capture?.drain() }        }        // A tap that arrived before the gate resolved was HELD; now it is        // replayed, once. `useNotificationTaps({isReady})`'s rule, kept: a cold        // start's tap must land on the screen it named, not be lost because the        // file was not open yet.        //        // Through `open`, not `push` (design 2026-09-13 §4.3/§4.4). What `open`        // DOES with the route is the HOST's rule (`Navigator.arrival`), not        // this view's: the phone pushes it over the stack, and the Mac replaces        // the path with the list AND the page the route names, so a link into        // a record opens the list it belongs to instead of sitting beside        // whichever list the launch selected.        //        // An ACTION-tier route goes back to Home first on the phone, where        // capture is drawn — `open`'s own rule, for every caller.        //        // Each link's database is shown in this window before its route opens,        // and a database this device does not hold opens nothing        // (`Surfaces/Databases/DatabaseLinkPlacing.swift`).        .task {            let links = DatabaseLinkPlacing(model: databases, scene: windowDatabase, toasts: toasts, core: core)            taps.open(placing: { await links.place($0) }) { route in navigator.open(route) }        }        // The sync facts are read ONCE here rather than by Home's own read:        // Home asks one question of the crate (design P4) and this is a        // different question, kept live after this by the `sync` events.        .task { if leads { await sync.refresh() } }    }    /// Pay an owed share drain, if the gate has a file open to drain into.    ///    /// **One drain per foreground**, and this is one of the four things that    /// may ask for it. A knock arriving in a foreground the `.active` edge has    /// already drained is not a second drain: the only entry that could still    /// be waiting is a refusal put back for a later try, and spending that try    /// in the same second is the bug `Boot/ShareArrivals.swift` describes.    private func drainSharesIfOwed() {        guard case .ready = boot.screen, !boot.holdsDrains, shareArrivals.takeOwedDrain() else { return }        Task { _ = await shares.drain() }    }    /// Import a package the system opened the app with. Ready, it goes    /// straight through the drain's branches (`ShareIntake.intake`) — not a    /// second drain, so a share waiting for its retry keeps waiting. Not    /// ready yet (a cold launch BY the package, the ordinary case), it waits    /// in the mailbox as a share would, and the drain the gate's `.ready`    /// pays takes it. The system's own copy (`Documents/Inbox`, the file is    /// opened as a copy) is removed once staged.    private func openPackage(_ url: URL) {        let staged = stageForIntake([url], at: CottonDate.format(Date()))        if url.path.contains("/Documents/Inbox/") { try? FileManager.default.removeItem(at: url) }        guard !staged.isEmpty else {            toasts.show(ShellLines.line("databases", "package.refused"), tone: .error)            return        }        if case .ready = boot.screen, !boot.holdsDrains {            Task { await shares.intake(staged) }            return        }        let mailbox = ShareMailbox()        for entry in staged { mailbox.append(entry) }        shareArrivals.arrived()    }    private func composeCapture() { session.composeCapture() }    /// What the table's arms need that the environment does not carry.    private var routeDeps: RouteDeps {        RouteDeps(            sync: sync,            boot: boot,            // `/settings#photos` keys its switch on the workspace, exactly as            // `useWorkspace(user?.id)` did; `nil` disables the row rather than            // drawing one that would write nowhere.            workspaceId: home.workspaceId,            chatExports: chatExports,            shares: shares,            home: home        )    }}// MARK: - The pushed screens' hostsenum SplashKnobs {    /// The object an app on its own ground launches with, cut out of its    /// icon, in its flavour's asset catalogue (`scripts/gen-launch-screens.py`).    static let launchObject = "LaunchObject"    /// The app's launch object, when its flavour has one: a flavour whose    /// object is not painted yet launches on its bare ground, and so does    /// its splash.    @MainActor static let object: Image? = {        #if canImport(UIKit)            UIImage(named: launchObject).map { Image(uiImage: $0) }        #else            nil        #endif    }()}/// What the splash lays: Notes' standing theme, a flat app's own colour, an/// app's own ground, or Home's plaster (Cotton).enum SplashGround: Equatable {    case notes, flat, face(FaceGround), plaster    static func of(notes: Bool, manifest: FlavourManifest?, face: FaceGround?) -> SplashGround {        if notes { return .notes }        // A flat app whose pages name no ground of their own (`blank`, the        // shell's paper: Days, Story, Meetings) launches on its own one        // colour, as its launch storyboard does. It laid the paper, and Days        // showed a cream page between its launch screen and its first day        // (21 Nov 2026). An app with a real ground (Keys' leather) keeps it.        if manifest?.flat == true, face == nil || face == .blank { return .flat }        if let face { return .face(face) }        return .plaster    }}/// A flat app's splash: its launch colour (`LaunchGround`), and its word mark if it has one.private struct SplashFlatGround: View {    var body: some View {        #if canImport(UIKit)        Color(uiColor: LaunchGround.colour).ignoresSafeArea()        #else        Color.clear        #endif        if let object = SplashKnobs.object {            object                .frame(maxWidth: .infinity, maxHeight: .infinity)                .ignoresSafeArea()                .accessibilityHidden(true)        }    }}/// Cotton Notes' splash: its standing theme's ground, from the first frame.private struct SplashNotesGround: View {    @Environment(\.colorScheme) private var scheme    var body: some View {        #if os(iOS)        Color(uiColor: NotesLook.standing(dark: scheme == .dark).ground).ignoresSafeArea()        #else        Color.clear        #endif        // Its wordmark, where the launch screen lays it (`LaunchObject`, light and dark): the mark stays put from the        // launch screen to the first note list (22 Nov 2026).        if let object = SplashKnobs.object {            object                .frame(maxWidth: .infinity, maxHeight: .infinity)                .ignoresSafeArea()                .accessibilityHidden(true)        }    }}/// The splash, drawn by the app rather than by a storyboard.////// Cotton's `UILaunchScreen` in `project.yml` names only its colour on purpose:/// without it the app runs letterboxed in a compatibility window, and with a/// storyboard the ground and the mark would be a second, unversioned copy of/// the design. So the launch screen is bare and this view continues it — the/// constellation-C on Home's plaster — and goes in ONE frame once the first/// screen takes it down: on the phone, once Home is read and stands whole/// (`FanLaunch`). Never a fade: a splash fading out over a Home is a faded/// Home with the logo over it (295 B, walker294: a ghost Home under the/// logo for 250 ms at every cold launch).public struct SplashOverlay: View {    @State private var visible = true    public init() {}    /// The transaction the splash goes in: no animation, its own or any    /// the caller's change carries — the frame before shows the splash, the    /// frame after the screen under it at full.    static var cut: Transaction {        var cut = Transaction(animation: nil)        cut.disablesAnimations = true        return cut    }    public var body: some View {        ZStack {            if visible {                ZStack {                    // **The splash is the ground every first screen stands                    // on** — Home's plaster, the same one the gate                    // screens and Home paint (redesign phase 19), so the seam                    // out of the splash is one material rather than a white                    // page giving way to plaster. The system's bare launch                    // screen before it is still light (`UIUserInterfaceStyle:                    // Light` in every Info.plist), and a light warm plaster                    // after white is a far smaller step than the charcoal                    // splash that used to be the flash. The logo keeps the                    // default ink, unchanged.                    // An app that stands on a ground of its own draws its                    // launch screen again (its flavour's `LaunchScreen`                    // storyboard: the ground laid as `FaceGroundSurface` lays                    // it, from the screen's top left, and its icon's object                    // cut out and centred on the screen at its own size,                    // `LaunchObject`), so the first frame the app draws is the                    // launch screen's and nothing moves (13 Nov 2026).                    #if os(iOS)                    let notes = NotesRoot.applies                    #else                    let notes = false                    #endif                    switch SplashGround.of(notes: notes, manifest: FlavourManifest.current, face: FaceGround.launch) {                    case .notes:                        // Cotton Words launches flat on its standing theme's ground, light or dark,                        // as its launch screen does (flavour.json `flat`), with its wordmark.                        SplashNotesGround()                    case .flat:                        SplashFlatGround()                    case .face(let ground):                        FaceGroundSurface(ground).ignoresSafeArea()                        if let object = SplashKnobs.object {                            object                                .frame(maxWidth: .infinity, maxHeight: .infinity)                                .ignoresSafeArea()                                .accessibilityHidden(true)                        }                    case .plaster:                        PlasterGround().ignoresSafeArea()                        ConstellationMark().frame(width: 84, height: 120)                    }                }            }        }        .allowsHitTesting(visible)        .onAppear {            SplashState.shared.onHidden { withTransaction(Self.cut) { visible = false } }        }    }}/// Whether this app keeps reminders: Comms, Words and Story keep none (Android runs the pass in Days alone).enum ReminderApps {    static var keeps: Bool {        #if os(iOS)        return !(ChatRoot.applies || NotesRoot.applies || InkStoryRoot.applies)        #else        return true        #endif    }}