Cotton code
256 lines · 15.2 KB · SwiftRaw
// This phone's own device record as its card (owner, 27 Oct 2026: "so we// know if the app has fully synced or not"), on Settings' Backup card since// 1 Nov 2026 and on a Home an object still holds. The core serves a board's// `device` part naming this device's record (`board::THIS_DEVICE_KEY`), and// Home's page (`shell.today`) deals the device tool's own card for it first —// read again alone (`only: device`) as the sync moves. Synthetic ids only.#if os(iOS)import CottonKitimport CottonValuesimport SwiftUIimport XCTestimport UIKit@testable import CottonUI@MainActorfinal class HomeDeviceCardTests: XCTestCase {    /// The fixture's own device: the row Settings › This device opens    /// (`settings.json`'s `/device`), status "this device".    private func thisDevice() throws -> TableRecord {        let devices = try FixtureDefinitions.fixtureRecords(for: "device")        return try XCTUnwrap(devices.first { $0["status"].text == "this device" }, "the device fixture holds this device")    }    /// This device's card as `shell.today` deals it: the record with its live    /// sync columns, worn in the device table's face, its slots the card's    /// words (title the name, subtitle the state, facts the sync rows).    private func deviceCard(_ record: TableRecord, done: Int = 812) throws -> [String: Any] {        var data = record.values        data["sync_rows_done"] = .number(Double(done))        data["sync_rows_total"] = .number(1_204)        data["sync_bytes"] = .number(3_145_728)        data["synced_at"] = .text("2026-10-27T09:30:00Z")        let values = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(data)) as? [String: Any])        return TodayAnswerJSON.card(            id: "device/\(record.id)", kind: "device", face: "plain", table: "device", record: record.id, data: values,            slots: [                "title": record["name"].text ?? "", "subtitle": record["state"].text ?? "",                "facts": [                    ["label": "Kind", "said": "iPhone"], ["label": "Rows synced", "said": "\(done)"],                    ["label": "Rows in all", "said": "1,204"], ["label": "Synced", "said": "3 MB"],                ],            ],            tap: ["card": "open.in_place"])    }    /// Home's page as the core answers it: this device's card, a day's row,    /// and the notices band's card.    private func page(_ record: TableRecord) throws -> String {        TodayAnswerJSON.answer(cards: [            try deviceCard(record),            TodayAnswerJSON.card(                id: "day/todo:t-invented", kind: "day", face: "today", table: "todo", record: "t-invented",                slots: ["title": "Invented errand", "line": "7:30 pm"],                opens: ["table": "todo", "id": "t-invented", "page": "t-invented"]),            TodayAnswerJSON.card(id: "part/notices", kind: "part", face: "part"),        ])    }    private func model(_ core: any CottonCalling) -> HomeModel {        HomeModel(core: core, toasts: ToastCenter(scheduler: ManualToastScheduler()))    }    /// RULE: the Home board the core serves names this device's record on its `device` part, the first part, and the app decodes it as it came — the app never works out which record is its own; a board served before the device has an identity names none, and the part draws nothing.    func testTheServedHomeBoardLeadsWithThisDevice() throws {        let id = try thisDevice().id        let served = #"{"id":"home","parts":[{"kind":"device","device_id":"\#(id)"},{"kind":"head","tags":[]},{"kind":"sync"},{"kind":"today"}]}"#        let board = try XCTUnwrap(BoardDefinition.decode(Data(served.utf8)))        XCTAssertEqual(board.parts.first?.settings["device_id"], .string(id))        XCTAssertEqual(board.parts.map(\.kind), ["device", "head", "sync", "today"], "the one-line sync part stays")        // The sync card is Home's again (owner, 2 Nov 2026): the shipped Home        // leads with it, as the deck draws only a `device` part's card.        XCTAssertEqual(BoardDefinition.home.parts.first?.kind, "device", "the shipped Home leads with this device's card")    }    /// RULE: Home's first card is this device's own record, as the core dealt it — drawn by the device tool's card with its sync facts (rows done of total, bytes) by the deck's own face dispatch, ahead of today's rows and the bands — so the owner sees at a glance whether the phone has fully synced.    func testHomesFirstCardIsThisDevicesCardWithItsSyncFacts() async throws {        let record = try thisDevice()        let home = model(ScriptedCore([CottonMethod.shellToday: .ok(try page(record))]))        XCTAssertNil(home.deviceCard, "before the page answers, no card")        await home.load()        let device = try XCTUnwrap(home.deviceCard, "this device's card is dealt")        XCTAssertEqual(device.table, "device")        XCTAssertEqual(device.deck.record.id, record.id)        XCTAssertEqual(device.deck.record.record["sync_rows_done"], .number(812))        XCTAssertEqual(device.deck.record.record["sync_rows_total"], .number(1_204))        XCTAssertEqual(device.deck.face, "plain", "the device table's existing face, no new one")        XCTAssertEqual(device.deck.slots["title"]?.text, record["name"].text)        let cards = try XCTUnwrap(home.answer?.cards)        XCTAssertEqual(cards.map(HomeToday.identifier),                       ["home-later-\(record.id)", "home-today-todo:t-invented", "home-part-notices"],                       "this device's card is first on Home's deck, in the core's order")        XCTAssertTrue(DeckFace.draws(device.deck.drawn(labels: DeckAnswer.Labels(by_slot: [:], by_column: [:]))),                      "drawn by the deck's own face dispatch")    }    /// RULE: this device's card moves with the sync, the page does not: it is read again alone (`shell.today {only: device}`) and takes the card's place in the page held, the rest of the page as it was.    func testTheDeviceCardIsReadAgainAloneAndTakesItsPlace() async throws {        let record = try thisDevice()        let core = ScriptedCore([CottonMethod.shellToday: .ok(try page(record))])        let home = model(core)        await home.load()        let moved = TodayAnswerJSON.answer(cards: [try deviceCard(record, done: 1_000)])        await core.answer(CottonMethod.shellToday, .ok(moved))        await home.readDevice()        let asked = await core.calls.filter { $0.method == CottonMethod.shellToday }        XCTAssertEqual(asked.count, 2)        XCTAssertTrue(asked[1].requestJSON.contains(#""only":"device""#), "the card alone: \(asked[1].requestJSON)")        XCTAssertEqual(home.deviceCard?.deck.record.record["sync_rows_done"], .number(1_000), "the card moved")        XCTAssertEqual(home.answer?.cards.map(\.kind), ["device", "day", "part"], "the rest of the page as it was")    }    /// RULE: a device card that cannot be read again leaves the card the page answered — no card is guessed and none is dropped — and a page with no device card holds none.    func testAnUnreadableDeviceKeepsTheCardItHad() async throws {        let record = try thisDevice()        let core = ScriptedCore([CottonMethod.shellToday: .ok(try page(record))])        let home = model(core)        await home.load()        await core.answer(CottonMethod.shellToday, .refuse(code: "unreadable", message: "invented"))        await home.readDevice()        XCTAssertEqual(home.deviceCard?.deck.record.record["sync_rows_done"], .number(812))        let bare = model(ScriptedCore([CottonMethod.shellToday: .ok(TodayAnswerJSON.answer())]))        await bare.load()        XCTAssertNil(bare.deviceCard)    }    /// RULE: Home's sync card opens IN PLACE, as any deck's record does (the card at rest on its ground, the acts tier beneath): opening it pushes no device record page, so Close leaves Home standing with its "+" (Cotton 348's walk: the pushed page had no "+" and nothing led back until a relaunch). Any other of Home's cards still opens on its tool's deck.    func testTheSyncCardOpensInPlaceAndCloseLeavesHome() throws {        let code = SourceSweep.withoutComments(            try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Surfaces/Board/HomeToday.swift", ownedBy: "home"))        let open = try XCTUnwrap(code.range(of: "private func open(_ card: TodayAnswer.Card) {"))        let device = try XCTUnwrap(code.range(of: "case \"device\":", range: open.upperBound..<code.endIndex))        let next = try XCTUnwrap(code.range(of: "case \"day\":", range: device.upperBound..<code.endIndex))        let opened = code[device.upperBound..<next.lowerBound]        XCTAssertTrue(opened.contains("deviceOpened = true"), "the sync card opens in place on Home")        XCTAssertFalse(opened.contains("navigator.open"), "nothing is pushed: Close leaves Home as it stood, its + with it")        XCTAssertTrue(code[next.upperBound...].contains("navigator.open(table: table"), "a birthday still opens its record")    }    /// RULE: Cotton's Home is the sync card and nothing else (owner, 2 Nov 2026): the shipped Home names this device's card and the tools the fan stands on, and no head, search, sync line, today, notices, recent, asked or done.    func testTheShippedHomeIsTheSyncCardAndTheTools() {        XCTAssertEqual(BoardDefinition.home.parts.map(\.kind), ["device", "tools"])    }    /// A served board may still name a device after the shipped Home moved it    /// to Backup (d1d3fb7d5). Hold Home's page until a pending frame reports:    /// neither the first simulator frame nor the read is bounded by a sleep.    func testHomeDoesNotDeclareItsFirstFrameReadyBeforeItsDeviceCard() async throws {        let record = try thisDevice()        let core = HeldPageCore(base: ScriptedCore([CottonMethod.shellToday: .ok(try page(record))]))        let home = model(core)        var readings: [FanPageReading] = []        let pending = expectation(description: "Home reports its pending device card")        pending.assertForOverFulfill = false        let ready = expectation(description: "Device card ready")        ready.assertForOverFulfill = false        let today = HomeToday(home: home, deckPage: true, devicePart: HomeDevicePart(id: record.id))        let view = FramedPage(page: AnyView(today), cover: FanCover(), laysGround: true,            arrival: FanPageArrival(id: "synthetic-home") { reading in                readings.append(reading)                if !reading.filled { pending.fulfill() }                if reading.ready { ready.fulfill() }            })        let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)        let window = UIWindow(windowScene: scene)        window.rootViewController = UIHostingController(rootView: view)        window.makeKeyAndVisible()        defer { window.isHidden = true; window.rootViewController = nil }        let asking = Task { await home.load() }        await fulfillment(of: [pending], timeout: 5)        XCTAssertFalse(readings.isEmpty)        XCTAssertFalse(readings.contains(where: \.ready), "Home is not ready while its page with its device card is unread")        await core.release()        await asking.value        await fulfillment(of: [ready], timeout: 5)        XCTAssertEqual(readings.last?.filled, true)    }    /// RULE: Home's sync card follows the board that names it whenever that board's read lands — also after the fan's live page last drew, which it does again only when its tile or database moves (`FanLivePage` is equatable on those alone): the record the `device` part names reaches the deck through its box (`HomeDevicePart`), never a value frozen into the page, so the card is read.    ///    /// WHY: Cotton 348's walk — after the sync card's Erase, Home said "Nothing    /// here yet" with no card and no Sign in: the fresh database turned the    /// window before Home's board read landed, and the live page kept the    /// shipped board's `device` part, which names no record.    func testABoardReadThatLandsAfterTheLivePageDrewBringsTheSyncCard() async throws {        let record = try thisDevice()        let core = DeviceReadWatch(base: ScriptedCore([CottonMethod.shellToday: .ok(try page(record))]))        let home = model(core)        let read = expectation(description: "the sync card is read once the board names a record")        read.assertForOverFulfill = false        await core.onDeviceRead { read.fulfill() }        let drawn = expectation(description: "Home's page has drawn")        drawn.assertForOverFulfill = false        let named = HomeDevicePart()        let live = FanLivePage(key: GridTile.home.key, index: 0, tiles: [GridTile.home.key], fresh: "synthetic-database", page: { _ in            FramedPage(page: AnyView(HomeToday(home: home, deckPage: true, devicePart: named).onAppear { drawn.fulfill() }),                       cover: FanCover(), laysGround: true)        })        let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)        let window = UIWindow(windowScene: scene)        window.rootViewController = UIHostingController(rootView: live.equatable())        window.makeKeyAndVisible()        defer { window.isHidden = true; window.rootViewController = nil }        // The live page has drawn on the shipped board: no record named yet.        await fulfillment(of: [drawn], timeout: 5)        let before = await core.deviceReads        XCTAssertEqual(before, 0, "no device is read before the board names one")        // The board's read lands; the live page's tile and database have not moved.        named.id = record.id        await fulfillment(of: [read], timeout: 5)    }}/// A core that says each read of this device's card alone (`only: device`).private actor DeviceReadWatch: CottonCalling {    let base: ScriptedCore    init(base: ScriptedCore) { self.base = base }    private(set) var deviceReads = 0    private var heard: (@Sendable () -> Void)?    func onDeviceRead(_ heard: @escaping @Sendable () -> Void) { self.heard = heard }    func callRaw(_ method: String, requestJSON: String) async throws -> String {        if method == CottonMethod.shellToday, requestJSON.contains(#""only":"device""#) {            deviceReads += 1            heard?()        }        return try await base.callRaw(method, requestJSON: requestJSON)    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async { await base.subscribe(handler) }    func close() async { await base.close() }}/// A core that holds every `shell.today` until released.private actor HeldPageCore: CottonCalling {    let base: ScriptedCore    init(base: ScriptedCore) { self.base = base }    private var released = false    private var waiting: [CheckedContinuation<Void, Never>] = []    func release() {        released = true        waiting.forEach { $0.resume() }        waiting = []    }    func callRaw(_ method: String, requestJSON: String) async throws -> String {        if method == CottonMethod.shellToday && !released {            await withCheckedContinuation { waiting.append($0) }        }        return try await base.callRaw(method, requestJSON: requestJSON)    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async { await base.subscribe(handler) }    func close() async { await base.close() }}#endif