Cotton code
411 lines · 18.5 KB · SwiftRaw
// The machines the server admits, and the pairings waiting — as Home's device// line, the Mac's sidebar and the settings sheet's Devices row read them, and// the approve and decline Home's waiting line offers.//// The Devices list and a device's page are the device TABLE's now// (`Sources/native Device records.swift`, drawn by the list and the page);// this model keeps the reads and the two verbs the screens that are not that// table still need.//// **The digits are SHOWN here, never typed**, and that is the change. They used// to be a secret the approver typed off the joining device's screen, so a// pending row carrying them would have handed the second factor to whoever// could read the list. They are not a secret any more: the server derives them// from the joining key and the pairing id and gives the same six to everybody// with a right to the question — the joining screen, this list, the push.// Knowing them proves nothing; SEEING THE SAME ONES is the whole of the second// factor, and a row that withheld the number would leave the screen with// nothing to ask ("Does it show 482 913?").//// So `phone/devices.rs::pending_row` PROJECTS exactly `pairingId, name,// platform, appVersion, createdAt, expiresAt, digits` — explicitly, never by// spreading — and what is still absent is the joining device's KEY, because the// digits are a pure function of it and the pairing id.//// The digits travel UP again in [`ApprovePendingRequest`], as an ECHO of the// row: not a proof of who is asking (the signature is that) but a proof of// WHICH request the person was looking at. A queue that moved between the draw// and the tap refuses rather than admitting the wrong device.//// ## The three rules this model exists to keep//// **The rows are the FILE's, and they are drawn first.** `cotton_devices` is// a synced table, so every device admitted to this database is on this// phone already; `read.devices` answers it with no round trip and the list// is on screen before any Mac is asked anything. The old `devices.list` over// HTTP — three tries, a backoff, a skeleton until the server answered — is// gone (2026-09-25): a screen about "who may open this database" that itself// needed the server open was a skeleton on every train. What the file does// not carry is `lastSeenAt` and `serving`, and `DeviceStatus` says what a// row reads without them. A local read that fails is still a sentence and// never a skeleton (`listError`), because a skeleton must have an end.//// **Pending is polled every five seconds while the screen is FOCUSED, and not// at all while it is away** (`PENDING_POLL_MS`, `pendingPollInterval`). Here// that is a `.task` tied to the screen's lifetime: SwiftUI cancels it on// disappear, so there is no timer that outlives the screen. It is the ONE// network read left here, and it never blocks the rows: `load()` reads the// file first and asks the serving Mac after.//// **Every landed verb re-reads BOTH lists** — `useInvalidateDevices` invalidates// the approved list and the pending list together, because approving a pending// pairing moves a row from one to the other.import CottonKitimport Foundation@MainActor@Observablepublic final class DevicesModel {    /// How often the pending list is re-read while the screen is up —    /// `PENDING_POLL_MS = 5000`, in seconds.    public static let pendingPollSeconds: TimeInterval = 5    // ── What the screen draws ────────────────────────────────────────────    private(set) var devices: [ApprovedDevice] = []    /// The id the server admits THIS device by (`read.devices`' `thisDevice`,    /// off the identity the transport signs with). It was once compared    /// against the device key's own public half; the crate answers it beside    /// the list, so the row is marked from the same answer it was drawn from.    public private(set) var thisDeviceId: String?    /// The pairings waiting, as the crate answered them — read in place. Six    /// fields, no sorting and no arithmetic, so there is nothing for a type to    /// hold that a key does not say better.    public private(set) var pending: [JSONValue] = []    /// The list has never answered yet — the skeleton's condition    /// (`devicesLoading`).    public private(set) var isFirstRead = true    /// What the last list read threw, or `nil` when it answered.    public private(set) var listError: (any Error)?    /// Which pending row is deciding — its two buttons are inert while it is.    public private(set) var busyPairing: String?    private let core: any CottonCalling    private let toasts: ToastCenter    public init(core: any CottonCalling, toasts: ToastCenter) {        self.core = core        self.toasts = toasts    }    // ── Reading ──────────────────────────────────────────────────────────    /// The rows, then the queue — in that order, always: the file answers    /// at once and the serving Mac may not answer at all.    public func load() async {        await loadDevices()        await loadPending()    }    /// The approved list, off the file. One read, no retry: a local read    /// that fails is a file this device cannot read, and asking it again in    /// a second is not what fixes that.    public func loadDevices() async {        do {            let answer = try await core.callJSON(CottonMethod.readDevices)            devices = answer.list("devices").map(ApprovedDevice.init)            thisDeviceId = answer.text("thisDevice")            listError = nil        } catch {            // No toast: the sentence is drawn in the card alone, and the            // screen's one toast belongs to the four MUTATION flows that call            // `DevicesModel.say(_:)`. The rows already in hand are kept —            // a list this device read a minute ago is still the file's.            listError = error        }        isFirstRead = false    }    /// The pairings waiting on this phone's answer.    ///    /// It has no failure surface of its own and must not grow one: the screen    /// draws no card at all when the list is empty, so a poll that could not    /// reach the server leaves the last answer on screen and says nothing.    public func loadPending() async {        guard let answer = try? await core.callJSON(CottonMethod.devicesPending) else { return }        pending = answer.list("pending")    }    // ── What the screen reads off the lists ──────────────────────────────    /// Live rows first, then removed ones — `[...live, ...removed]` — and ONE    /// row per device key.    ///    /// A key re-approved after a removal holds its removed approval beside the    /// live one (store version 41: a row per approval). The device is the key,    /// so the list draws it once, as it stands today: its live row if it has    /// one, else its newest removed row (the answer is newest approval first).    var ordered: [ApprovedDevice] {        let live = devices.filter { !$0.isRevoked }        let liveKeys = Set(live.map(\.deviceId))        var seen = Set<String>()        return (live + devices.filter { $0.isRevoked && !liveKeys.contains($0.deviceId) })            .filter { seen.insert($0.deviceId).inserted }    }    /// The approved devices as Home's device line and the Mac's sidebar    /// status line need them — live rows first, removed after.    ///    /// **`lastSeenAt` and `serving` are `nil` off the file**, and the two    /// stamps the file DOES carry go in their place: the Mac's own reading    /// (`reportedAt`) and the approval (`approvedAt`). `DeviceStatus` states    /// what each reads as. Which Mac holds the relay line is the election,    /// in the runtime of the Mac answering, and no column of the file.    public var deviceLines: [DeviceLine] {        ordered.map { device in            DeviceLine(                id: device.deviceId,                name: device.name,                platform: device.platform,                appVersion: device.appVersion,                lastSeenAt: device.lastSeenAt,                reportedAt: device.reportedAt,                approvedAt: device.approvedAt,                revokedAt: device.revokedAt,                isThisDevice: isThisPhone(device),                serving: device.serving            )        }    }    /// The sentence the devices card says when the FILE could not be read.    ///    /// A server's refusal of this phone is no longer here: the rows are the    /// file's and stay readable whatever the server said, and the refusal is    /// the banner over the whole app (`BootModel.readOnly`). Two sentences    /// about one refusal, one of them hiding rows the phone holds, was the    /// wall this screen used to be.    public var refusalSentence: String? {        DeviceRefusalWords.cardSentence(error: listError)    }    /// Whether the card draws that sentence INSTEAD of whatever it is holding.    ///    /// A local read that fails is a file this device cannot read right now,    /// and rows drawn over it would be rows nobody can vouch for.    public var showsRefusal: Bool {        refusalSentence != nil    }    /// The row the crate called this device.    func isThisPhone(_ device: ApprovedDevice) -> Bool {        guard let thisDeviceId, !thisDeviceId.isEmpty else { return false }        return device.deviceId == thisDeviceId    }    // ── The verbs ────────────────────────────────────────────────────────    /// Approve a pending pairing, echoing the digits the ROW showed.    ///    /// **The echo is the row's own, and a row with no number cannot be    /// approved from here.** The person compared the six on this screen with    /// the six on the device in front of them; sending them back is how the    /// server checks that the queue did not move between the draw and the tap.    /// A `digits` this screen could not have drawn would be a screen that lost    /// track of which request it was showing, so it refuses rather than    /// guessing — a server that predates the digits answers `null`, and there    /// is no question to put.    public func approvePending(_ pairing: JSONValue) async {        let pairingId = pairing.text("pairingId") ?? ""        guard let digits = pairing.text("digits"), !digits.isEmpty else {            toasts.show(DeviceRefusalWords.noDigits, tone: .error)            return        }        await decide(pairingId) {            try await self.core.approvePairing(pairingId, digits: digits)            self.toasts.show(                ShellLines.line("devices", "is_approved", ["name": "\(pairing.text("name") ?? "")"]),                tone: .success            )        }    }    /// Decline a pending pairing. It says nothing on success — the row simply    /// goes.    public func declinePending(_ pairing: JSONValue) async {        let pairingId = pairing.text("pairingId") ?? ""        await decide(pairingId) {            try await self.core.declinePairing(pairingId)        }    }    private func decide(_ pairingId: String, _ act: @escaping () async throws -> Void) async {        busyPairing = pairingId        do {            try await act()            // The queue moved on the server; the approved row reaches this            // phone by the next pull, and the rows are read again then            // (the `.devices` family). Both are asked now so a decision            // never leaves a stale card on screen.            await loadDevices()            await loadPending()        } catch {            say(error)        }        busyPairing = nil    }    private func say(_ error: any Error) {        toasts.show(DeviceRefusalWords.toastSentence(for: error), tone: .error)    }}// MARK: - One approved device/// One row of `read.devices`, BUILT from the answer rather than decoded.////// **A kept type, and the reason is the work.** The list sorts (live rows/// first, removed after), names who approved or removed each row by looking the/// actor's id up in the list ITSELF (`DeviceWords.actor`), and marks the row/// the crate called this device — passes over the same fields in a model and/// a pure-words helper that tests build directly. Spelling `text("deviceId")`/// at each of those comparisons would put the identity the device list's/// security rests on into a string literal, again and again.////// The keys are `list_devices`' (`cotton-tools/src/mcp/handlers/devices.rs`),/// a missing column as `null`, and every line of the init is an accessor/// call, so the key sweep sees each one. `lastSeenAt` and `serving` are read/// too: the tool does not write them — they are the registry's and the/// election's, neither of which is in the file — so both are `nil` off this/// read, and `DeviceStatus` says what a row reads without them. They stay on/// the type because the Mac's in-process `devices.list` answers the same/// shape WITH them, and one row type is one set of comparisons.////// `deviceId` and `name` are read UNTRIMMED: the id goes straight back out in a/// request body and the name is seeded into the rename field, so trimming/// either would quietly rewrite what the person stored. The rest are read with/// `text(_:)`, where a blank column and an absent one mean the same thing to/// every reader below.struct ApprovedDevice: Equatable, Sendable {    var deviceId: String    var name: String    var platform: String?    var appVersion: String?    var approvedAt: String?    /// Another device's id, or `"self"` for the root row the server wrote at    /// boot.    var approvedBy: String?    /// The registry's stamp. `nil` off the file — see the type's header.    var lastSeenAt: String?    /// The Mac's own reading about itself (`sampledAt`), written every    /// fifteen minutes by its session host and synced — the one "recently    /// up" stamp the file carries.    var reportedAt: String?    /// Whether this device is the Mac answering for the database right now —    /// the server's own runtime fact, not a column of the row. `nil` off the    /// file, and on a Mac the answering server cannot speak for. See    /// `DeviceStatus`.    var serving: Bool?    var revokedAt: String?    var revokedBy: String?    /// B5: `"restored"` when the Mac rewrote itself from a backup and retired    /// this row.    var revokedReason: String?    /// B5: when this Mac last showed its recovery key.    var recoveryKeyShownAt: String?    init(_ json: JSONValue) {        deviceId = json.untrimmed("deviceId") ?? ""        name = json.untrimmed("name") ?? ""        platform = json.text("platform")        appVersion = json.text("appVersion")        approvedAt = json.text("approvedAt")        approvedBy = json.text("approvedBy")        lastSeenAt = json.text("lastSeenAt")        reportedAt = json.text("sampledAt")        serving = json.maybeFlag("serving")        revokedAt = json.text("revokedAt")        revokedBy = json.text("revokedBy")        revokedReason = json.text("revokedReason")        recoveryKeyShownAt = json.text("recoveryKeyShownAt")    }    /// For a test that wants one row and not a tree. Every argument is    /// defaulted, because the answer defaults every column but two.    init(        deviceId: String = "",        name: String = "",        platform: String? = nil,        appVersion: String? = nil,        approvedAt: String? = nil,        approvedBy: String? = nil,        lastSeenAt: String? = nil,        reportedAt: String? = nil,        serving: Bool? = nil,        revokedAt: String? = nil,        revokedBy: String? = nil,        revokedReason: String? = nil,        recoveryKeyShownAt: String? = nil    ) {        self.deviceId = deviceId        self.name = name        self.platform = platform        self.appVersion = appVersion        self.approvedAt = approvedAt        self.approvedBy = approvedBy        self.lastSeenAt = lastSeenAt        self.reportedAt = reportedAt        self.serving = serving        self.revokedAt = revokedAt        self.revokedBy = revokedBy        self.revokedReason = revokedReason        self.recoveryKeyShownAt = recoveryKeyShownAt    }    /// A row the person removed, or the Mac retired when it restored itself.    var isRevoked: Bool { revokedAt != nil }}// MARK: - The one approve and the one decline/// Approving and declining a waiting device, said once for every place that/// asks: Home's waiting line (`DevicesModel`), the join request a notification/// opens (`JoinRequestModel`) and the device table's page actions/// (`native Device records`). Each caller decides WHICH digits to echo — always/// the ones its own row showed — and says the refusal in its own place.extension CottonCalling {    /// `devices.approvePending`, echoing the six digits the person saw.    /// Answers the core's answer, whose `device.deviceId` is the device let in.    @discardableResult    func approvePairing(_ pairingId: String, digits: String) async throws -> JSONValue {        try await callJSON(CottonMethod.devicesApprovePending, ApprovePendingRequest(pairingId: pairingId, digits: digits))    }    /// `devices.declinePending`: not let in; it can ask again.    /// Answers the act's receipt ("Turned away …"); there is no undo.    @discardableResult    func declinePairing(_ pairingId: String) async throws -> ActAnswer {        try await pageAct(CottonMethod.devicesDeclinePending, DeclinePendingRequest(pairingId: pairingId))    }}// MARK: - What the five `devices.*` verbs are sent/// `devices.approvePending` — `{pairingId, digits}`.////// Six ASCII numerals, ECHOED off the row; the crate checks the grammar again/// below the boundary (`phone/devices.rs::digits`) as an echo guard, so a/// screen that lost track of which request it was showing is a refusal rather/// than a round trip.struct ApprovePendingRequest: Encodable, Sendable {    var pairingId: String    var digits: String    init(pairingId: String, digits: String) {        self.pairingId = pairingId        self.digits = digits    }}/// `devices.declinePending` — `{pairingId}`. The BODY the crate then posts is/// an empty object, not an absent one; that is its business, not this app's.struct DeclinePendingRequest: Encodable, Sendable {    var pairingId: String    init(pairingId: String) {        self.pairingId = pairingId    }}