Cotton code
794 lines · 41.5 KB · SwiftRaw
// Synthetic Home on a simulator, for looking at Home and recording it: the// app's own stack host, Home's board surface and the screens a tile opens,// over the bundled synthetic records in memory and a scripted core — no// household, keychain, network or owner's data. Built and launched by// `scripts/ui-tests-stub.sh --home-preview <udid>`.//// Launch arguments://   -home-board bare          a Home board with no parts (the frame still stands)//   -home-tiles N             how many tiles Home holds (default: every tool)//   -home-keys a|b            these tools' tiles first, in this order//   -hears "line|line"        what the record button "hears", one line a tap//                             (a simulator has no speech model); a Machines//                             tile and a person found by search come with it//   -scale "k=v,k=v"          theme scale tokens set over the shipped paper//                             theme, e.g. the owner's fan (fan_tile_w=72,//                             fan_step_deg=8,fan_visible_deg=76)//   -tools-late SECONDS       Home's tools arrive this long after launch, as//                             on a cold app whose read is slow//   -show-touches             a dot where each finger is: drawn at touch-down,//                             turned hollow at touch-up, so a recording shows//                             to the frame when a tap landed and lifted//   -databases "A|B"          the databases held, the first the personal one//                             (default: one, "Synthetic"); two or more draw//                             the fan's row of caps. A cap chosen switches as//                             the app's root does (`RootView.stack`): the new//                             database's Home is read while the old one//                             stands, then the stack is rebuilt on it, drawn//                             from that read in one frame//   -home-read-ms N           Home's read takes N ms (default 0), as a real//                             database's does (lane stalepic: 2–4 s on 285)//   -databases-late SECONDS   the first two databases are held at launch and//                             the rest arrive this long after, as copies do//   cottonhomepreview://record/<table>/<id>//                             opens that record over Home as a tap does//   cottonhomepreview://device, or -show-device at launch//                             opens This device (the bundled phone's row)//                             (scripts/perf/fan.sh's record-at-rest phase;//                             the URL type is the perf project's own)//   -open-record <table>/<id>  opens that record on the shown card's page at launch//   -page-walk                the shown card's page opens a note, a person//                             from it and a meeting from the person (no slip//                             touched, so each cross-fades), jumps back two,//                             then goes back to the root — what the navigator//                             is asked, a few seconds apart, for a recording;//                             the zoom and a spoken turn are a tap's//   -page-check               the page check (`PageCheck`): the main thread at//                             rest under each record, logged//   -perf-cold-start          write Documents/cold-start.json: ms from the//                             kernel's process start to the first frame after//                             Home (the fan) appeared (scripts/perf/fan.sh)//   -imported-tool            a Holidays tool made from data, with views of its own//   -list-rows N              Meetings, Mood, People and Email list N invented//                             rows more than their bundled few, so each//                             scrolls several screens (scripts/perf/scroll.sh);//                             the core's record reads answer from the same//                             rows, because Email reads its list through it//// The launch is the app's own: the splash (`SplashOverlay`) over the first// frame, the held list and Home read after it, and the splash down once Home// is read and stands whole (`FanLaunch`).import CottonKitimport SwiftUIimport UIKit@testable import CottonUI@main@MainActorfinal class HomePreviewApp: UIResponder, UIApplicationDelegate {    func application(_ application: UIApplication, configurationForConnecting session: UISceneSession,                     options: UIScene.ConnectionOptions) -> UISceneConfiguration {        let configuration = UISceneConfiguration(name: "Home preview", sessionRole: session.role)        configuration.delegateClass = HomePreviewScene.self        return configuration    }}@MainActorprivate final class HomePreviewScene: UIResponder, UIWindowSceneDelegate {    var window: UIWindow?    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options: UIScene.ConnectionOptions) {        guard let scene = scene as? UIWindowScene else { return }        let window = ProcessInfo.processInfo.arguments.contains("-show-touches")            ? TouchShowingWindow(windowScene: scene) : UIWindow(windowScene: scene)        self.window = window        window.rootViewController = UIHostingController(rootView: HomePreview())        window.makeKeyAndVisible()    }}private func argument(_ name: String) -> String? {    let arguments = ProcessInfo.processInfo.arguments    guard let at = arguments.firstIndex(of: name), arguments.indices.contains(at + 1) else { return nil }    return arguments[at + 1]}/// The theme the preview draws: the shipped paper theme, with the scale/// tokens `-scale` names set over it.enum PreviewTheme {    static var worn: Theme {        var theme = Theme.paper        for pair in (argument("-scale") ?? "").split(separator: ",") {            let parts = pair.split(separator: "=")            if parts.count == 2, let value = Double(parts[1]) {                theme.scale.values[String(parts[0])] = CGFloat(value)            }        }        return theme    }}@MainActorprivate struct HomePreview: View {    @State private var navigator = Navigator()    @State private var toasts = ToastCenter()    @State private var world: World?    @State private var taps = PendingTaps()    @State private var terminals = TerminalBus()    @State private var stores = SettingsTableStores()    @State private var stale = StalePages()    /// Everything the preview draws over, made once.    @MainActor    struct World {        let home: HomeModel        let deps: RouteDeps        let definitions: TableDefinitions        let records: FixtureRecords        let board: BoardDefinition        let core: ScriptedCore        let sync: SyncModel        let boot: BootModel        let alarms: AlarmSyncModel        let databases: DatabasesModel        let themes: ThemeModel        let scene: DatabaseScene        /// The core every screen is handed: the scripted one, or with        /// `-list-rows` the one whose record reads answer from `records`.        let calls: any CottonCalling    }    var body: some View {        // The app's launch, as its root draws it (`RootView`): the splash —        // the logo on the paper — over everything from the first frame,        // until Home is read and stands whole (`FanLaunch`), its timeline        // from the window's first appearance (`SwitchClock.launching`).        ZStack {            preview            SplashOverlay()        }        // As the app's root hosts it: a lift dims the whole window.        .liftsActs()        .onAppear { SwitchClock.launching() }    }    private var preview: some View {        Group {            if let world {                // The shown database's own name, as the app's root passes it.                let shownName = world.scene.shown(in: world.databases)?.name ?? "Synthetic"                // As the app's root keys its stack (`RootView.shownKey`).                let shownKey = world.scene.shown(in: world.databases).flatMap { $0.isPersonal ? nil : $0.databaseId } ?? "personal"                // As `HomeBoard` names the shown database to read.                let shownCalls: String? = {                    let shown = world.home.shownDatabase(scene: world.scene, in: world.databases)                    return shown.known ? shown.database ?? "" : nil                }()                StackHost(navigator: navigator, deps: world.deps) {                    BoardSurface<SearchResults>(                        project: .constant(nil),                        // As the app's Home passes them (`HomeBoard`): the shown                        // database's own order, resolved for it in this frame.                        tools: world.home.drawnRows(scene: world.scene, in: world.databases, everyTool: false),                        arrangement: world.home.drawnTiles(scene: world.scene, in: world.databases),                        projects: [],                        databaseName: shownName,                        board: world.board,                        home: BoardHome(model: world.home, devices: nil, databaseName: shownName, project: nil, now: Date(),                                        onLeaveProject: {}),                        results: nil,                        onOpenTable: { navigator.open(HomeBoard.route(for: $0, in: world.home.dataRows, definitions: world.definitions)) },                        onOpenTool: { tool in if let route = Route.parse(tool.path) { navigator.open(route) } })                    // Read as it shows, as `HomeBoard` reads: not before the                    // held list names the shown database, the switch's read                    // once, and again for an answer read for another.                    .task {                        guard shownCalls != nil else { return }                        await world.home.loadUnlessPrepared()                    }                    .task(id: [shownCalls ?? "unnamed", world.home.answeredFor ?? "personal"]) {                        guard let shownCalls else { return }                        await world.home.readAgainIfAskedElsewhere(shown: shownCalls.isEmpty ? nil : shownCalls)                    }                }                // Another database shown: rebuilt on it, on the answer the                // switch read before it turned (`RootView.stack`,                // `.onChange(of: shownKey)`, and `HomeBoard`'s read as it shows).                .id(shownKey)                .environment(stale)                .onChange(of: shownKey) { _, _ in                    SwitchClock.mark("shown", world.scene.shownId)                    navigator.popToRoot()                    world.home.turnToAsked()                }                // The launch's ceiling and a screen opened over Home at                // launch, as the app's root has them.                .task { await FanLaunch.waitOutCeiling() }                .onChange(of: !navigator.path.isEmpty || navigator.capture != nil, initial: true) { _, over in                    if over { FanLaunch.stand() }                }                // The window's database seeded from the held list, as the                // app's root does (`DatabaseSceneWiring`): the list first,                // then what is said around it; a list that moves seeds again.                .task {                    let shown = await world.databases.refreshList()                    await world.scene.seed(from: world.databases)                    await world.databases.refreshAround(shown: shown)                }                .onChange(of: world.databases.held) { _, _ in                    Task { await world.scene.seed(from: world.databases) }                }                .environment(navigator)                .environment(toasts)                .environment(\.tableDefinitions, world.definitions)                .environment(\.records, world.records)                .environment(\.cottonCore, world.calls)                // The record button's dock writes through the scripted core.                .environment(\.cottonCapture, CaptureContext(                    userId: "preview", workspaceId: "preview", core: world.core, report: { _ in }))                .environment(\.dictationSource, ScriptedHearing.source)                // The parser's Swift port: the scripted core reads no phrases.                // The Ask in memory: with none, every composer says it cannot                // write here, and a recording shows that instead of the page.                .environment(\.askSending, FixtureAsk())                // What the app's root hands every screen (`RootView.stack`),                // over the scripted core.                .environment(taps)                .environment(world.alarms)                .environment(terminals)                .environment(\.cottonSync, world.sync)                .environment(world.databases)                .environment(world.boot)                .environment(stores)                .environment(world.themes)                .environment(world.scene)                .environment(\.theme, PreviewTheme.worn)                .onAppear { if ProcessInfo.processInfo.arguments.contains("-perf-cold-start") { ColdStart.measure() } }                // `-dev.frames.on YES`: one line a second of frames drawn and                // late (`DevFrames`), at tmp/dev-frames.log — the simulator's                // stand-in for Instruments' Hitches, which does not run there.                .task { DevFrames.shared.startIfAsked() }                .onChange(of: navigator.tile ?? "home", initial: true) { _, tile in DevFrames.shared.place = tile }                .task { if ProcessInfo.processInfo.arguments.contains("-show-device") { navigator.open(.device) } }                .task {                    // A record opened on the shown card's page at launch.                    guard let record = argument("-open-record")?.split(separator: "/"), record.count == 2 else { return }                    try? await Task.sleep(for: .seconds(1))                    navigator.open(.tableRecord(table: String(record[0]), id: String(record[1])))                }                .task { if ProcessInfo.processInfo.arguments.contains("-page-walk") { await PageWalk.run(navigator) } }                .task { if PageCheck.asked { await PageCheck.run(navigator) } }                .onOpenURL { url in                    let parts = url.pathComponents.filter { $0 != "/" }                    if url.host == "device" { return navigator.open(.device) }                    guard url.host == "record", parts.count == 2 else { return }                    navigator.open(.tableRecord(table: parts[0], id: parts[1]))                }            } else {                Color.clear            }        }        // The app root's own measure of the top safe area (`CottonApp`).        .measuresTopInset()        .task { if world == nil { world = await Self.make(toasts: toasts) } }    }    static func make(toasts: ToastCenter) async -> World {        let loaded = FixtureDefinitions.load().definitions + ImportedTool.tables        var keys: [String] = []        for definition in loaded {            if let key = definition.tool?.key, !keys.contains(key) { keys.append(key) }        }        // An imported tool's tile, beside the built-ins (`-imported-tool`).        keys += ImportedTool.tools.map(\.id)        // Named tiles first, in the order given: a walk turns to them.        if let first = argument("-home-keys")?.components(separatedBy: "|") {            keys = first.filter(keys.contains) + keys.filter { !first.contains($0) }        }        if let most = argument("-home-tiles").flatMap(Int.init) { keys = Array(keys.prefix(most)) }        var tiles = keys.map { ["id": "tool/\($0)", "tool": $0] }        if ScriptedHearing.lines != nil { tiles.append(["id": "code/agent_login", "tool": "code", "table": "agent_login", "name": "Machines"]) }        let answer: [String: Any] = [            "askedOfYou": ["rows": [], "total": 0], "projects": [], "counts": [:], "workspace": NSNull(),            "arrangement": ["tiles": tiles], "doneForYou": [],        ]        let json = String(data: (try? JSONSerialization.data(withJSONObject: answer)) ?? Data(), encoding: .utf8) ?? "{}"        // The databases held, invented: the first is the personal one.        let names = argument("-databases")?.components(separatedBy: "|") ?? ["Synthetic"]        let held: [[String: Any]] = names.enumerated().map { index, name in            ["databaseId": index == 0 ? "preview-personal" : "preview-\(index)", "name": name,             "kind": index == 0 ? "personal" : "shared",             // A shared database is shared with someone: invented people.             "people": index == 0 ? [] : Array(["Asha", "Ravi", "Meera"].prefix(1 + (index - 1) % 3))]        }        func listing(_ held: [[String: Any]]) -> String {            String(data: (try? JSONSerialization.data(withJSONObject: ["databases": held, "shown": [], "elsewhere": []])) ?? Data(),                   encoding: .utf8) ?? "{}"        }        // `-databases-late S`: the first two are held at launch and the rest        // arrive S seconds later, as copies do after a launch — the caps' arc        // grows, and nothing of the fan may move (295 B).        let databasesLate = argument("-databases-late").flatMap(Double.init)        let databasesJSON = listing(databasesLate == nil ? held : Array(held.prefix(2)))        // Home's answer, and a kept thought for the record button's send.        let late = argument("-tools-late").flatMap(Double.init)        let empty = #"{"askedOfYou":{"rows":[],"total":0},"projects":[],"counts":{},"workspace":null,"arrangement":{"tiles":[]},"doneForYou":[]}"#        let core = ScriptedCore([            CottonMethod.readDatabases: .ok(databasesJSON),            CottonMethod.readHome: .ok(late == nil ? json : empty),            CottonMethod.captureCreate: .ok(#"{"id":"preview-thought","kind":"thought"}"#),            // Every search finds the bundled first person.            CottonMethod.readFind: .ok(#"{"hits":[{"kind":"person","id":"example-person-1","title":"Example Person"}]}"#),            // This device is the bundled phone's row.            CottonMethod.readDevices: .ok(#"{"thisDevice":"example-device-2"}"#),            // Me is the bundled first person, with no print: the card wears            // their initials.            // Today on Me: one invented event and one invented todo, today.            CottonMethod.readDay: .ok(previewToday()),            CottonMethod.readYou: .ok(#"{"database_id":"example-personal","person_id":"example-person-1","name":"Example Person","print":null,"sign_in":[],"devices_count":1}"#),        ])        let readMs = argument("-home-read-ms").flatMap(Int.init) ?? 0        let databases = DatabasesModel(source: CoreDatabases(core: core))        let home = HomeModel(core: SlowHomeCore(base: core, readMs: readMs), toasts: toasts, databases: databases)        let sync = SyncModel(core: core)        let boot = BootModel(core: core, clock: .instant)        let deps = RouteDeps(            sync: sync, boot: boot, workspaceId: nil,            chatExports: ChatExportHandoff(), home: home, onJoin: {})        // The fan is the app's frame, never the board's: `-home-board bare`        // hands Home a board with no parts, and the dial still stands.        let shipped = BoardDefinition.shipped("home")        let parts = argument("-home-board") == "bare" ? [] : shipped.parts        // A window reopened on the database it showed (`@SceneStorage`): the        // held list, read after the first frame, names it.        let scene = DatabaseScene(shownId: "preview-personal")        // Home reads the database the window's calls name, as the root aims        // it; a switch reads the new database before it turns, and Home turns        // with the calls and reads them if its answer is another's        // (`WindowSession`). Nothing is read here: the launch reads as the        // app's does, under the splash.        home.askingDatabase = { [calls = scene.calls] in calls.id }        scene.prepare = { [home] id, calls in await home.prepare(shown: id, calls: calls) }        scene.aimed = { [home, calls = scene.calls] _ in            home.turnToAsked()            let asked = calls.id            Task { @MainActor in await home.readAgainIfAskedElsewhere(shown: asked) }        }        if let databasesLate {            let every = listing(held)            Task {                try? await Task.sleep(for: .seconds(databasesLate))                await core.answer(CottonMethod.readDatabases, .ok(every))                await databases.refreshList()            }        }        if let late {            Task {                try? await Task.sleep(for: .seconds(late))                await core.answer(CottonMethod.readHome, .ok(json))                await home.load()            }        }        let records = ListRows.records(loaded, rows: ListRows.count ?? 0)        return World(            home: home, deps: deps, definitions: TableDefinitions(loaded), records: records,            board: BoardDefinition(id: shipped.id, parts: parts), core: core, sync: sync, boot: boot,            alarms: AlarmSyncModel(core: core), databases: databases,            themes: ThemeModel(themes: CoreThemes(core: core)), scene: scene,            calls: RowsCore(base: core, records: records, definitions: loaded))    }}/// The scripted core with Home's read taking `readMs`, as a real database's/// does — and, as the core's own call, not stopped by the task that asked.private final class SlowHomeCore: CottonCalling, @unchecked Sendable {    nonisolated let base: ScriptedCore    nonisolated let readMs: Int    nonisolated init(base: ScriptedCore, readMs: Int) {        self.base = base        self.readMs = readMs    }    nonisolated func callRaw(_ method: String, requestJSON: String) async throws -> String {        if method == CottonMethod.readHome, readMs > 0 {            await withCheckedContinuation { (done: CheckedContinuation<Void, Never>) in                DispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(readMs)) { done.resume() }            }        }        return try await base.callRaw(method, requestJSON: requestJSON)    }    nonisolated func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async { await base.subscribe(handler) }    nonisolated func close() async { await base.close() }}/// `-list-rows N`: the lists the scroll sweep flings (scripts/perf/scroll.sh)/// hold N invented rows beyond their bundled few. A bundled list of two or/// five rows does not scroll, so the fan never folds over it and a fling/// measures nothing. Each row is a bundled fixture row again under a new id,/// its title numbered and its date stepped back five hours a row, so the/// list's own order spreads them down the page. Invented data only.enum ListRows {    static let count = argument("-list-rows").flatMap(Int.init)    /// The tables of Meetings, Mood, People and Email.    static let tables: Set<String> = ["meeting", "mood", "person", "email_thread"]    /// The preview's rows: the bundled fixtures, Email's scripted mailbox    /// (`ScriptedMailbox`), and with `-list-rows` N more of each list's.    static func records(_ definitions: [TableDefinition], rows: Int) -> FixtureRecords {        var records: [String: [TableRecord]] = [:]        for definition in definitions {            var bundled = (try? FixtureDefinitions.fixtureRecords(for: definition.id)) ?? []            if definition.id == ScriptedMailbox.table { bundled += ScriptedMailbox.threads() }            bundled += ImportedTool.rows[definition.id] ?? []            records[definition.id] = tables.contains(definition.id) && rows > 0 ? bundled + more(of: bundled, in: definition, rows) : bundled        }        return FixtureRecords(definitions: definitions, records: records, tools: ImportedTool.tools)    }    static func more(of bundled: [TableRecord], in definition: TableDefinition, _ rows: Int) -> [TableRecord] {        guard !bundled.isEmpty else { return [] }        let dated = Set([definition.date, definition.sort?.column].compactMap { $0 })        return (0 ..< rows).map { index in            var row = bundled[index % bundled.count]            row.id = "synthetic-\(definition.id)-\(index + 1)"            if let title = row[definition.title].text { row.values[definition.title] = .text("\(title) \(index + 1)") }            for key in dated {                guard let text = row[key].text, let at = CottonDate.parse(text) else { continue }                row.values[key] = .text(CottonDate.format(at.addingTimeInterval(-Double(index + 1) * 5 * 3600)))            }            return row        }    }}/// `-imported-tool`: one tool made from data, as a person imports one — a/// Holidays tool over its own table, with two views of its own (All, and This/// month) — so its ring stands on the fan like a built-in's. Invented data only.enum ImportedTool {    static let on = CommandLine.arguments.contains("-imported-tool")    static let table = "synthetic_holiday"    static var tables: [TableDefinition] {        guard on else { return [] }        let json = #"{"format_version":1,"id":"synthetic_holiday","name":"Holiday","plural":"Holidays","builtin":false,"tile":{"face":"slip-list"},"columns":[{"key":"name","name":"Name","type":"text"},{"key":"month","name":"Month","type":"text"},{"key":"starts_on","name":"Starts","type":"date"}],"title":"name","slip":{"title":"name","subtitle":"month","trailing":"starts_on"},"page":[{"heading":null,"columns":["name","month","starts_on"]}]}"#        return (try? JSONDecoder().decode(TableDefinition.self, from: Data(json.utf8))).map { [$0] } ?? []    }    static var tools: [ToolDefinition] {        guard on else { return [] }        var tool = ToolDefinition(            id: "synthetic-holidays", name: "Holidays", tables: [table], instructions: "Invented holidays.",            automations: [], author: .init(device: "preview", name: "Preview"), signature: nil)        var all = DefinitionToolView(_generated: (), id: "all", label: "All", read: ["table": .string(table)])        all.isDefault = true        var month = DefinitionToolView(            _generated: (), id: "this_month", label: "This month",            read: ["table": .string(table), "where": .object(["month": .string("This month")])])        month.isDefault = false        tool.views = [all, month]        return [tool]    }    static var rows: [String: [TableRecord]] {        guard on else { return [:] }        let made: [(String, String, String)] = [            ("Invented beach week", "This month", "2026-10-24"), ("Example mountain trip", "Next month", "2026-11-14"),            ("Synthetic city break", "This month", "2026-10-30"), ("Made-up lake weekend", "Later", "2027-01-09"),        ]        return [table: made.enumerated().map { index, holiday in            TableRecord(id: "synthetic-holiday-\(index + 1)", values: [                "name": .text(holiday.0), "month": .text(holiday.1), "starts_on": .text(holiday.2),            ])        }]    }}/// Email's scripted mailbox: invented conversations, one of each kind of/// sender and some from today, so every view on Email's ring (Today,/// Records, People, Junk, All) has mail to draw on the preview. Dated from/// the moment the preview starts; invented data only.enum ScriptedMailbox {    static let table = "email_thread"    static func threads(now: Date = Date()) -> [TableRecord] {        let mail: [(String, String, String, String, Double)] = [            ("Synthetic Friend", "friend@example.invalid", "person", "Lunch on the invented terrace?", 1),            ("Example Shop", "orders@shop.example.invalid", "service", "Your example order has shipped", 2),            ("Invented Prize Desk", "winner@junk.example.invalid", "junk", "You have won an example prize", 3),            ("Example Bank", "statements@bank.example.invalid", "service", "Your synthetic statement is ready", 30),            ("Example Neighbour", "neighbour@example.invalid", "person", "The example fence, again", 50),        ]        return mail.enumerated().map { index, letter in            let (sender, address, kind, subject, hoursAgo) = letter            let at = CottonDate.format(now.addingTimeInterval(-hoursAgo * 3600))            return TableRecord(id: "synthetic-mail-\(index + 1)", values: [                "subject": .text(subject), "sender": .text(sender), "sender_address": .text(address),                "preview": .text("An invented message for the preview."), "first_at": .text(at), "last_at": .text(at),                "email_count": .number(1), "read_state": .text(index == 0 ? "unread" : "read"), "starred": .bool(false),                "in_inbox": .bool(true), "binned": .bool(false), "sender_kind": .text(kind),            ])        }    }}/// The Passwords vault's list on the preview: invented secrets of every kind,/// answered to `read.secrets` (narrowed by its `kind`) with a vault this/// device holds the key to, so each view on Passwords' ring has rows. No/// value is ever sealed or shown here; invented data only.enum ScriptedVault {    static let secrets: [(kind: String, name: String)] = [        ("login", "Example portal"), ("login", "Invented forum"), ("login", "Synthetic bank login"),        ("identity", "Example passport"), ("api_key", "Invented weather API"), ("card", "Example travel card"),        ("note", "Synthetic door codes"), ("document", "Example lease"),    ]    static func answer(kind: String?) -> String {        let rows = secrets.enumerated().filter { kind == nil || $0.element.kind == kind }.map { index, secret in            let login = secret.kind == "login"            return """            {"id":"synthetic-secret-\(index + 1)","kind":"\(secret.kind)","name":"\(secret.name)",\            "site":\(login ? "\"example.invalid\"" : "null"),"username":\(login ? "\"nobody\"" : "null"),\            "service":null,"hint":null,"isSet":true,"legacy":false,"lastUsedAt":null,"expiresAt":null,\            "trashedAt":null,"createdAt":"2026-09-01T00:00:00.000Z","updatedAt":"2026-09-02T00:00:00.000Z"}            """        }        let status = #"{"hasKey":true,"wrapped":true,"unlocked":false,"until":null,"legacyCount":0,"vmkVersion":1}"#        return #"{"ok":true,"data":{"secrets":["# + rows.joined(separator: ",") + #"],"status":"# + status + #","kinds":{}}}"#    }}/// The core's `records.list` and `records.get` answered from the preview's/// in-memory rows, for a screen that reads through the core rather than/// `\.records` — Email's list (`EmailRecords`), which asks a page by its/// offset and is told the next one's, and a view's plan section by the/// reader's day ("today": the rows dated that day); and the vault's list/// (`ScriptedVault`). Every other method goes to the scripted core.private final class RowsCore: CottonCalling, @unchecked Sendable {    nonisolated let base: any CottonCalling    nonisolated let records: FixtureRecords    nonisolated let definitions: [String: TableDefinition]    nonisolated init(base: any CottonCalling, records: FixtureRecords, definitions: [TableDefinition]) {        self.base = base        self.records = records        self.definitions = Dictionary(definitions.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })    }    /// Whether a row is dated on the reader's `today` (YYYY-MM-DD), by the    /// table's date column, else its sort's.    private nonisolated func dated(_ row: TableRecord, on today: String?, in table: String) -> Bool {        let definition = definitions[table]        guard let column = definition?.date ?? definition?.sort?.column, let text = row[column].text,              let at = CottonDate.parse(text) else { return false }        let day = today.flatMap { CottonDate.formatter("yyyy-MM-dd", Calendar.current).date(from: $0) } ?? Date()        return Calendar.current.isDate(at, inSameDayAs: day)    }    private struct Asked: Decodable {        let table: String        let id: String?        let ids: [String]?        let page: Int?        let query: String?        let `where`: [String: RecordValue]?        let section: String?        let today: String?    }    private struct Row: Encodable {        let id: String        let data: [String: RecordValue]    }    private struct Page: Encodable {        let records: [Row]        let next_page: Int?        let total: Int    }    /// `read.secrets`' request: its narrowing rides under `args`.    private struct AskedSecrets: Decodable {        struct Args: Decodable { let kind: String? }        let args: Args?    }    nonisolated func callRaw(_ method: String, requestJSON: String) async throws -> String {        if method == CottonMethod.readSecrets {            let kind = (try? JSONDecoder().decode(AskedSecrets.self, from: Data(requestJSON.utf8)))?.args?.kind            return ScriptedVault.answer(kind: kind)        }        guard method == CottonMethod.recordsList || method == CottonMethod.recordsGet,              let asked = try? JSONDecoder().decode(Asked.self, from: Data(requestJSON.utf8))        else { return try await base.callRaw(method, requestJSON: requestJSON) }        do {            let answer: Data            if method == CottonMethod.recordsGet {                guard let id = asked.id, let record = try await records.get(table: asked.table, id: id) else {                    return #"{"ok":false,"error":{"code":"not_found","message":"no such record"}}"#                }                answer = try JSONEncoder().encode(Row(id: record.id, data: record.values))            } else if let ids = asked.ids {                var rows: [Row] = []                for id in ids {                    if let record = try await records.get(table: asked.table, id: id) { rows.append(Row(id: record.id, data: record.values)) }                }                answer = try JSONEncoder().encode(Page(records: rows, next_page: nil, total: rows.count))            } else {                // The core's page is an offset; the fixture store's an index of its page size.                let size = FixtureRecords.pageSize                let page = try await records.list(                    table: asked.table, project: nil, query: asked.query, page: (asked.page ?? 0) / size,                    where: asked.where ?? [:])                if asked.section == "today" {                    let rows = page.records.filter { dated($0, on: asked.today, in: asked.table) }                    answer = try JSONEncoder().encode(Page(                        records: rows.map { Row(id: $0.id, data: $0.values) }, next_page: nil, total: rows.count))                } else {                    answer = try JSONEncoder().encode(Page(                        records: page.records.map { Row(id: $0.id, data: $0.values) },                        next_page: page.next.map { $0 * size }, total: page.total ?? page.records.count))                }            }            return #"{"ok":true,"data":"# + String(decoding: answer, as: UTF8.self) + "}"        } catch {            return #"{"ok":false,"error":{"code":"refused","message":"the preview's rows could not answer"}}"#        }    }    nonisolated func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async { await base.subscribe(handler) }    nonisolated func close() async { await base.close() }}/// The record button's ears on a simulator: each session "hears" the next of/// `-hears`' lines, a word at a time, and settles it when the button stops;/// the meter moves with a voice's rise and fall while it speaks.private final class ScriptedHearing: SpeechRecognizing, AudioLevelSource {    static let lines: [String]? = argument("-hears").map { $0.components(separatedBy: "|") }    private static var next = 0    static var source: DictationSource? {        guard lines != nil else { return nil }        return DictationSource {            let hearing = ScriptedHearing()            return DictationModel(recogniser: hearing, levels: hearing)        }    }    private var sink: SpeechEventSink?    private var levels: AudioLevelSink?    private var line = ""    private var speaking: Task<Void, Never>?    private var metering: Task<Void, Never>?    func onLevel(_ sink: @escaping AudioLevelSink) { levels = sink }    func onEvent(_ sink: @escaping SpeechEventSink) { self.sink = sink }    func access() async -> CapabilityGateResult { .ready }    func prepare(_ hints: DictationHints) {}    func start(_ hints: DictationHints) {        let lines = Self.lines ?? []        line = lines.isEmpty ? "" : lines[Self.next % lines.count]        Self.next += 1        sink?(.started)        metering = Task { [weak self] in            var step = 0.0            while !Task.isCancelled {                self?.levels?(0.35 + 0.3 * sin(step) + 0.25 * sin(step * 2.7))                step += 0.4                try? await Task.sleep(for: .milliseconds(50))            }        }        let words = line.split(separator: " ").map(String.init)        speaking = Task { [weak self] in            for count in words.indices {                try? await Task.sleep(for: .milliseconds(450))                guard !Task.isCancelled else { return }                self?.sink?(.partial(words[...count].joined(separator: " ")))            }        }    }    func stop() {        speaking?.cancel()        metering?.cancel()        sink?(.segment(line))        sink?(.ended)    }    func cancel() {        speaking?.cancel()        metering?.cancel()        sink?(.failed(.aborted))    }}/// Cold start to the first frame of Home, as the speed gate measures it/// (`scripts/speedgate/SpeedApp.swift`): from the kernel's record of when the/// process started to the next display-link frame once Home has appeared.@MainActorprivate final class ColdStart: NSObject {    private static var held: ColdStart?    private var link: CADisplayLink?    static func measure() {        let clock = ColdStart()        held = clock        clock.link = CADisplayLink(target: clock, selector: #selector(frame(_:)))        clock.link?.add(to: .main, forMode: .common)    }    @objc private func frame(_ link: CADisplayLink) {        link.invalidate()        ColdStart.held = nil        var info = kinfo_proc()        var size = MemoryLayout<kinfo_proc>.stride        var name: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]        guard sysctl(&name, 4, &info, &size, nil, 0) == 0 else { return }        let started = info.kp_proc.p_starttime        let start = Double(started.tv_sec) + Double(started.tv_usec) / 1_000_000        let ms = (Date().timeIntervalSince1970 - start) * 1000        let folder = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]        let body = #"{"cold_ms":\#(String(format: "%.1f", ms))}"#        try? Data(body.utf8).write(to: folder.appendingPathComponent("cold-start.json"), options: .atomic)    }}/// `-page-walk`: a card's page opening records in place and going back, for/// a recording. Asked of the navigator, so no slip is touched: each opening/// cross-fades (a tap's zoom is recorded by tapping).@MainActor enum PageWalk {    static func run(_ navigator: Navigator) async {        try? await Task.sleep(for: .seconds(3))        guard let tile = navigator.tile else { return }        let steps: [() -> Void] = [            { navigator.open(.notesNote(id: "example-note-1")) },            { navigator.open(.peoplePerson(id: "example-person-1")) },            { navigator.open(.meetingsMeeting(id: "example-meeting-ready")) },            { navigator.back(to: 1, on: tile) },            { navigator.back(to: 0, on: tile) },        ]        for step in steps {            step()            try? await Task.sleep(for: .seconds(3))        }    }}/// `-show-touches`: each touch drawn over everything, filled while down and/// hollow for a moment after it lifts, so a screen recording carries the/// touch's own frames (a walk times a response from them).private final class TouchShowingWindow: UIWindow {    private var dots: [ObjectIdentifier: UIView] = [:]    override func sendEvent(_ event: UIEvent) {        super.sendEvent(event)        for touch in event.allTouches ?? [] {            let key = ObjectIdentifier(touch)            let point = touch.location(in: self)            switch touch.phase {            case .began:                let dot = UIView(frame: CGRect(x: 0, y: 0, width: 28, height: 28))                dot.layer.cornerRadius = 14                dot.backgroundColor = UIColor.systemBlue.withAlphaComponent(0.85)                dot.isUserInteractionEnabled = false                dot.center = point                addSubview(dot)                dots[key] = dot            case .moved, .stationary:                dots[key]?.center = point            case .ended, .cancelled:                guard let dot = dots.removeValue(forKey: key) else { continue }                dot.center = point                dot.backgroundColor = .clear                dot.layer.borderColor = UIColor.systemBlue.cgColor                dot.layer.borderWidth = 3                DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { dot.removeFromSuperview() }            default: break            }        }    }}/// `read.day`'s answer for the preview: an invented event at ten and an/// invented todo due at five, both today.private func previewToday() -> String {        let start = Calendar.current.startOfDay(for: Date())        let at = { (hour: Double) in CottonDate.format(start.addingTimeInterval(hour * 3600)) }        return #"{"occurrences":[{"eventId":"example-event-1","startsAt":"\#(at(10))","event":{"title":"Example planning call"}}],"todos":[{"id":"example-todo-1","title":"Water the example garden","dueAt":"\#(at(17))","status":"open"}]}"#}