Cotton code
349 lines · 14.8 KB · SwiftRaw
// The envelope, and the shape of every answer this app reads.//// `cotton_call`'s contract is `{"ok":true,"data":…}` or// `{"ok":false,"error":{code,message,details}}`, and nothing above the boundary// should ever have to know that. These cases drive `CottonCalling` through the// scripted double, which is the same seam every screen test uses — so a change// to the envelope goes red HERE, once, rather than in nine screen tests at// their fifth assertion.import XCTest@testable import CottonKitfinal class CottonCoreTests: XCTestCase {    /// RULE: The phone's version label carries its build — "1.0.0 (248)" — because the cutover tool's Mac-last gate reads the build from the synced device row; with no build it is the marketing version alone.    func testThePhonesVersionLabelCarriesItsBuild() {        XCTAssertEqual(CottonConfig.versionLabel(short: "1.0.0", build: "248"), "1.0.0 (248)")        XCTAssertEqual(CottonConfig.versionLabel(short: "1.0.0", build: nil), "1.0.0")        XCTAssertEqual(CottonConfig.versionLabel(short: "1.0.0", build: ""), "1.0.0")        XCTAssertNil(CottonConfig.versionLabel(short: nil, build: "248"))    }    func testASuccessfulAnswerDecodesIntoItsType() async throws {        let core = ScriptedCore([            CottonMethod.readBoot: .ok(                #"{"paired":true,"stage":"ready","ownerId":"o1","workspaceId":"w1"}"#            )        ])        let boot: BootRead = try await core.call(CottonMethod.readBoot)        XCTAssertTrue(boot.paired)        XCTAssertEqual(boot.ownerId, "o1")        XCTAssertEqual(boot.workspaceId, "w1")    }    func testARefusalArrivesAsAnErrorCarryingItsCode() async {        let core = ScriptedCore([            CottonMethod.workspaceStartLocal: .refuse(code: "rate_limited", message: "wait")        ])        do {            _ = try await core.call(CottonMethod.workspaceStartLocal, as: JSONValue.self)            XCTFail("a refusal must not read as an answer")        } catch let error as CottonCallError {            XCTAssertEqual(error.code, "rate_limited")            XCTAssertEqual(error.message, "wait")        } catch {            XCTFail("wrong error type: \(error)")        }    }    func testAnUnknownMethodIsRefusedRatherThanAnswered() async {        // `server.start` on a phone answers `unknown_method` BY CONSTRUCTION —        // the dispatch arm is `#[cfg]`-gated out rather than stubbed, so it        // cannot lie. The double reproduces that for anything unscripted.        let core = ScriptedCore()        do {            _ = try await core.call("server.start", as: JSONValue.self)            XCTFail("a phone has no server")        } catch let error as CottonCallError {            XCTAssertEqual(error.code, "unknown_method")        } catch {            XCTFail("wrong error type: \(error)")        }    }    func testAnAnswerThatIsNotAnEnvelopeIsReportedAsSuch() async {        let core = ScriptedCore([CottonMethod.readBoot: .garbage("<html>")])        do {            _ = try await core.call(CottonMethod.readBoot, as: BootRead.self)            XCTFail("that is not an envelope")        } catch let error as CottonClientError {            XCTAssertEqual(error, .malformedAnswer("<html>"))        } catch {            XCTFail("wrong error type: \(error)")        }    }    /// **An unreadable answer is a SENTENCE, never its own payload.**    ///    /// Every screen's last-resort formatter is `String(describing:)` over    /// whatever it caught, and an error that is not a `LocalizedError` is an    /// error whose contents get drawn. The walk of 15 Sep 2026 found the FFI's    /// write envelope — braces, quotes and a base64-looking key — written on    /// the record sheet in red handwriting where the reason a recording had not    /// been filed belonged.    func testAnUnreadableAnswerReadsAsASentenceAndKeepsItsPayloadForTheLog() {        let error = CottonClientError.malformedAnswer(#"{"answer":{"id":"m-1"},"rail":"client"}"#)        let said = error.errorDescription ?? ""        XCTAssertFalse(said.isEmpty)        XCTAssertFalse(said.contains("{"), "no JSON on a screen: \(said)")        XCTAssertFalse(said.contains("rail"), said)        XCTAssertTrue(said.hasSuffix("."), "a sentence: \(said)")        // The payload is still there, for the log and for a report.        XCTAssertTrue(error.rawAnswer.contains("\"rail\""))    }    func testTheRequestIsSentAsJSONAndTheMethodIsRecorded() async throws {        let core = ScriptedCore([CottonMethod.write: .ok(#"{"tool":"create_todo"}"#)])        _ = try await core.call(            CottonMethod.write,            WriteRequest(tool: "create_todo", args: .object(["title": .string("milk")])),            as: WriteAnswer.self        )        let calls = await core.calls        XCTAssertEqual(calls.count, 1)        XCTAssertEqual(calls.first?.method, "write")        XCTAssertTrue(calls.first?.requestJSON.contains("\"tool\":\"create_todo\"") ?? false)        XCTAssertTrue(calls.first?.requestJSON.contains("milk") ?? false)    }    func testAConfigCarriesThePhoneSFieldsAndNoneOfTheMacS() throws {        // `OpenConfig` is `deny_unknown_fields` and the Mac's members are        // `#[cfg(feature = "host")]`, so a stray field here is a phone that        // will not open at all. A nil optional is an ABSENT field, which is        // what makes the optionals safe.        let encoded = try JSONEncoder().encode(            CottonConfig(containerPath: "/tmp/x", appVersion: "1.0.0", timeZone: "Asia/Kolkata")        )        let sent = try JSONDecoder().decode(JSONValue.self, from: encoded)        guard case .object(let fields) = sent else { return XCTFail("not an object") }        XCTAssertEqual(fields["containerPath"]?.string, "/tmp/x")        XCTAssertEqual(fields["timeZone"]?.string, "Asia/Kolkata")        XCTAssertNil(fields["deviceSecret"], "an unset optional is not sent")        XCTAssertEqual(            Set(fields.keys),            ["flavor", "containerPath", "appVersion", "timeZone"],            "a stray field is a phone that will not open at all"        )        XCTAssertEqual(fields["flavor"]?.string, "dev", "a test process is Cotton Dev")    }    func testTheMacSConfigSaysWhichAppItIsToo() throws {        let encoded = try JSONEncoder().encode(CottonConfig.host(home: "/tmp/home", packaged: false))        let sent = try JSONDecoder().decode(JSONValue.self, from: encoded)        guard case .object(let fields) = sent else { return XCTFail("not an object") }        XCTAssertEqual(fields["flavor"]?.string, AppFlavor.current.rawValue)    }    func testEventsBufferedBeforeSubscribeAreReplayedInOrder() async {        // The stream's own rule: everything buffered before now is replayed        // first, in order. The double keeps it so a screen test can emit before        // the model has attached.        let core = ScriptedCore()        await core.emit(kind: "client", payload: .object(["phase": .string("download")]))        await core.emit(kind: "data", payload: .object(["tables": .array([.string("cotton_todos")])]))        let box = EventCollector()        await core.subscribe { event in box.append(event) }        XCTAssertEqual(box.kinds(), ["client", "data"])    }    func testAClientEventIsReadIntoItsPhaseAndAnUnknownOneIsDropped() {        XCTAssertEqual(            ClientEvent.from(                CottonEvent(                    kind: "client",                    payload: .object([                        "phase": .string("home"),                        "stage": .string("tick"),                    ])                )            ),            .home(stage: "tick")        )        XCTAssertEqual(            ClientEvent.from(                CottonEvent(                    kind: "data",                    payload: .object([                        "tables": .array([.string("cotton_todos")]),                        "origin": .string("pull"),                    ])                )            ),            .data(tables: ["cotton_todos"], origin: "pull")        )        // The core may be one build ahead. An unknown frame has never been a        // reason to stop.        XCTAssertNil(            ClientEvent.from(                CottonEvent(kind: "client", payload: .object(["phase": .string("teleport")]))            )        )        XCTAssertNil(ClientEvent.from(CottonEvent(kind: "tunnel", payload: .null)))    }    // MARK: - The sync loop's own status    private func syncFrame(_ fields: [String: JSONValue]) -> ClientEvent? {        var payload = fields        payload["phase"] = .string("sync")        return ClientEvent.from(CottonEvent(kind: "client", payload: .object(payload)))    }    /// **Every shape the loop publishes decodes**, and each carries its    /// state word through: a pass starting, a pass finishing, a backoff with    /// the crate's reason and its next attempt, a terminal refusal with its    /// sentence, and a stop somebody asked for.    func testEveryShapeTheSyncLoopPublishesIsReadIntoItsStatus() throws {        let syncing = try XCTUnwrap(syncFrame(["state": .string("syncing"), "pending": .number(2)]))        XCTAssertEqual(syncing, .sync(SyncLoopRead(state: "syncing", pending: 2)))        let idle = try XCTUnwrap(            syncFrame([                "state": .string("idle"), "pending": .number(0),                "lastPullAt": .string("2026-09-25T10:00:00.000Z"),                "lastPushAt": .string("2026-09-25T09:59:00.000Z"),                "failures": .number(0),            ])        )        XCTAssertEqual(            idle,            .sync(                SyncLoopRead(                    state: "idle", pending: 0, lastPullAt: "2026-09-25T10:00:00.000Z",                    lastPushAt: "2026-09-25T09:59:00.000Z"                )            )        )        let waiting = try XCTUnwrap(            syncFrame([                "state": .string("waiting"), "pending": .number(3),                "lastError": .string("the server did not answer"),                "nextAttemptAt": .string("2026-09-25T10:00:30.000Z"),                "failures": .number(2),            ])        )        XCTAssertEqual(            waiting,            .sync(                SyncLoopRead(                    state: "waiting", pending: 3, lastError: "the server did not answer",                    failures: 2, nextAttemptAt: "2026-09-25T10:00:30.000Z"                )            )        )        let stopped = try XCTUnwrap(            syncFrame([                "state": .string("stopped"), "pending": .number(1),                "lastError": .string("403 device_revoked"),                "stoppedReason": .string("this phone's access was revoked on that server — pair it again to reconnect"),                "failures": .number(1),            ])        )        XCTAssertEqual(            stopped,            .sync(                SyncLoopRead(                    state: "stopped", pending: 1, lastError: "403 device_revoked", failures: 1,                    stoppedReason: "this phone's access was revoked on that server — pair it again to reconnect"                )            )        )        let byHand = try XCTUnwrap(syncFrame(["state": .string("stopped"), "pending": .number(0)]))        XCTAssertEqual(byHand, .sync(SyncLoopRead(state: "stopped")))    }    /// The MEDIA DRAIN's status is a phase-less frame with the same two keys    /// and overlapping state words. It is not a sync status, and it is not a    /// cycle either — it carries no `pushed` — so it is dropped, as it always    /// was. A tagged frame with no state word is dropped too: "idle" painted    /// over a frame that said nothing would be the silent wrong answer.    func testAPhaselessStatusAndATaggedFrameWithNoStateAreBothDropped() {        XCTAssertNil(            ClientEvent.from(                CottonEvent(                    kind: "client",                    payload: .object(["state": .string("idle"), "pending": .number(0), "synced": .number(4)])                )            )        )        XCTAssertNil(syncFrame(["pending": .number(2)]))        XCTAssertNil(syncFrame(["state": .string(""), "pending": .number(2)]))    }    /// The cold read carries the same object under `loop`, and `null` there    /// is "no loop is running" — decoded as absent, never as idle.    func testTheStatusReadCarriesTheLoopOrNone() throws {        let running = try JSONDecoder().decode(            SyncStatusRead.self,            from: Data(                #"{"connected":true,"pending":2,"canReachServer":true,"loop":{"state":"waiting","pending":2,"lastError":"no route","nextAttemptAt":"2026-09-25T10:00:30.000Z","failures":3,"lastPullAt":"2026-09-25T09:00:00.000Z"}}"#                    .utf8            )        )        XCTAssertEqual(            running.loop,            SyncLoopRead(                state: "waiting", pending: 2, lastPullAt: "2026-09-25T09:00:00.000Z", lastError: "no route",                failures: 3, nextAttemptAt: "2026-09-25T10:00:30.000Z"            )        )        let none = try JSONDecoder().decode(            SyncStatusRead.self,            from: Data(#"{"connected":true,"pending":0,"canReachServer":true,"loop":null}"#.utf8)        )        XCTAssertNil(none.loop)        let absent = try JSONDecoder().decode(            SyncStatusRead.self,            from: Data(#"{"connected":true,"pending":0,"canReachServer":true}"#.utf8)        )        XCTAssertNil(absent.loop)    }}/// A thread-safe sink, because the real stream delivers from any thread.final class EventCollector: @unchecked Sendable {    private let lock = NSLock()    private var events: [CottonEvent] = []    func append(_ event: CottonEvent) {        lock.lock()        defer { lock.unlock() }        events.append(event)    }    func kinds() -> [String] {        lock.lock()        defer { lock.unlock() }        return events.map(\.kind)    }    func all() -> [CottonEvent] {        lock.lock()        defer { lock.unlock() }        return events    }}#if canImport(CottonFFI)    /// A call hops off the cooperative pool onto a queue, and the hop keeps    /// the awaiting task's priority: a screen's read at the queue's default    /// class sat behind every other process on a busy Mac (lane I5).    final class CoreHandlePriorityTests: XCTestCase {        func testACallRunsAtTheAwaitingTasksPriority() {            XCTAssertEqual(CoreHandle.qos(for: .userInteractive).qosClass, .userInteractive)            XCTAssertEqual(CoreHandle.qos(for: .userInitiated).qosClass, .userInitiated)            XCTAssertEqual(CoreHandle.qos(for: .high).qosClass, .userInitiated)            XCTAssertEqual(CoreHandle.qos(for: .medium).qosClass, .default)            XCTAssertEqual(CoreHandle.qos(for: .utility).qosClass, .utility)            XCTAssertEqual(CoreHandle.qos(for: .low).qosClass, .utility)            XCTAssertEqual(CoreHandle.qos(for: .background).qosClass, .background)        }    }#endif