// 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.importCottonKitimportSwiftUI@MainActor @ObservablefinalclassPersonalObject: 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.enumStand: Equatable {case localcase connectingcase connectedcase backingUpcase backupFailed }privatelet client: BusinessClientprivatelet 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.privatevar 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 = falseNotificationCenter.default.post(name: .personalSignInEnded, object: nil, userInfo: ["signedIn": signedIn]) } }/// A credential was kept while the sheet was up. @ObservationIgnored privatevar 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 = .numbervar phone = ""var code = ""var name = ""private(set) var signing = falseprivate(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 privatevar askPolling: Task<Void, Never>?/// 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 .connectedcase"connecting": return .connectingcase"backing_up": return .backingUpcase"failed": return .backupFaileddefault: 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?)? {iflet held = who { return held }guardlet session = client.session() else { returnnil }let held = (name: session.person.name, number: session.person.phone ?? session.phone) who = heldreturn held } @ObservationIgnored privatevar 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.enumCopyChange: 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 = clientself.core = coreself.business = nameself.server = server offersPasskey = PasskeyPlatform.offersHere(server: server) }/// The session a manifest asks for: one that names a personal object.staticfunc of(_ manifest: FlavourManifest?, core: any CottonCalling) -> PersonalObject? {guardlet manifest, let address = manifest.personalObject else { returnnil }returnPersonalObject(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 {iflet 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: truecase .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 = clientlet signedIn = awaitTask.detached { client.session() != nil }.valueguard signedIn else { returnawait 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 = clientlet signedIn = awaitTask.detached { client.session() != nil }.valueguard 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.privatefunc 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 {awaitChatSignOut.forgetDevice?() client.forget() #if os(iOS)SettingsRemembered.forget()ChatYouRows.forget() #endifSelf.door(open: false) refusal = nilawait 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()awaitChatSignOut.forgetDevice?() client.forget() #if os(iOS)SettingsRemembered.forget()ChatYouRows.forget() #endifSelf.door(open: false) refusal = nildo {tryawait 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() #endifSelf.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()awaitChatSignOut.forgetDevice?() client.forget() #if os(iOS)SettingsRemembered.forget()ChatYouRows.forget() #endififlet databaseId, !databaseId.isEmpty { dataKeys.forget(database: databaseId) } who = nilSelf.door(open: false) refusal = nilawait 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 {structForgot: 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).privatestaticfunc 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.environmentguardlet 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).guardcase .local = stand else { Log.write("walk sign-in: not signed out plainly; nothing done"); return }Log.write("walk sign-in: signing in") phone = numberawait askCode()guardcase .code(let challenge) = pane else { Log.write("walk sign-in: no code was asked"); return } code = givenawait confirm(challenge)// A number with no account is asked its name once the code is proved (NEXT-SIGNIN).ifcase .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 = clientlet phone = phone.trimmingCharacters(in: .whitespaces)Log.write("personal sign-in: asking a code")await sign {let challenge = tryawaitTask.detached { tryawait client.askCode(phone: phone) }.valueLog.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 = clientlet 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 = falseawait sign {do {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: signedIn = true } } catchlet setToGo asAccountSetToGo {// 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() }privatefunc signedInGoOn() async { signedInThisAsk = true asking = falseawait 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 = clientvar kept = falseawait sign { _ = tryawaitTask.detached { tryawait client.keep(setToGo) }.value kept = true }guard kept else { return } pane = .numberawait 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 = clientawait sign { tryawaitTask.detached { tryawait client.leave(setToGo) }.value }guard signInRefusal == nilelse { 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 = clientlet phone = phone.trimmingCharacters(in: .whitespaces)let deviceName = ThisPhone.deviceName() stopAsking() askPolled = nilLog.write("personal sign-in: asking another device")await sign {let vaultKey = awaitTask.detached { try? VaultKeyring().publicKey() }.valuelet card = tryawaitTask.detached { tryawait client.ask(phone: phone, deviceName: deviceName, vaultKey: vaultKey) }.valueself.askCard = cardself.pane = .askingself.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 = nilif pane == .asking { pane = .number } }privatefunc 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.privatefunc poll(_ card: JSONValue) {guardlet askId = card.text("askId") else { return }let every = max(1, card.decimal("pollSeconds") ?? 3)let client = client askPolling = Task { [weakself] inwhile !Task.isCancelled {try? awaitTask.sleep(for: .seconds(every))guardletself, !Task.isCancelled, self.asking, self.askCard?.text("askId") == askId else { return }let answer: JSONValuedo { answer = tryawaitTask.detached { tryawait client.askPoll(askId: askId) }.value } catch {self.refused(error)return }guard !Task.isCancelled, self.askCard?.text("askId") == askId else { return }self.askPolled = answerif answer.text("state") == "approved" {awaitself.approved(answer)return }if answer.flag("done") { return } } } }privatefunc approved(_ answer: JSONValue) async {let client = clientlet phone = phone.trimmingCharacters(in: .whitespaces)var kept = falseawait sign { _ = tryawaitTask.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 = falseawait sign {let begun = tryawaitTask.detached { tryawait client.passkeyBegin() }.valueguardlet challengeId = begun.text("challengeId"), let request = begun.text("requestJson") else {throwCottonCallError(code: "passkey_refused", message: "") }let response: Stringdo { response = tryawaitAccountPasskeySheet.signIn(requestJSON: request) } catchAccountPasskeyRefusal.cancelled {self.signInRefusal = SignInWords.passkeyCancelledreturn } catch {throwCottonCallError(code: "passkey_refused", message: "") }let session = tryawaitTask.detached { tryawait client.passkeySignIn(challengeId: challengeId, responseJSON: response) }.valueiflet phone = session.phone { self.phone = phone } signedIn = true }guard signedIn else { return }Log.write("personal sign-in: a passkey")awaitself.signedIn() #endif }/// A credential is kept: the sheet closes and the phone connects, as after a code.privatefunc 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 = nilawait connect(topUp: true) sayWhereTheSignInStands()await rereadUnlessBackingUp() }privatefunc 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.privatefunc 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.privatefunc connect(topUp: Bool = false) async {let client = client connecting = truedo {// 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" ? awaitNetworkUnmetered.shared.now() : nil _ = tryawaitTask.detached {tryawait client.connectPersonal(deviceName: deviceName, appVersion: appVersion, topUp: topUp, unmetered: unmetered) }.value refusal = nil connecting = falseSelf.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 = falseawait 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 = standawait 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`).privatefunc standLocal(signedOut: Bool = false) async { who = nildo {tryawait 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.privatefunc sign(_ act: @escaping () asyncthrows -> Void) async { signing = true signInRefusal = nildefer { signing = false }do {tryawait act() } catchlet error asCottonCallError {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`).enumRemoval: Equatable {case removecase erasevar 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.extensionNotification.Name {/// The sign-in sheet closed; `userInfo["signedIn"]` says whether a credential was kept.staticlet personalSignInEnded = Notification.Name("cotton.personal.signInEnded")}@MainActorenumPersonalSessionFlows {staticfunc run(_ request: RecordKeptFlow, personal: PersonalObject?) async -> Bool {guardlet personal else { returnfalse }switch request.flow {case .signIn: await personal.backUp()case .signOut: await personal.stopBackingUp()case .eraseThisDevice: personal.asksRemoval = .erasecase .leaveDatabase, .reportProblem, .vaultUnlock, .shareInk, .keepFilm, .removeFilmDownload, .keepEpisode, .removeEpisodeDownload, .keepBook, .removeBookDownload, .addBookFile, .keepSong, .removeSongDownload, .keepAlbum, .removeAlbumDownload: returnfalse }returntrue }}/// 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.structPersonalSheets: 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) privatevar vaultLookfunc body(content: Content) -> someView {iflet personal, let look = vaultLook { content.modifier(CustomerSheets(model: personal)) .overlay {iflet asked = personal.asksRemoval {VaultConfirmView(asking: VaultAsking( confirm: VaultConfirm(title: asked.title, body: asked.message, yes: asked.confirm, no: ""), tone: .danger) { yes in personal.asksRemoval = nilif yes { Task { await personal.removeFromThisPhone() } } }) .environment(\.vault, look) .accessibilityIdentifier("backup-remove-ask") } } } elseiflet personal { content.modifier(CustomerSheets(model: personal)) .confirmDecision( item: Bindable(personal).asksRemoval, title: \.title, message: \.message, confirmLabel: \.confirm, identifier: "backup-remove-ask" ) { _ inTask { await personal.removeFromThisPhone() } } } else { content } }}