// The list's reader over `shell.list`: an answer decodes whole and is drawn as // it is said, a later page lands under its own section, a stream of data events // is one more ask, and a list drawn again draws its last answer at once. What // the answer SAYS is the core's (`shell_list_tests.rs`). Every record is invented. import CottonKit import CottonValues import Foundation import XCTest @testable import CottonUI @MainActor final class ListAnswerTests: XCTestCase { private static let todo = TableDefinition( id: "todo", name: "Todo", plural: "Todos", columns: [ ColumnDefinition(key: "title", type: .text, required: true), ColumnDefinition(key: "status", type: .choice, choices: ["open", "done"]), ], title: "title", slip: SlipLayout(title: "title", toggle: "status"), tile: TileLayout(face: .slipList), page: [PageSection(heading: nil, columns: ["title", "status"])]) private static let chore = TableDefinition( id: "chore", name: "Chore", plural: "Chores", columns: [ColumnDefinition(key: "title", type: .text, required: true)], title: "title", slip: SlipLayout(title: "title"), tile: TileLayout(face: .slipList), page: [PageSection(heading: nil, columns: ["title"])]) private static func chores(_ count: Int) -> [TableRecord] { (1...count).map { TableRecord(id: String(format: "invented-chore-%03d", $0), values: ["title": .text("Invented chore \($0)")]) } } /// A whole `shell.list` answer, every key said: a folded section with its /// count in words, rows with slip words, a check and its write, a stamp /// and acts, the menu, the links (archived and earlier), the index, the /// filter row, clear, Select, the drag, the beat, the grid, recent and notes. private static let canned = #""" {"table":"todo","title":"Invented todos","head":{"lines":[{"line":"2 today"}]}, "sections":[ {"id":"today","heading":"Today","open":true,"folds":false,"rows":[ {"id":"invented-todo-1", "slip":{"title":"Invented errand","subtitle":"Invented garden","caption":"9:00 am","caption_late":false, "byline":{"words":"by hand","red":false},"badge":{"symbol":"star","spoken":"Starred"},"unread":true, "stub":{"day":"7","month":"Nov"}, "record":{"id":"invented-todo-1","table":"todo","data":{"title":"Invented errand","status":"open"}}}, "toggled":false,"toggle":{"status":"done"},"dimmed":false,"stamp":null,"deletes":true,"acts":["done","drop"],"press":[],"tap":"open.page"}, {"id":"invented-todo-2", "slip":{"title":"Invented call","record":{"id":"invented-todo-2","data":{"title":"Invented call","status":"done"}}}, "toggled":true,"toggle":{"status":"open"},"dimmed":true,"stamp":"done","deletes":true,"acts":[],"press":[],"tap":"open.page"}]}, {"id":"late","heading":"Late","open":false,"folds":true,"count":"3 todos","note":"Invented note under Late", "lines":["3 late"],"rows":[]}], "acts":{"done":{"label":"Mark done","kind":"write","red":false,"primary":true,"icon":"checkmark"}, "drop":{"label":"Drop","red":true}}, "menu":[{"id":"select","label":"Select","red":false}, {"id":"rename","label":"Rename list","red":false,"asks":{"words":{"hint":"A name"}}}, {"id":"archived","label":"Archived","red":false,"opens":{"table":"todo","archived":true,"title":"Archived · Todos"}}], "links":[ {"id":"archived","label":"Archived","words":"Archived · 4","count":4,"lead":false,"above":false, "opens":{"table":"todo","archived":true,"title":"Archived · Todos"}}, {"id":"earlier","label":"Earlier","words":"Earlier · 12","count":12,"lead":false,"above":true, "opens":{"table":"todo","section":"earlier","title":"Earlier"}}], "groups":null,"offers_new_group":true, "index":[{"letter":"I","row":"invented-todo-1","at":0}], "filter":{"column":"status","all":"All","tabs":true,"values":[{"value":"open","word":"Open"},{"value":"done","word":"Done"}], "reviews":false,"review":null}, "empty":null, "clear":{"label":"Clear done","question":"Clear 1 done todo?","message":"Invented message.","confirm":"Clear","done":"Cleared."}, "select":{"deletes":true,"adds_to_group":true,"word":"Delete"}, "reorders":true,"polls":5,"across":2, "recent":[{"id":"invented-todo-2","title":"Invented call","when":"2 min ago"}], "notes":["Invented note of an absent group."], "count":4,"next":null} """# /// Waits (bounded) until `done` holds; the bound is a hang guard, not a timing. private func until(_ what: String, _ done: () async -> Bool) async throws { for _ in 0..<400 { if await done() { return } try await Task.sleep(for: .milliseconds(5)) } XCTFail("never: \(what)") } /// RULE (shell-list-reader, 7 Nov 2026): A `shell.list` answer decodes whole — sections, rows, acts, menu, links, index, filter, clear, Select, the drag, the beat, the grid, recent, notes, count and cursor — and the list draws its sections exactly as said: each section's id, heading, fold, count in words, note and lines, and each row's check write, stamp and acts, deciding none of it. func testAnAnswerDecodesWholeAndIsDrawnAsSaid() async throws { let answer = try JSONDecoder().decode(ListAnswer.self, from: Data(Self.canned.utf8)) XCTAssertEqual(answer.title, "Invented todos") XCTAssertEqual(answer.head?.lines?.first?.line, "2 today") XCTAssertEqual(answer.sections.map(\.id), ["today", "late"]) XCTAssertEqual(answer.sections[0].rows[0].slip.byline?.words, "by hand") XCTAssertEqual(answer.acts["done"]?.label, "Mark done") XCTAssertEqual(answer.acts["drop"]?.red, true) XCTAssertEqual(answer.menu.map(\.id), ["select", "rename", "archived"]) XCTAssertNotNil(answer.menu[1].asks) XCTAssertEqual(answer.links.map(\.words), ["Archived · 4", "Earlier · 12"]) XCTAssertEqual(answer.links[0].opens.archived, true) XCTAssertEqual(answer.links[1].opens.section, "earlier") XCTAssertNil(answer.groups) XCTAssertTrue(answer.offers_new_group) XCTAssertEqual(answer.index?.map(\.letter), ["I"]) XCTAssertEqual(answer.filter?.values.map(\.word), ["Open", "Done"]) XCTAssertNil(answer.empty) XCTAssertEqual(answer.clear?.question, "Clear 1 done todo?") XCTAssertTrue(answer.select.deletes && answer.select.adds_to_group) XCTAssertTrue(answer.reorders) XCTAssertEqual(answer.polls, 5) XCTAssertEqual(answer.across, 2) XCTAssertEqual(answer.recent.map(\.when), ["2 min ago"]) XCTAssertEqual(answer.notes, ["Invented note of an absent group."]) XCTAssertEqual(answer.count, 4) XCTAssertNil(answer.next) let core = CannedListCore(Self.canned) let store = FixtureRecords(definitions: [Self.todo], records: ["todo": []]) let model = RecordListModel(definition: Self.todo, store: store, core: core, seeds: ListSeeds()) await model.reload(project: nil, query: "") XCTAssertEqual(core.asks, 1) XCTAssertEqual(model.phase, .loaded) let sections = model.sections XCTAssertEqual(sections.map(\.id), ["today", "late"]) XCTAssertEqual(sections.map(\.heading), ["Today", "Late"]) XCTAssertEqual(sections.map(\.closed), [false, true], "a section that folds is drawn shut") XCTAssertEqual(sections.map(\.said), [nil, "3 todos"], "the folded heading's count, in the core's words") XCTAssertEqual(sections[1].note, "Invented note under Late") XCTAssertEqual(sections[1].lines, ["3 late"]) XCTAssertEqual(sections[0].records.map(\.id), ["invented-todo-1", "invented-todo-2"]) XCTAssertEqual(sections[1].records, [], "a folded section is asked for when opened") XCTAssertEqual(model.records.first?["title"], .text("Invented errand")) XCTAssertEqual(model.row("invented-todo-1")?.toggle, ["status": .text("done")]) XCTAssertEqual(model.row("invented-todo-1")?.acts, ["done", "drop"]) XCTAssertEqual(model.row("invented-todo-2")?.stamp, "done") XCTAssertEqual(model.row("invented-todo-2")?.dimmed, true) XCTAssertTrue(model.canReorder, "the drag is the answer's `reorders`") XCTAssertEqual(model.total, 4) XCTAssertFalse(model.hasMore) XCTAssertFalse(model.holdsNothing) } /// RULE (shell-list-reader, 7 Nov 2026): The next page is asked from the answer's cursor, and its rows land under the section of the same id, after the rows already drawn, never twice; the list stops at a nil cursor. func testLoadMoreAsksTheNextCursorAndAppendsUnderTheSameSection() async throws { let core = ListCoreFake() let store = FixtureRecords(definitions: [Self.chore], records: ["chore": Self.chores(120)]) let model = RecordListModel(definition: Self.chore, store: store, core: core, seeds: ListSeeds()) await model.reload(project: nil, query: "") XCTAssertEqual(model.records.count, 50) XCTAssertTrue(model.hasMore) await model.loadMore() XCTAssertEqual(model.records.count, 100) XCTAssertEqual(model.sections.map(\.id), ["all"], "the second page lands under the first's section") await model.loadMore() XCTAssertEqual(model.records.count, 120) XCTAssertFalse(model.hasMore) await model.loadMore() XCTAssertEqual(core.asks, 3, "no ask past the last page") XCTAssertEqual(core.asked.map { $0["cursor"] as? Int }, [0, 50, 100]) XCTAssertEqual(core.asked.map { $0["limit"] as? Int }, [50, 50, 50]) XCTAssertEqual(Set(model.records.map(\.id)), Set(Self.chores(120).map(\.id))) XCTAssertEqual(model.sections.map(\.id), ["all"]) XCTAssertEqual(model.sections[0].records.count, 120, "no row twice") } /// RULE (shell-list-reader, 7 Nov 2026): Data events while a read is on its way are ONE more ask after it lands, never one per tick and never a restart of the read on its way. func testDataMovedWhileAReadIsOutAsksOnceMore() async throws { let core = ListCoreFake() let store = GatedRecords(FixtureRecords(definitions: [Self.chore], records: ["chore": Self.chores(3)])) let model = RecordListModel(definition: Self.chore, store: store, core: core, seeds: ListSeeds()) await model.reload(project: nil, query: "") XCTAssertEqual(core.asks, 1) await store.hold() model.dataMoved() try await until("the re-read is on its way") { await store.waiting > 0 } for _ in 0..<10 { model.dataMoved() } await store.release() try await until("both re-reads land") { model.settled == 2 } try await Task.sleep(for: .milliseconds(50)) XCTAssertEqual(model.settled, 2) XCTAssertEqual(core.asks, 3, "the first read, the re-read on its way, and ONE after it for ten ticks") XCTAssertEqual(model.records.count, 3) } /// RULE (shell-list-reader, 7 Nov 2026): A second list of the same table, narrowing and database draws the answer the first one kept at once — loaded, before its own read reaches the core — and that read then lands over it once. func testASecondModelForTheSameKeyDrawsTheSeedAtOnce() async throws { let seeds = ListSeeds(directory: nil) let store = GatedRecords(FixtureRecords(definitions: [Self.chore], records: ["chore": Self.chores(3)])) let first = RecordListModel(definition: Self.chore, store: store, core: ListCoreFake(), seeds: seeds) await first.reload(project: nil, query: "") XCTAssertNotNil(seeds.answer(for: ListSeeds.Key(table: "chore", filter: [:], project: nil, archived: false, section: nil))) let core = ListCoreFake() await store.hold() let second = RecordListModel(definition: Self.chore, store: store, core: core, seeds: seeds) let read = Task { await second.reload(project: nil, query: "") } try await until("the second read is on its way") { await store.waiting > 0 } XCTAssertEqual(second.phase, .loaded, "no skeleton over a list drawn before") XCTAssertEqual(second.records.map(\.id), first.records.map(\.id), "the seed's rows, before the read answered") XCTAssertEqual(core.asks, 0, "drawn before the core was asked") await store.release() await read.value XCTAssertEqual(core.asks, 1) XCTAssertEqual(second.seedsReplaced, 1) XCTAssertEqual(second.records.map(\.id), first.records.map(\.id)) } } /// A core that answers every `shell.list` with one canned answer, counting asks. private final class CannedListCore: CottonCalling, @unchecked Sendable { private let lock = NSLock() private var _asks = 0 private let data: String var asks: Int { lock.withLock { _asks } } init(_ data: String) { self.data = data } func callRaw(_ method: String, requestJSON: String) async throws -> String { guard method == CottonMethod.shellList else { return #"{"ok":true,"data":{}}"# } lock.withLock { _asks += 1 } return #"{"ok":true,"data":"# + data + "}" } func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) {} func close() {} }