Cotton code
169 lines · 13.2 KB · SwiftRaw
import CottonKitimport CottonValuesimport XCTest@testable import CottonUI@MainActorfinal class CouldNotReadTests: XCTestCase {    /// A could-not-read line of the shell's `reading` set, as the app has it.    private func words(_ key: String) -> String { ShellLines.line("reading", "could_not_read.\(key)") }    /// A synthetic database whose tools draw AI usage — no tool ships it    /// now — made from a kit table the core answered, renamed.    private var drawn: TableDefinitions {        get throws {            let fixture = try XCTUnwrap(try DefinitionCatalogue.fixture(in: CottonUIResources.bundle))            let note = try XCTUnwrap(fixture.tableRows["note"])            func table(_ id: String, _ plural: String, _ extra: [String: Any]) throws -> TableDefinition {                var row = try XCTUnwrap(JSONSerialization.jsonObject(with: note) as? [String: Any])                row["id"] = id                row["plural"] = plural                row.removeValue(forKey: "role")                row.merge(extra) { $1 }                return try TableDefinition.decode(JSONSerialization.data(withJSONObject: row))            }            return TableDefinitions([try table("ai_calls", "AI usage", [:])])        }    }    /// RULE: a read the core cut (`could_not_read`, details.why busy|too_long) is said in a line of the shell's `reading` set (`could_not_read.*`), filled with the database's name — on every database, whatever tools it holds: the words lived on the `database` definition until it was deleted, and every failed read then drew a blank (Documents on the owner's phone, 22 Oct 2026) — never the core's own sentence, and on Home with no Try again, since Home keeps trying by itself; every other refusal keeps its own path (architect's rulings 21:00 (4) and 22:03 IST 16 Oct 2026: the raw refusal under the caps on 289).    func testACutReadIsSaidInTheDefinitionsLineNeverTheCoresSentence() async throws {        let shipped = try drawn        let busy = CottonCallError(code: "could_not_read", message: "the pool is busy", details: .object(["why": .string("busy")]))        let slow = CottonCallError(code: "could_not_read", message: "past the deadline", details: .object(["why": .string("too_long")]))        XCTAssertEqual(CouldNotRead.of(busy), .busy)        XCTAssertEqual(CouldNotRead.of(slow), .tooLong)        XCTAssertNil(CouldNotRead.of(CottonCallError(code: "unavailable", message: "no")), "another refusal keeps its own path")        let line = CouldNotRead.tooLong.line(database: "Heron", definitions: shipped)        XCTAssertEqual(line, words("too_long").replacingOccurrences(of: "{database}", with: "Heron"), "the set's words, filled")        XCTAssertFalse(line.contains("{database}"))        XCTAssertFalse(line.contains(slow.message), "never the core's sentence")        let bare = CouldNotRead.busy.line(database: "Heron", definitions: TableDefinitions([]))        XCTAssertTrue(bare.hasPrefix("Heron") && !bare.contains("could_not_read"), "a database with no tools still says the line: \(bare)")        // Home says the core's line (`shell.today`'s `failed`), and offers        // Try again only where the core says the read does not keep trying.        let notices = SourceSweep.withoutComments(            try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Surfaces/Board/BoardNotices.swift", ownedBy: "home"))        let cut = try XCTUnwrap(notices.range(of: "if home.answer?.failed?.keeps_trying ?? true {"))        let other = try XCTUnwrap(notices.range(of: "} else {", range: cut.upperBound..<notices.endIndex))        XCTAssertFalse(notices[cut.upperBound..<other.lowerBound].contains("action:"), "Home offers no Try again for a cut read")        XCTAssertTrue(CouldNotRead.tooLong.keepsTrying)        XCTAssertFalse(CouldNotRead.other.keepsTrying, "any other failure offers Try again")    }    /// RULE: every caught read error becomes visible text only through `CouldNotRead.line(for:)`, which says a definition's line for the core's cut and for every other code or error alike — never the error's `message`, `localizedDescription` or description, which carry an address and a resolver's words (walker 294 row G, 17 Oct 2026).    func testEveryReadErrorSaysADefinitionsLineNeverItsOwnWords() throws {        let shipped = try drawn        let other = words("other")        let transport = CottonCallError(code: "unavailable", message: "dial tcp 192.0.2.7:443: no such host")        struct Opaque: Error {}        for error in [transport, Opaque()] as [Error] {            let line = CouldNotRead.line(for: error, database: "Heron", definitions: shipped)            XCTAssertEqual(line, other.replacingOccurrences(of: "{database}", with: "Heron"))            XCTAssertFalse(line.contains("192.0.2.7"), "never the transport's text")            XCTAssertFalse(line.contains(error.localizedDescription))            XCTAssertEqual(CouldNotRead.reading(error), .other)        }        let away = CottonCallError(code: "could_not_read", message: "dial tcp 192.0.2.7:443", details: .object(["why": .string("mac_away")]))        XCTAssertEqual(CouldNotRead.line(for: away, database: "Heron", definitions: shipped),                       words("mac_away").replacingOccurrences(of: "{database}", with: "Heron"))        XCTAssertFalse(CouldNotRead.line(for: transport).contains("{database}"), "unnamed, the subject is still filled")    }    /// RULE: a read whose facts live only on the serving Mac (AI usage) and whose Mac is not heard answers `could_not_read` `why: on_the_mac` at once, and the page says the database definition's `on_the_mac` line with the Mac's last-heard age and the table's plural — "Mac heard 13 min ago · AI usage is read on the Mac" — never the core's message, a URL, an errno or a resolver's words; a Mac never heard says the Mac-away line (295 rule 15, walker294).    func testOnTheMacSaysTheDefinitionsLineWithTheMacsAge() throws {        let shipped = try drawn        let said = words("on_the_mac")        let now = try XCTUnwrap(CottonDate.parse("2026-10-17T10:13:00.000Z"))        let message = "records.list ai_calls: https://relay.invalid/v1 errno 61 could not be resolved"        let error = CottonCallError(code: "could_not_read", message: message, details: .object([            "why": .string("on_the_mac"), "table": .string("ai_calls"), "heard_at": .string("2026-10-17T10:00:00.000Z"),            "@day_parts": .object(["heard_at": .object(["ago": .string("13 min ago")])]),        ]))        XCTAssertEqual(CouldNotRead.reading(error), .onTheMac(heardAt: "13 min ago", table: "ai_calls"))        let line = CouldNotRead.line(for: error, database: "Heron", definitions: shipped, now: now)        let plural = try XCTUnwrap(shipped["ai_calls"]?.plural)        XCTAssertEqual(line, said.replacingOccurrences(of: "{heard}", with: "13 min ago").replacingOccurrences(of: "{what}", with: plural))        XCTAssertEqual(line, "Mac heard 13 min ago \u{00B7} AI usage is read on the Mac")        for words in ["http", "relay", "errno", "resolved", "{"] {            XCTAssertFalse(line.contains(words), "no transport words: \(line)")        }        XCTAssertTrue(CouldNotRead.reading(error).keepsTrying, "it shows the moment the Mac is heard")        let never = CottonCallError(code: "could_not_read", message: message, details: .object([            "why": .string("on_the_mac"), "table": .string("ai_calls"),        ]))        XCTAssertEqual(CouldNotRead.line(for: never, database: "Heron", definitions: shipped, now: now),                       words("mac_away").replacingOccurrences(of: "{database}", with: "Heron"))    }    /// RULE: a busy file over a list already drawn keeps its rows and says nothing — the re-read lands on its own — while an empty list, and every other refusal over drawn rows (the Mac away, its facts on the Mac), is still said (walker294 row 116: "Personal is busy on this phone" over a drawn Copies list).    func testABusyReadOverADrawnListSaysNothing() {        XCTAssertFalse(CouldNotRead.isSaid(.busy, over: 3), "drawn rows stand quietly")        XCTAssertTrue(CouldNotRead.isSaid(.busy, over: 0), "nothing drawn: the wait is said")        XCTAssertTrue(CouldNotRead.isSaid(.macAway, over: 3), "a Mac away is said over what it last gave")        XCTAssertTrue(CouldNotRead.isSaid(nil, over: 3), "a refusal of its own words is said")    }    /// RULE: a read that met a table mid-move (`could_not_read`, `why: moving`, with its table) draws the database definition's `moving` line with the table's plural — no digits, so no schema or version number, never the core's sentence — and offers no Try again: it keeps trying by itself, waiting on the move's done signal rather than a backoff (passivemove rule 3).    func testMovingSaysTheDefinitionsLineWithNoNumbersAndNoTryAgain() throws {        let shipped = try drawn        let said = words("moving")        let message = "This list is being worked out \u{2014} try again in a moment. (schema 131 \u{2192} 132)"        let error = CottonCallError(code: "could_not_read", message: message, details: .object([            "why": .string("moving"), "table": .string("ai_calls"), "database": .string("w1"),        ]))        let stall = CouldNotRead.reading(error)        XCTAssertEqual(stall, .moving(table: "ai_calls"))        let plural = try XCTUnwrap(shipped["ai_calls"]?.plural)        let line = CouldNotRead.line(for: error, database: "Heron", definitions: shipped)        XCTAssertEqual(line, said.replacingOccurrences(of: "{what}", with: plural).replacingOccurrences(of: "{database}", with: "Heron"))        XCTAssertNil(line.rangeOfCharacter(from: .decimalDigits), "no number of a schema or version: \(line)")        XCTAssertFalse(line.contains("worked out"), "never the core's sentence")        XCTAssertFalse(line.contains("{"), "every slot filled")        XCTAssertTrue(stall.keepsTrying, "no Try again")        XCTAssertTrue(stall.waitsForMove, "it waits on the move's done signal")        XCTAssertFalse(CouldNotRead.busy.waitsForMove)        let unnamed = CouldNotRead.moving(table: nil).line(database: "Heron", definitions: shipped)        XCTAssertEqual(unnamed, said.replacingOccurrences(of: "{what}", with: "Heron").replacingOccurrences(of: "{database}", with: "Heron"),                       "a read of no one table says the database")        // The list's failed state draws the one line with no act.        let surface = SourceSweep.withoutComments(            try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Surfaces/RecordListSurface.swift", ownedBy: "lists"))        let moving = try XCTUnwrap(surface.range(of: "case .failed where model.readStall?.waitsForMove == true:"))        let next = try XCTUnwrap(surface.range(of: "case .failed:", range: moving.upperBound..<surface.endIndex))        XCTAssertFalse(surface[moving.upperBound..<next.lowerBound].contains("action"), "a list mid-move offers no Try again")        // Every other failed list offers Try again (owner's ask, 22 Oct 2026).        let failed = surface[next.upperBound...].prefix(900)        XCTAssertTrue(failed.contains("action: { Task { await reload() } }"), "a failed list offers Try again")    }    /// RULE: Home whose read met a table mid-move (the core's `failed.why` `moving`) reads again on the move's done signal — the `data` event of origin `moved` — whatever tables it names; and that signal moves the records revision every list re-reads a failed first read on (passivemove rule 3).    func testAReadMidMoveIsReadAgainOnTheDoneSignal() async throws {        let core = ScriptedCore([CottonMethod.shellToday: .ok(TodayAnswerJSON.answer(            failed: ["why": "moving", "line": "AI usage is being worked out", "keeps_trying": true]))])        let home = HomeModel(core: core, toasts: ToastCenter(scheduler: ManualToastScheduler()))        await home.load()        XCTAssertEqual(home.answer?.failed?.why, "moving")        XCTAssertNil(home.receive(.data(tables: [], origin: "pull", database: "w1")), "an event naming nothing Home draws reads nothing")        let done = try XCTUnwrap(home.receive(.data(tables: ["_computed"], origin: ClientEvent.movesDoneOrigin, database: "w1")),                                 "the done signal reads Home again")        await done.value        let reads = await core.methodsCalled().filter { $0 == CottonMethod.shellToday }.count        XCTAssertEqual(reads, 2, "one read, on the signal")        XCTAssertTrue(ClientEvent.data(tables: ["_computed"], origin: ClientEvent.movesDoneOrigin).isMovesDone)        let sync = SyncModel(core: ScriptedCore([:]), clock: .instant)        let revision = sync.revision        sync.receive(.data(tables: ["cotton_ai_calls", "_computed"], origin: ClientEvent.movesDoneOrigin, database: "w1"))        XCTAssertEqual(sync.revision, revision + 1, "the done signal moves the revision lists re-read on")        let surface = SourceSweep.withoutComments(            try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Surfaces/RecordListSurface.swift", ownedBy: "lists"))        let onRevision = try XCTUnwrap(surface.range(of: ".onChange(of: revision) { _, _ in"))        let body = surface[onRevision.upperBound...].prefix(400)        XCTAssertTrue(body.contains("if model.phase == .failed") && body.contains("await reload()"),                      "a list whose first read failed reads again on the revision")    }}