//! `shell.home {retry?, refusal?}` — Home, sign-in, backup and sync as one //! answer (boundary review move 5, 5 Nov 2026: the core answers what to show, //! a platform shell only draws). //! //! ```json //! { "gate": { "stage", "code", "refusal": "wall|banner|none", "erase", //! "beat", "words": {…}, "progress": {done, total}|null, //! "ways_out": [{ "id", "label", "weight": "ink|line|red" }] }, //! "stand": "local|connecting|connected|backing_up|failed", //! "backup": { "sent", "of", "line" }, //! "sync": { "state", "line", "line_state", "counter", "failures" }, //! "seen": { "state", "line" } (SYNC SEEN: the line an app's home says; `shell_account::seen`) //! "device": { "id", "copy_bytes", "rows", "caught_up_at" }, //! "acts": [{ "id", "label", "rank": "main|more|away", "red" }], //! "notices":[{ "id", "words", "kind" }] } //! ``` //! //! **The gate** is the boot's whole decision, in its order: a move that //! failed stops on its page; a refusal of this device paints first (a wall, //! or — over a copy that is open — a banner, or nothing when the copy stays //! writable); an open that failed is the fallback; a ladder running (and //! [`SETTLE_MS`] past its last step) is the move's page; a start that failed //! is its own fallback; a device of an app that founds no database (a //! business's) and holds none is at its door; a copy that is open is the app; //! anything else is //! a wait, which says its step past [`CEILING_MS`] and that it is taking long //! past [`STALL_MS`] of nothing moving. The words, the ways out and the wait's //! clock (`m:ss`) are the kit's lines (`boot.json`, `refusal.json`), filled //! here. //! //! **The core starts the copy itself**: there is no first-open choice //! (owner, 6 Nov 2026: Cotton is local-first, an app opens and works on its //! own database at once and Sign in merges it into the object later). An ask //! on a device that holds no database, of an app that founds one (genesis //! personal), starts it there and then (`workspace.startLocal`, named by the //! ask's `device_name`) — on a cold install, after a Remove from this phone //! and after an erase alike — unless a connect or an adopt is moving the copy. //! //! **The core opens the copy itself**: the first ask of a paired device //! starts the open on a thread of its own (never on the caller's, so the //! gate answers while a write-ahead log is recovered or a ladder runs), and //! says `{phase: home}` on the client stream when it ends. While the gate //! waits, the stream says `{phase: home, stage: tick}` once a second: the //! shell asks again on each, and that is the clock's cadence. `retry: true` //! begins a new wait and a new open. //! //! **The rest** is read only once the copy is open, never opening one: //! where this device stands with its personal object (the connection record, //! a connect in flight, an adopt's own status), the sync line and phase the //! banner used to derive, this device's copy, its acts in the order a card //! offers them, and Home's one line when it has earned one. use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use cotton_core::rules::shell_lines::resolve; use serde_json::{json, Value}; use crate::handle::CottonHandle; use crate::methods::MethodError; /// Past this, a wait says what it is waiting for. pub const CEILING_MS: i64 = 5_000; /// Past this with nothing moving, a wait says it is taking long. pub const STALL_MS: i64 = 10_000; /// The move's last step stays up this long once the ladder is done. pub const SETTLE_MS: i64 = 800; /// How often the stream ticks while the gate waits. pub const TICK_MS: u64 = 1_000; /// The client stream's phase for the gate's own events. pub const PHASE: &str = "home"; /// The refusals the app opens its own copy under, read-only. pub const READ_ONLY_REFUSALS: [&str; 2] = ["device_not_approved", "device_bad_signature"]; /// The refusals the app opens its own copy under and keeps writing in. pub const OPEN_REFUSALS: [&str; 1] = ["upgrade_required"]; /// Where one boot's wait stands, held by the handle for its life. #[derive(Debug, Default)] pub struct Watch { state: Mutex, /// The ticker thread is running. ticking: AtomicBool, /// The last answer was a wait: the ticker goes on. waiting: AtomicBool, /// A `personal.connect` or adopt is moving the copy: no open starts. connecting: AtomicBool, /// One start at a time: a second ask waits and finds the copy made. starting: Mutex<()>, /// How many times Home's page (`shell.today`) failed in a row with /// nothing read: its next ask waits longer. pub(crate) today_tries: std::sync::atomic::AtomicUsize, } #[derive(Debug, Default)] struct WatchState { began_ms: Option, beat_ms: Option, beats: u64, moved: String, open: OpenRun, done_seen_ms: Option, } #[derive(Debug, Default, Clone, PartialEq, Eq)] enum OpenRun { #[default] NotAsked, Running, Opened, Failed(String), } impl Watch { /// A `personal.connect` (or an adopt making its copy) runs. pub fn connecting(&self, running: bool) { self.connecting.store(running, Ordering::SeqCst); } fn lock(&self) -> std::sync::MutexGuard<'_, WatchState> { self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } } // ── The facts, and the answer over them ────────────────────────────────── /// Everything the answer is decided from — what [`call`] reads off the core, /// and what a test writes out by hand. #[derive(Debug, Clone, Default)] pub struct Facts { pub mac: bool, pub paired: bool, pub refusal: Option, pub open: Open, pub migration: Option, pub settling: bool, pub elapsed_ms: i64, pub quiet_ms: i64, pub beats: u64, /// This app founds its own database (genesis personal): a device holding /// none starts one, never stands at a door. pub founds: bool, /// Why the start this ask made did not make a database. pub start_failed: Option, /// This app backs up to a personal object: Sign in and Sign out are offered. pub signs_in: bool, /// This app syncs at all (Rigby never does). pub syncs: bool, pub stand: Stand, pub adopt: Option, /// Why the last connect of a sign-in did not take: `(code, words)`. pub connect_refused: Option<(String, String)>, /// Why the object stopped taking this phone's credential, while it stands. pub signed_out: Option, pub sync: Option, pub device: Option, /// This device's copy is the object's and its first pull has not ended: /// the person's things are on their way (`bringing`), never "nothing here". pub bringing: bool, /// How far that first pull has got, as the object counts it. pub loading: Loading, /// And the last pass failed (a 5xx, nothing reached): Cotton could not /// be reached just now, said in place of `bringing`'s words. pub unreached: bool, /// This device waits for another of the person's to let it in (GETTING-IN.md): the slim line's words, said in /// place of "Loading your data…", which stood for as long as it waited (walk on dev, 22 Nov 2026). pub waiting: Option, /// The app's name, for the sign-in lines' `{name}`. pub name: String, pub now_ms: i64, } /// How far a first pull has got: of the items the person's account holds /// for this app (`total`, as the object counted them when the pass began), /// how many this phone holds now (`done`), and whether files (photos, /// documents, audio) still wait to come after them. Megabytes are not said: /// the object knows how many items a pass carries, never their bytes before /// they are sent, so a size would be a guess. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct Loading { pub done: Option, pub total: Option, pub files_after: bool, } impl Loading { /// Whole percent, never 100 while the pass runs; none before the first page counts. pub fn percent(&self) -> Option { match (self.done, self.total) { (Some(done), Some(total)) if total > 0 => Some((done.min(total) * 100 / total).min(99)), _ => None, } } } /// THE ONE PROGRESS LINE every app draws while a first pull runs (owner, 21 /// Nov 2026): "Loading your data… 42%" with a thin bar, then gone. `percent` /// is null until the first page has counted; `then` names the files that /// come after the items. fn loading(facts: &Facts) -> Value { let percent = facts.loading.percent(); let fill = percent.map(|n| n.to_string()); let key = match (&fill, facts.loading.files_after) { (Some(_), true) => "home.loading.counted_then", (Some(_), false) => "home.loading.counted", (None, true) => "home.loading.then", (None, false) => "home.bringing", }; let fills: Vec<(&str, &str)> = fill.as_deref().map(|n| vec![("percent", n)]).unwrap_or_default(); json!({ "words": line("boot", key, facts.mac, &fills), "line": line("boot", "home.bringing", facts.mac, &[]), "percent": percent, "done": facts.loading.done, "total": facts.loading.total, "then": facts.loading.files_after.then(|| line("boot", "home.loading.files", facts.mac, &[])), }) } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Refusal { pub code: String, pub erase: bool, pub server_url: Option, } #[derive(Debug, Clone, Default, PartialEq, Eq)] pub enum Open { /// Not asked yet, or reading the file. #[default] Reading, /// Moving the last run's saved changes in first. Recovering, Open, Failed(String), /// The copy could not be moved to this build in place. NotMoved, } #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Migration { pub done: u32, pub total: u32, pub finished: bool, pub failed: Option, } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum Stand { #[default] Local, Connecting, Connected, BackingUp, Failed, } impl Stand { pub fn word(self) -> &'static str { match self { Stand::Local => "local", Stand::Connecting => "connecting", Stand::Connected => "connected", Stand::BackingUp => "backing_up", Stand::Failed => "failed", } } } #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Adopt { pub status: String, pub sent: u64, pub rows: u64, pub code: Option, pub line: Option, /// While it waits for the key: the key is being made on this, the /// person's first phone (`seal.status` `founds`, or no key minted yet), a /// moment with nothing to do. Otherwise the key is held elsewhere and the /// person must approve this phone or enter the recovery code. pub founding: bool, } #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct SyncFacts { /// No server: the database lives here alone. pub alone: bool, /// The core's line and its typed state (`rules::sync_status`). pub line: String, pub line_state: String, pub pending: u64, /// The loop's word, `None` while no loop runs. pub loop_state: Option, pub failures: u64, pub stopped: Option, pub last_pull_at: Option, } #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Device { pub id: Option, pub copy_bytes: Option, pub rows: Option, pub caught_up_at: Option, } /// One refusal's words and ways out (`refusal.json`). struct Said { kind: &'static str, retryable: bool, way_out: Option<&'static str>, } fn said_of(code: &str) -> Option { let (kind, retryable, way_out) = match code { "not_moved" => ("not_moved", true, None), "signup_closed" => ("signup_closed", false, Some("sign_out")), "upgrade_required" => ("upgrade", true, None), "rate_limited" => ("rate_limited", true, None), "snapshot_stalled" => ("stalled", true, None), "snapshot_hash_mismatch" => ("damaged", true, None), "no_workspace" => ("no_workspace", true, Some("sign_out")), "device_not_approved" => ("not_approved", false, None), "device_revoked" => ("revoked", false, None), "device_bad_signature" => ("bad_signature", false, None), "device_key_unreadable" | "no_device_key" => ("key_unreadable", false, Some("reset_key")), "device_clock" => ("clock", true, Some("sign_out")), "keychain_unavailable" => ("keychain_unavailable", true, None), "keychain_locked" => ("keychain_locked", true, None), "scope_refused" => ("scope", false, None), _ => return None, }; Some(Said { kind, retryable, way_out }) } /// Whether the app reads its own copy under `code` rather than being walled. pub fn reads_under(code: &str) -> bool { READ_ONLY_REFUSALS.contains(&code) || OPEN_REFUSALS.contains(&code) } /// `line` in the kit's words, the host's own (`.phone` / `.mac`) first. fn line(set: &str, key: &str, mac: bool, fills: &[(&str, &str)]) -> String { let host = if mac { "mac" } else { "phone" }; resolve(set, &format!("{key}.{host}"), &[], fills) .or_else(|| resolve(set, key, &[], fills)) .unwrap_or_default() } fn way(id: &str, label: String, weight: &str) -> Value { json!({"id": id, "label": label, "weight": weight}) } /// A sentence as an app named `name` says it: the word Cotton becomes the /// app's own name, so a business's customer never reads Cotton on a gate /// (19 Oct 2026); an app whose name starts with Cotton keeps /// it whole ("Cotton Books", never "Cotton Books Books"). pub fn said(text: &str, name: &str) -> String { if name.is_empty() || name == "Cotton" || !text.contains("Cotton") { return text.to_string(); } let rest = name.strip_prefix("Cotton").unwrap_or(""); let word = |c: Option| c.is_some_and(|c| c.is_alphanumeric() || c == '_'); let mut out = String::with_capacity(text.len()); let mut at = 0; while let Some(found) = text[at..].find("Cotton") { let start = at + found; let mut end = start + "Cotton".len(); if text[end..].starts_with("DB for Mac") { end += "DB for Mac".len(); } let bounded = !word(text[..start].chars().next_back()) && !word(text[end..].chars().next()); let named = !rest.is_empty() && text[end..].starts_with(rest); out.push_str(&text[at..start]); out.push_str(if bounded && !named { name } else { &text[start..end] }); at = end; } out.push_str(&text[at..]); out } /// Every string in `value`, said in the app's name. fn in_name(value: &mut Value, name: &str) { match value { Value::String(text) => *text = said(text, name), Value::Array(items) => items.iter_mut().for_each(|item| in_name(item, name)), Value::Object(fields) => fields.values_mut().for_each(|field| in_name(field, name)), _ => {} } } /// The whole answer, over `facts`. pub fn answer(facts: &Facts) -> Value { let mut gate = gate(facts); in_name(&mut gate["words"], &facts.name); in_name(&mut gate["ways_out"], &facts.name); let open = gate["stage"] == "open"; let sync = sync(facts); let mut answer = json!({ "gate": gate, "stand": facts.stand.word(), "backup": backup(facts), "sync": sync, "device": facts.device.as_ref().filter(|_| open).map(|device| json!({ "id": device.id, "copy_bytes": device.copy_bytes, "rows": device.rows, "caught_up_at": device.caught_up_at, })), // ONE plain state for every app's empty screen (launch-fast, 20 Nov // 2026): while a signed-in copy's first pull runs, an app with // nothing to show yet says its things are on their way rather than // that it has none. // And when the last pass failed, that Cotton could not be reached // just now (incident, 21 Nov 2026): `state` tells the two apart. "bringing": if open && facts.bringing { let mut bringing = loading(facts); bringing["state"] = json!(if facts.unreached { "unreached" } else { "bringing" }); if facts.unreached { let words = line("boot", "home.unreached", facts.mac, &[]); bringing["words"] = json!(words); bringing["line"] = json!(words); } if let Some(words) = facts.waiting.as_ref().filter(|_| !facts.unreached) { bringing["words"] = json!(words); bringing["line"] = json!(words); } bringing } else { Value::Null }, "acts": if open { acts(facts) } else { Vec::new() }, "notices": if open { notices(facts, &sync) } else { Vec::new() }, }); for part in ["backup", "acts", "notices"] { in_name(&mut answer[part], &facts.name); } answer } /// The stages a wait is drawn in: the ticker runs under them. pub fn waits(stage: &str) -> bool { matches!(stage, "wait" | "opening" | "stalled" | "moving") } fn gate(facts: &Facts) -> Value { let mac = facts.mac; let mut gate = json!({ "stage": "wait", "code": null, "refusal": "none", "erase": false, "beat": facts.beats, "words": {}, "progress": null, "ways_out": [], }); // A MOVE THAT FAILED stops on its own page with the mover's reason. if let Some(reason) = facts.migration.as_ref().and_then(|migration| migration.failed.clone()) { gate["stage"] = json!("move_failed"); gate["words"] = json!({ "title": line("boot", "screen.migration_failure_title", mac, &[]), "body": line("boot", "screen.migration_failure_body", mac, &[]), "detail": reason, }); gate["ways_out"] = json!([ way("retry", line("refusal", "actions.try_again", mac, &[]), "ink"), way("copy_details", line("boot", "screen.copy_error_details", mac, &[]), "line"), ]); return gate; } let opening = matches!(facts.open, Open::Reading | Open::Recovering); let refusal = facts.refusal.clone().or_else(|| (facts.open == Open::NotMoved).then(|| Refusal { code: "not_moved".into(), erase: false, server_url: None, })); if let Some(refusal) = &refusal { let open = facts.open == Open::Open; let placement = if refusal.erase || !open { "wall" } else if OPEN_REFUSALS.contains(&refusal.code.as_str()) { "none" } else if READ_ONLY_REFUSALS.contains(&refusal.code.as_str()) { "banner" } else { "wall" }; gate["code"] = json!(refusal.code); gate["refusal"] = json!(placement); gate["erase"] = json!(refusal.erase); // The wall is for a device with NO file, and the open says so: until // it answers, a refusal the copy is read under waits with the splash. let held = placement == "wall" && reads_under(&refusal.code) && !refusal.erase && facts.paired && opening; if placement == "wall" && !held { gate["stage"] = json!("refused"); refused(&mut gate, refusal, mac); return gate; } if placement != "wall" { refused(&mut gate, refusal, mac); } } // A START THAT FAILED: nothing was made, and Try again starts again. if let Some(reason) = &facts.start_failed { gate["stage"] = json!("failed"); gate["words"] = json!({ "title": line("boot", "screen.error_fallback_title", mac, &[]), "body": line("boot", "screen.start_error_failed", mac, &[]), "detail": reason, }); gate["ways_out"] = json!([way("retry", line("refusal", "actions.try_again", mac, &[]), "ink")]); return gate; } if let Open::Failed(message) = &facts.open { gate["stage"] = json!("failed"); gate["words"] = json!({ "title": line("boot", "screen.error_fallback_title", mac, &[]), "body": line("boot", "screen.error_fallback_body", mac, &[]), "detail": message, }); gate["ways_out"] = json!([way("retry", line("refusal", "actions.try_again", mac, &[]), "ink")]); return gate; } if let Some(migration) = facts.migration.as_ref().filter(|migration| !migration.finished || facts.settling) { gate["stage"] = json!("moving"); let mut words = json!({ "title": line("boot", "screen.wait_moving_title", mac, &[]), "body": line("boot", "screen.wait_moving_body", mac, &[]), "clock": clock(facts.elapsed_ms), }); if migration.done > 0 && migration.total > 0 { let percent = (u64::from(migration.done) * 100 / u64::from(migration.total)).to_string(); let (done, total) = (migration.done.to_string(), migration.total.to_string()); words["progress"] = json!(line("boot", "screen.move_step", mac, &[("done", &done), ("total", &total), ("percent", &percent)])); gate["progress"] = json!({"done": migration.done, "total": migration.total}); } gate["words"] = words; return gate; } // An app that founds no database of its own, on a device holding none: // its business's door (the shell draws the business's own shell). if !facts.paired && refusal.is_none() && !facts.founds { gate["stage"] = json!("door"); return gate; } if facts.open == Open::Open { gate["stage"] = json!("open"); return gate; } // The wait: the splash, then its step past the ceiling, then that it is // taking long — never a way out while a copy is opening. let (title, body) = match facts.open { Open::Recovering => ("screen.wait_opening_title", "screen.wait_recovering_body"), _ => ("screen.wait_opening_title", "screen.wait_opening_body"), }; let stalled = facts.quiet_ms >= STALL_MS; let slow = stalled || facts.elapsed_ms >= CEILING_MS; gate["stage"] = json!(if stalled { "stalled" } else if slow { "opening" } else { "wait" }); let mut words = json!({ "title": line("boot", title, mac, &[]), "body": line("boot", body, mac, &[]), "clock": clock(facts.elapsed_ms), }); if slow { words["usually"] = json!(line("boot", "screen.wait_usually_afew_seconds", mac, &[])); } if stalled { words["note"] = json!(line("boot", "screen.wait_stalled_still_opening", mac, &[])); } gate["words"] = words; gate } /// A refusal's words and ways out onto `gate`. fn refused(gate: &mut Value, refusal: &Refusal, mac: bool) { let Some(said) = said_of(&refusal.code) else { gate["words"] = json!({ "title": line("boot", "screen.error_fallback_title", mac, &[]), "body": line("boot", "screen.error_fallback_body", mac, &[]), "detail": refusal.code, }); gate["ways_out"] = json!([way("retry", line("refusal", "actions.try_again", mac, &[]), "ink")]); return; }; let kind = said.kind; let body = match refusal.server_url.as_deref().filter(|url| kind == "bad_signature" && !url.is_empty()) { Some(url) => line("refusal", "bad_signature.body_at", mac, &[("url", url)]), None => line("refusal", &format!("{kind}.body"), mac, &[]), }; gate["words"] = json!({ "reason": line("refusal", &format!("{kind}.reason"), mac, &[]), "title": line("refusal", &format!("{kind}.title"), mac, &[]), "body": body, }); let mut ways = Vec::new(); if said.retryable { ways.push(way("retry", line("refusal", "actions.try_again", mac, &[]), "ink")); } match said.way_out { Some("sign_out") => ways.push(way("sign_out", line("refusal", "actions.leave_this_database", mac, &[]), "red")), Some("reset_key") => ways.push(way("reset_key", line("refusal", "actions.start_over", mac, &[]), "red")), _ => {} } if refusal.code == "device_revoked" { ways.push(way("erase", line("refusal", "actions.erase", mac, &[]), "red")); } gate["ways_out"] = json!(ways); } /// The wait's `m:ss`, in the kit's words. pub fn clock(elapsed_ms: i64) -> String { let seconds = elapsed_ms.max(0) / 1_000; let (minutes, seconds) = ((seconds / 60).to_string(), format!("{:02}", seconds % 60)); resolve("boot", "home.clock", &[], &[("minutes", &minutes), ("seconds", &seconds)]).unwrap_or_default() } /// The loop's word, as one a screen keys on — what `SyncModel.phase` derived. fn phase(facts: &SyncFacts) -> &'static str { if facts.alone { return "alone"; } let Some(state) = facts.loop_state.as_deref() else { return "offline" }; if facts.stopped.is_some() { return "failed"; } match state { "syncing" if facts.failures > 0 => "waiting", "syncing" => "syncing", "waiting" => "waiting", "idle" => "idle", _ => "offline", } } fn sync(facts: &Facts) -> Value { match facts.sync.as_ref().filter(|_| facts.open == Open::Open) { None => json!({"state": "offline", "line": "", "line_state": null, "counter": 0, "failures": 0}), Some(sync) => json!({ "state": phase(sync), "line": sync.line, "line_state": sync.line_state, "counter": sync.pending, "failures": sync.failures, }), } } /// Whether the person's things are on their way to this phone's copy: it is /// the object's and its first pull has not ended, or a backup or restore /// connected it and its rows have not all gone up yet (waiting for this /// phone's key, or sending since). Meanwhile an empty deck says it is /// bringing them, never "nothing here" (`empty.bringing`). pub(crate) fn bringing(client: &crate::shell::client::ClientController) -> bool { if !client.signed_in() { return false; } client.adopting().is_some_and(|adopting| adopting.running()) || first_pull_running(client) } fn backup(facts: &Facts) -> Value { let name = facts.name.as_str(); let adopt = facts.adopt.as_ref(); let (sent, of) = adopt.map_or((0, 0), |adopt| (adopt.sent, adopt.rows)); let line = match facts.stand { Stand::BackingUp => { let (sent, rows) = (grouped(sent), grouped(of)); // The copy is connected and the rows wait for this phone's key, in // two cases worded apart (owner, 21 Nov 2026): a first phone's key // being made is a moment ("Setting up your account…"); a key held // on another phone needs the person ("One more step: …"). let line = match adopt { Some(adopt) if adopt.status == crate::phone::adopt::WAITING_KEY && adopt.founding => "object.backup.setting_up", Some(adopt) if adopt.status == crate::phone::adopt::WAITING_KEY => "object.backup.waiting_key", // Every row sent, the adopt waits for the new copy to pull the whole account down through the version // the object answered (`adopt::catch_up`): "1 of 1" said for minutes was no count of anything (KEPT // FOUR, Android walk 27 Nov 2026), so the line says it syncs, with no count. Some(adopt) if adopt.status == crate::phone::adopt::SENDING && adopt.sent >= adopt.rows => "object.backup.syncing", _ => "object.backup.backing_up", }; resolve("board", line, &[], &[("sent", &sent), ("rows", &rows)]) } Stand::Connecting => resolve("board", "object.backup.connecting", &[], &[]), // An adopt that failed says the object's line; a connect that was // refused says the kit's line for its code, or its own words when // the kit has none for it (never the general line alone: "could not // sign in" hid why for two hours on 11 Nov 2026). Stand::Failed => adopt.filter(|adopt| adopt.status == crate::phone::adopt::FAILED).map_or_else( || facts.connect_refused.as_ref().and_then(|(code, words)| { resolve("board", &format!("customer.refusal.{code}"), &[], &[("name", name)]) // An object that did not answer says so plainly, never its words. .or_else(|| cotton_client::transport::object::names_an_unanswered_object(code, words).then(|| refusal_line(cotton_client::transport::object::UNANSWERED, name)).flatten()) .or_else(|| refusal_line("refused", name).map(|general| if cotton_client::seal::names_a_seal_refusal(words) { general } else { format!("{general} ({words})") })) }), // A sealing refusal's own words are never said here (the log keeps them). |adopt| adopt.line.clone().filter(|words| !cotton_client::seal::names_a_seal_refusal(words)).or_else(|| refusal_line(adopt.code.as_deref().unwrap_or("refused"), name)), ), Stand::Connected if adopt.is_some_and(|adopt| adopt.status == crate::phone::adopt::DONE) => resolve("board", "object.backup.backed_up", &[], &[]), Stand::Connected => None, Stand::Local => facts.signs_in.then(|| resolve("board", "object.backup.body", &[], &[])).flatten(), }; json!({"sent": sent, "of": of, "line": line.unwrap_or_default()}) } /// A count with its thousands grouped: "1,300". fn grouped(n: u64) -> String { let digits = n.to_string(); let mut out = String::new(); for (index, digit) in digits.chars().enumerate() { if index > 0 && (digits.len() - index).is_multiple_of(3) { out.push(','); } out.push(digit); } out } /// A sign-in refusal in the kit's words (`customer.refusal.`), the /// general one for a code it has none for. fn refusal_line(code: &str, name: &str) -> Option { resolve("board", &format!("customer.refusal.{code}"), &[], &[("name", name)]) .or_else(|| resolve("board", "customer.refusal.refused", &[], &[("name", name)])) } fn act(id: &str, label: Option, rank: &str, red: bool) -> Value { json!({"id": id, "label": label.unwrap_or_default(), "rank": rank, "red": red}) } /// This device's acts, in the order its card offers them. fn acts(facts: &Facts) -> Vec { if !facts.signs_in { return Vec::new(); } let say = |key: &str| resolve("boot", &format!("home.acts.{key}"), &[], &[]); match facts.stand { Stand::Local => vec![act("sign_in", say("sign_in"), "main", false), act("erase", say("erase"), "away", true)], Stand::Connecting => Vec::new(), Stand::Connected => vec![ // Sync now is the one act (owner, 21 Nov 2026): signed in is syncing, never "backing up". act("sync_now", say("sync_now"), "main", false), act("sign_out", say("sign_out"), "more", false), act("erase", say("erase"), "away", true), ], Stand::BackingUp => vec![act("sign_out", resolve("board", "object.backup.stop", &[], &[]), "more", false)], Stand::Failed => vec![ act("try_again", say("try_again"), "main", false), act("sign_out", say("sign_out"), "more", false), act("erase", say("erase"), "away", true), ], } } /// Home's lines, each only when it has earned its place (what /// `HomeAttention` decided): everything here alone, a device not syncing, /// a refusal, a sign-in the object stopped taking, a backup just done. fn notices(facts: &Facts, sync: &Value) -> Vec { let mac = facts.mac; let mut notices = Vec::new(); if let Some(code) = &facts.signed_out { if let Some(words) = refusal_line(code, &facts.name) { notices.push(json!({"id": "signed_out", "words": words, "kind": "refusal"})); } } if facts.stand == Stand::Connected && facts.adopt.as_ref().is_some_and(|adopt| adopt.status == crate::phone::adopt::DONE) { notices.push(json!({"id": "backed_up", "words": resolve("board", "object.backup.backed_up", &[], &[]), "kind": "done"})); } let failures = sync["failures"].as_u64().unwrap_or(0); let not_synced = match sync["state"].as_str().unwrap_or("offline") { "alone" => { notices.push(json!({"id": "alone", "words": line("boot", "screen.home_no_mac_yet", mac, &[]), "kind": "quiet"})); false } "failed" => { let device = line("machines", "host.lower", mac, &[]); notices.push(json!({"id": "refused", "words": line("gate", "home_refused", mac, &[("device", &device)]), "kind": "amber"})); false } "waiting" => failures >= 2, "offline" => facts.sync.is_some(), _ => false, }; if not_synced { let since = facts.device.as_ref().and_then(|device| device.caught_up_at.as_deref()) .and_then(cotton_store::protocol::js::parse_date_ms); let words = match since { Some(at) => { let when = cotton_core::rules::sync_status::SyncWords::shipped().age(facts.now_ms.saturating_sub(at)); line("boot", "screen.home_not_synced_since", mac, &[("when", &when)]) } None => line("boot", "screen.home_not_synced_yet", mac, &[]), }; notices.push(json!({"id": "not_synced", "words": words, "kind": "amber"})); } notices } // ── Reading the facts off the core ─────────────────────────────────────── /// `shell.home`. pub fn call(handle: &CottonHandle, request: &Value) -> Result { let client = handle.client(); let watch = handle.home(); let now = client.clock().now().timestamp_millis(); if request.get("retry").and_then(Value::as_bool) == Some(true) { *watch.lock() = WatchState::default(); } let held = match request.get("refusal") { None | Some(Value::Null) => None, Some(Value::String(code)) => Some(Refusal { code: code.clone(), erase: false, server_url: None }), Some(_) => return Err(MethodError::new("bad_request", "refusal is the code of a refusal the app holds")), }; let device_name = match request.get("device_name") { None | Some(Value::Null) => None, Some(Value::String(name)) => Some(name.clone()), Some(_) => return Err(MethodError::new("bad_request", "device_name is the name this phone is filed under")), }; let (mut paired, unreadable) = match client.joined_workspace() { Ok(paired) => (paired, None), Err(reason) => (true, Some(reason)), }; let refusal = held.or_else(|| client.standing_refusal().map(|standing| Refusal { code: standing["code"].as_str().unwrap_or_default().to_string(), erase: standing["erase"].as_bool().unwrap_or(false), server_url: standing["serverUrl"].as_str().map(str::to_string), })); let founds = client.genesis() == cotton_core::genesis::Genesis::Personal; let moving = watch.connecting.load(Ordering::SeqCst) || client.adopting().is_some_and(|adopting| adopting.running()); let mut start_failed = None; if !paired && refusal.is_none() && founds && !moving { match start(handle, &watch, device_name.as_deref()) { Ok(()) => paired = true, Err(reason) => start_failed = Some(reason), } } let opens = paired && unreadable.is_none() && refusal.as_ref().is_none_or(|refusal| reads_under(&refusal.code) && !refusal.erase); if opens { ensure_open(handle, &watch); } let progress = handle.commands().progress(); let (open, migration, settling, elapsed_ms, quiet_ms, beats) = { let mut state = watch.lock(); let began = *state.began_ms.get_or_insert(now); let open = match (&unreadable, &state.open) { (Some(reason), _) => Open::Failed(reason.clone()), (None, OpenRun::Opened) => Open::Open, (None, OpenRun::Failed(reason)) => { let not_moved = read_workspace(handle).and_then(|workspace| cotton_client::bootstrap::not_moved::why(handle.layout(), &workspace)); if not_moved.is_some() { Open::NotMoved } else { Open::Failed(reason.clone()) } } (None, _) => match client.opening() { Some(crate::shell::client::OpenStep::Recovering) => Open::Recovering, _ => Open::Reading, }, }; let migration = progress.migration.as_ref().map(|step| { use cotton_client::replica::MigrationEvent; match step { MigrationEvent::Start { total, .. } => Migration { done: 0, total: total.to_owned() as u32, ..Migration::default() }, MigrationEvent::Step { index, total, .. } => Migration { done: index.to_owned() as u32, total: total.to_owned() as u32, ..Migration::default() }, MigrationEvent::Done { .. } => Migration { finished: true, ..Migration::default() }, MigrationEvent::Failed { message, .. } => Migration { failed: Some(message.clone()), ..Migration::default() }, } }); if migration.as_ref().is_some_and(|migration| migration.finished) { state.done_seen_ms.get_or_insert(now); } let settling = state.done_seen_ms.is_some_and(|seen| now - seen < SETTLE_MS); // What moved since the last answer restarts the stall bound. let moved = format!("{open:?}|{migration:?}"); if moved != state.moved { state.moved = moved; state.beat_ms = Some(now); state.beats += 1; } let beat = state.beat_ms.unwrap_or(began); (open, migration, settling, now - began, now - beat, state.beats) }; let signs_in = client.syncs() && client.genesis() == cotton_core::genesis::Genesis::Personal; let adopting = client.adopting().map(|adopting| (adopting.running(), adopting.status())); let adopt = adopting.as_ref().map(|(_, status)| Adopt { status: status.status.to_string(), sent: status.sent, rows: status.rows, code: status.code.clone(), line: status.line.clone(), founding: status.status == crate::phone::adopt::WAITING_KEY && crate::phone::seal::call_on(&client, "seal.status", &json!({})) .is_ok_and(|seal| seal["founds"] == json!(true) || seal["minted"] == json!(false)), }); let connect_refused = client.connect_refused(); let stand = match &adopting { Some((true, _)) => Stand::BackingUp, Some((false, status)) if status.status == crate::phone::adopt::FAILED => Stand::Failed, _ if watch.connecting.load(Ordering::SeqCst) => Stand::Connecting, _ if client.signed_in() => Stand::Connected, _ if connect_refused.is_some() => Stand::Failed, _ => Stand::Local, }; let opened = open == Open::Open; let status = opened.then(|| client.sync_status()); let sync = status.as_ref().filter(|status| status["connected"] == true).map(|status| SyncFacts { alone: status["state"] == crate::shell::client::NO_SERVER_YET || !client.syncs(), line: status["status"]["line"]["words"].as_str().unwrap_or_default().to_string(), line_state: status["status"]["line"]["state"].as_str().unwrap_or_default().to_string(), pending: status["pending"].as_u64().unwrap_or(0), loop_state: status["loop"]["state"].as_str().map(str::to_string), failures: status["loop"]["failures"].as_u64().unwrap_or(0), stopped: status["loop"]["stoppedReason"].as_str().map(str::to_string), last_pull_at: status["lastPullAt"].as_str().map(str::to_string), }); let device = opened.then(|| Device { id: client.self_device_id(), copy_bytes: read_workspace(handle).map(|workspace| copy_bytes(&handle.layout().replica(&workspace))), rows: client.with_file(|file| { file.driver.get("SELECT MAX(rowid) AS n FROM _writes", &[]).map_err(|error| error.to_string()) .map(|row| row.and_then(|row| row.int("n")).and_then(|n| u64::try_from(n).ok())) }).ok().flatten(), caught_up_at: sync.as_ref().and_then(|sync| sync.last_pull_at.clone()), }); // Where the copy stands (`phone::copy_standing`): its first pull under // way, and whether the last pass failed; or a backup still sending. let standing = if opened { crate::phone::copy_standing::of(&client) } else { crate::phone::copy_standing::Standing::Held }; let bringing = opened && (standing != crate::phone::copy_standing::Standing::Held || bringing(&client)); let unreached = standing == crate::phone::copy_standing::Standing::Unreached; // Counted only while a pass brings rows: a copy whose rows have all come and wait for the key has no pass to // count, and the last pass's figures would stand still on the line. let loading = if bringing && (first_pull_running(&client) || !crate::phone::copy_standing::waits_for_key(&client)) { let pass = client.sync_progress().map(|progress| progress.state()); let count = |n: Option| n.and_then(|n| u64::try_from(n).ok()); Loading { done: pass.as_ref().and_then(|pass| count(pass.done)), total: pass.as_ref().and_then(|pass| count(pass.total)), files_after: client .with_file(|file| { file.driver.get("SELECT 1 AS n FROM _media WHERE local_path IS NULL AND state = 'synced' LIMIT 1", &[]).map_err(|error| error.to_string()).map(|row| row.is_some()) }) .unwrap_or(false), } } else { Loading::default() }; let facts = Facts { mac: cfg!(target_os = "macos") && !cfg!(test), paired, refusal, open, migration, settling, elapsed_ms, quiet_ms, beats, founds, start_failed, signs_in, syncs: client.syncs(), stand, adopt, connect_refused, signed_out: client.signed_out_code(), sync, device, bringing, loading, unreached, waiting: if bringing { crate::phone::getting_in::waiting_line(&client) } else { None }, name: handle.app_name().to_string(), now_ms: now, }; let mut answer = answer(&facts); // SYNC SEEN (owner, 25 Nov 2026): the one quiet line each app's home says of sync, as Account decides it. if opened { answer["seen"] = crate::methods::shell_account::seen(&client); } let waiting = answer["gate"]["stage"].as_str().is_some_and(waits); watch.waiting.store(waiting, Ordering::SeqCst); if waiting { tick(&watch, handle.events()); } Ok(answer) } /// Whether this signed-in phone's copy is the object's and its first pull /// has not ended: the person's things are still on their way. pub fn first_pull_running(client: &crate::shell::client::ClientController) -> bool { client.signed_in() && client.with_file(|file| { file.driver .get("SELECT hlc_seen FROM _cursors WHERE author_device_id = ?", &[rusqlite::types::Value::Text(cotton_client::transport::object::CURSOR_KEY.to_string())]) .map_err(|error| error.to_string()) .map(|row| row.and_then(|row| row.text("hlc_seen").map(str::to_string))) }).is_ok_and(|held| { let cursors = held.into_iter().map(|held| (cotton_client::transport::object::CURSOR_KEY.to_string(), held)).collect(); cotton_client::transport::object::first_pull_underway(&cursors) }) } /// Start this device's own database, once: a second ask waits on the first /// and finds the copy made. fn start(handle: &CottonHandle, watch: &Watch, device_name: Option<&str>) -> Result<(), String> { let _one = watch.starting.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); if handle.client().joined_workspace().unwrap_or(true) { return Ok(()); } match crate::phone::commands::start_local(handle, &json!({"deviceName": device_name})) { Ok(_) => Ok(()), Err(refused) if refused.code == "already_started" => Ok(()), Err(refused) => Err(refused.message), } } /// The workspace `connection.json` names, if any. fn read_workspace(handle: &CottonHandle) -> Option { cotton_client::connection::read_connection(&handle.layout().connection_json()).ok().flatten().and_then(|stored| stored.workspace_id) } /// The copy's bytes on disk, its write-ahead log with it. fn copy_bytes(replica: &std::path::Path) -> u64 { let mut wal = replica.as_os_str().to_owned(); wal.push("-wal"); [replica.to_path_buf(), std::path::PathBuf::from(wal)].iter() .filter_map(|path| std::fs::metadata(path).ok()) .map(|meta| meta.len()) .sum() } /// Start the open, once a boot, on a thread of its own. fn ensure_open(handle: &CottonHandle, watch: &Arc) { if watch.connecting.load(Ordering::SeqCst) { return; } { let mut state = watch.lock(); if state.open != OpenRun::NotAsked { return; } state.open = OpenRun::Running; } let client = handle.client(); let watch = Arc::clone(watch); let events = Arc::clone(handle.events()); std::thread::Builder::new() .name("cotton-home-open".into()) .spawn(move || { let opened = client.open_copy(); watch.lock().open = match opened { Ok(()) => OpenRun::Opened, Err(reason) => OpenRun::Failed(reason), }; events.emit(crate::events::EventKind::Client, json!({"phase": PHASE, "stage": "opened"})); }) .map(drop) .unwrap_or_else(|error| tracing::warn!("the open's thread did not start: {error}")); } /// Say `{phase: home, stage: tick}` once a second while the gate waits. fn tick(watch: &Arc, events: &Arc) { if watch.ticking.swap(true, Ordering::SeqCst) { return; } let watch = Arc::clone(watch); let events = Arc::clone(events); std::thread::Builder::new() .name("cotton-home-tick".into()) .spawn(move || loop { std::thread::sleep(std::time::Duration::from_millis(TICK_MS)); if !watch.waiting.load(Ordering::SeqCst) { watch.ticking.store(false, Ordering::SeqCst); return; } events.emit(crate::events::EventKind::Client, json!({"phase": PHASE, "stage": "tick"})); }) .map(drop) .unwrap_or_else(|_| tracing::warn!("the gate's ticker did not start")); } #[cfg(test)] #[path = "shell_home_tests.rs"] mod tests;