Cotton code
159 lines · 10.0 KB · SwiftRaw
import CottonKitimport CottonValuesimport XCTest@testable import CottonUI/// The unlock window's card: drawn from what/// `unlock.card` answers, Allow hands the vault key read behind presence to/// `unlock.allow` with the tables left on, Not now declines, and End now ends/// an open window. Synthetic rows and keys only.@MainActorfinal class UnlockAsksTests: XCTestCase {    private static let scalar = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"    private static let card = #"""    {"card": {"face": "unlock.card", "requestId": "req-1", "minutes": 15,      "fields": {"title": "Allow Claude (claude.ai) to read Messages and Notes for 15 minutes?", "asker": "Claude (claude.ai)",        "toggles": [{"table": "message", "label": "Messages", "on": true}, {"table": "note", "label": "Notes", "on": true}],        "minutes": "15 minutes", "expires": "Waits 5 more minutes"},      "acts": [{"id": "allow", "label": "Allow", "receipt": "Allowed"}, {"id": "decline", "label": "Not now", "receipt": "Not now"}]},     "pollSeconds": 5}    """#    private static let windows = #"""    {"windows": [{"grantId": "g-1", "requestId": "req-1", "tables": ["note"], "endsAt": "2099-01-01T00:00:00Z", "said": "Notes · 12 minutes left"}],     "acts": [{"id": "end", "label": "End now", "receipt": "Ended"}]}    """#    private func asks(_ core: ScriptedCore, keys: InMemoryVaultKeyStore = InMemoryVaultKeyStore(seeded: scalar)) -> (UnlockAsks, Said) {        let said = Said()        let vault = VaultAccess(keyring: VaultKeyring(keys: keys, cache: InMemorySecretStore()), ask: { .allowed })        return (UnlockAsks(core: core, vault: vault, say: { words, _ in said.words.append(words) }), said)    }    final class Said { var words: [String] = [] }    /// RULE: The card is the core's: its face, its places and its acts as `unlock.card` answered them, and the open windows' rows with End now as `unlock.windows` answered them; no card answered is no card drawn.    func testTheCardAndTheWindowsAreWhatTheCoreAnswered() async {        let core = ScriptedCore([CottonMethod.unlockCard: .ok(Self.card), CottonMethod.unlockWindows: .ok(Self.windows)])        let (model, _) = asks(core)        await model.read()        XCTAssertEqual(model.card?.face, "unlock.card")        XCTAssertEqual(model.card?.text("title"), "Allow Claude (claude.ai) to read Messages and Notes for 15 minutes?")        XCTAssertEqual(model.acts.map(\.label), ["Allow", "Not now"])        XCTAssertEqual(model.windows, [UnlockWindowRow(grantId: "g-1", said: "Notes · 12 minutes left")])        XCTAssertEqual(model.windowAct?.label, "End now")        await core.answer(CottonMethod.unlockCard, .ok(#"{"card": null, "pollSeconds": null}"#))        await model.read()        XCTAssertNil(model.card)    }    /// RULE: Allow reads the vault key and hands it to `unlock.allow` with the request, the tables still switched on and the asked minutes, and says the act's receipt; a switched-off table is not sent.    func testAllowHandsTheKeyWithTheTablesLeftOn() async throws {        let core = ScriptedCore([            CottonMethod.unlockCard: .ok(Self.card), CottonMethod.unlockWindows: .ok(Self.windows),            CottonMethod.unlockAllow: .ok(#"{"grantId": "g-1", "endsAt": "2026-11-12T10:15:00Z", "tables": ["note"], "minutes": 15}"#),        ])        let (model, said) = asks(core)        await model.read()        model.flip("message")        guard case .list(let toggles)? = model.card?.fields["toggles"], case .object(let first) = toggles[0] else { return XCTFail("no toggles") }        XCTAssertEqual(first["on"], .bool(false), "the switch is drawn as flipped")        await model.act(try XCTUnwrap(model.acts.first { $0.id == "allow" }))        let sent = await core.calls.first { $0.method == CottonMethod.unlockAllow }        let body = try JSONSerialization.jsonObject(with: Data(try XCTUnwrap(sent).requestJSON.utf8)) as? [String: Any]        XCTAssertEqual(body?["requestId"] as? String, "req-1")        XCTAssertEqual(body?["tables"] as? [String], ["note"])        XCTAssertEqual(body?["minutes"] as? Int, 15)        XCTAssertEqual(body?["privateKey"] as? String, Self.scalar)        XCTAssertEqual(said.words, ["Allowed"])    }    private static let timed = #"""    {"card": {"face": "unlock.card", "requestId": "req-2", "minutes": 60, "client": "Claude",      "durations": [{"minutes": 15, "label": "15 minutes", "on": false}, {"minutes": 60, "label": "1 hour", "on": true},                    {"minutes": 1440, "label": "1 day", "on": false}, {"minutes": 0, "label": "Until I turn it off", "on": false}],      "fields": {"title": "Allow Claude to read Messages?", "asker": "Claude",        "toggles": [{"table": "message", "label": "Messages", "on": true}], "minutes": "1 hour", "expires": "Waits 5 more minutes"},      "acts": [{"id": "allow", "label": "Allow", "receipt": "Allowed"}, {"id": "decline", "label": "Not now", "receipt": "Not now"}]},     "pollSeconds": 5}    """#    /// RULE: The card offers the core's four lengths with the assistant's suggestion chosen; the person's pick is what Allow sends (0 for until turned off) and what the card's stamp says, and it stands while the same request is read again (e2e rulings R4).    func testThePersonsLengthIsWhatAllowSends() async throws {        let core = ScriptedCore([            CottonMethod.unlockCard: .ok(Self.timed), CottonMethod.unlockWindows: .ok(Self.windows),            CottonMethod.unlockAllow: .ok(#"{"grantId": "g-2", "endsAt": "9999-12-31T00:00:00Z", "tables": ["message"], "minutes": 0}"#),        ])        let (model, _) = asks(core)        await model.read()        XCTAssertEqual(model.durations.map(\.label), ["15 minutes", "1 hour", "1 day", "Until I turn it off"])        XCTAssertEqual(model.chosen, 60, "the suggestion starts chosen")        model.choose(try XCTUnwrap(model.durations.last))        XCTAssertEqual(model.card?.text("minutes"), "Until I turn it off")        await model.read()        XCTAssertEqual(model.chosen, 0, "the pick stands across a read of the same request")        await model.act(try XCTUnwrap(model.acts.first { $0.id == "allow" }))        let sent = await core.calls.first { $0.method == CottonMethod.unlockAllow }        let body = try JSONSerialization.jsonObject(with: Data(try XCTUnwrap(sent).requestJSON.utf8)) as? [String: Any]        XCTAssertEqual(body?["minutes"] as? Int, 0)    }    /// RULE: A person cancelling the presence prompt calls nothing and says nothing; a refusal says the core's own sentence.    func testACancelledPromptCallsNothingAndARefusalSaysTheCoresWords() async throws {        let core = ScriptedCore([            CottonMethod.unlockCard: .ok(Self.card), CottonMethod.unlockWindows: .ok(Self.windows),            CottonMethod.unlockAllow: .refuse(code: "bad_tables", message: "Switch on at least one table to allow, or choose Not now."),        ])        let cancelled = asks(core, keys: InMemoryVaultKeyStore(seeded: Self.scalar, failing: .cancelled))        await cancelled.0.read()        await cancelled.0.act(try XCTUnwrap(cancelled.0.acts.first { $0.id == "allow" }))        let allowed = await core.calls.filter { $0.method == CottonMethod.unlockAllow }        XCTAssertTrue(allowed.isEmpty)        XCTAssertEqual(cancelled.1.words, [])        let (model, said) = asks(core)        await model.read()        await model.act(try XCTUnwrap(model.acts.first { $0.id == "allow" }))        XCTAssertEqual(said.words, ["Switch on at least one table to allow, or choose Not now."])    }    /// RULE: Not now posts `unlock.decline` for the request and End now posts `unlock.end` for the window, each saying its receipt.    func testNotNowDeclinesAndEndNowEnds() async throws {        let core = ScriptedCore([            CottonMethod.unlockCard: .ok(Self.card), CottonMethod.unlockWindows: .ok(Self.windows),            CottonMethod.unlockDecline: .ok(#"{"declined": "req-1"}"#), CottonMethod.unlockEnd: .ok(#"{"ended": "g-1"}"#),        ])        let (model, said) = asks(core)        await model.read()        await model.act(try XCTUnwrap(model.acts.first { $0.id == "decline" }))        await model.end(try XCTUnwrap(model.windows.first))        let calls = await core.calls        XCTAssertEqual(calls.first { $0.method == CottonMethod.unlockDecline }?.requestJSON, #"{"requestId":"req-1"}"#)        XCTAssertEqual(calls.first { $0.method == CottonMethod.unlockEnd }?.requestJSON, #"{"grantId":"g-1"}"#)        XCTAssertEqual(said.words, ["Not now", "Ended"])    }    /// RULE: an Allow the core holds while this device's vault founds says no receipt; the card it answers then carries the setting-up `status` and no acts, drawn as such.    func testAHeldAllowShowsTheCoresStatusLineAndNoActs() async throws {        let held = #"""        {"card": {"face": "unlock.card", "requestId": "req-1", "minutes": 15,          "fields": {"title": "Allow Claude (claude.ai) to read Notes for 15 minutes?", "asker": "Claude (claude.ai)",            "toggles": [{"table": "note", "label": "Notes", "on": true}], "minutes": "15 minutes", "expires": "Waits 5 more minutes"},          "acts": [], "status": "Setting up this device's vault. The window opens by itself once Cotton has its key."},         "pollSeconds": 5}        """#        let core = ScriptedCore([            CottonMethod.unlockCard: .ok(Self.card), CottonMethod.unlockWindows: .ok(Self.windows),            CottonMethod.unlockAllow: .ok(#"{"held": true, "requestId": "req-1", "said": "Setting up this device's vault. The window opens by itself once Cotton has its key."}"#),        ])        let (model, said) = asks(core)        await model.read()        XCTAssertNil(model.status)        await core.answer(CottonMethod.unlockCard, .ok(held))        await model.act(try XCTUnwrap(model.acts.first { $0.id == "allow" }))        XCTAssertEqual(said.words, [], "the card's status line says it, not a receipt")        XCTAssertEqual(model.status, "Setting up this device's vault. The window opens by itself once Cotton has its key.")        XCTAssertTrue(model.acts.isEmpty, "nothing to tap a second time")    }}