// 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. import CottonValues import Foundation import XCTest @testable import CottonUI @MainActor final class ChangeReceiptTests: XCTestCase { private static let 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"])] ) private static let byline = "An example assistant" private static func errands() -> [TableRecord] { (1...3).map { n in TableRecord(id: "example-errand-\(n)", values: [ "title": .text("Example errand \(n)"), "done": .bool(false), "position": .number(Double(n)), ]) } } private func store(answersUndo: Bool = true) -> FixtureRecords { FixtureRecords( definitions: [Self.errand], records: ["errand": Self.errands()], byline: Self.byline, answersUndo: answersUndo) } private func 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() async throws { let entered = expectation(description: "Undo entered the write") let gate = UndoGate(onEntered: { entered.fulfill() }) let spy = SpyRecords(inner: store(), undoGate: gate) let change = try await spy.update(table: "errand", id: "example-errand-1", patch: ["done": .bool(true)]) let receipt = ChangeReceiptModel(change: change) let ready = receipt.undoLabel let 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() async throws { let spy = SpyRecords(inner: store()) let change = try await spy.update(table: "errand", id: "example-errand-1", patch: ["done": .bool(true)]) let receipt = ChangeReceiptModel(change: change) async let first = receipt.undo(through: spy) async let 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() async throws { let records = store() let change = try await 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() async throws { let records = store() let list = RecordListModel(definition: Self.errand, store: records, core: ListCoreFake(), seeds: ListSeeds()) await list.reload(project: nil, query: "") let written = try await list.write(list.records[0], ["done": .bool(true)]) await list.undone(written) XCTAssertTrue(list.lastChangeUndone) let acted = try await 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() async throws { 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 = try await 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 { _ = try await 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 { _ = try await 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 = try await 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() async throws { let records = store() let before = try await records.get(table: "errand", id: "example-errand-1") let updated = try await records.update(table: "errand", id: "example-errand-1", patch: ["title": .text("Changed"), "done": .bool(true)]) XCTAssertEqual(updated.before, before) let back = try await records.undo(changeId: updated.id) let restored = try await 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 = try await records.delete(table: "errand", id: "example-errand-1") _ = try await records.undo(change: deleted.id) let returned = try await records.get(table: "errand", id: "example-errand-1") XCTAssertEqual(returned, before) let created = try await records.create(table: "errand", data: ["title": .text("Example errand 5")]) let made = try XCTUnwrap(created.after?.id) _ = try await records.undo(change: created.id) let gone = try await 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 = try SourceSweep.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 = ["CottonUI/Surfaces/NewThoughtOverlay.swift"] for (name, text) in sources { let code = SourceSweep.withoutComments(text) let toastUndos = try SourceSweep.matches(#"toasts\.show\([^\n]*undo:"#, in: code) XCTAssertEqual(toastUndos, [], "\(name) offers an undo on a toast") if receipts.contains(name) { continue } XCTAssertEqual(try SourceSweep.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: FixtureRecords let undoGate: UndoGate? private(set) var undone: [String] = [] init(inner: FixtureRecords, undoGate: UndoGate? = nil) { self.inner = inner self.undoGate = undoGate } func tableDefinitions() async throws -> [TableDefinition] { try await inner.tableDefinitions() } func count(table: String) async throws -> Int { try await inner.count(table: table) } func list(table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue]) async throws -> RecordPage { try await inner.list(table: table, project: project, query: query, page: page, where: filter) } func get(table: String, id: String) async throws -> TableRecord? { try await inner.get(table: table, id: id) } func create(table: String, data: [String: RecordValue]) async throws -> ChangeRecord { try await inner.create(table: table, data: data) } func update(table: String, id: String, patch: [String: RecordValue]) async throws -> ChangeRecord { try await inner.update(table: table, id: id, patch: patch) } func delete(table: String, id: String) async throws -> ChangeRecord { try await inner.delete(table: table, id: id) } func reorder(table: String, ids: [String]) async throws -> ChangeRecord { try await inner.reorder(table: table, ids: ids) } func link(table: String, id: String, column: String, target: String) async throws -> ChangeRecord { try await inner.link(table: table, id: id, column: column, target: target) } func undo(change: String) async throws -> ChangeRecord { undone.append(change) if let undoGate { await undoGate.hold() } return try await inner.undo(change: change) } } private actor UndoGate { let onEntered: @Sendable () -> Void private var waiting: CheckedContinuation? init(onEntered: @escaping @Sendable () -> Void) { self.onEntered = onEntered } func hold() async { await withCheckedContinuation { waiting = $0; onEntered() } } func release() { waiting?.resume(); waiting = nil } }