// A business app's account and its pages' model: who is signed in by phone// number, or the way to sign in, and everything the business's object// answered (`business.pages`).//// A hand-built Swift section, for the reason the vault's screens are: it holds// a credential, and a definition may say how a page looks but never where a// credential goes. The client is `BusinessClient`'s; this file draws Me (the// signed-in person and Sign out, or the sign-in row) and the number-and-code// sheet, and keeps no credential of its own.//// The model decides nothing about the business: `load` syncs the core's cache// (carrying the Keychain's credential) and reads the pages from it; an act is// posted as the row carried it (`business.act`), and its answer is already in// the cache, so the pages are read again with no network. A refusal is said// by the kit's line for its code; two are also acted on — `not_signed_in`// opens the sign-in sheet and takes the act once they are in, and// `credential_revoked` forgets the credential and reads the business as a// stranger again.importCottonKitimportSwiftUI/// Where the number-and-code sheet stands: the number, the code for the/// challenge the number was answered with, the name (only once that code is/// proved for a number with no account yet), or an ask another device approves.enumPhoneSignInPane: Equatable {case number, code(BusinessChallenge), asking/// NEXT-SIGNIN (owner, 28 Nov 2026): the code is proved and the number has no account; its name, then the same code.case name(BusinessChallenge)/// The account is set to be deleted: Keep my account or Leave it to be deleted (DELETE_ACCOUNT.md "(30 days)").case deleting(AccountSetToGo)}/// What the number-and-code sheet (`CustomerSheets`) draws and asks: a/// business app's account (`HomeCustomerModel`) and Cotton's sign-in to the/// owner's personal object (`PersonalObject`, opened by Backup) — one sheet.@MainActor protocolPhoneSignInModel: AnyObject, Observable {var asking: Bool { get set }var pane: PhoneSignInPane { get }var phone: String { get set }var code: String { get set }var name: String { get set }var signing: Bool { get }var signInRefusal: String? { get }/// A refusal goes as soon as the number or the code is typed again (store pass, 24 Nov 2026).func clearRefusal()/// The name the sheet's lines say: the business's, or the app's.var business: String { get }func askCode() asyncfunc confirm(_ challenge: BusinessChallenge) async/// The ways in beside a code (Cotton's own sign-in, never a business's):/// approve on another device, then a passkey (the owner's order, 17 Nov 2026).var offersOtherWays: Bool { get }/// Of those, a passkey: only where the app and the phone can do one (`PasskeyPlatform`).var offersPasskey: Bool { get }/// `personal.ask`'s card, and its last `personal.askPoll`.var askCard: JSONValue? { get }var askPolled: JSONValue? { get }func askAnother() asyncfunc cancelAsk()func passkey() async/// The 30 days (DELETE_ACCOUNT.md): keep the account and go on signing in, or leave it to be deleted.func keepAccount(_ setToGo: AccountSetToGo) asyncfunc leaveAccount(_ setToGo: AccountSetToGo) async}extensionPhoneSignInModel {func keepAccount(_ setToGo: AccountSetToGo) async {}func leaveAccount(_ setToGo: AccountSetToGo) async {}var offersOtherWays: Bool { false }var offersPasskey: Bool { false }var askCard: JSONValue? { nil }var askPolled: JSONValue? { nil }func askAnother() async {}func cancelAsk() {}func passkey() async {}}@MainActor @ObservablefinalclassHomeCustomerModel: PhoneSignInModel {typealiasPane = PhoneSignInPanelet client: BusinessClient/// The business's name, as its manifest says it: the refusal lines name it.let business: String/// The zone the rows' days and times are said in.privatelet zone: String/// Everything the object answered, as the cache holds it; nil before the/// first read.private(set) var pages: BusinessPages?/// Who is signed in; nil before the Keychain has been read or when nobody is.private(set) var session: BusinessSession?private(set) var read = false/// The pages have been read (or refused): until then the shell's ground/// stands alone.private(set) var pagesRead = false/// The act the object refused for want of a person, with its answers:/// taken once, after the sign-in.privatevar pending: (act: BusinessAct, answers: [String])?var asking = falsevar pane: Pane = .numbervar phone = ""var code = ""/// The name a number with no account gives, once its code is proved.var name = ""/// An act is with the business.private(set) var busy = false/// The sheet's own call (Send code, Sign in) is with the business: the/// sheet's arrow waits on it alone, never on the pages' reads.private(set) var signing = false/// What went wrong on a page or with an act, said over the page.private(set) var refusal: String?/// What went wrong with the sheet's own call, said on the sheet.private(set) var signInRefusal: String?init(client: BusinessClient, business: String, zone: String = TimeZone.current.identifier) {self.client = clientself.business = businessself.zone = zone }/// The rows of the view a tile's `key` stands for, in its order.func rows(_ key: String) -> [BusinessRow] { CustomerShellTiles.view(key, in: pages)?.view.rows ?? [] }/// The Keychain, then a sync carrying its credential, then the pages/// from the cache — read even when the sync was refused, so a phone/// with no network draws what it last held.func load() async {let client = client session = awaitTask.detached { client.session() }.value read = trueawait syncThenRead() }privatefunc syncThenRead() async {let client = clientlet zone = zone// Off the main thread: the client reads the Keychain.var refused = awaitSelf.refused { _ = tryawaitTask.detached { tryawait client.sync(zone: zone) }.value }iflet code = refused, BusinessRefusal.forgets(code) {// The client forgot it: the business is read as a stranger's. session = nil refused = awaitSelf.refused { _ = tryawaitTask.detached { tryawait client.sync(zone: zone) }.value } }let unread = await readPages() refusal = niliflet code = refused ?? unread { refusal = HomeCustomerRefusal.line(code: code, business: business) } pagesRead = true }/// The pages from the cache; the refusal's code when they would not read. @discardableResult privatefunc readPages() async -> String? {let client = clientlet zone = zonedo { pages = tryawaitTask.detached { tryawait client.pages(zone: zone) }.valuereturnnil } catchlet error asCottonCallError {return error.code } catch {return"refused" } }/// Post `act` with its picks' `answers`, then read the pages again from/// the cache the answer landed in.func take(_ act: BusinessAct, answers: [String]) async { busy = true refusal = nildefer { busy = false }let client = clientlet zone = zonelet refused = awaitSelf.refused { _ = tryawaitTask.detached { tryawait client.act(act, answers: answers, zone: zone) }.value }switch refused {casenil:iflet unread = await readPages() { refusal = HomeCustomerRefusal.line(code: unread, business: business) }caselet code? where code == BusinessRefusal.notSignedIn: ask() pending = (act, answers)caselet code? whereBusinessRefusal.forgets(code): session = nilawait syncThenRead() refusal = HomeCustomerRefusal.line(code: code, business: business)caselet code?: refusal = HomeCustomerRefusal.line(code: code, business: business) } }/// The sign-in sheet, from the number.func start() { pending = nil ask() }/// The sheet opens on an empty number, as Cotton's does/// (`PersonalObject.start`): one sheet, one way to open it.privatefunc ask() { pane = .number phone = "" code = "" name = "" signInRefusal = nil asking = true }func clearRefusal() { if signInRefusal != nil { signInRefusal = nil } }func askCode() async {let client = clientlet phone = phone.trimmingCharacters(in: .whitespaces)await sign {let challenge = tryawaitTask.detached { tryawait client.askCode(phone: phone) }.value// The code is the person's to type.self.code = ""self.pane = .code(challenge) } }/// Sign in with the code; then the business is synced for the new role,/// and the act that asked for a person is taken.func confirm(_ challenge: BusinessChallenge) async {let client = clientlet phone = phone.trimmingCharacters(in: .whitespaces)let code = code.trimmingCharacters(in: .whitespaces)let name = pane == .name(challenge) ? name.trimmingCharacters(in: .whitespaces) : ""await sign {switchtryawaitTask.detached(operation: { tryawait client.signIn(phone: phone, challenge: challenge, code: code, name: name.isEmpty ? nil : name, nameAfter: true) }).value {case .nameNeeded:self.name = ""self.pane = .name(challenge)case .signedIn(let session):self.session = sessionself.asking = false } }guard session != nil, !asking else { return }await syncThenRead()iflet pending {self.pending = nilawait take(pending.act, answers: pending.answers) } }func signOut() async { busy = truedefer { busy = false }let client = clientawaitTask.detached { await client.signOut() }.value session = nil pending = nilawait syncThenRead() }/// The sheet's own call, its refusal said on the sheet.privatefunc sign(_ act: @escaping () asyncthrows -> Void) async { signing = true signInRefusal = nildefer { signing = false }iflet code = awaitSelf.refused(act) { signInRefusal = HomeCustomerRefusal.line(code: code, business: business) } }/// The code of the refusal `call` ended in; nil when it was answered.privatestaticfunc refused(_ call: () asyncthrows -> Void) async -> String? {do {tryawait call()returnnil } catchlet error asCottonCallError {return error.code } catch {return"refused" } }}/// Me: the sign-in row while nobody is signed in, else who is signed in and/// Sign out. Sign-in is asked at the first act the object refuses for want/// of a person — a sheet over the page — or here, never on a page ahead of it.structCustomerPage: View {let model: HomeCustomerModel @Environment(\.theme) privatevar themevar body: someView { VStack(alignment: .leading, spacing: 10) {iflet session = model.session {Text(HomeCustomerWords.signedIn(session.phone ?? session.person.phone ?? "")) .font(theme.type.body(HomeCustomerKnobs.lineSize)) .foregroundStyle(theme.colors.ink.color) .accessibilityIdentifier("home-customer-signed-in")PaperTypedButton(HomeCustomerWords.signOut) { Task { await model.signOut() } } .disabled(model.busy) .accessibilityIdentifier("home-customer-sign-out") } elseif model.read {// An act row, chevron and press state, as every other act row.TypedRow(symbol: "phone", label: HomeCustomerWords.offer) { model.start() } .accessibilityIdentifier("home-customer-sign-in") }if !model.asking, let refusal = model.refusal { CustomerRefusalLine(refusal: refusal) } } }}structCustomerRefusalLine: View {let refusal: String @Environment(\.theme) privatevar themevar body: someView {Text(refusal) .font(theme.type.body(HomeCustomerKnobs.refusalSize)) .foregroundStyle(theme.colors.inkSecondary.color) .accessibilityIdentifier("home-customer-refusal") }}/// The number-and-code sheet, hung once over every page the model draws.structCustomerSheets<Model: PhoneSignInModel>: ViewModifier { @Bindable var model: Model @Environment(\.vaultLook) privatevar vaultLookfunc body(content: Content) -> someView { #if os(iOS)iflet look = vaultLook {// Inside Cotton Vault the sheet is drawn in Vault's look. content .overlay {if model.asking {// On Vault's ground itself, no slip around it.VaultSignInSheet(model: model, look: look) .transition(.move(edge: .bottom)) } } .animation(.easeOut(duration: 0.22), value: model.asking) } else { content.cottonCard(isPresented: $model.asking) { sheet } } #else content.cottonCard(isPresented: $model.asking) { sheet } #endif }/// The number, asked the same way in both of the number's panes.privatevar numberField: someView {PaperFormSection(HomeCustomerWords.numberHeading) {PaperTextField(HomeCustomerWords.numberHint, text: $model.phone) .keyboardType(.phonePad) .accessibilityIdentifier("home-customer-phone") } }privatevar sheet: someView { VStack(alignment: .leading, spacing: 20) {switch model.pane {case .number where model.offersOtherWays: numberField// The number, then a code by text; beside it, approval from a device already signed in (NEXT-SIGNIN// 3, owner, 28 Nov 2026: the ask's square code and six digits, `personal.ask`). A passkey stays where// one is offered.let typed = !model.phone.trimmingCharacters(in: .whitespaces).isEmpty HStack(spacing: 14) {PaperInkCircle(symbol: "arrow.right", label: HomeCustomerWords.send, isEnabled: typed, isBusy: model.signing) {Task { await model.askCode() } }PaperTypedButton(HomeCustomerWords.send) { Task { await model.askCode() } } .disabled(!typed || model.signing) } .accessibilityIdentifier("home-customer-send")PaperTypedButton(SignInWords.ask) { Task { await model.askAnother() } } .disabled(!typed || model.signing) .accessibilityIdentifier("signin-ask")if model.offersPasskey {PaperTypedButton(SignInWords.passkey) { Task { await model.passkey() } } .disabled(model.signing) .accessibilityIdentifier("signin-passkey") }case .number: numberFieldPaperInkCircle(symbol: "arrow.right", label: HomeCustomerWords.send, isEnabled: !model.phone.trimmingCharacters(in: .whitespaces).isEmpty, isBusy: model.signing) {Task { await model.askCode() } } .accessibilityIdentifier("home-customer-send")case .asking:iflet card = model.askCard {AskingCard(card: card, polled: model.askPolled, again: { Task { await model.askAnother() } }, sendCode: { model.cancelAsk(); Task { await model.askCode() } }, cancel: { model.cancelAsk() }) }case .deleting(let setToGo):Text(setToGo.words.heading).paperTitle(22).accessibilityAddTraits(.isHeader)Text(setToGo.words.line).fixedSize(horizontal: false, vertical: true)PaperTypedButton(setToGo.words.keep) { Task { await model.keepAccount(setToGo) } } .disabled(model.signing).accessibilityIdentifier("signin-keep-account")PaperTypedButton(setToGo.words.leave) { Task { await model.leaveAccount(setToGo) } } .disabled(model.signing).accessibilityIdentifier("signin-leave-account")case .code(let challenge):// Where the code went, first (store pass, 24 Nov 2026), the number masked by the core (NEXT-SIGNIN).iflet sentTo = challenge.sentTo, !sentTo.isEmpty {Text(verbatim: sentTo) .paperBody(ink: .pencil) .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("home-customer-sent-to") }PaperFormSection(HomeCustomerWords.codeHeading) {PaperTextField(HomeCustomerWords.codeHint, text: $model.code) .keyboardType(.numberPad) .accessibilityIdentifier("home-customer-code") }PaperInkCircle(label: HomeCustomerWords.confirm, isEnabled: HomeCustomerKnobs.codeReady(model.code), isBusy: model.signing) {Task { await model.confirm(challenge) } } .accessibilityIdentifier("home-customer-confirm")PaperTypedButton(HomeCustomerWords.sendAgain) { Task { await model.askCode() } } .disabled(model.signing) .accessibilityIdentifier("home-customer-send-again")case .name(let challenge):// Only for a number with no account, once its code is proved: never beside the code.PaperFormSection(HomeCustomerWords.nameHeading) {PaperTextField(HomeCustomerWords.nameHint(model.business), text: $model.name) .accessibilityIdentifier("home-customer-name") }PaperInkCircle(label: HomeCustomerWords.confirm, isEnabled: !model.name.trimmingCharacters(in: .whitespaces).isEmpty, isBusy: model.signing) {Task { await model.confirm(challenge) } } .accessibilityIdentifier("home-customer-name-confirm") }iflet refusal = model.signInRefusal { CustomerRefusalLine(refusal: refusal) } } .onChange(of: model.phone) { model.clearRefusal() } .onChange(of: model.code) { model.clearRefusal() } .padding(HomeCustomerKnobs.sheetInset) }}/// The sign-in's own words beside the board's (`signin` kit set).enumSignInWords {staticvar ask: String { ShellLines.line("signin", "ask") }staticvar passkey: String { ShellLines.line("signin", "passkey.sign_in") }staticvar passkeyCancelled: String { ShellLines.line("signin", "passkey.cancelled") }}/// The asking device's card (`personal.ask`, then each `personal.askPoll`):/// the core's heading, where to open the ask, then — once the other phone has/// opened it — the code large, to be typed there. Done (refused, expired,/// used, lost), it offers asking again or a code; while it waits, a code/// instead and Cancel.structAskingCard: View {let card: JSONValuelet polled: JSONValue?let again: () -> Voidlet sendCode: () -> Voidlet cancel: () -> Void @Environment(\.theme) privatevar theme/// A sentence naming Cotton, said in this app's own name.privatestaticfunc named(_ text: String?) -> String { ShellLines.said(text ?? "", as: ShellLines.speaker) }/// `personal.ask`'s square code, one string per row; nil from a core that draws none.staticfunc square(_ card: JSONValue) -> [String]? {guardlet rows = card["qr"]?["rows"]?.array?.compactMap(\.string), !rows.isEmpty else { returnnil }return rows }var body: someView {let done = polled?.flag("done") == truelet approved = polled?.text("state") == "approved" VStack(alignment: .leading, spacing: 14) {Text(Self.named(card.text("heading"))) .paperTitle(22)// The square code a signed-in phone scans, while nobody has opened the ask yet (NEXT-SIGNIN 3).if polled?.text("code") == nil, !done, let rows = AskingCard.square(card) {SquareCodeView(rows: rows) .frame(width: HomeCustomerKnobs.squareSide, height: HomeCustomerKnobs.squareSide) .accessibilityIdentifier("signin-ask-square") }iflet code = polled?.text("code") {Text(Self.named(polled?.text("line"))) .font(theme.type.body(HomeCustomerKnobs.lineSize)) .foregroundStyle(theme.colors.ink.color)Text(code) .font(theme.type.body(HomeCustomerKnobs.codeSize)) .monospacedDigit() .foregroundStyle(theme.colors.ink.color) .accessibilityIdentifier("signin-ask-code")Text(Self.named(polled?.text("check"))) .font(theme.type.body(HomeCustomerKnobs.refusalSize)) .foregroundStyle(theme.colors.inkSecondary.color) } else {Text(Self.named(polled?.text("line") ?? card.text("line"))) .font(theme.type.body(HomeCustomerKnobs.lineSize)) .foregroundStyle(done && !approved ? theme.colors.error.color : theme.colors.ink.color) .accessibilityIdentifier("signin-ask-state") }iflet left = polled.map({ $0.text("left") }) ?? card.text("left") {Text(left) .font(theme.type.body(HomeCustomerKnobs.refusalSize)) .foregroundStyle(theme.colors.inkSecondary.color) }if done && !approved {PaperTypedButton(polled?.text("again") ?? "", action: again) .accessibilityIdentifier("signin-ask-again")PaperTypedButton(polled?.text("sendCode") ?? card.text("sendCode") ?? "", action: sendCode) } elseif !approved {PaperTypedButton(card.text("sendCode") ?? "", action: sendCode)PaperTypedButton(card.text("cancel") ?? "", action: cancel) .accessibilityIdentifier("signin-ask-cancel") } } }}enumHomeCustomerWords {staticvar offer: String { ShellLines.line("board", "customer.offer") }staticvar numberHeading: String { ShellLines.line("board", "customer.number_heading") }staticvar numberHint: String { ShellLines.line("board", "customer.number_hint") }staticvar send: String { ShellLines.line("board", "customer.send") }staticvar codeHeading: String { ShellLines.line("board", "customer.code_heading") }staticvar codeHint: String { ShellLines.line("board", "customer.code_hint") }staticfunc sentTo(_ number: String) -> String { ShellLines.line("board", "customer.sent_to", ["number": number]) }staticvar sendAgain: String { ShellLines.line("board", "customer.send_again") }staticvar nameHeading: String { ShellLines.line("board", "customer.name_heading") }staticfunc nameHint(_ business: String) -> String { ShellLines.line("board", "customer.name_hint", ["name": business]) }staticvar confirm: String { ShellLines.line("board", "customer.confirm") }staticvar signOut: String { ShellLines.line("board", "customer.sign_out") }staticfunc signedIn(_ phone: String) -> String {let number = phone.hasPrefix("test:+") ? String(phone.dropFirst(5)) : phonereturnShellLines.line("board", "customer.signed_in", ["number": number]) }}/// What a person reads when a call is refused: the refusal's own line, by/// its code, from the kit's lines (`board` `customer.refusal.<code>`) — never/// the message that came with it (the object's or the core's, composed for a/// log), and never a sentence of the phone's own. A code the kit does not/// name reads as `refused`; `{name}` is the business's name.publicenumHomeCustomerRefusal {staticlet set = "board"staticfunc path(_ code: String) -> String { "customer.refusal." + code }publicstaticfunc line(code: String, business: String) -> String {let fills = ["name": business]returnShellLines.shipped(set, path(code), fills) ?? ShellLines.shipped(set, path("refused"), fills) ?? "" }}enumHomeCustomerKnobs {staticlet lineSize: CGFloat = 16staticlet refusalSize: CGFloat = 14staticlet sheetInset: CGFloat = 20staticlet codeLength = 6/// The matching code on the asking device: large, read across a table.staticlet codeSize: CGFloat = 38/// The ask's square code, large enough for another phone's camera across a table.staticlet squareSide: CGFloat = 200/// Whether Sign in can be pressed: the code is its six digits.staticfunc codeReady(_ code: String) -> Bool { code.trimmingCharacters(in: .whitespaces).count == codeLength }}