// 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. import CottonKit import SwiftUI /// 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. enum PhoneSignInPane: 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 protocol PhoneSignInModel: 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() async func 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() async func 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) async func leaveAccount(_ setToGo: AccountSetToGo) async } extension PhoneSignInModel { 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 @Observable final class HomeCustomerModel: PhoneSignInModel { typealias Pane = PhoneSignInPane let 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. private let 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. private var pending: (act: BusinessAct, answers: [String])? var asking = false var pane: Pane = .number var 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 = client self.business = business self.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 = await Task.detached { client.session() }.value read = true await syncThenRead() } private func syncThenRead() async { let client = client let zone = zone // Off the main thread: the client reads the Keychain. var refused = await Self.refused { _ = try await Task.detached { try await client.sync(zone: zone) }.value } if let code = refused, BusinessRefusal.forgets(code) { // The client forgot it: the business is read as a stranger's. session = nil refused = await Self.refused { _ = try await Task.detached { try await client.sync(zone: zone) }.value } } let unread = await readPages() refusal = nil if let 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 private func readPages() async -> String? { let client = client let zone = zone do { pages = try await Task.detached { try await client.pages(zone: zone) }.value return nil } catch let error as CottonCallError { 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 = nil defer { busy = false } let client = client let zone = zone let refused = await Self.refused { _ = try await Task.detached { try await client.act(act, answers: answers, zone: zone) }.value } switch refused { case nil: if let unread = await readPages() { refusal = HomeCustomerRefusal.line(code: unread, business: business) } case let code? where code == BusinessRefusal.notSignedIn: ask() pending = (act, answers) case let code? where BusinessRefusal.forgets(code): session = nil await syncThenRead() refusal = HomeCustomerRefusal.line(code: code, business: business) case let 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. private func ask() { pane = .number phone = "" code = "" name = "" signInRefusal = nil asking = true } func clearRefusal() { if signInRefusal != nil { signInRefusal = nil } } func askCode() async { let client = client let phone = phone.trimmingCharacters(in: .whitespaces) await sign { let challenge = try await Task.detached { try await 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 = client let phone = phone.trimmingCharacters(in: .whitespaces) let code = code.trimmingCharacters(in: .whitespaces) let name = pane == .name(challenge) ? name.trimmingCharacters(in: .whitespaces) : "" await sign { switch try await Task.detached(operation: { try await 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 = session self.asking = false } } guard session != nil, !asking else { return } await syncThenRead() if let pending { self.pending = nil await take(pending.act, answers: pending.answers) } } func signOut() async { busy = true defer { busy = false } let client = client await Task.detached { await client.signOut() }.value session = nil pending = nil await syncThenRead() } /// The sheet's own call, its refusal said on the sheet. private func sign(_ act: @escaping () async throws -> Void) async { signing = true signInRefusal = nil defer { signing = false } if let code = await Self.refused(act) { signInRefusal = HomeCustomerRefusal.line(code: code, business: business) } } /// The code of the refusal `call` ended in; nil when it was answered. private static func refused(_ call: () async throws -> Void) async -> String? { do { try await call() return nil } catch let error as CottonCallError { 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. struct CustomerPage: View { let model: HomeCustomerModel @Environment(\.theme) private var theme var body: some View { VStack(alignment: .leading, spacing: 10) { if let 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") } else if 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) } } } } struct CustomerRefusalLine: View { let refusal: String @Environment(\.theme) private var theme var body: some View { 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. struct CustomerSheets: ViewModifier { @Bindable var model: Model @Environment(\.vaultLook) private var vaultLook func body(content: Content) -> some View { #if os(iOS) if let 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. private var numberField: some View { PaperFormSection(HomeCustomerWords.numberHeading) { PaperTextField(HomeCustomerWords.numberHint, text: $model.phone) .keyboardType(.phonePad) .accessibilityIdentifier("home-customer-phone") } } private var sheet: some View { 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: numberField PaperInkCircle(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: if let 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). if let 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") } if let 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). enum SignInWords { static var ask: String { ShellLines.line("signin", "ask") } static var passkey: String { ShellLines.line("signin", "passkey.sign_in") } static var 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. struct AskingCard: View { let card: JSONValue let polled: JSONValue? let again: () -> Void let sendCode: () -> Void let cancel: () -> Void @Environment(\.theme) private var theme /// A sentence naming Cotton, said in this app's own name. private static func 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. static func square(_ card: JSONValue) -> [String]? { guard let rows = card["qr"]?["rows"]?.array?.compactMap(\.string), !rows.isEmpty else { return nil } return rows } var body: some View { let done = polled?.flag("done") == true let 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") } if let 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") } if let 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) } else if !approved { PaperTypedButton(card.text("sendCode") ?? "", action: sendCode) PaperTypedButton(card.text("cancel") ?? "", action: cancel) .accessibilityIdentifier("signin-ask-cancel") } } } } enum HomeCustomerWords { static var offer: String { ShellLines.line("board", "customer.offer") } static var numberHeading: String { ShellLines.line("board", "customer.number_heading") } static var numberHint: String { ShellLines.line("board", "customer.number_hint") } static var send: String { ShellLines.line("board", "customer.send") } static var codeHeading: String { ShellLines.line("board", "customer.code_heading") } static var codeHint: String { ShellLines.line("board", "customer.code_hint") } static func sentTo(_ number: String) -> String { ShellLines.line("board", "customer.sent_to", ["number": number]) } static var sendAgain: String { ShellLines.line("board", "customer.send_again") } static var nameHeading: String { ShellLines.line("board", "customer.name_heading") } static func nameHint(_ business: String) -> String { ShellLines.line("board", "customer.name_hint", ["name": business]) } static var confirm: String { ShellLines.line("board", "customer.confirm") } static var signOut: String { ShellLines.line("board", "customer.sign_out") } static func signedIn(_ phone: String) -> String { let number = phone.hasPrefix("test:+") ? String(phone.dropFirst(5)) : phone return ShellLines.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.`) — 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. public enum HomeCustomerRefusal { static let set = "board" static func path(_ code: String) -> String { "customer.refusal." + code } public static func line(code: String, business: String) -> String { let fills = ["name": business] return ShellLines.shipped(set, path(code), fills) ?? ShellLines.shipped(set, path("refused"), fills) ?? "" } } enum HomeCustomerKnobs { static let lineSize: CGFloat = 16 static let refusalSize: CGFloat = 14 static let sheetInset: CGFloat = 20 static let codeLength = 6 /// The matching code on the asking device: large, read across a table. static let codeSize: CGFloat = 38 /// The ask's square code, large enough for another phone's camera across a table. static let squareSide: CGFloat = 200 /// Whether Sign in can be pressed: the code is its six digits. static func codeReady(_ code: String) -> Bool { code.trimmingCharacters(in: .whitespaces).count == codeLength } }