Cotton code
540 lines · 25.8 KB · SwiftRaw
// THE ACCOUNT CARD'S PAGE (owner, 11 Nov 2026): this phone's sign-in and its// sync, one card, the first to the LEFT of the app's first card in every// Cotton app. The core answers it whole (`shell.account`,// `crates/cotton-ffi/src/methods/shell_account.rs`): who is signed in, the// app and its build, the database and the Worker's host, the last sync, the// rows waiting and the rows here, the last error — every line a kit line —// and the acts that stand now (Sign in; Back up now and Sign out). This page// draws that card on the plain face, whole in one screenshot, and turns the// fan into its acts on a tap or a hold; a tap on one runs it as every tool// act runs (`EditingFan.runTool`, `tools.act`). It decides nothing.//// YOUR PEOPLE (14 Nov 2026), part of the same answer while signed in: the// people this person connects with, one relationship with Cotton chat's.// A card says who they are (asking, waiting, connected, in the core's order,// each section's names on it) and its fan holds Add a person, whose number is// typed in the short-text input (`DeckEditor.addPerson`, the same add Send's// tier opens); a card after it for each person, whose fan holds the acts the// core answered (Accept, Refuse, Block, Remove), each run as the core named// its call.//// RECOVERY AND WHAT ASSISTANTS READ (16 Nov 2026; e2e// rulings R4, R7c, R7d), two more cards on the same plain face, every word// the core's: on a phone holding the vault, the recovery card (the code's// line, the iCloud Keychain copy, who can help) whose fan holds Show my// recovery code, Make a new code and Ask someone to help, each behind the// phone's lock (`Boot/RecoveryKeys.swift`), and the code itself while shown// with Copy and Done; and What assistants read (`unlock.reads`): the latest// reads.//// OPEN ACCESS (the owner, 17 Nov 2026), right after the Account card while// any window is open (`OpenAccess.swift`, `unlock.windows`): each window by// its assistant, its tables and the time left, and End on each on the fan.// It replaced the standing banner at the foot; no window, no card.//// PASSKEYS (19 Nov 2026; Android's `PasskeyPart.kt`), after// recovery's while signed in (`signin.passkeys`): the heading and its line,// Add a passkey on its fan (the system sheet, `AccountPasskeySheet`), then a// card for each passkey, whose fan holds Remove, asked first on the slip.import CottonFacesimport CottonKitimport CottonPaperimport CottonValuesimport SwiftUI/// `shell.account`'s answer.struct AccountAnswer: Decodable, Sendable {    struct Fact: Decodable, Equatable, Sendable {        /// Which fact (`app`, `database`, `synced`, `waiting`, `here`, `sent_up`, `error`).        var id: String?        let label: String        let said: String    }    struct Card: Decodable, Equatable, Sendable {        let title: String        let subtitle: String        let facts: [Fact]    }    /// Your people: each person and what can be done with them.    struct People: Decodable, Equatable, Sendable {        struct Act: Decodable, Equatable, Sendable {            struct Call: Decodable, Equatable, Sendable {                let method: String                let request: JSONValue            }            let id: String            let words: String            var red: Bool?            var primary: Bool?            let call: Call        }        struct Row: Decodable, Equatable, Sendable {            let number: String            let words: String            var detail: String?            var initials: String?            var acts: [Act]?        }        struct Section: Decodable, Equatable, Sendable {            let id: String            let title: String            let rows: [Row]        }        let title: String        let add: SendAdd?        var sections: [Section]?        /// Nobody yet, or the object out of reach, in the core's words.        var empty: String?        var unreachable: String?        /// Each person in the core's order, with the section they stand in.        var rows: [(section: Section, row: Row)] {            (sections ?? []).flatMap { section in section.rows.map { (section, $0) } }        }    }    let line: String    let stand: String    let card: Card    /// This phone cannot reach the person's database now (the sync stopped, a sign-in or backup that did not finish).    var trouble: Bool?    let actions: [CardAction]    let tile: FanTileLook?    var people: People?    /// The card as the plain face draws it: its title, who is signed in,    /// and each line under its label.    var drawn: DeckCard {        DeckCard(face: "plain", corner: nil, pressing: false, pace: nil, plate: nil, fields: [            "title": .text(card.title),            "subtitle": .text(card.subtitle),            "facts": .list(card.facts.map { .object(["label": .text($0.label), "said": .text($0.said)]) }),        ])    }    /// Your people's card: each section under its title with its names; or    /// why nobody stands there.    static func drawn(_ people: People) -> DeckCard {        let facts: [RecordValue] = (people.sections ?? []).map { section in            .object(["label": .text(section.title), "said": .text(section.rows.map(\.words).joined(separator: "\n"))])        }        return DeckCard(face: "plain", corner: nil, pressing: false, pace: nil, plate: nil, fields: [            "title": .text(people.title),            "subtitle": .text(people.unreachable ?? people.empty ?? ""),            "facts": .list(facts),        ])    }    /// One person's card: who they are, what stands between you, and where.    static func drawn(_ row: People.Row, in section: People.Section) -> DeckCard {        DeckCard(face: "plain", corner: nil, pressing: false, pace: nil, plate: nil, fields: [            "title": .text(row.words),            "subtitle": .text(row.detail ?? ""),            "facts": .list([.object(["label": .text(section.title), "said": .text(row.number)])]),        ])    }}extension Notification.Name {    /// Someone added from the short-text input (`DeckEditor.addPerson`): Account reads its people again.    static let cottonPeopleChanged = Notification.Name("com.cottondb.people.changed")}struct AccountPage: View {    /// The card's id on the fan (`account`).    let card: String    /// The table of the tool whose views tier holds the card: what the acts    /// fan stands over (`DeckEditTarget.emptyDeck`).    let table: String    @Environment(\.cottonCore) private var core    @Environment(\.cottonSync) private var sync    @Environment(\.deckEditor) private var editor    @Environment(\.cottonHaptics) private var haptics    @Environment(\.scenePhase) private var scenePhase    @Environment(ToastCenter.self) private var toasts: ToastCenter?    @State private var answer: AccountAnswer?    @State private var recovery: RecoveryKeys?    @State private var windows: JSONValue?    @State private var claude: JSONValue?    @State private var reads: JSONValue?    @State private var passkeys: JSONValue?    /// The passkey Remove was asked for, until the slip is answered.    @State private var removing: AccountPasskeyRow?    private struct Item: Identifiable { let id: String }    private struct Ask: Encodable, Sendable { let commit: String }    private struct Asked: Hashable {        var revision: Int        var pulled: String?        var phase: String        var active: Bool    }    /// The Account card, Open access, recovery's and What assistants read    /// while they stand, Your people's, then each person's.    private var items: [Item] {        guard let answer else { return [] }        var items = [Item(id: card)]        if OpenAccess(windows) != nil { items.append(Item(id: Self.openAccessCard)) }        if YourClaude(claude) != nil { items.append(Item(id: Self.claudeCard)) }        if holdsVault { items.append(Item(id: Self.recoveryCard)) }        if reads?.text("heading") != nil { items.append(Item(id: Self.readsCard)) }        // The card stands where a passkey can be added here, or while one is kept, so it can be removed.        if passkeys?.text("heading") != nil, Self.offersPasskey || !AccountPasskeyRow.all(passkeys).isEmpty {            items.append(Item(id: Self.passkeysCard))            items += AccountPasskeyRow.all(passkeys).map { Item(id: Self.passkeyCard($0.id)) }        }        guard let people = answer.people else { return items }        return items + [Item(id: Self.peopleCard)] + people.rows.map { Item(id: Self.personCard($0.row.number)) }    }    static let peopleCard = "people"    static let recoveryCard = "recovery"    static let readsCard = "reads"    static let openAccessCard = "open-access"    static let claudeCard = "your-claude"    static let passkeysCard = "passkeys"    /// Whether this app and phone can make a Cotton passkey for the host the app signs in at (`PasskeyPlatform`).    static let offersPasskey: Bool = FlavourManifest.current?.personalObject.map { PasskeyPlatform.offersHere(server: $0.server) } ?? false    static func passkeyCard(_ id: String) -> String { "passkey-\(id)" }    /// Signed in on a phone holding the vault: recovery's card stands.    private var holdsVault: Bool {        guard let status = recovery?.status else { return false }        return status.flag("signedIn") && status.flag("holdsVault")    }    static func personCard(_ number: String) -> String { "person-\(number)" }    var body: some View {        CardDeck(items: items, emptyLine: "", open: { offer($0.id) }, holds: { offer($0.id) }) { item in            if let answer {                PlainFace(card: drawn(item.id, in: answer))                    .onCardPaper(.framed)            }        }        .confirmDecision(item: $removing, title: \.confirm, message: { _ in "" }, confirmLabel: \.remove,                         identifier: "passkey-remove-confirm") { row in            Task { await removePasskey(row) }        }        .preference(key: FanPageReadingPreference.self, value: FanPageReading(filled: answer != nil))        .onReceive(NotificationCenter.default.publisher(for: .cottonPeopleChanged)) { _ in Task { await read() } }        // It moves with the sync and with a sign-in made over it: read on        // each pass, as the app comes back, and every few seconds.        .task(id: Asked(revision: sync?.revision ?? 0, pulled: sync?.lastPullAt, phase: sync?.loop?.state ?? "", active: scenePhase == .active)) {            while !Task.isCancelled {                await read()                try? await Task.sleep(for: .seconds(HomeSyncKnobs.every))            }        }    }    private func read() async {        guard let core else { return }        let ask = Ask(commit: (Bundle.main.object(forInfoDictionaryKey: "CottonBuildCommit") as? String) ?? "")        if let next = try? await core.call(CottonMethod.shellAccount, ask, as: AccountAnswer.self) { answer = next }        if recovery == nil {            recovery = RecoveryKeys(core: core, vault: VaultAccess(), say: { [toasts] words, tone in toasts?.show(words, tone: tone) })        }        await recovery?.refresh()        windows = try? await core.callJSON(CottonMethod.unlockWindows)        claude = try? await core.callJSON(CottonMethod.assistantScreen)        reads = try? await core.callJSON(CottonMethod.unlockReads)        // Signed in only: a phone with no door to its object answers nothing, and no card stands.        passkeys = try? await core.callJSON(CottonMethod.signinPasskeys)    }    /// Passkeys' card: the heading, and how many sign in (or how to start).    private func passkeysDrawn() -> DeckCard {        DeckCard(face: "plain", corner: nil, pressing: false, pace: nil, plate: nil, fields: [            "title": .text(passkeys?.text("heading") ?? ""),            "subtitle": .text(passkeys?.text("line") ?? ""),            "facts": .list([]),        ])    }    /// Add a passkey: the creation request, the system sheet, then the passkey kept at the object.    private func addPasskey() async {        guard let core else { return }        #if os(iOS)            do {                let options = try await core.callJSON(CottonMethod.signinPasskeyOptions)                guard let request = options.text("requestJson") else { throw CottonCallError(code: "passkey_refused", message: "") }                let response: String                do {                    response = try await AccountPasskeySheet.add(requestJSON: request)                } catch AccountPasskeyRefusal.cancelled {                    toasts?.show(SignInWords.passkeyCancelled)                    return                } catch {                    throw CottonCallError(code: "passkey_refused", message: "")                }                struct Add: Encodable, Sendable { let responseJson: String; let name: String }                let said = try await core.callJSON(CottonMethod.signinPasskeyAdd, Add(responseJson: response, name: ThisPhone.deviceName()))                if let words = said.text("said") { toasts?.show(words, tone: .success) }            } catch let error as CottonCallError {                toasts?.show(HomeCustomerRefusal.line(code: error.code, business: ShellLines.speaker ?? ""), tone: .error)            } catch {                toasts?.show(ActionRefused.words(for: error), tone: .error)            }        #endif        await read()    }    private func removePasskey(_ row: AccountPasskeyRow) async {        guard let core else { return }        struct Remove: Encodable, Sendable { let id: String; let name: String }        do {            let said = try await core.callJSON(CottonMethod.signinPasskeyRemove, Remove(id: row.id, name: row.name))            if let words = said.text("said") { toasts?.show(words) }        } catch {            toasts?.show((error as? CottonCallError)?.message ?? ActionRefused.words(for: error), tone: .error)        }        await read()    }    /// Recovery's card: the code's line (no code yet, out of date, or made    /// on its date), the iCloud copy's line, who can help, and the code    /// itself while shown.    private func recoveryDrawn() -> DeckCard {        let status = recovery?.status        let code = status?["code"]        let title: String?        if code?.text("made") == nil {            title = recovery?.line("offer")        } else if code?.maybeFlag("current") == false {            title = recovery?.line("stale")        } else {            title = code?.text("line")        }        var facts: [RecordValue] = []        if let helper = status?["trusted"]?.text("line") { facts.append(.object(["label": .text(""), "said": .text(helper)])) }        if let shown = recovery?.shown { facts.append(.object(["label": .text(""), "said": .text(shown.code)])) }        let apple = status?["apple"]?.text("made") != nil ? recovery?.line("appleKept") : nil        return DeckCard(face: "plain", corner: nil, pressing: false, pace: nil, plate: nil, fields: [            "title": .text(title ?? ""),            "subtitle": .text(apple ?? ""),            "facts": .list(facts),        ])    }    /// What assistants read: the latest reads; or that none read anything    /// yet. The open windows stand on Open access.    private func readsDrawn() -> DeckCard {        let facts: [RecordValue] = (reads?.list("reads") ?? []).compactMap { read in            read.text("said").map { .object(["label": .text(""), "said": .text($0)]) }        }        return DeckCard(face: "plain", corner: nil, pressing: false, pace: nil, plate: nil, fields: [            "title": .text(reads?.text("heading") ?? ""),            "subtitle": .text(facts.isEmpty ? reads?.text("none") ?? "" : ""),            "facts": .list(facts),        ])    }    private func drawn(_ id: String, in answer: AccountAnswer) -> DeckCard {        if id == Self.recoveryCard { return recoveryDrawn() }        if id == Self.readsCard { return readsDrawn() }        if id == Self.openAccessCard, let open = OpenAccess(windows) { return open.drawn }        if id == Self.claudeCard, let mine = YourClaude(claude) { return mine.drawn }        if id == Self.passkeysCard { return passkeysDrawn() }        if let row = AccountPasskeyRow.all(passkeys).first(where: { Self.passkeyCard($0.id) == id }) { return row.drawn }        guard let people = answer.people else { return answer.drawn }        if id == Self.peopleCard { return AccountAnswer.drawn(people) }        if let person = people.rows.first(where: { Self.personCard($0.row.number) == id }) {            return AccountAnswer.drawn(person.row, in: person.section)        }        return answer.drawn    }    /// The fan becomes the card's acts, as the core says they stand now:    /// the Account card's tool acts, Your people's Add a person, or a    /// person's acts.    private func offer(_ id: String) {        guard let editor else { return }        haptics.press()        Task {            await read()            guard let answer else { return }            let target = DeckEditTarget.emptyDeck(of: table)            if id == Self.recoveryCard, let recovery {                editor.offer(recoveryOffers(recovery, answer: answer, target: target), for: target)            } else if id == Self.passkeysCard, Self.offersPasskey, let add = passkeys?.text("add") {                editor.offer([DeckOffer(id: "passkey-add", word: add, primary: true, tile: answer.tile) { _ in await addPasskey() }], for: target)            } else if let row = AccountPasskeyRow.all(passkeys).first(where: { Self.passkeyCard($0.id) == id }) {                editor.offer([DeckOffer(id: "passkey-remove", word: row.remove, tile: answer.tile) { _ in removing = row }], for: target)            } else if id == Self.claudeCard, let mine = YourClaude(claude) {                editor.offer(claudeOffers(mine, answer: answer, target: target), for: target)            } else if id == Self.openAccessCard || id == Self.readsCard {                editor.offer(endOffers(answer: answer), for: target)            } else if id == Self.peopleCard, let add = answer.people?.add {                editor.offer([DeckOffer(id: "people-add", word: add.words, tile: answer.tile) { _ in editor.addPerson(add, core: core) }], for: target)            } else if let person = answer.people?.rows.first(where: { Self.personCard($0.row.number) == id }) {                let acts = (person.row.acts ?? []).map { act in                    DeckOffer(id: "people-\(act.id)", word: act.words, primary: act.primary == true, tile: answer.tile) { _ in await run(act) }                }                editor.offer(acts, for: target)            } else {                editor.openToolActs(answer.actions, for: target, tile: answer.tile)            }        }    }    /// Recovery's acts: Copy and Done while the code is shown; else Show my    /// recovery code (while the code is current), Make a new code, and Ask    /// someone to help, which deals the person's connected people.    private func recoveryOffers(_ recovery: RecoveryKeys, answer: AccountAnswer, target: DeckEditTarget) -> [DeckOffer] {        var offers: [DeckOffer] = []        let word = { (key: String) in recovery.line(key) }        if recovery.shown != nil {            if let copy = word("copy") { offers.append(DeckOffer(id: "recovery-copy", word: copy, tile: answer.tile) { _ in recovery.copy() }) }            if let done = word("done") { offers.append(DeckOffer(id: "recovery-done", word: done, tile: answer.tile) { _ in await recovery.dismiss() }) }            return offers        }        let code = recovery.status?["code"]        if code?.text("made") != nil, code?.maybeFlag("current") != false, let show = word("show") {            offers.append(DeckOffer(id: "recovery-show", word: show, tile: answer.tile) { _ in await recovery.show() })        }        if let make = word("makeNew") {            offers.append(DeckOffer(id: "recovery-make", word: make, tile: answer.tile) { _ in await recovery.makeNew() })        }        let people = answer.people?.sections?.first { $0.id == Self.connected }?.rows ?? []        if !people.isEmpty, let ask = word("askHelp") {            offers.append(DeckOffer(id: "recovery-ask", word: ask, tile: answer.tile) { _ in                if let pick = word("helperPick") { toasts?.show(pick) }                editor?.offer(people.map { person in                    DeckOffer(id: "recovery-trust-\(person.number)", word: person.words, tile: answer.tile) { _ in                        await recovery.trust(number: person.number, name: person.words)                    }                }, for: target)            })        }        return offers    }    /// Your Claude's acts: each table (a tap deals its three settings),    /// Remove, and Connect Claude.    private func claudeOffers(_ mine: YourClaude, answer: AccountAnswer, target: DeckEditTarget) -> [DeckOffer] {        var offers: [DeckOffer] = mine.tables.map { table in            DeckOffer(id: "claude-table-\(table.table)", word: "\(table.label) · \(table.said)", tile: answer.tile) { _ in                editor?.offer(table.choices.filter { !$0.on }.map { choice in                    DeckOffer(id: "claude-\(table.table)-\(choice.access)", word: choice.label, tile: answer.tile) { _ in                        await scope(table, to: choice.access)                    }                }, for: target)            }        }        if let remove = mine.remove {            offers.append(DeckOffer(id: "claude-remove", word: remove, tile: answer.tile) { _ in await claudeCall(CottonMethod.assistantRemove) })        }        if let connect = mine.connect {            offers.append(DeckOffer(id: "claude-connect", word: connect, primary: true, tile: answer.tile) { _ in await connectClaude() })        }        return offers    }    /// One table's setting: Off and Ask each time at once; On for a table    /// left off on the card behind the phone's lock.    private func scope(_ table: YourClaude.Table, to access: String) async {        guard let core else { return }        if access == "on", table.needsLock {            let name = table.table            let handed = await VaultAccess().handing(CottonMethod.assistantScope, through: core) { key in                YourClaude.SignedScope(table: name, access: access, privateKey: key)            }            sayHanded(handed, done: nil)        } else {            await claudeCall(CottonMethod.assistantScope, YourClaude.Scope(table: table.table, access: access))        }        await read()    }    /// Connect Claude: behind the phone's lock; the core says where to add it.    private func connectClaude() async {        guard let core else { return }        let handed = await VaultAccess().handing(CottonMethod.assistantConnect, through: core) { key in YourClaude.Signed(privateKey: key) }        sayHanded(handed, done: nil)        await read()    }    private func sayHanded(_ handed: VaultHanding, done: String?) {        switch handed {        case .answered(let said):            if let words = said.text("said") ?? done { toasts?.show(words, tone: .success) }        case .cancelled:            return        case .noPresence:            toasts?.show(ShellLines.line("unlock", "no_presence"), tone: .error)        case .refused(let words):            toasts?.show(words, tone: .error)        }    }    private func claudeCall(_ method: String, _ request: some Encodable & Sendable = EmptyRequest()) async {        guard let core else { return }        do {            let said = try await core.callJSON(method, request)            if let words = said.text("said") { toasts?.show(words) }        } catch {            toasts?.show((error as? CottonCallError)?.message ?? ActionRefused.words(for: error), tone: .error)        }        await read()    }    /// The section of Your people a helper is chosen from.    static let connected = "people"    /// End on each open window, named by its assistant.    private func endOffers(answer: AccountAnswer) -> [DeckOffer] {        guard let core, let open = OpenAccess(windows) else { return [] }        return open.rows.compactMap { row in            guard let word = open.endWord(row) else { return nil }            return DeckOffer(id: "end-\(row.grantId)", word: word, tile: answer.tile) { _ in                do {                    try await OpenAccess.end(row, core: core)                    if let receipt = open.end?.receipt { toasts?.show(receipt) }                } catch {                    toasts?.show((error as? CottonCallError)?.message ?? ActionRefused.words(for: error), tone: .error)                }                await read()            }        }    }    /// One act on a person, run as the core named its call; what it says is    /// said, and the people are read again.    private func run(_ act: AccountAnswer.People.Act) async {        guard let core else { return }        do {            let said = try await core.callJSON(act.call.method, act.call.request)            if let words = said["said"]?.string, !words.isEmpty { toasts?.show(words) }        } catch {            toasts?.show((error as? CottonCallError)?.message ?? ActionRefused.words(for: error), tone: .error)        }        await read()    }}/// One passkey as `signin.passkeys` says it.struct AccountPasskeyRow: Equatable, Identifiable {    let id: String    let name: String    let when: String    let remove: String    let confirm: String    static func all(_ answer: JSONValue?) -> [AccountPasskeyRow] {        (answer?["passkeys"]?.array ?? []).compactMap { one in            guard let id = one.text("id"), let remove = one.text("remove") else { return nil }            return AccountPasskeyRow(id: id, name: one.text("name") ?? "", when: one.text("when") ?? "", remove: remove,                                     confirm: one.text("confirm") ?? remove)        }    }    var drawn: DeckCard {        DeckCard(face: "plain", corner: nil, pressing: false, pace: nil, plate: nil, fields: [            "title": .text(name), "subtitle": .text(when), "facts": .list([]),        ])    }}