// A list and a page whose rows are the phone's own draw them off// ONE local read, and everything else — link titles, counts, the catalogue,// acts — fills in after. The defect this holds: the list assigned its rows// only after a second query (`linkTitles`, one per linked table, serially)// and the page only after the definitions, the get AND the titles, so every// open drew skeleton bars for as long as the slowest of them took.importCottonKitimportCottonValuesimportFoundationimport XCTest@testable importCottonUI@MainActorfinalclassRecordListFirstDrawTests: XCTestCase {func testAPendingFirstReadLoadsButAPendingRefreshKeepsRows() asyncthrows {let definition = TableDefinition(id: "pending_first_read", name: "Record", plural: "Records", columns: [ColumnDefinition(key: "title", type: .text)], title: "title", slip: SlipLayout(title: "title"), tile: TileLayout(face: .slipList), page: [])let row = TableRecord(id: "pending-1", values: ["title": .text("Example record")])let store = FirstDrawRecords(row: row, holdRows: true)let model = RecordListModel(definition: definition, store: store, core: ListCoreFake(), seeds: ListSeeds())let first = Task { await model.reload(project: nil, query: "") }tryawait until { store.rowReads == 1 } XCTAssertEqual(store.rowReads, 1) XCTAssertEqual(model.phase, .loading, "the first read chooses the shared loading content") XCTAssertTrue(model.records.isEmpty)await store.gate.release()await first.value XCTAssertEqual(model.phase, .loaded) XCTAssertEqual(model.records, [row])await store.gate.close()let refresh = Task { await model.refresh() }tryawait until { store.rowReads == 2 } XCTAssertEqual(store.rowReads, 2, "the refresh is blocked in its local read") XCTAssertEqual(model.phase, .loaded, "refresh never replaces rows with a skeleton") XCTAssertEqual(model.records, [row])await store.gate.release()await refresh.value }/// A person's note, linked to its person: a row whose link titles answer after it.privatestaticlet scene = TableRecord( id: "o1", values: ["body": .text("Likes the window seat"), "person_id": .text("s1")])privatefunc scenes() throws -> TableDefinition {let loaded = FixtureDefinitions.load(from: tryTestResources.bundle())returntry XCTUnwrap(loaded.definitions.first { $0.id == "person_note" }, "the kit's person_note") }/// Waits (bounded) until `done` holds; the bound is a hang guard, not a timing.privatefunc until(_ done: () -> Bool) asyncthrows {for _ in0..<2_000where !done() { tryawaitTask.sleep(for: .milliseconds(1)) } }/// RULE: a surface's first draw performs no network call and no more than one local read — a list publishes its rows and `.loaded` off exactly ONE `list`, before its link titles answer.func testAListDrawsItsRowsOffOneReadBeforeItsTitles() asyncthrows {let store = FirstDrawRecords(row: Self.scene)let model = RecordListModel(definition: try scenes(), store: store, core: ListCoreFake(), seeds: ListSeeds())let reading = Task { await model.reload(project: nil, query: "") }// A list drawn before may stand at once off its kept seed; wait for the read.tryawait until { model.phase == .loaded && !store.calls.isEmpty } XCTAssertEqual(model.phase, .loaded) XCTAssertEqual(model.records.map(\.id), ["o1"]) XCTAssertEqual(store.calls, ["list"], "one local read, nothing else answered before the rows drew") XCTAssertTrue(model.linkTitles.byID.isEmpty, "the titles have not answered")await store.gate.release()await reading.value XCTAssertEqual(model.linkTitles.byID["s1"], "Example person", "the titles fill in after") }}/// Holds every caller until released.private actor Gate {privatevaropen = falseprivatevar waiting: [CheckedContinuation<Void, Never>] = []func close() { open = false }func wait() async {guard !open else { return }await withCheckedContinuation { waiting.append($0) } }func release() {open = true waiting.forEach { $0.resume() } waiting = [] }}/// A store whose `list` and `get` answer at once and whose every other read/// is held at the gate; it records each call that ANSWERED, in order.privatefinalclassFirstDrawRecords: Records, @unchecked Sendable {let gate = Gate()privatelet row: TableRecordprivatelet holdRows: Boolprivatelet lock = NSLock()privatevar answered: [String] = []privatevar startedRows = 0init(row: TableRecord, holdRows: Bool = false) {self.row = rowself.holdRows = holdRows }var calls: [String] { lock.withLock { answered } }var rowReads: Int { lock.withLock { startedRows } }privatefunc answer(_ name: String) { lock.withLock { answered.append(name) } }privatefunc held(_ name: String) async {await gate.wait() answer(name) }func tableDefinitions() asyncthrows -> [TableDefinition] {await held("tableDefinitions")return [] }func count(table: String) asyncthrows -> Int {await held("count")return1 }func lastChanged(table: String) asyncthrows -> String? {await held("lastChanged")returnnil }func toolDefinitions() asyncthrows -> [ToolDefinition] {await held("toolDefinitions")return [] }func list(table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue]) asyncthrows -> RecordPage { lock.withLock { startedRows += 1 }if holdRows { await gate.wait() } answer("list")returnRecordPage(records: [row], next: nil) }func linkTitles(for links: [RecordLink]) asyncthrows -> LinkTitles {await held("linkTitles")returnLinkTitles(["s1": "Example person"]) }func get(table: String, id: String) asyncthrows -> TableRecord? { answer("get")return row }func create(table: String, data: [String: RecordValue]) asyncthrows -> ChangeRecord { throwRecordsError.unknownTable(table) }func update(table: String, id: String, patch: [String: RecordValue]) asyncthrows -> ChangeRecord {await held("update")throwRecordsError.unknownTable(table) }func delete(table: String, id: String) asyncthrows -> ChangeRecord { throwRecordsError.unknownTable(table) }func reorder(table: String, ids: [String]) asyncthrows -> ChangeRecord { throwRecordsError.unknownTable(table) }func link(table: String, id: String, column: String, target: String) asyncthrows -> ChangeRecord {throwRecordsError.unknownTable(table) }func undo(change: String) asyncthrows -> ChangeRecord { throwRecordsError.unknownChange(change) }}