Cotton code
85 lines · 5.1 KB · SwiftRaw
// Home's sync card opened (owner, 2 Nov 2026): its acts tier is this// device's own record's, as every record's is, and lists exactly Sign out or// Sign in, Sync now while signed in, Share ink (3 Nov 2026: the ink the// phone kept, to the share sheet), and Erase last and red. The acts are the// device table's commands (`device.json`), offered on the `session` the core// projects onto this device's own row where the app backs up to a personal// object; an app with none (Rigby) keeps the acts it had. Which acts stand,// in which order, Erase red and last, is the core's (`shell.opened`:// `card_actions_tests`, `opened_tests`, `phone_only_tests`). Synthetic ids only.#if os(iOS)import CottonKitimport CottonValuesimport XCTest@testable import CottonUI@MainActorfinal class SyncCardActsTests: XCTestCase {    /// The shell's device table (a phone before sign-in) and the personal    /// kit's (the object's, after it): the card offers the same acts on both.    private func definitions() throws -> [TableDefinition] {        try ["crates/cotton-core/kits/shell/tables/device.json", "crates/cotton-core/kits/personal/tables/device.json"].map { path in            let json = try SourceSweep.mustRead(path, ownedBy: "home-sync")            return try JSONDecoder().decode(TableDefinition.self, from: Data(json.utf8))        }    }    private func thisDevice(session: String?) -> TableRecord {        var values: [String: RecordValue] = ["name": .text("Invented phone"), "status": .text("this device"), "kind": .text("iPhone")]        if let session { values["session"] = .text(session) }        return TableRecord(id: "synthetic-device", values: values)    }    /// RULE: each of the four runs the app's flow for this device's own row — never an engine write; Erase is red and destroys, and the flow asks first in the Backup card's own words (a card's acts run at once, and a removed copy has no undo).    func testEachSessionActIsTheAppsFlowAndEraseAsksFirst() async throws {        for definition in try definitions() {            let commands = Dictionary(uniqueKeysWithValues: (definition.commands ?? []).map { ($0.id, $0) })            for (id, flow) in [("sign_in", "signIn"), ("sign_out", "signOut"), ("share_ink", "shareInk"), ("erase_here", "eraseThisDevice")] {                let command = try XCTUnwrap(commands[id], id)                XCTAssertEqual(command.method, "settings.openFlow", id)                XCTAssertEqual(command.data?["flow"], .text(flow), id)                XCTAssertEqual(command.bindings?["origin_id"], "$id", id)            }            let erase = try XCTUnwrap(commands["erase_here"])            XCTAssertTrue(erase.asksFirst)            XCTAssertNil(erase.confirm, "the flow asks, in the Backup card's words, never a second time")        }        // No personal object (Rigby): the flow runs nothing.        let erase = try JSONDecoder().decode(RecordKeptFlow.self, from: Data(            #"{"flow":"eraseThisDevice","origin":{"table":"device","id":"synthetic-device"},"database":null}"#.utf8))        let ran = await PersonalSessionFlows.run(erase, personal: nil)        XCTAssertFalse(ran)    }    /// RULE: Sync now from the card lands as the core ran it: `records.command` answers `sync.now`'s own report, whose `pending` is the outbox's count, and the act says "Syncing" — never "That change was not saved." (Cotton 348's walk).    func testSyncNowFromTheCardLandsTheCoresAnswer() async throws {        let definition = try XCTUnwrap(definitions().first)        let syncNow = try XCTUnwrap(definition.commands?.first { $0.id == "sync_now" })        let core = SyncNowCore()        let change = try await core.recordCommand(table: "device", id: "synthetic-device", command: syncNow, picked: nil)        XCTAssertEqual(change.said?.said, "Syncing")        XCTAssertFalse(change.pending)        XCTAssertFalse(change.undoable, "a pass has no way back")        let asked = await core.asked        XCTAssertEqual(asked, ["records.command"])    }    /// RULE: a session flow from the card runs at the root, through a Settings host too: the host hands it up rather than refusing it as another table's.    func testSessionFlowsReachTheRoot() {        XCTAssertTrue([RecordKeptFlow.Flow.signIn, .signOut, .eraseThisDevice, .shareInk].allSatisfy(\.session))        XCTAssertFalse([RecordKeptFlow.Flow.leaveDatabase, .reportProblem, .vaultUnlock].contains(where: \.session))    }}/// A core answering `records.command` for Sync now as cotton-ffi does: the/// command's outcome over `sync.now`'s own report (`ClientController::sync_now`).private actor SyncNowCore: CottonCalling {    private(set) var asked: [String] = []    func callRaw(_ method: String, requestJSON: String) async throws -> String {        asked.append(method)        return #"{"ok":true,"data":{"command":"sync_now","kind":"update","receipt":"Syncing","undo":null,"open":null,"answer":{"pushed":2,"pulled":5,"behind":false,"behindBy":null,"wakeRefusal":null,"pending":3,"lastPullAt":"2026-11-02T09:00:00Z"}}}"#    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {}    func close() async {}}#endif