// Cotton and the person's own personal object: one Durable Object on the // Worker, signed in to at the open host every person shares — phone number // and code, the Worker finding the number's database or making it on a first // sign-in, the credential and that database's id in the Keychain // (`BusinessClient`) — whose copy on this phone the decks read once it is // connected (`personal.connect`, `crates/cotton-ffi/src/phone/ // personal_object.rs`). // // COTTON WORKS BEFORE ANYONE SIGNS IN (owner, 1 Nov 2026). A fresh install // starts its own database on the phone at the gate's first ask (no app asks), // and this session decides nothing at launch but whether the phone holds a // credential: one that does connects as it always did (no network once its // copy is made); one that does not stands local, its own database the // authority because nothing else exists. Signing in is Backup's act // (Settings › Backup, `BackupRoute`), never a gate in front of the app: // // - local: no credential, or none the object takes. The phone's own // database (a fresh start, or the copy it kept when it stopped backing up) // is the one the decks read, and the Backup card offers the sign-in. // - connecting: a credential, its copy being connected. // - connected: the object is the authority; the phone applies writes // locally, queues them and the object re-applies them and wins. // - backing up: signed in, and the phone's own database holds rows a person // made, which no connect may overwrite: they are being brought into the // object (`personal.adopt`, on the core's own thread), the decks still // reading the phone's database until the object's copy is made. The // Backup card asks `shell.home` once a second while it is up; the core // says when the adopt ends (`client` `{phase: personal, stage: adopted | // adopt_failed}`), so the stand follows wherever the person is. // // WHERE THE PHONE STANDS IS THE CORE'S (`shell.home`'s `stand` and `backup`, // boundary review move 5): this session runs the acts — the sheet, the // Keychain's credential, the connect — and draws the stand it is told. // - backup failed: the object's line, the credential kept, the local // database whole; Try again resumes from the rows still unsent. // // Stop backing up forgets the credential and keeps the copy as the local // database (it is the person's data); Remove from this phone deletes it and // a fresh local database starts. A sync the object answers 401 stands the // phone local the same way, the refusal said on the Backup card. // // A hand-built Swift host, for `HomeCustomer`'s reason: it holds the way to a // credential, and a definition may say how a page looks but never where a // credential goes. import CottonKit import SwiftUI @MainActor @Observable final class PersonalObject: PhoneSignInModel { /// Where the session stands, as the core answers it (`shell.home`'s /// `stand`); an act of this phone's own in flight reads as connecting. enum Stand: Equatable { case local case connecting case connected case backingUp case backupFailed } private let client: BusinessClient private let core: any CottonCalling /// Where this phone keeps each database's data key; a deleted account's goes. @ObservationIgnored var dataKeys: any DataKeyKeeping = DataKeychain() /// The app's name, as its manifest says it: the sheet's lines name it. let business: String /// The server Backup signs in at, as the Cotton server card says it. let server: String /// The core's answer for Home, last read: the stand and the backup's line. private(set) var home: HomeAnswer? /// A connect of this phone's own is out. private var connecting = false /// The sign-in sheet is up. When it closes, `personalSignInEnded` says whether it signed in, so an app that asked /// something first (Sites' "Keep only on this phone") is told the sign-in was left. var asking = false { didSet { guard oldValue, !asking else { return } let signedIn = signedInThisAsk signedInThisAsk = false NotificationCenter.default.post(name: .personalSignInEnded, object: nil, userInfo: ["signedIn": signedIn]) } } /// A credential was kept while the sheet was up. @ObservationIgnored private var signedInThisAsk = false /// The one ask before this phone's copy is deleted (`PersonalSheets`), /// in the words of the act that raised it: the Backup card's red row /// (Remove from this phone) or Erase on this device's card. var asksRemoval: Removal? private(set) var pane: PhoneSignInPane = .number var phone = "" var code = "" var name = "" private(set) var signing = false private(set) var signInRefusal: String? /// A refusal goes as soon as the number or the code is typed again (store pass, 24 Nov 2026). func clearRefusal() { if signInRefusal != nil { signInRefusal = nil } } /// Cotton's own sign-in offers every way in, in the owner's order. var offersOtherWays: Bool { true } /// A passkey among them only where this app and phone can do one for the server it signs in at (`PasskeyPlatform`). let offersPasskey: Bool /// `personal.ask`'s card while another device is asked, and its last poll. private(set) var askCard: JSONValue? private(set) var askPolled: JSONValue? @ObservationIgnored private var askPolling: Task? /// Why a connect this phone asked for did not take, said on the Backup /// card: the call's own refusal. private(set) var refusal: String? var stand: Stand { if connecting { return .connecting } switch home?.stand { case "connected": return .connected case "connecting": return .connecting case "backing_up": return .backingUp case "failed": return .backupFailed default: return .local } } /// The backup's line, in the core's words (its count, its failure). var backupLine: String { home?.backup.line ?? "" } /// The adopt finished this launch: the Backup card says Backed up. var backedUp: Bool { home?.notices.contains { $0.id == "backed_up" } == true } /// Who this phone's Keychain says is signed in, read once: their number /// (the object's, else as typed at sign-in) and name. Chat's You draws /// them on its first frame, before `chat.profile` answers. var signedInWho: (name: String?, number: String?)? { if let held = who { return held } guard let session = client.session() else { return nil } let held = (name: session.person.name, number: session.person.phone ?? session.phone) who = held return held } @ObservationIgnored private var who: (name: String?, number: String?)? /// What changed under the boot: the copy it reads (connected, kept /// local), or none is left (removed from this phone) and a fresh local /// database starts. enum CopyChange: Equatable, Sendable { case changed, removed } /// The boot reads again: the database the decks read has changed. @ObservationIgnored var reread: @MainActor (CopyChange) async -> Void = { _ in } @ObservationIgnored var beforeRemove: @MainActor () -> Void = {} /// How a sign-in's stand is said wherever the person is (the root's /// toasts): the core's own line, as an error when the sign-in did not /// finish. The held card and the fan have no Backup card to read it on /// (signin-sticks, 11 Nov 2026: a phone that kept its credential and /// stayed signed out said nothing). @ObservationIgnored var say: @MainActor (_ line: String, _ failed: Bool) -> Void = { _, _ in } /// After Delete account, the core's heading and line, standing in a card over the app until Close (store pass, /// 24 Nov 2026: a passing toast was easy to miss; Android's DeletedCard). The root draws it (RootView). var deletedSaid: String? init(client: BusinessClient, core: any CottonCalling, name: String, server: String) { self.client = client self.core = core self.business = name self.server = server offersPasskey = PasskeyPlatform.offersHere(server: server) } /// The session a manifest asks for: one that names a personal object. static func of(_ manifest: FlavourManifest?, core: any CottonCalling) -> PersonalObject? { guard let manifest, let address = manifest.personalObject else { return nil } return PersonalObject(client: BusinessClient(core: core, address: address), core: core, name: manifest.name, server: address.server) } /// The boot's own read of the same answer. func take(_ answer: HomeAnswer) { home = answer } /// Ask the core where this phone stands now. func refresh() async { if let answer = try? await core.call(CottonMethod.shellHome, as: HomeAnswer.self) { home = answer } } /// Whether the phone's own database is the one the decks read: before /// backup, and while its rows go up. var isLocal: Bool { switch stand { case .local, .backingUp, .backupFailed: true case .connecting, .connected: false } } /// At launch, before the boot reads: a phone holding a credential /// connects its copy; any other is signed out, and a copy an object's /// person left is set aside for them, never drawn (one copy, one object: /// the core's `copy_aside`). No sheet, ever. func launch() async { let client = client let signedIn = await Task.detached { client.session() != nil }.value guard signedIn else { return await standLocal(signedOut: true) } await connect() } /// Backup's act: a phone holding a credential connects again; any other /// opens the number-and-code sheet. func backUp() async { let client = client let signedIn = await Task.detached { client.session() != nil }.value guard signedIn else { return start() } await connect(topUp: true) sayWhereTheSignInStands() await rereadUnlessBackingUp() } /// The core's line for a sign-in that is going up or did not finish /// (`shell.home`'s `stand` and `backup.line`): said, never silence. private func sayWhereTheSignInStands() { guard stand == .backingUp || stand == .backupFailed, !backupLine.isEmpty else { return } say(backupLine, stand == .backupFailed) } /// Sign out: the Keychain forgets the credential, the copy is set aside /// for this person's next sign-in, and the phone stands on a fresh local /// database of its own. func stopBackingUp() async { await ChatSignOut.forgetDevice?() client.forget() #if os(iOS) SettingsRemembered.forget() ChatYouRows.forget() #endif Self.door(open: false) refusal = nil await standLocal(signedOut: true) await reread(.changed) } /// Remove from this phone: the copy goes, and with nothing held the /// boot starts a fresh local database. func removeFromThisPhone() async { beforeRemove() await ChatSignOut.forgetDevice?() client.forget() #if os(iOS) SettingsRemembered.forget() ChatYouRows.forget() #endif Self.door(open: false) refusal = nil do { try await client.removeCopy() } catch { Log.write("personal: the copy could not be removed: \(error)") refusal = HomeCustomerRefusal.line(code: (error as? CottonCallError)?.code ?? "refused", business: business) } await refresh() await reread(.removed) } /// The object no longer takes this phone's credential (a sync answered /// 401): the Keychain forgets it and the copy is set aside until this /// person signs in again; the core says why (`shell.home`'s notice). func signedOut(code: String) async { Log.write("personal: signed out by the object: \(code)") client.forget() #if os(iOS) SettingsRemembered.forget() ChatYouRows.forget() #endif Self.door(open: false) await standLocal(signedOut: true) await reread(.changed) } /// The account was deleted (assets/design/shared/DELETE_ACCOUNT.md): here, by `account.delete`, whose answer names /// the database; the core has already forgotten the copy and stands on a fresh local database. This forgets what /// only the phone keeps of it, the sign-in and that database's data key (never this phone's own vault key, which /// is the device's), and opens the app afresh, the core's line said once. func accountDeleted(databaseId: String?, heading: String? = nil, line: String?) async { Log.write("personal: the account was deleted") beforeRemove() await ChatSignOut.forgetDevice?() client.forget() #if os(iOS) SettingsRemembered.forget() ChatYouRows.forget() #endif if let databaseId, !databaseId.isEmpty { dataKeys.forget(database: databaseId) } who = nil Self.door(open: false) refusal = nil await refresh() await reread(.removed) let said = [heading, line].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: "\n\n") if !said.isEmpty { deletedSaid = said } } /// Deleted from another phone or the website (a 410 `account_deleted`): the core forgets the copy /// (`account.forget`, never `personal.standLocal`: nothing is set aside), then as `accountDeleted`. func deletedElsewhere(line: String?) async { struct Forgot: Decodable { let databaseId: String? } let forgot = try? await core.call("account.forget", as: Forgot.self) await accountDeleted(databaseId: forgot?.databaseId, line: line) } /// The door opened or closed, said to whoever holds one of its own (Cotton chat). private static func door(open: Bool) { NotificationCenter.default.post(name: .cottonPersonalDoor, object: nil, userInfo: ["open": open]) } #if COTTON_DEV /// A Dev walk on a simulator nobody taps (Keep's measured walk; its simulators live in a device /// set XCUITest cannot reach): a synthetic number and the dev code from the launch environment /// (`SIMCTL_CHILD_WALK_COTTON_PHONE`, `SIMCTL_CHILD_WALK_COTTON_CODE`) sign in, exactly as typing them would. Only /// when signed out; the code is never logged. func walkSignIn() async { let environment = ProcessInfo.processInfo.environment guard let number = environment["WALK_COTTON_PHONE"], !number.isEmpty, let given = environment["WALK_COTTON_CODE"], !given.isEmpty else { return } // Only from plainly signed out: never over a copy being backed up or one whose backup failed (review LOW). guard case .local = stand else { Log.write("walk sign-in: not signed out plainly; nothing done"); return } Log.write("walk sign-in: signing in") phone = number await askCode() guard case .code(let challenge) = pane else { Log.write("walk sign-in: no code was asked"); return } code = given await confirm(challenge) // A number with no account is asked its name once the code is proved (NEXT-SIGNIN). if case .name(let proved) = pane { name = "Walk Member" await confirm(proved) } Log.write("walk sign-in: \(isLocal ? "not signed in" : "signed in")") } #endif /// The sign-in sheet, from an empty number. func start() { cancelAsk() pane = .number phone = "" code = "" name = "" signInRefusal = nil asking = true } func askCode() async { let client = client let phone = phone.trimmingCharacters(in: .whitespaces) Log.write("personal sign-in: asking a code") await sign { let challenge = try await Task.detached { try await client.askCode(phone: phone) }.value Log.write("personal sign-in: challenge \(challenge.challengeId)") // The code is the person's to type. self.code = "" self.pane = .code(challenge) } } /// Sign in with the code, then connect: the object's copy, or — with /// rows a person made here — the phone keeps its own database for adopt. func confirm(_ challenge: BusinessChallenge) async { let client = client let phone = phone.trimmingCharacters(in: .whitespaces) let code = code.trimmingCharacters(in: .whitespaces) // The name only on its own step, once the code is proved for a number with no account (NEXT-SIGNIN, 28 Nov 2026). let name = pane == .name(challenge) ? name.trimmingCharacters(in: .whitespaces) : "" var signedIn = false await sign { do { 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: signedIn = true } } catch let setToGo as AccountSetToGo { // Set to be deleted: nothing kept, nothing connected; the card asks Keep or Leave (DELETE_ACCOUNT.md). self.pane = .deleting(setToGo) } } guard signedIn else { return } await signedInGoOn() } private func signedInGoOn() async { signedInThisAsk = true asking = false await connect(topUp: true) sayWhereTheSignInStands() await rereadUnlessBackingUp() } /// Keep my account: `account.keep`, then the sign-in goes on exactly as any other. func keepAccount(_ setToGo: AccountSetToGo) async { let client = client var kept = false await sign { _ = try await Task.detached { try await client.keep(setToGo) }.value kept = true } guard kept else { return } pane = .number await signedInGoOn() } /// Leave it to be deleted: that sign-in ends at the server, nothing is kept, the card closes signed out. func leaveAccount(_ setToGo: AccountSetToGo) async { let client = client await sign { try await Task.detached { try await client.leave(setToGo) }.value } guard signInRefusal == nil else { return } pane = .number code = "" asking = false } /// Approve on another device (`personal.ask`): this phone names its /// vault key's public half, read with no prompt, so the one approval also /// lets it into the vault; then the poll, at the core's pace, until done. func askAnother() async { let client = client let phone = phone.trimmingCharacters(in: .whitespaces) let deviceName = ThisPhone.deviceName() stopAsking() askPolled = nil Log.write("personal sign-in: asking another device") await sign { let vaultKey = await Task.detached { try? VaultKeyring().publicKey() }.value let card = try await Task.detached { try await client.ask(phone: phone, deviceName: deviceName, vaultKey: vaultKey) }.value self.askCard = card self.pane = .asking self.poll(card) } } /// Back to the number: the ask is let lapse (the other phone's card goes when it does). func cancelAsk() { stopAsking() askCard = nil askPolled = nil if pane == .asking { pane = .number } } private func stopAsking() { askPolling?.cancel() askPolling = nil } /// `personal.askPoll` every `pollSeconds` while the sheet stands on this /// ask: approved, the credential (already claimed by the core with this /// device's key) is kept and the phone connects, as after a code. private func poll(_ card: JSONValue) { guard let askId = card.text("askId") else { return } let every = max(1, card.decimal("pollSeconds") ?? 3) let client = client askPolling = Task { [weak self] in while !Task.isCancelled { try? await Task.sleep(for: .seconds(every)) guard let self, !Task.isCancelled, self.asking, self.askCard?.text("askId") == askId else { return } let answer: JSONValue do { answer = try await Task.detached { try await client.askPoll(askId: askId) }.value } catch { self.refused(error) return } guard !Task.isCancelled, self.askCard?.text("askId") == askId else { return } self.askPolled = answer if answer.text("state") == "approved" { await self.approved(answer) return } if answer.flag("done") { return } } } } private func approved(_ answer: JSONValue) async { let client = client let phone = phone.trimmingCharacters(in: .whitespaces) var kept = false await sign { _ = try await Task.detached { try client.keep(granted: answer, phone: phone) }.value kept = true } guard kept else { return } Log.write("personal sign-in: approved by another device") await signedIn() } /// Sign in with a passkey: the system sheet, no number typed /// (`personal.passkeyBegin`, then `personal.passkeySignIn`). func passkey() async { #if os(iOS) let client = client cancelAsk() var signedIn = false await sign { let begun = try await Task.detached { try await client.passkeyBegin() }.value guard let challengeId = begun.text("challengeId"), let request = begun.text("requestJson") else { throw CottonCallError(code: "passkey_refused", message: "") } let response: String do { response = try await AccountPasskeySheet.signIn(requestJSON: request) } catch AccountPasskeyRefusal.cancelled { self.signInRefusal = SignInWords.passkeyCancelled return } catch { throw CottonCallError(code: "passkey_refused", message: "") } let session = try await Task.detached { try await client.passkeySignIn(challengeId: challengeId, responseJSON: response) }.value if let phone = session.phone { self.phone = phone } signedIn = true } guard signedIn else { return } Log.write("personal sign-in: a passkey") await self.signedIn() #endif } /// A credential is kept: the sheet closes and the phone connects, as after a code. private func signedIn() async { // Who is signed in is read again from the new sign-in: Settings' card kept the last account's number // after signing in with another (launch-ios, 23 Nov 2026). The remembered Settings list was for the other // state. who = nil #if os(iOS) SettingsRemembered.forget() ChatYouRows.forget() #endif stopAsking() signedInThisAsk = true asking = false askCard = nil askPolled = nil await connect(topUp: true) sayWhereTheSignInStands() await rereadUnlessBackingUp() } private func refused(_ error: Error) { let code = (error as? CottonCallError)?.code ?? "refused" Log.write("personal sign-in refused: \(code)") signInRefusal = HomeCustomerRefusal.line(code: code, business: business) } /// The boot reads again once a connect changed the database it reads; /// an adopt changes nothing yet, and `followAdopt` reads again once the /// object's copy is made. private func rereadUnlessBackingUp() async { guard !isBackingUp else { return } await reread(.changed) } /// `personal.connect`: connected, its rows going up for adopt, or local /// with the refusal's line, the copy kept. A sign-in and a Back up now /// say so (`topUp`): the core sends the object every row it lacks. private func connect(topUp: Bool = false) async { let client = client connecting = true do { // This phone as its copy's device list files it. let deviceName = ThisPhone.deviceName() let appVersion = ThisPhone.appVersion() // Cotton Data says whether the network is unmetered: Keep everything's whole copy starts only on Wi-Fi // (CONTRACT iPhone brief 14). The other apps say nothing, as before. let unmetered: Bool? = FlavourManifest.current?.flavour == "data" ? await NetworkUnmetered.shared.now() : nil _ = try await Task.detached { try await client.connectPersonal(deviceName: deviceName, appVersion: appVersion, topUp: topUp, unmetered: unmetered) }.value refusal = nil connecting = false Self.door(open: true) await refresh() } catch { let code = (error as? CottonCallError)?.code ?? "refused" Log.write("personal: connect refused: \(code)") refusal = HomeCustomerRefusal.line(code: code, business: business) connecting = false await standLocal() } } /// The adopt moved or ended: ask where this phone stands, and read the /// boot again once the object's copy is the one the decks read. func followAdopt() async { let was = stand await refresh() // A backup that stopped is said, and the fan dealt again: its Account // tile says where the phone stands now, never the Backing up it dealt. if was != .backupFailed, stand == .backupFailed { sayWhereTheSignInStands() await reread(.changed) } if was != .connected, stand == .connected { await reread(.changed) } } /// Whether the rows a person made are on their way up. var isBackingUp: Bool { stand == .backingUp } /// Whatever copy the phone holds stays as its local database and dials /// the object no more (`personal.standLocal`). private func standLocal(signedOut: Bool = false) async { who = nil do { try await client.standLocal(signedOut: signedOut) } catch { Log.write("personal: could not stand local: \(error)") } await refresh() } /// 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 } do { try await act() } catch let error as CottonCallError { Log.write("personal sign-in refused: \(error.code) \(error.message)") signInRefusal = HomeCustomerRefusal.line(code: error.code, business: business) } catch { Log.write("personal sign-in refused: \(error)") signInRefusal = HomeCustomerRefusal.line(code: "refused", business: business) } } } /// The act that asks before this phone's copy is deleted, each asking in its /// own kit lines: the Backup card's Remove from this phone, or Erase on this /// device's card (Home's sync card). Both delete the copy the same way /// (`PersonalObject.removeFromThisPhone`). enum Removal: Equatable { case remove case erase var title: String { ShellLines.line("board", self == .remove ? "object.backup.remove" : "customer.erase") } var message: String { ShellLines.line("board", self == .remove ? "object.backup.remove_ask" : "customer.erase_ask") } var confirm: String { ShellLines.line("board", self == .remove ? "object.backup.remove_confirm" : "customer.erase_confirm") } } /// This device's own Sign in, Sign out and Erase — the acts `device.json` /// offers on its card, Home's sync card (owner, 2 Nov 2026) — run as the /// Backup card runs them: Sign in is Back up (the number-and-code sheet, or a /// connect with a credential held), Sign out is Stop backing up (the copy /// stays as this phone's local database), Erase deletes the copy as Remove /// from this phone does, asked first in Erase's own words — a card's acts /// run at once, and this one cannot be undone. /// The root runs them wherever the card is opened (`\.nativeKeptFlow`); an /// app with no personal object runs none, and its card offers none. extension Notification.Name { /// The sign-in sheet closed; `userInfo["signedIn"]` says whether a credential was kept. static let personalSignInEnded = Notification.Name("cotton.personal.signInEnded") } @MainActor enum PersonalSessionFlows { static func run(_ request: RecordKeptFlow, personal: PersonalObject?) async -> Bool { guard let personal else { return false } switch request.flow { case .signIn: await personal.backUp() case .signOut: await personal.stopBackingUp() case .eraseThisDevice: personal.asksRemoval = .erase case .leaveDatabase, .reportProblem, .vaultUnlock, .shareInk, .keepFilm, .removeFilmDownload, .keepEpisode, .removeEpisodeDownload, .keepBook, .removeBookDownload, .addBookFile, .keepSong, .removeSongDownload, .keepAlbum, .removeAlbumDownload: return false } return true } } /// Over the whole stack: the number-and-code sheet Sign in raises from Home's /// card as Back up does from Settings › Backup, and the one ask before this /// phone's copy is removed. struct PersonalSheets: ViewModifier { let personal: PersonalObject? /// An app with a look of its own (Vault, Health, Notes, Story, Days) asks in it, never on a paper slip. @Environment(\.vaultLook) private var vaultLook func body(content: Content) -> some View { if let personal, let look = vaultLook { content.modifier(CustomerSheets(model: personal)) .overlay { if let asked = personal.asksRemoval { VaultConfirmView(asking: VaultAsking( confirm: VaultConfirm(title: asked.title, body: asked.message, yes: asked.confirm, no: ""), tone: .danger) { yes in personal.asksRemoval = nil if yes { Task { await personal.removeFromThisPhone() } } }) .environment(\.vault, look) .accessibilityIdentifier("backup-remove-ask") } } } else if let personal { content.modifier(CustomerSheets(model: personal)) .confirmDecision( item: Bindable(personal).asksRemoval, title: \.title, message: \.message, confirmLabel: \.confirm, identifier: "backup-remove-ask" ) { _ in Task { await personal.removeFromThisPhone() } } } else { content } } }