// Home, driven through its model — a READER of the core's answer // (`shell.today`; the shell boundary, 7 Nov 2026). // // What the page says — the Asked of you rows and their paths, the Done for // you receipts and what an Undo writes, a failed read's line and when it is // asked again — is the core's, held by `shell_today_tests.rs`. What is here is // what the model still does: hold the answer, hand its parts to the bands, ask // again when the core or a data event says so, and hand an Undo to the core. import CottonKit import XCTest @testable import CottonUI @MainActor final class HomeModelTests: XCTestCase { // ── Fixtures ───────────────────────────────────────────────────────── private func model(_ home: String?) -> (HomeModel, ScriptedCore, ToastCenter) { let core = ScriptedCore(home.map { [CottonMethod.shellToday: .ok($0)] } ?? [:]) let toasts = ToastCenter(scheduler: ManualToastScheduler()) return (HomeModel(core: core, toasts: toasts), core, toasts) } /// The smallest answer that is still a whole one. private func answer( asked: [[String: Any]] = [], done: [[String: Any]] = [], families: [String] = TodayAnswerJSON.families ) -> String { TodayAnswerJSON.answer( arrangement: TodayAnswerJSON.arrangement(["calendar", "notes", "passwords", "people", "todos"], manual: false), asked: asked, done: done, families: families) } /// The core's words for two rows, in its order, and a row of a key this /// build does not know between them. private static let askedRows = [ TodayAnswerJSON.asked("invites", count: 5, label: "5 invites to answer", path: "/invites"), TodayAnswerJSON.asked("somethingNewer", count: 9, label: "9 of something", path: "/"), TodayAnswerJSON.asked("assistantsAsked", count: 2, label: "2 questions from assistants", path: "/decide"), ] /// Three receipts as the core words them — two to take back, one to /// change — and one of a kind this build does not know. private static let receipts = [ TodayAnswerJSON.done( "filed", id: "t-1", label: "Filed as a todo", text: "Call the plumber", when: "2 h ago", path: "/thoughts/thought/t-1"), TodayAnswerJSON.done("somethingNewer", id: "x", label: "Something"), TodayAnswerJSON.done( "remembered", id: "m-1", label: "Remembered", text: "Prefers mornings", when: "yesterday", path: "/memory/m-1"), TodayAnswerJSON.done( "couldNotRead", id: "d-1", label: "Could not read", text: "Lease.pdf", when: "2 days ago", action: "change", path: "/documents/document/d-1"), ] private func object(_ json: String) throws -> [String: Any] { try XCTUnwrap(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any]) } // ── The answer's parts ─────────────────────────────────────────────── func testAnswersNothingWhileTheReadIsStillOut() { let (home, _, _) = model(nil) // Before the first answer: no rows, no total, no families. A band that // guessed would flash a figure and then correct itself. XCTAssertNil(home.answer) XCTAssertTrue(home.askedItems.isEmpty) XCTAssertTrue(home.doneItems.isEmpty) XCTAssertFalse(home.bandUnreadable) } /// RULE: the Asked of you rows are the core's — its order, its labels, its paths; a key this build does not know is left out, and a board's `asked` part draws the rows it names in its own order. func testTheAnswersAskedRowsAreTheCoresWordsAndPaths() async { let (home, _, _) = model(answer(asked: Self.askedRows)) await home.load() XCTAssertEqual(home.askedItems.map(\.key), [.invites, .assistantsAsked], "the core's order, an unknown key left out") XCTAssertEqual(home.askedItems.map(\.label), ["5 invites to answer", "2 questions from assistants"]) XCTAssertEqual(home.askedItems.map(\.path), ["/invites", "/decide"]) } /// RULE: the Done for you receipts are the core's — its order, its words, its age; a kind or action this build does not know is left out, and a board's `done` part draws the kinds it names. func testTheAnswersDoneRowsAreTheCoresReceipts() async { let (home, _, _) = model(answer(done: Self.receipts)) await home.load() XCTAssertEqual(home.doneItems.map(\.kind), [.filed, .remembered, .couldNotRead]) XCTAssertEqual(home.doneItems.map(\.action), [.undo, .undo, .change]) XCTAssertEqual(home.doneItems.first?.text, "Call the plumber") XCTAssertEqual(home.doneItems.first?.when, "2 h ago") XCTAssertEqual(home.doneItems.first?.path, "/thoughts/thought/t-1") } func testTheBandIsUnreadableWhenTheCoreSaysSo() async { let (home, _, _) = model(TodayAnswerJSON.answer(unreadable: true)) await home.load() XCTAssertTrue(home.bandUnreadable) XCTAssertTrue(home.askedItems.isEmpty) } /// RULE: the notices are the answer's, in its order: Home finds one by the board's kind (`attention`, `update`, `readRefusal`…) and the unreadable databases by their prefix, and says nothing of its own. func testTheNoticesAreTheAnswers() async { let (home, _, _) = model(TodayAnswerJSON.answer(notices: [ TodayAnswerJSON.notice("attention", words: "Not synced since 2 h ago", kind: "amber"), TodayAnswerJSON.notice("update", words: "Update Cotton on your Mac", kind: "update", side: "mac"), TodayAnswerJSON.notice("unreadable/0", words: "Garden could not be read"), ])) XCTAssertNil(home.notice("attention"), "no answer, no notice") await home.load() XCTAssertEqual(home.notices.map(\.id), ["attention", "update", "unreadable/0"]) XCTAssertEqual(home.notice("attention")?.words, "Not synced since 2 h ago") XCTAssertEqual(home.notice("update")?.side, "mac") XCTAssertNil(home.notice("readRefusal")) XCTAssertEqual(home.unreadable.map(\.words), ["Garden could not be read"]) } // ── Done for you's Undo ────────────────────────────────────────────── /// RULE: an Undo is the core's (`shell.undo {kind, id}`): Home toasts the core's `said` and reads the page again, so the row leaves because the file says so. func testUndoAsksTheCoreThenReadsAgainAndSaysTheCoresWords() async throws { let (home, core, toasts) = model(answer(done: Self.receipts)) await core.answer(CottonMethod.shellUndo, .ok(#"{"said":"Kept as a thought"}"#)) await home.load() await home.undo(try XCTUnwrap(home.doneItems.first { $0.kind == .filed })) let methods = await core.methodsCalled() XCTAssertEqual(methods, [CottonMethod.shellToday, CottonMethod.shellUndo, CottonMethod.shellToday]) let sent = await core.calls.filter { $0.method == CottonMethod.shellUndo } let request = try object(try XCTUnwrap(sent.first).requestJSON) XCTAssertEqual(request["kind"] as? String, "filed") XCTAssertEqual(request["id"] as? String, "t-1") XCTAssertEqual(toasts.current?.message, "Kept as a thought") XCTAssertEqual(toasts.current?.tone, .success) XCTAssertTrue(home.undoing.isEmpty) } func testAChangeRowAsksNothing() async throws { let (home, core, _) = model(answer(done: Self.receipts)) await home.load() // A document that could not be read has nothing to take back: its // row's tap is the change, and an undo called on it is a no-op. await home.undo(try XCTUnwrap(home.doneItems.first { $0.kind == .couldNotRead })) let methods = await core.methodsCalled() XCTAssertEqual(methods, [CottonMethod.shellToday]) } func testARefusedUndoSaysTheRefusalAndDoesNotReadAgain() async throws { let (home, core, toasts) = model(answer(done: Self.receipts)) await core.answer(CottonMethod.shellUndo, .refuse(code: "refused", message: "That thought was edited.")) await home.load() await home.undo(try XCTUnwrap(home.doneItems.first)) XCTAssertEqual(toasts.current?.message, "That thought was edited.") XCTAssertEqual(toasts.current?.tone, .error) let methods = await core.methodsCalled() XCTAssertEqual(methods, [CottonMethod.shellToday, CottonMethod.shellUndo]) XCTAssertEqual(home.doneItems.count, 3, "the row stays: nothing was taken back") XCTAssertTrue(home.undoing.isEmpty) } // ── What Home asks for, and what it does not ───────────────────────── /// RULE: a burst of asks while Home's read of the same database is out is /// one read and at most one after it, never a read each — every family's /// data event of one sync pull queued a read behind itself on the 290 walk /// and it was refused (readpool). func testABurstOfAsksIsOneReadAndOneAfter() async { let (home, core, _) = model(answer()) let asks = (0..<5).map { _ in Task { @MainActor in await home.load() } } for ask in asks { await ask.value } let reads = await core.methodsCalled().filter { $0 == CottonMethod.shellToday }.count XCTAssertGreaterThanOrEqual(reads, 1) XCTAssertLessThanOrEqual(reads, 2, "five asks read \(reads) times") } func testAsksForOneReadAndNoOthers() async throws { let (home, core, _) = model(answer()) await home.load() let asked = await core.calls // ONE read: Home paints one screen, and several round trips is several // chances to paint a half-resolved page. XCTAssertEqual(asked.map(\.method), [CottonMethod.shellToday]) // The device's own day, in its zone. let request = try object(try XCTUnwrap(asked.first).requestJSON) XCTAssertEqual(request["timezone"] as? String, Calendar.current.timeZone.identifier) XCTAssertNotNil(request["today"] as? String) } func testRefreshIsTheSameOneRead() async { let (home, core, _) = model(answer()) await home.load() await home.refresh() let asked = await core.methodsCalled() XCTAssertEqual(asked, [CottonMethod.shellToday, CottonMethod.shellToday]) } func testWritesNothingAtAll() async { let (home, core, _) = model(answer(asked: Self.askedRows)) await home.load() _ = home.askedItems let asked = await core.methodsCalled() // Home is a page of doors. It has no verb of its own — every decision // is taken on the surface that owns it. XCTAssertFalse(asked.contains(CottonMethod.write)) } // ── The families ───────────────────────────────────────────────────── /// RULE: the families whose data events read Home again are the answer's own (`families`), never a list kept on this side; before an answer there are none. func testTheFamiliesAreTheAnswers() async { let (home, _, _) = model(answer(families: ["todos", "calendar", "somethingNewer"])) XCTAssertTrue(home.families.isEmpty, "no answer, no families") await home.load() XCTAssertEqual(home.families, [.todos, .calendar], "the answer's, a family this build does not know left out") XCTAssertTrue(home.concerns([.todos])) XCTAssertFalse(home.concerns([.photos])) XCTAssertFalse(home.concerns([])) } /// Every family the core names has to be REACHABLE from a real `data` /// event — a family no table maps to is a family Home waits on for ever. func testEveryAnsweredFamilyIsReachableFromSomeTable() async { let (home, _, _) = model(answer()) await home.load() XCTAssertEqual(home.families.count, TodayAnswerJSON.families.count, "every family the core names is one this build knows") for family in home.families { let tables = InvalidationMap.entries .filter { $0.families.contains(family) } .flatMap(\.tables) XCTAssertFalse( tables.isEmpty, "no table in InvalidationMap invalidates \(family), so Home would never re-read for it" ) XCTAssertTrue(home.concerns(InvalidationMap.families(for: tables))) } } // ── The events ─────────────────────────────────────────────────────── func testAFoldOnAWatchedTableMakesHomeReadAgain() async { let (home, core, _) = model(answer()) await home.load() // `cotton_comments` is where an assistant's question lives — the To // decide band's first row and the exact staleness this wiring exists // to prevent. let reload = home.receive(.data(tables: ["cotton_comments"], origin: "write")) XCTAssertNotNil(reload, "a fold on a watched table started no read") await reload?.value let asked = await core.methodsCalled() XCTAssertEqual(asked, [CottonMethod.shellToday, CottonMethod.shellToday]) } func testAFoldOnATableHomeDoesNotObserveCostsNothing() async { let (home, core, _) = model(answer()) await home.load() // Photos, and the FTS shadow tables that move on every single fold. let quiet = home.receive(.data(tables: ["cotton_photos", "fts_notes"], origin: "pull")) XCTAssertNil(quiet, "an unobserved fold started a read") let asked = await core.methodsCalled() XCTAssertEqual(asked, [CottonMethod.shellToday]) } func testBytesLandingOnThisPhoneAreNotHomesButACaptureWritingTheLedgerIs() async { let (home, core, _) = model(answer()) await home.load() // The thumbnail sweep's tick: `_media` moved, no row did. Sixty of // these an hour while a library comes down, and each one used to be a // Home read. XCTAssertNil(home.receive(.data(tables: ["_media"], origin: ClientEvent.localMediaOrigin))) var asked = await core.methodsCalled() XCTAssertEqual(asked, [CottonMethod.shellToday]) // A capture writes `_media` too — that one is rows, and Home reads. let reload = home.receive(.data(tables: ["_media"], origin: "write")) XCTAssertNotNil(reload) await reload?.value asked = await core.methodsCalled() XCTAssertEqual(asked, [CottonMethod.shellToday, CottonMethod.shellToday]) } /// RULE: the core's `{phase: home, stage: today}` (a read that failed, asked again on the core's backoff) reads Home again; every other stage of the phase is not Home's page. func testTheCoresTodayStageReadsAgainAndNoOtherStageDoes() async { let (home, core, _) = model(answer()) await home.load() XCTAssertNil(home.receive(.home(stage: "tick"))) let again = home.receive(.home(stage: "today")) XCTAssertNotNil(again, "the core said ask again") await again?.value let asked = await core.methodsCalled() XCTAssertEqual(asked, [CottonMethod.shellToday, CottonMethod.shellToday]) } func testTheOtherPhasesAreNotHomes() async { let (home, core, _) = model(answer()) await home.load() for event in [ ClientEvent.cycle(pushed: 1, pulled: 0, behind: nil, pending: 0, lastPullAt: nil), .home(stage: "tick"), .bootstrap(stage: "ready", workspaceId: "w", code: nil, message: nil, retryable: nil), .migrate(stage: "done", from: 1, to: 2, index: nil, total: nil, version: nil, message: nil), ] { XCTAssertNil(home.receive(event)) } let asked = await core.methodsCalled() XCTAssertEqual(asked, [CottonMethod.shellToday]) } } @MainActor final class HomeRereadRuleTests: XCTestCase { /// RULE: Home re-reads only after this device's own write to a table a tile counts — a fold (another device, a database switch) and a write no tile counts (dictations, the audit) never re-reads it (architect 2335 item 6). func testOnlyAnOwnWriteToATilesTableAsksHomeAgain() { let sync = SyncModel(core: ScriptedCore([:]), clock: .instant) sync.receive(.data(tables: ["cotton_todos"], origin: "pull")) XCTAssertEqual(sync.localWrites, 0, "a fold is not this device's write") sync.receive(.data(tables: ["cotton_todos"], origin: SyncModel.writeOrigin)) XCTAssertEqual(sync.localWrites, 1) XCTAssertTrue(HomeData.tileReads(sync.localWrote), "a todo written here moves the Todos tile") sync.receive(.data(tables: ["cotton_dictations"], origin: SyncModel.writeOrigin)) XCTAssertFalse(HomeData.tileReads(sync.localWrote), "no tile counts dictations: \(sync.localWrote)") sync.receive(.data(tables: ["cotton_secrets"], origin: SyncModel.writeOrigin)) XCTAssertTrue(HomeData.tileReads(sync.localWrote), "the Passwords tile counts secrets") } }