Cotton code
424 lines · 19.0 KB · SwiftRaw
// **A typed or spoken sentence becomes a thought with the network off.**//// The lane's headline "Done when", exercised end to end — and the one case in// this target that assembles the REAL objects rather than a double of them:// a real ``DockModel`` over a real ``CaptureService`` over a real// ``PendingLinks`` over the real ``CorePendingLinkWriter``. `DockModelTests`// and `ComposerTests` both stop at ``CaptureSending`` (their `RecordingCapture`// stands in for the whole write), so nothing until now had ever run the// composer's words through the service that writes them, the intent list that// remembers their chips, and the writer that later applies them. The only// object replaced here is the one below the boundary: `CottonCalling`.//// ── Why the crate itself is not driven, and what that costs ──────────────────//// **`capture.create` is not answered by any build in this checkout.** The// dispatch in `crates/cotton-ffi/src/methods.rs` has// `write`, `export.build`, the `read.` prefix and the host-only arms — and no// capture arm at all; `CottonMethod.captureCreate`'s own doc calls it one of// "the two methods 4p landed beside them", and that lane has not landed. The// XCFramework in `.ffi/` confirms it: neither `capture.create` nor `read.home`// is in the archive. So a real-crate capture write would answer// `unknown_method` today, and a test asserting THAT would pin a gap rather// than the behaviour, and go red the day the gap closes.//// What that leaves uncovered is exactly one seam: the JSON `capture.create`// sends crossing into Rust and a row landing in the file. Everything above it —// the trim, the chips, the plan, the clear-before-the-write, the rollback, the// intent remembered against the row that landed, the drain that applies it when// the record finally exists — is the real code here. When `phone/capture.rs`// lands, the one thing owed to this file is a sibling case that opens a real// core over a temporary container and sends one sentence through it.//// ── What "the network is off" means on this path ────────────────────────────//// It does NOT mean the write fails. **A capture is a LOCAL write and it is// finished** (`CaptureService`'s own header): the row lands in the file on this// phone, and the server's routing worker files it when the op eventually gets// there. So the offline story is three facts, and each has a case below:////   1. the local write happens and NOTHING on the send path asks the network,//   2. a dictated sentence takes that same local path and asks the network//      NOTHING at all — the transcript is the thought, and there is no polish//      call to fail because there is no polish,//   3. the capture is never ROUTED while the phone is alone, so the chips have//      no record to land on and must WAIT rather than be dropped.//// The core double distinguishes a dead transport from a refusal on purpose:// only a `CottonCallError` means the core deliberated, and `PendingLinks` drops// an intent for one and keeps it for the other.import CottonKitimport Foundationimport XCTest@testable import CottonUI// MARK: - The phone, alone/// A core with the network taken away.////// `ScriptedCore` cannot express this: every answer it gives is an envelope, so/// it can refuse but it cannot be UNREACHABLE, which is what a phone with no/// signal actually is.private actor OfflineCore: CottonCalling {    /// What this phone can reach for one method.    enum Reach: Sendable {        /// Answered off the file on this phone — the `data` half of the        /// envelope. No network was involved and none could have been.        case local(String)        /// The transport is dead. Deliberately NOT a ``CottonCallError``: the        /// core never deliberated, and that difference is what decides whether        /// a waiting chip is kept or let go.        case unreachable    }    /// A transport that did not carry the question. Any error type but    /// `CottonCallError` says so.    struct NoSignal: Error {}    struct Asked: Sendable, Equatable {        let method: String        let requestJSON: String    }    private let reach: [String: Reach]    private var log: [Asked] = []    init(_ reach: [String: Reach]) { self.reach = reach }    func callRaw(_ method: String, requestJSON: String) async throws -> String {        log.append(Asked(method: method, requestJSON: requestJSON))        switch reach[method] ?? .unreachable {        case .local(let json):            return #"{"ok":true,"data":\#(json)}"#        case .unreachable:            throw NoSignal()        }    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) {}    func close() {}    // ── What a case asks it ───────────────────────────────────────────────    func methodsAsked() -> [String] { log.map(\.method) }    func requests(_ method: String) -> [String] {        log.filter { $0.method == method }.map(\.requestJSON)    }}/// The intent list, in memory — no `UserDefaults`, no app group.private final class MemoryIntentStore: PendingLinkStore, @unchecked Sendable {    private let lock = NSLock()    private var map: [String: Data] = [:]    func data(_ key: String) -> Data? { lock.withLock { map[key] } }    func set(_ key: String, _ value: Data?) {        lock.withLock {            if let value {                map[key] = value            } else {                map.removeValue(forKey: key)            }        }    }    /// Whether this device is holding anything at all. The SHAPE of what it    /// holds is `PendingLinksTests`' business; what matters here is only that    /// a chip was not thrown away.    var holdsSomething: Bool { lock.withLock { !map.isEmpty } }}/// The three facts the drain cannot read for itself — with the server that/// would have answered the first one switched off.private actor ScriptedFiling: PendingLinkSource {    private var answer: FiledCapture?    private let slugs: [String: String]    init(slugs: [String: String]) { self.slugs = slugs }    func filed(_ inboxItemId: String) async -> FiledCapture? { answer }    func ownPerson(ofPersonNote recordId: String) async -> OwnPerson { .known("per-owner") }    func projectSlug(_ projectId: String) async -> String? { slugs[projectId] }    /// The op reached the server, the router filed it, and sync brought the    /// records back. Everything before this call is the phone on its own.    func theRouterFiled(_ records: [RoutedRecord]) {        answer = FiledCapture(routedRecords: records)    }}// MARK: - The cases@MainActorfinal class CaptureOfflineTests: XCTestCase {    private var recogniser = FakeRecogniser()    private var haptics = RecordingHaptics()    private var toasts = ToastCenter(scheduler: ManualToastScheduler())    override func setUp() async throws {        recogniser = FakeRecogniser()        haptics = RecordingHaptics()        toasts = ToastCenter(scheduler: ManualToastScheduler())    }    /// The whole capture path, assembled as the app assembles it.    private struct Kit {        let core: OfflineCore        let store: MemoryIntentStore        let filing: ScriptedFiling        let links: PendingLinks        let model: DockModel        let troubles: Collected<PendingLinkTrouble>        /// Every capture the dock reported as landed.        let landed: Collected<String>    }    /// `capture.create` and `write` are answered off this phone's own file;    /// everything else is unreachable, which is what a phone with no signal    /// answers for every method there is.    private static let alone: [String: OfflineCore.Reach] = [        CottonMethod.captureCreate: .local(#"{"id":"itm-1"}"#),        CottonMethod.write: .local(#"{"rail":"client"}"#),    ]    private func kit(        place: DockPlace = .page,        reach: [String: OfflineCore.Reach] = CaptureOfflineTests.alone    ) -> Kit {        let core = OfflineCore(reach)        let store = MemoryIntentStore()        let filing = ScriptedFiling(slugs: ["pr-meri": "meri"])        let troubles = Collected<PendingLinkTrouble>()        let links = PendingLinks(            userId: "u-owner",            workspaceId: "ws-file",            store: store,            source: filing,            writer: CorePendingLinkWriter(core: core),            // A fixed clock: the expiry is a week and a wall clock would make            // this suite's answer depend on the day it runs.            now: { Date(timeIntervalSince1970: 1_785_542_400) },            report: { troubles.append($0) }        )        let dictation = DictationModel(            recogniser: recogniser,            levels: recogniser,            timings: DictationModel.Timings(                stopGuard: .milliseconds(200),                cancelGuard: .milliseconds(150),                tick: .milliseconds(5)            )        )        let words = DockVocabulary()        words.supply(            projects: [VocabularyProject(id: "pr-meri", name: "Meri", status: "active")],            people: [VocabularyPerson(id: "per-ravi", name: "Ravi Kumar")]        )        let landed = Collected<String>()        let model = DockModel(            place: place,            captures: CaptureService(core: core, links: links),            media: CoreMediaCapture(core: core),            dictation: dictation,            vocabulary: words,            haptics: haptics,            toasts: toasts        )        model.onCaptured = { landed.append($0.text("id") ?? "") }        return Kit(            core: core,            store: store,            filing: filing,            links: links,            model: model,            troubles: troubles,            landed: landed        )    }    private let meri = SigilCandidate(id: "pr-meri", name: "Meri")    private let ravi = SigilCandidate(id: "per-ravi", name: "Ravi Kumar")    // MARK: - A typed sentence, with nothing to send it to    func testATypedSentenceBecomesAThoughtWithTheNetworkOff() async {        let kit = kit()        kit.model.fieldEdited("  order the seed trays  ")        await kit.model.send()        // The row landed, on this phone, with no signal at all.        XCTAssertEqual(kit.landed.values, ["itm-1"])        XCTAssertNil(toasts.current, "a capture that landed says nothing")        XCTAssertEqual(kit.model.text, "", "the pill is ready for the next thought")        // **The whole point.** ONE method crossed the boundary, and it is the        // local write. No `capture.route` on send — the commit POST once raced        // the routing worker and the worker's win discarded the plan the person        // had approved on screen — and no sync pass either: a send that asked        // the network for anything would be a send that could fail on a plane.        let asked = await kit.core.methodsAsked()        XCTAssertEqual(asked, [CottonMethod.captureCreate])        // The words that crossed are the trimmed ones, and no plan rode along.        let sent = await kit.core.requests(CottonMethod.captureCreate).first ?? ""        XCTAssertTrue(sent.contains(#""text":"order the seed trays""#), "sent: \(sent)")        XCTAssertFalse(sent.contains(#""plan""#), "an unplanned capture sends no plan")    }    // MARK: - A spoken one takes the same path    func testASpokenSentenceTakesTheSameLocalPathAndTheRawWordsStand() async {        let kit = kit()        await kit.model.startDictation()        recogniser.emit(.started)        recogniser.speak("call the cold chain vendor")        recogniser.whenStopped = { [recogniser = self.recogniser] in            recogniser.emit(.segment("call the cold chain vendor"))            recogniser.emit(.ended)        }        await kit.model.finishDictation()        // The merge fed the SAME field the thumb writes to, which is why send        // needs no second path for a spoken thought.        XCTAssertEqual(kit.model.text, "call the cold chain vendor")        XCTAssertTrue(kit.model.canSend)        // NOTHING on this path asks the network for the words: the transcript        // is the thought, and no server is consulted about it.        let asked = await kit.core.methodsAsked()        XCTAssertTrue(asked.isEmpty, "asked: \(asked)")        XCTAssertNil(toasts.current)        await kit.model.send()        XCTAssertEqual(kit.landed.values, ["itm-1"])        // ONE method over the whole life of a spoken thought, and it is the        // local write. Nothing on this path waits on a server, because nothing        // on this path asks one anything.        let whole = await kit.core.methodsAsked()        XCTAssertEqual(whole, [CottonMethod.captureCreate])        let sent = await kit.core.requests(CottonMethod.captureCreate).first ?? ""        XCTAssertTrue(sent.contains(#""text":"call the cold chain vendor""#), "sent: \(sent)")        // A dictated capture is words, not bytes: the recording key is the        // voice-note path's, and this one never had one.        XCTAssertFalse(sent.contains(#""audioKey""#))    }    // MARK: - The chips wait rather than vanish    func testTheChipsAPersonTypedWaitAsIntentsUntilThereIsARecordToPutThemOn() async {        let kit = kit()        kit.model.fieldEdited("#mer")        kit.model.pick(meri)        kit.model.fieldEdited("@rav")        kit.model.pick(ravi)        kit.model.fieldEdited("split the seed order")        XCTAssertEqual(kit.model.attachedChips.map(\.recordId), ["pr-meri", "per-ravi"])        await kit.model.send()        // The projects ride the capture row, where the server's filer can see        // them; the people do NOT, because a person edge hangs on the routed        // record and there is no row that argument could write.        let sent = await kit.core.requests(CottonMethod.captureCreate).first ?? ""        XCTAssertTrue(sent.contains(#""projectIds":["pr-meri"]"#), "sent: \(sent)")        XCTAssertFalse(sent.contains("per-ravi"), "a person id is not part of `capture.create`")        // ── The phone is alone, so the router has filed nothing ────────────        //        // Filing happens on the SERVER, minutes later. Until the op gets there        // the capture has become nothing, so there is no record to link and the        // only correct answer is to wait.        let waited = await kit.links.drain()        XCTAssertEqual(waited, 0, "nothing was routed, so nothing could settle")        let writesWhileAlone = await kit.core.requests(CottonMethod.write)        XCTAssertTrue(writesWhileAlone.isEmpty, "a drain with no record writes nothing")        XCTAssertTrue(kit.store.holdsSomething, "the chips are still held")        // ── The op reached the server and the records came back ────────────        await kit.filing.theRouterFiled([RoutedRecord(kind: "todo", id: "td-1")])        _ = await kit.links.drain()        let writes = await kit.core.requests(CottonMethod.write)        // The THOUGHT keeps its own membership whatever the capture became —        // through `update_thought`, the thought kind's own verb, which is the        // one that stamps a person's hand rather than an agent's.        XCTAssertTrue(            writes.contains { $0.contains("update_thought") && $0.contains(#""id":"itm-1""#) },            "the thought's own membership was never written: \(writes)"        )        // …and the record the capture became gets the same chip.        XCTAssertTrue(            writes.contains { $0.contains("link_to_project") && $0.contains(#""id":"td-1""#) },            "the routed record's membership was never written: \(writes)"        )        // The chip was resolved to the slug both writers demand, not sent as an        // id: the tools resolve `project` by slug and only accept an active one.        XCTAssertTrue(            writes.allSatisfy { $0.contains(#""project":"meri""#) },            "a project link went out under something other than its slug: \(writes)"        )    }    func testAPersonChipIsKeptRatherThanDroppedWhileNothingCanWriteAPersonEdge() async {        // No tool in `cotton-tools`' catalogue CREATES a `cotton_links` row, so        // `CorePendingLinkWriter.linkPerson` throws by declaration. What this        // pins is the CONSEQUENCE the gap was designed to have: the `@` chip        // waits in storage instead of vanishing, and every later drain tries        // again. A chip lost quietly is the one outcome that file exists to        // prevent — so this case fails loudly if a future writer ever starts        // swallowing that refusal.        let kit = kit()        kit.model.fieldEdited("@rav")        kit.model.pick(ravi)        kit.model.fieldEdited("ask about the quote")        await kit.model.send()        await kit.filing.theRouterFiled([RoutedRecord(kind: "note", id: "nt-1")])        let settled = await kit.links.drain()        XCTAssertEqual(settled, 0, "an intent whose person edge did not land is not settled")        XCTAssertFalse(kit.troubles.values.isEmpty, "the gap was swallowed rather than reported")        XCTAssertTrue(kit.store.holdsSomething, "the chip is still waiting")        // The proof that it was KEPT and not merely still on disk: a second        // drain finds it and tries the write again.        let troublesAfterFirst = kit.troubles.values.count        _ = await kit.links.drain()        XCTAssertGreaterThan(            kit.troubles.values.count, troublesAfterFirst,            "the second drain found no intent — the chip was dropped"        )    }    // MARK: - The one failure that must lose nothing    func testACaptureTheBoundaryNeverAnsweredGivesTheWordsBackAndRemembersNoChip() async {        // The local write is the one step on this path that must not fail. When        // it does, the two halves have to agree: the composer keeps the words,        // and the intent list remembers nothing — a capture that did not land        // has no id to hang a chip on, and inventing one would leave a chip        // waiting a week for a record that was never going to exist.        let kit = kit(reach: [CottonMethod.write: .local(#"{"rail":"client"}"#)])        kit.model.fieldEdited("#mer")        kit.model.pick(meri)        kit.model.fieldEdited("pay the seed bill")        await kit.model.send()        XCTAssertEqual(toasts.current?.tone, .error)        XCTAssertNotNil(toasts.current, "the failure is said")        XCTAssertEqual(kit.model.text, "pay the seed bill", "a thought must not vanish")        XCTAssertEqual(kit.model.attachedChips.map(\.recordId), ["pr-meri"], "nor its chip")        XCTAssertEqual(kit.landed.values, [], "nothing landed, so nothing re-reads")        XCTAssertFalse(kit.store.holdsSomething, "an intent was remembered for a row that never was")        let settled = await kit.links.drain()        XCTAssertEqual(settled, 0)        let writes = await kit.core.requests(CottonMethod.write)        XCTAssertTrue(writes.isEmpty, "a capture that never landed wrote a link")    }}