// The change receipt after every command (shared format: "Every write returns// a change record {id, byline, before, after} so the app can show it and offer// undo"; the receipt is the seventh face): what it prints for each command a// surface makes, its one Undo through the generic verb, the fixture side of// that verb, and the guard that no other undo is left in the surfaces.//// Every record and name here is invented.importCottonValuesimportFoundationimport XCTest@testable importCottonUI@MainActorfinalclassChangeReceiptTests: XCTestCase {privatestaticlet errand = TableDefinition( id: "errand", name: "Errand", plural: "Errands", columns: [ColumnDefinition(key: "title", name: "Title", type: .text, required: true),ColumnDefinition(key: "done", name: "Done", type: .bool),ColumnDefinition(key: "position", type: .number), ], title: "title", order: "position", slip: SlipLayout(title: "title", toggle: "done"), tile: TileLayout(face: .slipList), page: [PageSection(heading: nil, columns: ["title", "done"])] )privatestaticlet byline = "An example assistant"privatestaticfunc errands() -> [TableRecord] { (1...3).map { n inTableRecord(id: "example-errand-\(n)", values: ["title": .text("Example errand \(n)"),"done": .bool(false),"position": .number(Double(n)), ]) } }privatefunc store(answersUndo: Bool = true) -> FixtureRecords {FixtureRecords( definitions: [Self.errand], records: ["errand": Self.errands()], byline: Self.byline, answersUndo: answersUndo) }privatefunc facts(_ change: ChangeRecord, canUndo: Bool = true, undone: Bool = false) -> ChangeReceiptFacts {ChangeReceiptFacts.of( change, table: Self.errand, canUndo: canUndo, hasRecords: true, undone: undone, failed: false) }/// RULE: A receipt names a new record by its title, else by the column its slip is headed by, else by the kind of record it is — never by its id.func testAReceiptNeverNamesARecordByItsId() {let titled = TableRecord(id: "example-errand-9", values: ["title": .text("Buy string"),TableRecord.saidKey: .object(["slip": .object(["name": .text("Buy string")])])]) XCTAssertEqual(ChangeLines.title(titled, Self.errand), "Buy string")let blank = TableRecord(id: "example-errand-9", values: ["title": .text(" ")])let errandKind = ChangeLines.title(blank, Self.errand) XCTAssertFalse(errandKind.trimmingCharacters(in: .whitespaces).isEmpty) XCTAssertFalse(errandKind.contains(blank.id), "never by its id")let timed = TableDefinition( id: "alarm", name: "Alarm", plural: "Alarms", columns: [ColumnDefinition(key: "label", name: "Label", type: .text, placeholder: "Alarm"),ColumnDefinition(key: "time", name: "Time", type: .text, readonly: true), ], title: "label", slip: SlipLayout(title: "time", subtitle: "label"), tile: TileLayout(face: .slipList), page: [PageSection(heading: nil, columns: ["label"])] )let unlabelled = TableRecord(id: "example-alarm-1", values: ["label": .text(""), "time": .text("07:30")]) XCTAssertEqual(ChangeLines.title(unlabelled, timed), "07:30")let alarmKind = ChangeLines.title(TableRecord(id: "example-alarm-2", values: [:]), timed) XCTAssertFalse(alarmKind.contains("example-alarm-2"), "never by its id") XCTAssertNotEqual(alarmKind, errandKind, "named by the kind of record it is")let unknown = ChangeLines.title(TableRecord(id: "example-unknown-1", values: [:]), nil) XCTAssertFalse(unknown.isEmpty) XCTAssertFalse(unknown.contains("example-unknown-1")) }// ── What it prints, for every command ──// ── Undo ──/// RULE: While a receipt's Undo is waiting on the write, its action says it is in progress and a second tap sends nothing; only the answer can mark the receipt undone.func testAnUndoInFlightSaysSoAndCannotBeSentAgain() asyncthrows {let entered = expectation(description: "Undo entered the write")let gate = UndoGate(onEntered: { entered.fulfill() })let spy = SpyRecords(inner: store(), undoGate: gate)let change = tryawait spy.update(table: "errand", id: "example-errand-1", patch: ["done": .bool(true)])let receipt = ChangeReceiptModel(change: change)let ready = receipt.undoLabellet flight = Task { await receipt.undo(through: spy) }await fulfillment(of: [entered], timeout: 3) XCTAssertTrue(receipt.busy) XCTAssertFalse(receipt.undone) XCTAssertNotEqual(receipt.undoLabel, ready, "the disabled action must explain that its write is still going")let again = await receipt.undo(through: spy) XCTAssertNil(again)await gate.release()let back = await flight.value XCTAssertNotNil(back) XCTAssertFalse(receipt.busy) XCTAssertTrue(receipt.undone)let sent = await spy.undone XCTAssertEqual(sent, [change.id]) }/// RULE: Undo on the receipt calls the undo verb with that change's id exactly once, then reads as undone and offers nothing more.func testUndoCallsTheVerbOnceWithTheChangesIdAndReadsAsUndone() asyncthrows {let spy = SpyRecords(inner: store())let change = tryawait spy.update(table: "errand", id: "example-errand-1", patch: ["done": .bool(true)])let receipt = ChangeReceiptModel(change: change)asynclet first = receipt.undo(through: spy)asynclet second = receipt.undo(through: spy)let answers = await [first, second]let third = await receipt.undo(through: spy)let undone = await spy.undone XCTAssertEqual(undone, [change.id], "the verb was not called once with the change's id") XCTAssertEqual(answers.compactMap { $0 }.count, 1) XCTAssertNil(third) XCTAssertTrue(receipt.undone)let after = facts(change, undone: receipt.undone) XCTAssertNotEqual(after.head, facts(change).head, "an undone receipt says only that it is undone, never the old sentence") XCTAssertFalse(after.offersUndo, "an undone receipt offers its Undo again") XCTAssertNil(after.note) }/// RULE: Under Undone a receipt shows what the undo restored — each changed column from the value it undid back to the value it put back — never the change it undid (the Session defaults' Bypass → Ask stayed under Undone, ws-m4-code1's walk, 6 Oct).func testAnUndoneReceiptShowsWhatTheUndoRestored() asyncthrows {let records = store()let change = tryawait records.update( table: "errand", id: "example-errand-1", patch: ["title": .text("Example errand renamed")])let made = facts(change) XCTAssertEqual( made.body.map(\.kind), [.changed(name: "Title", before: "Example errand 1", after: "Example errand renamed")])let undone = facts(change, undone: true) XCTAssertNotEqual(undone.head, made.head) XCTAssertEqual( undone.body.map(\.kind), [.changed(name: "Title", before: "Example errand renamed", after: "Example errand 1")],"under Undone the receipt still shows the change it undid") }/// RULE: A change a table's own act made on the list (a Connected act, #1282) wears the same receipt as the list's verbs — never a sentence in a toast — and starts fresh, not undone.func testAListActsChangeWearsTheReceipt() asyncthrows {let records = store()let list = RecordListModel(definition: Self.errand, store: records, core: ListCoreFake(), seeds: ListSeeds())await list.reload(project: nil, query: "")let written = tryawait list.write(list.records[0], ["done": .bool(true)])await list.undone(written) XCTAssertTrue(list.lastChangeUndone)let acted = tryawait records.update(table: "errand", id: "example-errand-2", patch: ["done": .bool(true)]) list.received(acted) XCTAssertEqual(list.lastChange?.id, acted.id, "the act's change is not the list's newest") XCTAssertFalse(list.lastChangeUndone, "the act's receipt reads as undone") XCTAssertTrue(facts(acted).offersUndo) }/// RULE: A change that cannot be taken back shows no Undo and is its words alone, never "This can't be undone"; only a build without the undo verb says so.func testNoUndoIsOfferedWhenTheVerbsCannotTakeItBack() asyncthrows {let change = ChangeRecord(id: "change-9", byline: "You", before: nil, after: nil)let refused = facts(change, canUndo: false) XCTAssertFalse(refused.offersUndo) XCTAssertNil(refused.note)// The core's own word on the change, with its reason.let irreversible = facts(ChangeRecord(id: "change-10", byline: "You", before: nil, after: nil, undoable: false, reason: "Example reason.")) XCTAssertFalse(irreversible.offersUndo) XCTAssertNil(irreversible.note, "a receipt never says why it cannot be undone")// A build whose core lacks the verb mints no undoable change and refuses the verb.let lacking = store(answersUndo: false)let written = tryawait lacking.update(table: "errand", id: "example-errand-1", patch: ["done": .bool(true)]) XCTAssertFalse(written.undoable)let absent = facts(written) XCTAssertFalse(absent.offersUndo) XCTAssertEqual(absent.note, GenericVerbsWords.undoAbsent)do { _ = tryawait lacking.undo(change: written.id) XCTFail("a build without the verb undid a change") } catch { XCTAssertEqual(error as? GenericVerbsError, .absent(verb: "undo")) }// Nor does its generic verb answer when asked directly: absent is absent.do { _ = tryawait lacking.undo(changeId: written.id) XCTFail("a build without the verb answered the generic undo") } catch { XCTAssertEqual(error as? GenericVerbsError, .absent(verb: "undo")) }let kept = tryawait lacking.get(table: "errand", id: "example-errand-1") XCTAssertEqual(kept?["done"], .bool(true), "a refused undo put something back")// No Records in the environment: nothing to send the id through.let none = ChangeReceiptFacts.of(change, table: nil, canUndo: true, hasRecords: false, undone: false, failed: false) XCTAssertFalse(none.offersUndo) XCTAssertEqual(none.note, GenericVerbsWords.undoAbsent) }// ── The fixture side of the verb ──/// RULE: The fixture undo puts back exactly the record before the change — an update, a delete and a create each round-trip.func testTheFixtureUndoRestoresBefore() asyncthrows {let records = store()let before = tryawait records.get(table: "errand", id: "example-errand-1")let updated = tryawait records.update(table: "errand", id: "example-errand-1", patch: ["title": .text("Changed"), "done": .bool(true)]) XCTAssertEqual(updated.before, before)let back = tryawait records.undo(changeId: updated.id)let restored = tryawait records.get(table: "errand", id: "example-errand-1") XCTAssertEqual(restored, before) XCTAssertEqual(back.after, before, "the undoing change does not say what it put back") XCTAssertFalse(back.undoable, "the undo's own change is offered for undo")let deleted = tryawait records.delete(table: "errand", id: "example-errand-1") _ = tryawait records.undo(change: deleted.id)let returned = tryawait records.get(table: "errand", id: "example-errand-1") XCTAssertEqual(returned, before)let created = tryawait records.create(table: "errand", data: ["title": .text("Example errand 5")])let made = try XCTUnwrap(created.after?.id) _ = tryawait records.undo(change: created.id)let gone = tryawait records.get(table: "errand", id: made) XCTAssertNil(gone) }// ── One undo ──/// RULE: The surfaces draw no undo but a receipt — the change receipt, and the thought receipt whose capture has no change record to undo — no toast with an undo, no Undo button of their own.func testTheSurfacesHaveNoUndoButTheReceipt() throws {let sources = trySourceSweep.swiftSources().filter { $0.name.hasPrefix("CottonUI/Surfaces/") }/// RULE: The receipt sweep must read surfaces before it can enforce one receipt path. XCTAssertFalse(sources.isEmpty, "the sweep read no Surfaces files")// New thought's receipt (inside `NewThoughtOverlay.swift`) is the one// other receipt: `capture.create` answers no change record, so its Undo// is the thought kind's own verb (`ThoughtFiling.takeBack`), not a// second undo beside the change receipt's.let receipts: Set<String> = ["CottonUI/Surfaces/NewThoughtOverlay.swift"]for (name, text) in sources {let code = SourceSweep.withoutComments(text)let toastUndos = trySourceSweep.matches(#"toasts\.show\([^\n]*undo:"#, in: code) XCTAssertEqual(toastUndos, [], "\(name) offers an undo on a toast")if receipts.contains(name) { continue } XCTAssertEqual(trySourceSweep.matches(#""Undo""#, in: code), [], "\(name) draws an Undo of its own") } }}/// Records that counts the undo verb's calls, over the fixtures.private actor SpyRecords: Records {let inner: FixtureRecordslet undoGate: UndoGate?private(set) var undone: [String] = []init(inner: FixtureRecords, undoGate: UndoGate? = nil) {self.inner = innerself.undoGate = undoGate }func tableDefinitions() asyncthrows -> [TableDefinition] { tryawait inner.tableDefinitions() }func count(table: String) asyncthrows -> Int { tryawait inner.count(table: table) }func list(table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue]) asyncthrows -> RecordPage {tryawait inner.list(table: table, project: project, query: query, page: page, where: filter) }func get(table: String, id: String) asyncthrows -> TableRecord? { tryawait inner.get(table: table, id: id) }func create(table: String, data: [String: RecordValue]) asyncthrows -> ChangeRecord { tryawait inner.create(table: table, data: data) }func update(table: String, id: String, patch: [String: RecordValue]) asyncthrows -> ChangeRecord {tryawait inner.update(table: table, id: id, patch: patch) }func delete(table: String, id: String) asyncthrows -> ChangeRecord { tryawait inner.delete(table: table, id: id) }func reorder(table: String, ids: [String]) asyncthrows -> ChangeRecord { tryawait inner.reorder(table: table, ids: ids) }func link(table: String, id: String, column: String, target: String) asyncthrows -> ChangeRecord {tryawait inner.link(table: table, id: id, column: column, target: target) }func undo(change: String) asyncthrows -> ChangeRecord { undone.append(change)iflet undoGate { await undoGate.hold() }returntryawait inner.undo(change: change) }}private actor UndoGate {let onEntered: @Sendable () -> Voidprivatevar waiting: CheckedContinuation<Void, Never>?init(onEntered: @escaping @Sendable () -> Void) { self.onEntered = onEntered }func hold() async {await withCheckedContinuation { waiting = $0; onEntered() } }func release() { waiting?.resume(); waiting = nil }}