Cotton code
611 lines · 24.7 KB · SwiftRaw
// THE UNLOCK WINDOW'S CARD (12 Nov 2026): an// assistant asked over MCP to read sealed tables for a while, and this phone// answers. Everything here is drawn from what the core answers:////   * `unlock.card` — the oldest waiting request as the `unlock.card` face//     draws it (`card.fields`, every word the core's `unlock` lines), the//     acts as the face definition names them, and `pollSeconds` while one//     waits. The core answers a card only in an app whose kit carries the//     request table (Keys, Cotton), so this file decides no placement: a//     card answered is a card shown, over whatever the window is on.//   * *Allow* reads this device's vault key behind presence exactly as//     `vault.unlock` does (`VaultAccess.handing`) and hands it to//     `unlock.allow` with the tables switched on; *Not now* is//     `unlock.decline`.//   * While an Allow is held (this device's vault founding on that very//     Allow) the core answers the card with `status`, its setting-up line,//     and no acts: the line is drawn where the acts stand, and the window//     opens by itself when the core completes the Allow after the pass.//   * The card is modal to a tree reader: what is under it leaves the tree//     (`RootView`), and VoiceOver lands on the card's title when it rises.//   * `unlock.windows` — the windows open now, each with its words and//     *End now* (`unlock.end`): read here for the receipts, drawn only in//     Account's Open access card, never as a banner over the window.//   * THE WINDOW'S LENGTH IS THE PERSON'S (e2e rulings//     R4): the card's `durations` (15 minutes, 1 hour, 1 day,//     Until I turn it off, the assistant's suggestion on) stand as one row//     of choices in the acts strip under the card, and the chosen one is the//     `minutes` Allow sends (0 for until turned off) and the length the//     card's own stamp says. No new face: the row is the shell's buttons.//// The card is read at launch, at every foreground and after every sync pass,// and again every `pollSeconds` while it stands (the core's own pass already// syncs that often while a request waits).import CottonFacesimport CottonKitimport CottonPaperimport CottonValuesimport SwiftUI/// One act as the face definition names it (`card.acts`, a window's `acts`).struct UnlockAct: Equatable, Sendable {    let id: String    let label: String    let receipt: String    init?(_ value: RecordValue) {        guard case .object(let act) = value, let id = act["id"]?.text, let label = act["label"]?.text else { return nil }        self.id = id        self.label = label        receipt = act["receipt"]?.text ?? label    }}/// One open window's row.struct UnlockWindowRow: Equatable, Sendable, Identifiable {    let grantId: String    let said: String    /// Which assistant holds it, as the core names it.    var client: String? = nil    /// Open until the person turns it off.    var standing = false    var id: String { grantId }}/// One length the person may choose (`card.durations`).struct UnlockDuration: Equatable, Sendable {    let minutes: Int    let label: String}/// `unlock.card`'s answer.struct UnlockCardAnswer: Decodable, Sendable {    let card: RecordValue?    let pollSeconds: Double?}/// `unlock.windows`' answer.struct UnlockWindowsAnswer: Decodable, Sendable {    let windows: [RecordValue]    let acts: [RecordValue]}/// `unlock.allow`'s request: flat, the vault key a call parameter only. `everything` or `groups` is the choice made/// on the card in an app's own sheet (shared/DECISIONS.md "Your Claude asks"); the core turns it into the tables, and/// groups win over `tables`, which the paper and Vault's card still send.struct UnlockAllowRequest: Encodable, Sendable {    let requestId: String    let tables: [String]    var everything: Bool? = nil    var groups: [String]? = nil    let minutes: Int    let privateKey: String}/// The card's plain words (`card.ask`): who asks, what it can read, for how long, where to change it. Every word is/// the core's; no table is named.struct UnlockAskWords: Equatable, Sendable {    struct Choice: Equatable, Sendable { let label: String; var line: String? }    struct Group: Equatable, Sendable, Identifiable { let id: String; let label: String; var line: String? }    var who: String?    var what: String?    var everything: Choice?    var choose: Choice?    var groups: [Group] = []    var howLong: String?    var howLongLine: String?    var settings: String?    init?(_ value: RecordValue?) {        guard case .object(let ask)? = value else { return nil }        func choice(_ key: String) -> Choice? {            guard case .object(let said)? = ask[key], let label = said["label"]?.text else { return nil }            return Choice(label: label, line: said["line"]?.text)        }        who = ask["who"]?.text        what = ask["what"]?.text        everything = choice("everything")        choose = choice("choose")        if case .list(let rows)? = ask["groups"] {            groups = rows.compactMap { row in                guard case .object(let group) = row, let id = group["id"]?.text else { return nil }                return Group(id: id, label: group["label"]?.text ?? id, line: group["line"]?.text)            }        }        howLong = ask["howLong"]?.text        howLongLine = ask["howLongLine"]?.text        settings = ask["settings"]?.text    }}/// What the person chose on the sheet: everything asked, or the groups still ticked.struct UnlockChoice: Equatable, Sendable {    var choosing = false    var off: Set<String> = []    func picked(_ ask: UnlockAskWords) -> [String] { ask.groups.map(\.id).filter { !off.contains($0) } }    /// Allow stands only while Let me choose has something ticked.    func allows(_ ask: UnlockAskWords) -> Bool { !choosing || !picked(ask).isEmpty }    /// The request Allow sends for this choice.    func request(_ ask: UnlockAskWords, requestId: String, tables: [String], minutes: Int, key: String) -> UnlockAllowRequest {        choosing            ? UnlockAllowRequest(requestId: requestId, tables: tables, groups: picked(ask), minutes: minutes, privateKey: key)            : UnlockAllowRequest(requestId: requestId, tables: tables, everything: true, minutes: minutes, privateKey: key)    }}/// *Allow all* (`card.allowAll`, f1d096c29d): several of the person's own Claude Code machines wait; one lock allows/// each as it asked. `line` says who else waits.struct UnlockAllowAll: Equatable, Sendable {    let label: String    var line: String?    let requestIds: [String]    init?(_ value: RecordValue?) {        guard case .object(let all)? = value, let label = all["label"]?.text, case .list(let ids)? = all["requestIds"] else { return nil }        self.label = label        line = all["line"]?.text        requestIds = ids.compactMap(\.text)        guard requestIds.count > 1, !label.isEmpty else { return nil }    }}struct UnlockAllowAllRequest: Encodable, Sendable {    let requestIds: [String]    let privateKey: String}struct UnlockDeclineRequest: Encodable, Sendable {    let requestId: String}struct UnlockEndRequest: Encodable, Sendable {    let grantId: String}@MainActor@Observablefinal class UnlockAsks {    /// The card as the face draws it, its switches as the person left them.    private(set) var card: DeckCard?    private(set) var acts: [UnlockAct] = []    /// Where an Allow already given stands, in the core's words (`status`).    private(set) var status: String?    private(set) var windows: [UnlockWindowRow] = []    /// The lengths on offer, and the one chosen.    private(set) var durations: [UnlockDuration] = []    private(set) var chosen = 0    private(set) var windowAct: UnlockAct?    private(set) var busy = false    /// The card's plain words, the promise, and the lines under it (what an app's own sheet draws).    private(set) var ask: UnlockAskWords?    private(set) var title: String?    private(set) var reason: String?    private(set) var waits: [String] = []    /// Allow all, when the core offers it.    private(set) var allowAll: UnlockAllowAll?    /// The choice made on the sheet.    var choice = UnlockChoice()    /// A request put aside by a tap outside, Back or a pull: not raised again until the app is next opened, and no    /// answer sent.    private(set) var aside: String?    /// The card stands for the sheet: one is waiting, and it was not put aside.    var raised: Bool { card != nil && requestId != nil && requestId != aside }    /// The card is drawn in the app's own sheet (Words, Days, Story, Comms), so Allow sends the choice made there.    @ObservationIgnored var sheet = false    @ObservationIgnored private let core: any CottonCalling    @ObservationIgnored private let vault: VaultAccess    @ObservationIgnored private let say: @MainActor (String, CottonToast.Tone) -> Void    @ObservationIgnored private var requestId: String?    @ObservationIgnored private var minutes = 0    /// The tables the person switched off on this request's card.    @ObservationIgnored private var off: Set<String> = []    @ObservationIgnored private var pollSeconds: Double?    @ObservationIgnored private var poll: Task<Void, Never>?    init(core: any CottonCalling, vault: VaultAccess = VaultAccess(), say: @escaping @MainActor (String, CottonToast.Tone) -> Void) {        self.core = core        self.vault = vault        self.say = say        #if COTTON_DEV        // The seed stands from the start: a phone signed out has no sync pass to read it after.        if let seeded = UnlockCardSeed.answer() { take(seeded) }        #endif    }    /// Read the card and the open windows again.    func read() async {        #if COTTON_DEV        if let seeded = UnlockCardSeed.answer() {            if !UnlockCardSeed.answeredOnce { take(seeded) }            return        }        #endif        do {            let answer = try await core.call(CottonMethod.unlockCard, as: UnlockCardAnswer.self)            take(answer)        } catch {            Log.write("unlock: the card could not be read — \(error)")        }        do {            let answer = try await core.call(CottonMethod.unlockWindows, as: UnlockWindowsAnswer.self)            windowAct = answer.acts.compactMap(UnlockAct.init).first            windows = answer.windows.compactMap { row in                guard case .object(let window) = row, let grant = window["grantId"]?.text, let said = window["said"]?.text else { return nil }                var standing = false                if case .bool(let value)? = window["standing"] { standing = value }                return UnlockWindowRow(grantId: grant, said: said, client: window["client"]?.text, standing: standing)            }        } catch {            Log.write("unlock: the open windows could not be read — \(error)")        }        keepPolling()    }    private func take(_ answer: UnlockCardAnswer) {        pollSeconds = answer.pollSeconds        guard let value = answer.card, value != .null, case .object(let said) = value, let id = said["requestId"]?.text else {            card = nil            acts = []            status = nil            requestId = nil            off = []            durations = []            ask = nil            title = nil            reason = nil            waits = []            allowAll = nil            return        }        let fresh = id != requestId        if fresh {            off = []            choice = UnlockChoice()        }        ask = UnlockAskWords(said["ask"])        allowAll = UnlockAllowAll(said["allowAll"])        if case .object(let fields)? = said["fields"] {            title = fields["title"]?.text ?? said["title"]?.text            reason = fields["reason"]?.text            waits = [fields["expires"]?.text, fields["queue"]?.text].compactMap { $0 }        } else {            title = said["title"]?.text            reason = nil            waits = []        }        requestId = id        minutes = said["minutes"].flatMap { if case .number(let n) = $0 { Int(n) } else { nil } } ?? 0        var suggested: Int?        if case .list(let rows)? = said["durations"] {            durations = rows.compactMap { row in                guard case .object(let duration) = row, case .number(let n)? = duration["minutes"],                    let label = duration["label"]?.text else { return nil }                if case .bool(true)? = duration["on"] { suggested = Int(n) }                return UnlockDuration(minutes: Int(n), label: label)            }        } else {            durations = []        }        // A new request starts at the assistant's suggestion; the person's        // pick stands while the same request is read again.        if fresh || !durations.contains(where: { $0.minutes == chosen }) { chosen = suggested ?? minutes }        if case .list(let given)? = said["acts"] { acts = given.compactMap(UnlockAct.init) } else { acts = [] }        status = said["status"]?.text        switch DeckCard.read(value) {        case .success(let read)?: card = switched(read)        case .failure(let failure)?:            Log.write("unlock: the card does not read — \(failure)")            card = nil        case nil: card = nil        }    }    /// The card with each switch as the person left it, and the length they    /// chose on its stamp.    private func switched(_ read: DeckCard) -> DeckCard {        var card = read        if let pick = durations.first(where: { $0.minutes == chosen }) { card.fields["minutes"] = .text(pick.label) }        guard case .list(let rows)? = read.fields["toggles"] else { return card }        card.fields["toggles"] = .list(rows.map { row in            guard case .object(var toggle) = row, let table = toggle["table"]?.text else { return row }            toggle["on"] = .bool(!off.contains(table))            return .object(toggle)        })        return card    }    /// The tables switched on, in the card's order.    private var on: [String] {        guard case .list(let rows)? = card?.fields["toggles"] else { return [] }        return rows.compactMap { row in            guard case .object(let toggle) = row, let table = toggle["table"]?.text, !off.contains(table) else { return nil }            return table        }    }    /// A table's switch, flipped on the card.    func flip(_ table: String) {        if off.contains(table) { off.remove(table) } else { off.insert(table) }        if let card { self.card = switched(card) }    }    /// The sheet closed without an answer: the card waits until the app is next opened.    func putAside() { aside = requestId }    /// The app opened again: a card put aside is raised again.    func raiseAgain() { aside = nil }    /// Let me choose, or Everything back.    func choosing(_ on: Bool) { choice.choosing = on }    /// A group ticked or unticked under Let me choose.    func tick(_ group: String) {        if choice.off.contains(group) { choice.off.remove(group) } else { choice.off.insert(group) }    }    /// A length chosen on the row.    func choose(_ duration: UnlockDuration) {        chosen = duration.minutes        if let card { self.card = switched(card) }    }    func act(_ act: UnlockAct) async {        switch act.id {        case "allow": await allow(act)        case "decline": await decline(act)        default: Log.write("unlock: the card has no act \(act.id)")        }    }    private func allow(_ act: UnlockAct) async {        guard let requestId, !busy else { return }        busy = true        defer { busy = false }        let tables = on        let minutes = durations.isEmpty ? minutes : chosen        let ask = sheet ? ask : nil        let choice = choice        if let ask, !choice.allows(ask) { return }        #if COTTON_DEV        if UnlockCardSeed.asked != nil {            UnlockCardSeed.answered(ask.map { choice.request($0, requestId: requestId, tables: tables, minutes: minutes, key: "") })            say(act.receipt, .success)            take(UnlockCardAnswer(card: nil, pollSeconds: nil))            return        }        #endif        let handed = await vault.handing(CottonMethod.unlockAllow, through: core) { key in            if let ask { return choice.request(ask, requestId: requestId, tables: tables, minutes: minutes, key: key) }            return UnlockAllowRequest(requestId: requestId, tables: tables, minutes: minutes, privateKey: key)        }        switch handed {        case .answered(let answer):            // A held Allow is said by the card's own status line.            if !answer.flag("held") { say(act.receipt, .success) }        case .cancelled:            return        case .noPresence:            say(ShellLines.line("unlock", "no_presence"), .error)        case .refused(let words):            say(words, .error)        }        await read()    }    /// *Allow all*: one lock, then `unlock.allowAll` for every request it names; the first refusal said, and the card    /// read again (what is left waits as before).    func allowEvery() async {        guard let all = allowAll, !busy else { return }        busy = true        defer { busy = false }        #if COTTON_DEV        if UnlockCardSeed.asked != nil {            UnlockCardSeed.answeredAll(all.requestIds)            take(UnlockCardAnswer(card: nil, pollSeconds: nil))            return        }        #endif        let ids = all.requestIds        let handed = await vault.handing(CottonMethod.unlockAllowAll, through: core) { key in            UnlockAllowAllRequest(requestIds: ids, privateKey: key)        }        switch handed {        case .answered(let answer):            if case .array(let refused)? = answer["refused"], let said = refused.first?["said"]?.string, !said.isEmpty {                say(said, .error)            }        case .cancelled:            return        case .noPresence:            say(ShellLines.line("unlock", "no_presence"), .error)        case .refused(let words):            say(words, .error)        }        await read()    }    private func decline(_ act: UnlockAct) async {        guard let requestId, !busy else { return }        busy = true        defer { busy = false }        #if COTTON_DEV        if UnlockCardSeed.asked != nil {            say(act.receipt, .notice)            take(UnlockCardAnswer(card: nil, pollSeconds: nil))            return        }        #endif        do {            _ = try await core.callJSON(CottonMethod.unlockDecline, UnlockDeclineRequest(requestId: requestId))            say(act.receipt, .notice)        } catch let error as CottonCallError {            say(error.message, .error)        } catch {            say(ShellLines.line("passwords", "vault.this_phone_could_not"), .error)        }        await read()    }    /// *End now* on an open window.    func end(_ window: UnlockWindowRow) async {        guard let act = windowAct, !busy else { return }        busy = true        defer { busy = false }        do {            _ = try await core.callJSON(CottonMethod.unlockEnd, UnlockEndRequest(grantId: window.grantId))            say(act.receipt, .notice)        } catch let error as CottonCallError {            say(error.message, .error)        } catch {            say(ShellLines.line("passwords", "vault.this_phone_could_not"), .error)        }        await read()    }    /// While a card stands, read it again every `pollSeconds`.    private func keepPolling() {        guard card != nil, let seconds = pollSeconds, seconds > 0 else {            poll?.cancel()            poll = nil            return        }        guard poll == nil else { return }        poll = Task { @MainActor [weak self] in            try? await Task.sleep(for: .seconds(seconds))            guard let self, !Task.isCancelled else { return }            self.poll = nil            await self.read()        }    }}enum UnlockAsksKnobs {    static let cardWidth: CGFloat = 340    static let cardRatio: CGFloat = 1.42    static let gutter: CGFloat = 16    static let actsTop: CGFloat = 18    static let actSize: CGFloat = 19    static let windowSize: CGFloat = 14    static let veil = 0.38    /// A length not chosen, drawn fainter than the chosen one.    static let unpicked = 0.55}/// The card over the window while a request waits. An open window draws/// nothing here: it is listed in Account (Open access, `AccountPage`), with/// End on each, and no standing banner covers the fan (the owner, 17 Nov/// 2026).struct UnlockAsksLayer: View {    let asks: UnlockAsks    /// The app's own look, where it has one: Words, Days, Story and Comms raise the card in their own sheet    /// (`UnlockAskSheet.swift`); others keep the paper.    var look: VaultLook? = nil    @Environment(\.vaultLook) private var vaultLook    var body: some View {        ZStack {            #if os(iOS)            if vaultLook != nil {                // Inside Cotton Vault the card stands above the screen in                // Vault's look and pushes it down (`VaultUnlockStanding`).                EmptyView()            } else if let look, VaultLook.raisesAsks {                UnlockAskRaise(asks: asks, look: look)            } else if let card = asks.card {                paper(card)            }            #else            if let card = asks.card { paper(card) }            #endif        }        .animation(.easeOut(duration: 0.2), value: asks.card != nil)    }    /// The card on paper, as every other app draws it.    @ViewBuilder private func paper(_ card: DeckCard) -> some View {        Group {                Color.black.opacity(UnlockAsksKnobs.veil)                    .ignoresSafeArea()                    .accessibilityHidden(true)                VStack(spacing: UnlockAsksKnobs.actsTop) {                    face(card)                        .frame(maxWidth: UnlockAsksKnobs.cardWidth)                        .aspectRatio(1 / UnlockAsksKnobs.cardRatio, contentMode: .fit)                    VStack(spacing: 8) {                        if let status = asks.status {                            Text(status)                                .paperMeta(UnlockAsksKnobs.windowSize)                                .multilineTextAlignment(.center)                                .fixedSize(horizontal: false, vertical: true)                                .accessibilityIdentifier("unlock-status")                        }                        if !asks.durations.isEmpty, !asks.acts.isEmpty {                            ChipWrap(spacing: 14) {                                ForEach(asks.durations, id: \.minutes) { duration in                                    let picked = duration.minutes == asks.chosen                                    PaperTypedButton(duration.label, size: UnlockAsksKnobs.windowSize) {                                        asks.choose(duration)                                    }                                    .opacity(picked ? 1 : UnlockAsksKnobs.unpicked)                                    .underline(picked)                                    .accessibilityAddTraits(picked ? .isSelected : [])                                    .accessibilityIdentifier("unlock-duration-\(duration.minutes)")                                }                            }                        }                        if !asks.acts.isEmpty {                            HStack(spacing: 28) {                                ForEach(asks.acts, id: \.id) { act in                                    PaperTypedButton(act.label, size: UnlockAsksKnobs.actSize) {                                        Task { await asks.act(act) }                                    }                                    .disabled(asks.busy)                                    .accessibilityIdentifier("unlock-act-\(act.id)")                                }                            }                        }                    }                    .padding(.vertical, 10)                    .padding(.horizontal, 22)                    .background(PaperDye.cream.fill, in: RoundedRectangle(cornerRadius: 22))                }                .padding(UnlockAsksKnobs.gutter)                .coversTheRest(true)                .onAppear { UnlockAsksLayer.landOnTheCard() }                .transition(.opacity)        }    }    /// VoiceOver moves to the card as it rises: the screen changed, and the    /// first element of what stands is the face's title.    static func landOnTheCard() {        #if os(iOS)        UIAccessibility.post(notification: .screenChanged, argument: nil)        #endif    }    /// The card drawn by the face its id names.    @ViewBuilder private func face(_ card: DeckCard) -> some View {        if let face = FaceRegistry.face(card.face) {            face.view(card, picture: nil, taps: FaceTaps(flip: { table in asks.flip(table) }))        } else {            Color.clear.onAppear { Log.write("unlock: no face is registered for \(card.face)") }        }    }}