// 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).importCottonFacesimportCottonKitimportCottonPaperimportCottonValuesimportSwiftUI/// One act as the face definition names it (`card.acts`, a window's `acts`).structUnlockAct: Equatable, Sendable {let id: Stringlet label: Stringlet receipt: Stringinit?(_ value: RecordValue) {guardcase .object(let act) = value, let id = act["id"]?.text, let label = act["label"]?.text else { returnnil }self.id = idself.label = label receipt = act["receipt"]?.text ?? label }}/// One open window's row.structUnlockWindowRow: Equatable, Sendable, Identifiable {let grantId: Stringlet said: String/// Which assistant holds it, as the core names it.var client: String? = nil/// Open until the person turns it off.var standing = falsevar id: String { grantId }}/// One length the person may choose (`card.durations`).structUnlockDuration: Equatable, Sendable {let minutes: Intlet label: String}/// `unlock.card`'s answer.structUnlockCardAnswer: Decodable, Sendable {let card: RecordValue?let pollSeconds: Double?}/// `unlock.windows`' answer.structUnlockWindowsAnswer: 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.structUnlockAllowRequest: Encodable, Sendable {let requestId: Stringlet tables: [String]var everything: Bool? = nilvar groups: [String]? = nillet minutes: Intlet 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.structUnlockAskWords: Equatable, Sendable {structChoice: Equatable, Sendable { let label: String; var line: String? }structGroup: 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?) {guardcase .object(let ask)? = value else { returnnil }func choice(_ key: String) -> Choice? {guardcase .object(let said)? = ask[key], let label = said["label"]?.text else { returnnil }returnChoice(label: label, line: said["line"]?.text) } who = ask["who"]?.text what = ask["what"]?.text everything = choice("everything") choose = choice("choose")ifcase .list(let rows)? = ask["groups"] { groups = rows.compactMap { row inguardcase .object(let group) = row, let id = group["id"]?.text else { returnnil }returnGroup(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.structUnlockChoice: Equatable, Sendable {var choosing = falsevar 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.structUnlockAllowAll: Equatable, Sendable {let label: Stringvar line: String?let requestIds: [String]init?(_ value: RecordValue?) {guardcase .object(let all)? = value, let label = all["label"]?.text, case .list(let ids)? = all["requestIds"] else { returnnil }self.label = label line = all["line"]?.text requestIds = ids.compactMap(\.text)guard requestIds.count > 1, !label.isEmpty else { returnnil } }}structUnlockAllowAllRequest: Encodable, Sendable {let requestIds: [String]let privateKey: String}structUnlockDeclineRequest: Encodable, Sendable {let requestId: String}structUnlockEndRequest: Encodable, Sendable {let grantId: String}@MainActor@ObservablefinalclassUnlockAsks {/// 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 = 0private(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 privatelet core: any CottonCalling @ObservationIgnored privatelet vault: VaultAccess @ObservationIgnored privatelet say: @MainActor (String, CottonToast.Tone) -> Void @ObservationIgnored privatevar requestId: String? @ObservationIgnored privatevar minutes = 0/// The tables the person switched off on this request's card. @ObservationIgnored privatevar off: Set<String> = [] @ObservationIgnored privatevar pollSeconds: Double? @ObservationIgnored privatevar poll: Task<Void, Never>?init(core: any CottonCalling, vault: VaultAccess = VaultAccess(), say: @escaping @MainActor (String, CottonToast.Tone) -> Void) {self.core = coreself.vault = vaultself.say = say #if COTTON_DEV// The seed stands from the start: a phone signed out has no sync pass to read it after.iflet seeded = UnlockCardSeed.answer() { take(seeded) } #endif }/// Read the card and the open windows again.func read() async { #if COTTON_DEViflet seeded = UnlockCardSeed.answer() {if !UnlockCardSeed.answeredOnce { take(seeded) }return } #endifdo {let answer = tryawait core.call(CottonMethod.unlockCard, as: UnlockCardAnswer.self) take(answer) } catch {Log.write("unlock: the card could not be read — \(error)") }do {let answer = tryawait core.call(CottonMethod.unlockWindows, as: UnlockWindowsAnswer.self) windowAct = answer.acts.compactMap(UnlockAct.init).first windows = answer.windows.compactMap { row inguardcase .object(let window) = row, let grant = window["grantId"]?.text, let said = window["said"]?.text else { returnnil }var standing = falseifcase .bool(let value)? = window["standing"] { standing = value }returnUnlockWindowRow(grantId: grant, said: said, client: window["client"]?.text, standing: standing) } } catch {Log.write("unlock: the open windows could not be read — \(error)") } keepPolling() }privatefunc take(_ answer: UnlockCardAnswer) { pollSeconds = answer.pollSecondsguardlet 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 = nilreturn }let fresh = id != requestIdif fresh { off = [] choice = UnlockChoice() } ask = UnlockAskWords(said["ask"]) allowAll = UnlockAllowAll(said["allowAll"])ifcase .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 { ifcase .number(let n) = $0 { Int(n) } else { nil } } ?? 0var suggested: Int?ifcase .list(let rows)? = said["durations"] { durations = rows.compactMap { row inguardcase .object(let duration) = row, case .number(let n)? = duration["minutes"],let label = duration["label"]?.text else { returnnil }ifcase .bool(true)? = duration["on"] { suggested = Int(n) }returnUnlockDuration(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 }ifcase .list(let given)? = said["acts"] { acts = given.compactMap(UnlockAct.init) } else { acts = [] } status = said["status"]?.textswitchDeckCard.read(value) {case .success(let read)?: card = switched(read)case .failure(let failure)?:Log.write("unlock: the card does not read — \(failure)") card = nilcasenil: card = nil } }/// The card with each switch as the person left it, and the length they/// chose on its stamp.privatefunc switched(_ read: DeckCard) -> DeckCard {var card = readiflet pick = durations.first(where: { $0.minutes == chosen }) { card.fields["minutes"] = .text(pick.label) }guardcase .list(let rows)? = read.fields["toggles"] else { return card } card.fields["toggles"] = .list(rows.map { row inguardcase .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.privatevar on: [String] {guardcase .list(let rows)? = card?.fields["toggles"] else { return [] }return rows.compactMap { row inguardcase .object(let toggle) = row, let table = toggle["table"]?.text, !off.contains(table) else { returnnil }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) }iflet 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.minutesiflet 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)") } }privatefunc allow(_ act: UnlockAct) async {guardlet requestId, !busy else { return } busy = truedefer { busy = false }let tables = onlet minutes = durations.isEmpty ? minutes : chosenlet ask = sheet ? ask : nillet choice = choiceiflet ask, !choice.allows(ask) { return } #if COTTON_DEVifUnlockCardSeed.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 } #endiflet handed = await vault.handing(CottonMethod.unlockAllow, through: core) { key iniflet ask { return choice.request(ask, requestId: requestId, tables: tables, minutes: minutes, key: key) }returnUnlockAllowRequest(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:returncase .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 {guardlet all = allowAll, !busy else { return } busy = truedefer { busy = false } #if COTTON_DEVifUnlockCardSeed.asked != nil {UnlockCardSeed.answeredAll(all.requestIds) take(UnlockCardAnswer(card: nil, pollSeconds: nil))return } #endiflet ids = all.requestIdslet handed = await vault.handing(CottonMethod.unlockAllowAll, through: core) { key inUnlockAllowAllRequest(requestIds: ids, privateKey: key) }switch handed {case .answered(let answer):ifcase .array(let refused)? = answer["refused"], let said = refused.first?["said"]?.string, !said.isEmpty { say(said, .error) }case .cancelled:returncase .noPresence: say(ShellLines.line("unlock", "no_presence"), .error)case .refused(let words): say(words, .error) }await read() }privatefunc decline(_ act: UnlockAct) async {guardlet requestId, !busy else { return } busy = truedefer { busy = false } #if COTTON_DEVifUnlockCardSeed.asked != nil { say(act.receipt, .notice) take(UnlockCardAnswer(card: nil, pollSeconds: nil))return } #endifdo { _ = tryawait core.callJSON(CottonMethod.unlockDecline, UnlockDeclineRequest(requestId: requestId)) say(act.receipt, .notice) } catchlet error asCottonCallError { 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 {guardlet act = windowAct, !busy else { return } busy = truedefer { busy = false }do { _ = tryawait core.callJSON(CottonMethod.unlockEnd, UnlockEndRequest(grantId: window.grantId)) say(act.receipt, .notice) } catchlet error asCottonCallError { 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`.privatefunc keepPolling() {guard card != nil, let seconds = pollSeconds, seconds > 0else { poll?.cancel() poll = nilreturn }guard poll == nilelse { return } poll = Task { @MainActor [weakself] intry? awaitTask.sleep(for: .seconds(seconds))guardletself, !Task.isCancelled else { return }self.poll = nilawaitself.read() } }}enumUnlockAsksKnobs {staticlet cardWidth: CGFloat = 340staticlet cardRatio: CGFloat = 1.42staticlet gutter: CGFloat = 16staticlet actsTop: CGFloat = 18staticlet actSize: CGFloat = 19staticlet windowSize: CGFloat = 14staticlet veil = 0.38/// A length not chosen, drawn fainter than the chosen one.staticlet 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).structUnlockAsksLayer: 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) privatevar vaultLookvar body: someView { 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() } elseiflet look, VaultLook.raisesAsks {UnlockAskRaise(asks: asks, look: look) } elseiflet card = asks.card { paper(card) } #elseiflet 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 privatefunc paper(_ card: DeckCard) -> someView {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) {iflet 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 inlet picked = duration.minutes == asks.chosenPaperTypedButton(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 inPaperTypedButton(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.staticfunc landOnTheCard() { #if os(iOS) UIAccessibility.post(notification: .screenChanged, argument: nil) #endif }/// The card drawn by the face its id names. @ViewBuilder privatefunc face(_ card: DeckCard) -> someView {iflet 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)") } } }}