// 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. import CottonKit import CottonValues import Foundation import XCTest @testable import CottonUI @MainActor final class RecordListFirstDrawTests: XCTestCase { func testAPendingFirstReadLoadsButAPendingRefreshKeepsRows() async throws { 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: "") } try await 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() } try await 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. private static let scene = TableRecord( id: "o1", values: ["body": .text("Likes the window seat"), "person_id": .text("s1")]) private func scenes() throws -> TableDefinition { let loaded = FixtureDefinitions.load(from: try TestResources.bundle()) return try 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. private func until(_ done: () -> Bool) async throws { for _ in 0..<2_000 where !done() { try await Task.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() async throws { 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. try await 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 { private var open = false private var waiting: [CheckedContinuation] = [] 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. private final class FirstDrawRecords: Records, @unchecked Sendable { let gate = Gate() private let row: TableRecord private let holdRows: Bool private let lock = NSLock() private var answered: [String] = [] private var startedRows = 0 init(row: TableRecord, holdRows: Bool = false) { self.row = row self.holdRows = holdRows } var calls: [String] { lock.withLock { answered } } var rowReads: Int { lock.withLock { startedRows } } private func answer(_ name: String) { lock.withLock { answered.append(name) } } private func held(_ name: String) async { await gate.wait() answer(name) } func tableDefinitions() async throws -> [TableDefinition] { await held("tableDefinitions") return [] } func count(table: String) async throws -> Int { await held("count") return 1 } func lastChanged(table: String) async throws -> String? { await held("lastChanged") return nil } func toolDefinitions() async throws -> [ToolDefinition] { await held("toolDefinitions") return [] } func list(table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue]) async throws -> RecordPage { lock.withLock { startedRows += 1 } if holdRows { await gate.wait() } answer("list") return RecordPage(records: [row], next: nil) } func linkTitles(for links: [RecordLink]) async throws -> LinkTitles { await held("linkTitles") return LinkTitles(["s1": "Example person"]) } func get(table: String, id: String) async throws -> TableRecord? { answer("get") return row } func create(table: String, data: [String: RecordValue]) async throws -> ChangeRecord { throw RecordsError.unknownTable(table) } func update(table: String, id: String, patch: [String: RecordValue]) async throws -> ChangeRecord { await held("update") throw RecordsError.unknownTable(table) } func delete(table: String, id: String) async throws -> ChangeRecord { throw RecordsError.unknownTable(table) } func reorder(table: String, ids: [String]) async throws -> ChangeRecord { throw RecordsError.unknownTable(table) } func link(table: String, id: String, column: String, target: String) async throws -> ChangeRecord { throw RecordsError.unknownTable(table) } func undo(change: String) async throws -> ChangeRecord { throw RecordsError.unknownChange(change) } }