Cotton code
221 lines · 13.4 KB · SwiftRaw
import CottonKitimport CottonValuesimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class WhatsAppSendTests: XCTestCase {    private func layout(_ gate: String = "true") throws -> ConversationLayout {        try JSONDecoder().decode(ConversationLayout.self, from: Data("""        {"table":"message","links":["thread_id"],"body":"display_body","at":"sent_at","mine":{"column":"direction","values":["out"]},"can_send":\(gate),"queue":{"link":"thread_id","body":"body"}}        """.utf8))    }    // The live-link fact controls the composer. Missing or wrongly typed    // facts fail closed; an archive cannot acquire a send input by default.    func testLiveLinkColumnGatesSendingAndRoundTrips() throws {        let live = try layout(#""sendable""#)        XCTAssertTrue(live.takesWords(on: TableRecord(id: "thread", values: ["sendable": .bool(true)])))        XCTAssertFalse(live.takesWords(on: TableRecord(id: "thread", values: [:])))        XCTAssertFalse(live.takesWords(on: TableRecord(id: "thread", values: ["sendable": .bool(false)])))        XCTAssertFalse(live.takesWords(on: TableRecord(id: "thread", values: ["sendable": .text("true")])))        let again = try JSONDecoder().decode(ConversationLayout.self, from: JSONEncoder().encode(live))        XCTAssertEqual(again, live)        XCTAssertFalse(try layout("false").takesWords(on: TableRecord(id: "thread", values: ["sendable": .bool(true)])))    }    // Only words and the thread cross the local write boundary. The engine    // owns the id, sender, channel and queue state; display_body is read-only.    func testSendWritesOnlyTheEngineInput() throws {        XCTAssertEqual(try layout().sent("  A synthetic reply  ", thread: "thread"), [            "thread_id": .text("thread"), "body": .text("A synthetic reply")        ])        XCTAssertNil(try layout().sent(" \n ", thread: "thread"))    }    // A worker reserves its WhatsApp id before sending. That reserved id    // cannot tell the person it was sent; only the acknowledged state can.    func testDeliveryRequiresTheMacAcknowledgement() throws {        func row(_ state: String?, _ id: String? = nil, _ reason: String? = nil) -> TableRecord {            var values: [String: RecordValue] = ["direction": .text("out"), "channel": .text("whatsapp")]            if let state { values["send_state"] = .text(state) }            if let id { values["external_id"] = .text(id) }            if let reason { values["send_error"] = .text(reason) }            return TableRecord(id: "one", values: values)        }        XCTAssertEqual(MessageDelivery(row("queued")), .queued)        XCTAssertEqual(MessageDelivery(row("sending", "reserved-id")), .sending)        XCTAssertEqual(MessageDelivery(row("sent")), .sending)        XCTAssertEqual(MessageDelivery(row("sent", "acknowledged-id")), .sent)        XCTAssertEqual(MessageDelivery(row("read", "acknowledged-id")), .seen)        XCTAssertEqual(MessageDelivery(row("failed", nil, "WhatsApp is not linked on your Mac")), .failed("WhatsApp is not linked on your Mac"))        XCTAssertNil(MessageDelivery(row(nil)))        var incoming = row("failed")        incoming.values["direction"] = .text("in")        XCTAssertNil(MessageDelivery(incoming))    }    // A delayed Mac timestamp changes the receipt, not the row's position.    // Canonical ids keep acknowledgement and retry on the original slip.    func testAcknowledgementKeepsTheMessageInPlace() throws {        let layout = try layout()        var first = TableRecord(id: "first", values: [            "direction": .text("out"), "channel": .text("whatsapp"), "send_state": .text("queued"),            "created_at": .text("2026-10-07T00:00:00Z"), "sent_at": .text("2026-10-07T00:00:00Z")        ])        let second = TableRecord(id: "second", values: ["sent_at": .text("2026-10-07T00:00:01Z")])        let before = layout.merged(messages: [first, second], also: [])        XCTAssertNil(layout.footer(of: try XCTUnwrap(before.first), messages: nil))        first.values["send_state"] = .text("sent")        first.values["external_id"] = .text("acknowledged-id")        first.values["sent_at"] = .text("2026-10-07T00:00:10Z")        // As the next read hands it over: the send's clock in the core's words.        first = CoreSaid.read(first, days: ["sent_at": CoreSaid.day("2026-10-07", clock: "5:30 am")])        XCTAssertEqual(layout.ordered([first, second]).map(\.id), ["first", "second"])        let after = layout.merged(messages: [first, second], also: [])        XCTAssertEqual(after.map(\.id), before.map(\.id))        XCTAssertEqual(layout.footer(of: try XCTUnwrap(after.first), messages: nil), "5:30 am", "the Mac's send time, not the queue's")    }    // The phone creates one durable local row. Retry updates that same row    // with only the engine's queue transition, and cannot resend a sent row.    // All fixtures are synthetic; this guard never addresses real WhatsApp.    func testLocalQueueAndRetryUseTheExistingRecordVerbs() async throws {        let queued = #"{"table":"message","id":"local-id","data":{"thread_id":"thread","display_body":"A synthetic reply","body":"A synthetic reply","direction":"out","channel":"whatsapp","send_state":"queued","created_at":"2026-10-07T00:00:00Z","sent_at":"2026-10-07T00:00:00Z"}}"#        let changed = """        {"change":{"id":"change","table":"message","record_id":"local-id","verb":"create","byline":"user","after":{},"undoable":false},"record":\(queued)}        """        let core = ScriptedCore([            "records.create": .ok(changed), "records.update": .ok(changed),            "records.list": .ok("{\"table\":\"message\",\"records\":[\(queued)],\"total\":1}")        ])        let model = ConversationModel(layout: try layout(#""sendable""#), thread: "thread",            store: CoreRecords(core: core, bundle: try TestResources.bundle()),            threadRecord: TableRecord(id: "thread", values: ["sendable": .bool(true)]))        _ = try await model.send("A synthetic reply")        XCTAssertEqual(model.items.map(\.id), ["message:local-id"])        XCTAssertEqual(model.items.first?.words, "A synthetic reply")        XCTAssertNil(model.lastChange, "the sent slip is the receipt")        let initialCalls = await core.calls        let create = try XCTUnwrap(initialCalls.first { $0.method == "records.create" })        let input = try JSONDecoder().decode([String: RecordValue].self, from: Data(create.requestJSON.utf8))        XCTAssertEqual(input["data"], .object(["thread_id": .text("thread"), "body": .text("A synthetic reply")]))        var failed = try XCTUnwrap(model.messages.first)        failed.values["send_state"] = .text("failed")        _ = try await model.retry(failed)        let calls = await core.calls        let update = try XCTUnwrap(calls.first { $0.method == "records.update" })        let retry = try JSONDecoder().decode([String: RecordValue].self, from: Data(update.requestJSON.utf8))        XCTAssertEqual(retry["id"], .text("local-id"))        XCTAssertEqual(retry["patch"], .object(["send_state": .text("queued")]))        XCTAssertEqual(model.items.map(\.id), ["message:local-id"])        let noRetry = try await model.retry(try XCTUnwrap(model.messages.first))        XCTAssertNil(noRetry)        let methods = await core.methodsCalled()        XCTAssertEqual(methods.filter { $0 == "records.create" }.count, 1)    }    // The queued slip appears before the post-write read answers. A second    // tap while that read is pending cannot mint a second outbound row.    func testQueuedSlipAppearsBeforeReloadAndCannotBeSentTwice() async throws {        let core = PendingQueueCore()        let model = ConversationModel(layout: try layout(), thread: "thread",            store: CoreRecords(core: core, bundle: try TestResources.bundle()))        let send = Task { try await model.send("A synthetic reply") }        for _ in 0..<100 {            if await core.waiting { break }            try await Task.sleep(for: .milliseconds(10))        }        let waiting = await core.waiting        XCTAssertTrue(waiting)        XCTAssertEqual(model.items.map(\.id), ["message:local-id"])        XCTAssertEqual(model.items.first?.words, "A synthetic reply")        XCTAssertTrue(model.sending)        let duplicate = try await model.send("A synthetic reply")        XCTAssertNil(duplicate)        await core.finish()        _ = try await send.value        XCTAssertEqual(model.items.map(\.id), ["message:local-id"])        let creates = await core.creates        XCTAssertEqual(creates, 1)    }    // Only a failed outgoing slip can enter the bin. It leaves the thread    // immediately, and a binned slip cannot retry into the sender's queue.    // The backend keeps its failed state for an explicit restore from Bin.    func testOnlyFailedUnbinnedMessagesCanBeBinnedOrRetried() async throws {        let core = ScriptedCore([            "records.delete": .ok(#"{"change":{"id":"bin-change","table":"message","record_id":"failed-id","verb":"delete","after":{"send_state":"failed","trashed_at":"2026-10-07T01:00:00Z"},"undoable":true}}"#),            "records.list": .ok(#"{"table":"message","records":[{"table":"message","id":"failed-id","data":{"direction":"out","channel":"whatsapp","send_state":"failed","display_body":"Synthetic refusal"}}],"total":1}"#)        ])        let model = ConversationModel(layout: try layout(), thread: "thread",            store: CoreRecords(core: core, bundle: try TestResources.bundle()))        await model.load()        XCTAssertEqual(model.items.map(\.id), ["message:failed-id"])        // Even a failed post-delete read cannot keep the deleted slip here.        await core.answer("records.list", .refuse(code: "offline", message: "Synthetic read stopped"))        func row(_ state: String, trashed: Bool = false) -> TableRecord {            var values: [String: RecordValue] = ["direction": .text("out"), "channel": .text("whatsapp"), "send_state": .text(state)]            if trashed { values["trashed_at"] = .text("2026-10-07T01:00:00Z") }            return TableRecord(id: "failed-id", values: values)        }        // Failure acts belong to the local queue, and a binned conversation        // stays read-only even when it still holds an unbinned failed slip.        XCTAssertTrue(model.canRetryOrBin(row("failed")))        XCTAssertFalse(model.canRetryOrBin(row("sent")))        XCTAssertFalse(model.canRetryOrBin(row("queued")))        XCTAssertFalse(model.canRetryOrBin(row("failed", trashed: true)))        model.threadRecord = TableRecord(id: "thread", values: ["trashed_at": .text("2026-10-07T01:00:00Z")])        XCTAssertFalse(model.canRetryOrBin(row("failed")))        model.threadRecord = nil        let otherLayout = try JSONDecoder().decode(ConversationLayout.self, from: Data(#"{"table":"session_message","links":["session_id"],"body":"body","at":"created_at","mine":{"column":"role","values":["user"]},"can_send":true}"#.utf8))        let other = ConversationModel(layout: otherLayout, thread: "thread",            store: CoreRecords(core: core, bundle: try TestResources.bundle()))        XCTAssertFalse(other.canRetryOrBin(row("failed")))        let sent = try await model.binFailed(row("sent"))        let queued = try await model.binFailed(row("queued"))        let binned = try await model.binFailed(row("failed", trashed: true))        let retry = try await model.retry(row("failed", trashed: true))        XCTAssertNil(sent)        XCTAssertNil(queued)        XCTAssertNil(binned)        XCTAssertNil(retry)        let change = try await model.binFailed(row("failed"))        XCTAssertEqual(change?.id, "bin-change")        XCTAssertTrue(model.items.isEmpty)        let calls = await core.calls        let deletes = calls.filter { $0.method == "records.delete" }        XCTAssertEqual(deletes.count, 1)        let request = try JSONDecoder().decode([String: RecordValue].self,            from: Data(try XCTUnwrap(deletes.first).requestJSON.utf8))        XCTAssertEqual(request["id"], .text("failed-id"))        XCTAssertEqual(request["table"], .text("message"))        XCTAssertFalse(calls.contains { $0.method == "records.update" })    }}private actor PendingQueueCore: CottonCalling {    var waiting = false    var creates = 0    private var answer: CheckedContinuation<String, Never>?    private let row = #"{"table":"message","id":"local-id","data":{"thread_id":"thread","display_body":"A synthetic reply","direction":"out","channel":"whatsapp","send_state":"queued"}}"#    func callRaw(_ method: String, requestJSON: String) async -> String {        if method == "records.create" {            creates += 1            // A write's raw after can omit computed display_body; the            // following read will include it, but the slip cannot wait.            return #"{"ok":true,"data":{"change":{"id":"change","record_id":"local-id","after":{"thread_id":"thread","body":"A synthetic reply","direction":"out","channel":"whatsapp","send_state":"queued"},"undoable":false}}}"#        }        guard method == "records.list" else { return #"{"ok":false,"error":{"code":"missing","message":"Not here"}}"# }        return await withCheckedContinuation { answer in self.answer = answer; waiting = true }    }    func finish() {        answer?.resume(returning: "{\"ok\":true,\"data\":{\"table\":\"message\",\"records\":[\(row)],\"total\":1}}")        answer = nil    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) {}    func close() {}}