Cotton code
598 lines · 31.7 KB · RustRaw
//! `shell.account {commit?}` — THE ACCOUNT CARD, ANSWERED WHOLE (owner, 11//! Nov 2026): this phone's sign-in and its sync are one card, the first to//! the LEFT of the app's first card (`AppKit::aside`), in every Cotton app.//! Signed out there is nothing to sync, so two cards would split one fact.//!//! ```json//! { "key": "account", "name": "Account", "line": "Synced 13:46",//!   "stand": "local|connecting|connected|backing_up|failed",//!   "card": { "title", "subtitle", "facts": [{ "id", "label", "said" }] },//!   "trouble": bool,//!   "actions": [<a tool act, as `tools.acts` answers one>], "tile"?,//!   "people"? }//! ```//!//! - `line` is the tile's glance, the way a view's tile says a count, in//!   the words people know from other apps (owner, 21 Nov 2026): "Signed//!   out", "Syncing your data…", "Not syncing", "Syncing…", "Synced just now",//!   "Synced at 9:53", and "3 changes waiting to sync" only once the oldest//!   has waited [`WAITING_SAID_AFTER_MS`].//!   `shell.fan` says the same line on the card it deals ([`tile_line`]).//! - `card` is the status face, whole in one screenshot, every line a kit//!   line (`boot`'s `account`): who is signed in (`subtitle`), then the app//!   and its build, the database (the first eight of its id) and the Worker's//!   host, the last sync and whether it finished, the rows waiting to send//!   and the rows on this phone, and the last error in words with its time,//!   or none. No number, no credential, no secret is on it.//!   Each fact carries its `id` (`app`, `database`, `synced`, `waiting`,//!   `here`, `sent_up`, `error`), so an app that keeps the facts behind an//!   About (Chat's You, 21 Nov 2026) knows them without reading their words.//! - `trouble` is true while this phone cannot reach the person's database://!   the sync loop stopped, a sign-in that did not finish, a backup that//!   stopped. A screen says so plainly; the facts say why.//! - `actions` are the account acts that stand now, run through `tools.act`//!   as every tool act is: Sign in signed out (and after a sign-in that//!   failed), Back up now and Sign out signed in or while rows go up.//!//! - `people`, while signed in: Your people, the person's connections and//!   Add a person (`crate::phone::your_people`, whose top says its shape).//!//! `commit` is the build's commit, which only the app knows; its first seven are said.use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::shell::client::ClientController;use cotton_core::kit::{AppKit, ACCOUNT_ACTS, ACCOUNT_CARD};use cotton_core::rules::shell_lines::resolve;use serde_json::{json, Value};const SET: &str = "boot";fn say(line: &str, fills: &[(&str, &str)]) -> String {    resolve(SET, &format!("account.{line}"), &[], fills).unwrap_or_default()}/// Whether this app deals the Account card: its kit names it aside, and the/// app backs up to a personal object.pub fn dealt(client: &ClientController) -> bool {    let named = AppKit::at(client.layout().root()).ok().flatten().is_some_and(|kit| kit.aside.iter().any(|card| card == ACCOUNT_CARD));    named && crate::phone::tool_acts::account_status(client)["backs_up"] == json!(true)}/// The tool whose views the Account card stands left of: the kit's first,/// the one the app opens on; none where the app deals no Account card.pub fn home(client: &ClientController) -> Option<String> {    if !dealt(client) {        return None;    }    AppKit::at(client.layout().root()).ok().flatten().and_then(|kit| kit.tools.first().cloned())}/// The card's name, as the fan says it.pub fn name() -> String {    say("name", &[])}/// Where this phone stands with its object, off the client alone.#[derive(Debug, Clone, Default, PartialEq, Eq)]struct Standing {    signed_in: bool,    backing_up: bool,    /// The copy is being connected or put in place now (`ClientController::moving`).    moving: bool,    /// A sign-in that did not finish: a connect refused, or a backup that failed.    failed: bool,    /// This phone's rows were going up and the backup stopped: its own    /// database stands whole, and Sign in goes on from where it stopped.    backup_stopped: bool,    /// The sync loop has stopped, and why.    stopped: Option<String>,    pending: u64,    /// When the oldest change waiting to sync was made (epoch ms).    oldest_pending_ms: Option<i64>,    /// Writes this phone itself has held for [`SEAL_STUCK_AFTER_MS`] or more because it cannot seal them (a    /// `seal_*` refusal: no key, a key that does not open, a table whose seal it does not know yet).    seal_stuck: u64,    /// Now, on the client's clock (epoch ms).    now_ms: i64,    /// When this phone last synced, and whether that pass caught up.    synced_at: Option<String>,    caught_up: bool,    /// How far the pass under way has come, when the object said (its rows in all, and those here): a catch-up says it.    done: Option<i64>,    total: Option<i64>,    /// The last pass did not reach the person's account (offline): [`unreached`].    unreached: bool,    /// When the pass on the wire began (epoch ms), while one runs.    pass_started_ms: Option<i64>,    /// The person's zone, the times said in it.    zone: String,    /// Rows on this phone.    rows: Option<u64>,    /// The server was put back to an earlier time and this copy is being made again from it (RESTORE 2): when it    /// was put back to, said in the person's zone (empty when the server did not say).    restoring: Option<String>,    /// The last pass met the account held still (RESTORE 2): changes wait and go by themselves.    frozen: bool,}fn standing(client: &ClientController) -> Standing {    standing_with(client, &client.sync_status_bare(false))}/// [`standing`] from a sync status already read (`sync.status` decides its own `seen` so).fn standing_with(client: &ClientController, sync: &Value) -> Standing {    let status = crate::phone::tool_acts::account_status(client);    let signed_in = status["signed_in"] == json!(true);    let backing_up = status["backing_up"] == json!(true);    let adopt_failed = client.adopting().is_some_and(|adopting| !adopting.running() && adopting.status().status == crate::phone::adopt::FAILED);    let pass = client.sync_progress().map(|progress| progress.state());    let 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();    let now_ms = client.clock().now().timestamp_millis();    let seal_stuck = client        .with_file(|file| cotton_store::outbox::waiting(file.driver).map_err(|error| error.to_string()))        .ok()        .filter(|waiting| {            crate::shell::client::oldest_seal_waiting_at(waiting)                .and_then(|at| cotton_store::protocol::js::parse_date_ms(&at))                .is_some_and(|at| now_ms.saturating_sub(at) >= SEAL_STUCK_AFTER_MS)        })        .map(|waiting| waiting.by_code.iter().filter(|(code, _)| code.starts_with("seal_")).map(|(_, n)| u64::try_from(*n).unwrap_or(0)).sum())        .unwrap_or(0);    let oldest_pending_ms = client        .with_file(|file| cotton_store::outbox::oldest_pending_at(file.driver).map_err(|error| error.to_string()))        .ok()        .flatten()        .and_then(|at| cotton_store::protocol::js::parse_date_ms(&at));    // A connect over a copy this phone was signed in to that did not take is    // said (the card's trouble, the stopped glance) once it is over; one    // simply running is not trouble (owner's iPhone, Chat build 14).    let kept = client.kept_signed_in().is_some() && !client.signed_in();    let refused = !client.moving() && (adopt_failed || client.connect_refused().is_some());    Standing {        signed_in,        backing_up,        moving: client.moving(),        failed: (!signed_in || kept) && !backing_up && refused,        backup_stopped: !signed_in && !backing_up && adopt_failed,        stopped: signed_in.then(|| sync["loop"]["stoppedReason"].as_str().map(str::to_string)).flatten()            .or_else(|| signed_in.then(|| client.signed_out_code()).flatten()),        // What the person changed, each record once (a note written offline is one, not its writes and their        // receipts: the iPhone walk, 26 Nov 2026); the outbox's count when that cannot be read.        // A change set aside because it did not read waits too (QUEUE BAD OP 2): never "Synced" over it.        pending: client            .with_file(|file| {                let queued = cotton_store::outbox::pending_things(file.driver).map_err(|error| error.to_string())?;                let set_aside = cotton_store::rejected::undecodable_count(file.driver).map_err(|error| error.to_string())?;                // A change kept in a copy set aside whole waits too (QUEUE BAD OP 4).                let kept = i64::try_from(cotton_client::copy_keep::kept_changes(client.layout(), file.workspace_id).len()).unwrap_or(i64::MAX);                Ok(queued + set_aside + kept)            })            .ok()            .and_then(|n| u64::try_from(n).ok())            .unwrap_or_else(|| sync["pending"].as_u64().unwrap_or(0)),        oldest_pending_ms,        seal_stuck,        now_ms,        synced_at: pass.as_ref().and_then(|pass| pass.synced_at.clone()).or_else(|| sync["lastPullAt"].as_str().map(str::to_string)),        // A first fill that still owes tables it left for the next pass (a kit's late tables: Post's mail) has not        // caught up, whatever the last pass said (FIRST SYNC STATES: Account said "Synced at 2:30 pm" over 280,000        // mail rows still to come). The pictures' rows, which every first fill leaves, are files' business, not sync's.        caught_up: pass.as_ref().is_none_or(|pass| pass.caught_up) && !first_fill_owes(client),        done: pass.as_ref().filter(|pass| !pass.caught_up).and_then(|pass| pass.done),        total: pass.as_ref().filter(|pass| !pass.caught_up).and_then(|pass| pass.total),        unreached: signed_in && unreached(sync),        pass_started_ms: sync["loop"]["passStartedAt"].as_str().and_then(cotton_store::protocol::js::parse_date_ms),        zone: client.time_zone().unwrap_or("UTC").to_string(),        rows,        restoring: pass.as_ref().and_then(|pass| pass.restoring.clone()).filter(|_| signed_in).map(|at| if at.is_empty() { at } else { dated_clock(client, &at) }),        frozen: signed_in && pass.as_ref().is_some_and(|pass| pass.frozen),    }}/// Whether this copy's first fill still owes a table but the pictures' (`first_fill_owes`): its first sync is not over.fn first_fill_owes(client: &ClientController) -> bool {    client.signed_in()        && client            .with_file(|file| cotton_client::transport::object::first_fill_owes(file.driver))            .ok()            .flatten()            .is_some_and(|owed| owed.iter().any(|table| table != "media"))}/// A day and its time of day, as About's facts say when ("22 Nov 6:54 pm").fn dated_clock(client: &ClientController, iso: &str) -> String {    let zone = client.time_zone().unwrap_or("UTC");    match cotton_core::kit::local_clock(iso, zone, "%-d %b") {        Some(day) => format!("{day} {}", clock(zone, iso)),        None => iso.to_string(),    }}/// The time of day [iso] was, in the person's zone, as the lists say a time today ("6:54 pm"): Account said "Synced/// at 18:54" under a list that said "6:55 pm" (the launch walk, 22 Nov 2026).fn clock(zone: &str, iso: &str) -> String {    let zoned = cotton_store::protocol::js::parse_date_ms(iso).and_then(|ms| {        cotton_core::cotton_rules::zoned_clock::zoned_parts(ms, zone)            .or_else(|_| cotton_core::cotton_rules::zoned_clock::zoned_parts(ms, "UTC"))            .ok()    });    match zoned {        Some(at) => cotton_core::records::page::DateWords::shipped().clock(at.hour, at.minute),        None => iso.to_string(),    }}/// Whether the loop's last pass did not reach the person's account (offline, or the server did not answer): it is/// climbing its backoff ladder, not stopped.fn unreached(sync: &Value) -> bool {    sync["loop"]["failures"].as_i64().is_some_and(|failures| failures > 0) && sync["loop"]["stoppedReason"].is_null()}/// The loop's last pass did not reach the person's account: what Sync now says then.pub(crate) fn unreached_now(client: &ClientController) -> bool {    unreached(&client.sync_status())}fn line_of(stand: &Standing) -> String {    seen_of(stand).1}/// Where sync stands, as one state a screen keys on and the line it says (SYNC SEEN, owner 25 Nov 2026: "when it is/// syncing, if we show some indicator that it is syncing, we will just wait"): `signed_out`, `stopped`, `backing_up`,/// `catching_up`, `waiting` (changes waiting to sync), `unreached` (Cotton out of reach; the loop keeps trying), `up_to_date`./// Never `up_to_date` while a change is unsent or a pass has not caught up.fn seen_of(stand: &Standing) -> (&'static str, String) {    if stand.backing_up {        return ("backing_up", say("tile.backing_up", &[]));    }    if stand.backup_stopped {        return ("stopped", say("tile.backup_stopped", &[]));    }    // The server was put back to an earlier time and the copy is made again from it (RESTORE 2): one plain line    // until the new copy has caught up.    if let Some(at) = &stand.restoring {        return ("catching_up", if at.is_empty() { say("tile.restored_undated", &[]) } else { say("tile.restored", &[("time", at)]) });    }    // Signed in, its copy being connected or made again: its data is on the    // way, said as the home says it.    if stand.signed_in && stand.moving {        return ("catching_up", resolve(SET, "home.bringing", &[], &[]).unwrap_or_default());    }    if stand.signed_in && stand.failed {        return ("stopped", say("tile.stopped", &[]));    }    if !stand.signed_in {        return if stand.failed { ("stopped", say("tile.stopped", &[])) } else { ("signed_out", say("tile.signed_out", &[])) };    }    if stand.stopped.is_some() {        return ("stopped", say("tile.stopped", &[]));    }    // The account held still for a moment (RESTORE 2, `account_frozen`): the passes keep trying quietly, nothing is    // parked, and the changes go by themselves once it answers.    if stand.frozen {        return ("waiting", say("tile.frozen", &[]));    }    // A WRITE THIS PHONE CANNOT SEAL, held for a day, is said as that, never as a change on its way (UNSENT SEEN,    // 26 Nov 2026: the owner's Comms carried 10 unsent changes for a day while every pass answered ok). The phone    // itself holds it, so no server and no pass would ever say it.    if stand.seal_stuck > 0 {        let line = if stand.seal_stuck == 1 { "tile.waiting_sealed_one" } else { "tile.waiting_sealed" };        return ("waiting", say(line, &[("n", &stand.seal_stuck.to_string())]));    }    // A change not yet sent is said only once it has waited a while    // (owner, 21 Nov 2026): a change made a moment ago is on its way. Out of    // reach (offline), it is not on its way, and is said at once: offline,    // Account said "Synced at 18:54" over a note that had not gone (the launch    // walk, 22 Nov 2026).    if stand.pending > 0 && (stand.unreached || stand.oldest_pending_ms.is_none_or(|at| stand.now_ms.saturating_sub(at) >= WAITING_SAID_AFTER_MS)) {        let line = if stand.pending == 1 { "tile.waiting_one" } else { "tile.waiting" };        return ("waiting", say(line, &[("n", &stand.pending.to_string())]));    }    // On its way (a change a moment old) or a pass not caught up: syncing, never "synced" (SYNC SEEN, 25 Nov 2026).    if !stand.caught_up || stand.pending > 0 {        let far = stand.done.zip(stand.total).filter(|(done, total)| *total > 0 && done < total);        return match far {            Some((done, total)) => ("catching_up", say("tile.syncing_of", &[("done", &cotton_core::data::count(done.max(0) as u64)), ("total", &cotton_core::data::count(total as u64))])),            None => ("catching_up", say("tile.syncing", &[])),        };    }    // Out of reach with nothing waiting: Cotton is not reached, and the loop keeps trying (SYNC SEEN); when it last    // synced is the Sync page's `last`.    if stand.unreached {        return ("unreached", say("tile.unreached", &[]));    }    match &stand.synced_at {        Some(at) if cotton_store::protocol::js::parse_date_ms(at).is_some_and(|ms| stand.now_ms.saturating_sub(ms) < JUST_NOW_MS) => ("up_to_date", say("tile.synced_now", &[])),        Some(at) => ("up_to_date", say("tile.synced", &[("time", &clock(&stand.zone, at))])),        None => ("up_to_date", say("tile.signed_in", &[])),    }}/// How long a write this phone cannot seal waits before Account says so (UNSENT SEEN): a day.pub const SEAL_STUCK_AFTER_MS: i64 = 24 * 60 * 60 * 1000;/// How long a pass must have run before a home says it is syncing: a pass that ends sooner never flickers the line.pub const SHOW_AFTER_MS: i64 = 1_000;/// What an app's home says of sync, on `shell.home` and `sync.status` alike (SYNC SEEN, owner 25 Nov 2026): the/// state [`seen_of`] decides and its line; `spoken`, the words TalkBack and VoiceOver say once when the state changes/// (a catch-up without its ticking count); `since`, when the pass under way began (epoch ms), with `showAfterMs`, so a/// shell keeps the line it had until a pass has run that long; `percent`, how far a counted catch-up has come.pub fn seen(client: &ClientController) -> Value {    seen_said(&standing(client))}/// [`seen`] from a sync status already read.pub fn seen_with(client: &ClientController, sync: &Value) -> Value {    seen_said(&standing_with(client, sync))}fn seen_said(stand: &Standing) -> Value {    let (state, line) = seen_of(stand);    let catching_up = state == "catching_up";    let spoken = if catching_up && stand.signed_in && !stand.moving { say("tile.syncing", &[]) } else { line.clone() };    let mut said = json!({ "state": state, "line": line, "spoken": spoken, "showAfterMs": SHOW_AFTER_MS });    if catching_up {        if let Some(since) = stand.pass_started_ms {            said["since"] = json!(since);        }        if let Some((done, total)) = stand.done.zip(stand.total).filter(|(done, total)| *total > 0 && done < total) {            said["percent"] = json!((done.max(0) * 100 / total).clamp(0, 99));        }    }    said}/// How long a change waits unsent before the glance says it waits.pub const WAITING_SAID_AFTER_MS: i64 = 2 * 60 * 1000;/// A sync this recent is "just now".pub const JUST_NOW_MS: i64 = 60 * 1000;/// The tile's glance: what `shell.fan` says on the Account card it deals.pub fn tile_line(client: &ClientController) -> String {    line_of(&standing(client))}/// A Sync page (Comms' You, you-grouped.html, 22 Nov 2026): `title`, how sync stands as the glance says it; `last`,/// when it last synced ("Last synced at 9:53"), said only when the title is not that sync itself (changes waiting,/// not syncing); `trouble`, whether this phone cannot reach the person's account now. Signed in means syncing, so/// there is nothing else to offer but Sync now.pub fn sync_said(client: &ClientController) -> Value {    let stand = standing(client);    let title = line_of(&stand);    let synced = [say("tile.synced_now", &[])]        .into_iter()        .chain(stand.synced_at.iter().flat_map(|at| ["tile.synced", "tile.last_synced"].map(|line| say(line, &[("time", &clock(&stand.zone, at))]))))        .any(|said| said == title);    let last = stand.synced_at.as_ref().filter(|_| !synced && stand.signed_in).map(|at| say("tile.last_synced", &[("time", &clock(&stand.zone, at))]));    // UNSENT HEAL (26 Nov 2026): changes that cannot be sent and will not go by themselves, each said with its act.    let stuck = crate::methods::sync::stuck_part(client);    json!({ "title": title, "last": last, "trouble": stand.signed_in && (stand.stopped.is_some() || stand.failed), "stuck": stuck })}pub fn call(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    answer(handle, request, true)}/// The card, with Your people asked of the server (`ask_people`, `shell.account`/// and the whole `shell.settings`), or without them, from this phone alone/// (`shell.settings.now`: no network, so the list draws on its first frame)./// Whenever the server answers them, how many there are is kept for the next/// quick answer ([`crate::methods::shell_settings::keep_later`]).pub(crate) fn answer(handle: &CottonHandle, request: &Value, ask_people: bool) -> Result<Value, MethodError> {    let client = handle.client();    let stand = standing(&client);    let home = crate::methods::shell_home::call(handle, &json!({}))?;    // Who: the owner's name off this phone's copy, never the number.    let who = if stand.signed_in || stand.backing_up {        let name = crate::methods::dispatch(handle, "read.you", &json!({})).ok().and_then(|you| you["name"].as_str().map(str::trim).filter(|name| !name.is_empty()).map(str::to_string));        match name {            Some(name) => say("who.named", &[("name", &name)]),            None => say("who.unnamed", &[]),        }    } else if stand.backup_stopped {        say("who.backup_stopped", &[])    } else {        say("who.signed_out", &[])    };    let version = handle.app_version();    let app = match request["commit"].as_str().map(str::trim).filter(|commit| !commit.is_empty()) {        Some(commit) => {            let short: String = commit.chars().take(7).collect();            say("app.stamped", &[("name", handle.app_name()), ("version", version), ("commit", &short)])        }        None => say("app.unstamped", &[("name", handle.app_name()), ("version", version)]),    };    let held = cotton_client::connection::ConnectionFile::at(client.layout().connection_json()).read();    let database = match held.as_ref().and_then(|mine| mine.workspace_id.as_deref().map(|id| (id, mine))) {        Some((id, mine)) => {            let short: String = id.chars().take(8).collect();            let host = mine.base_url.split("://").nth(1).unwrap_or(&mine.base_url).split('/').next().unwrap_or_default();            if mine.mode.has_server() && !host.is_empty() { say("database.held", &[("id", &short), ("host", host)]) } else { say("database.local", &[("id", &short)]) }        }        None => say("database.none", &[]),    };    let synced = match (&stand.synced_at, &stand.stopped) {        (None, _) => say("synced.never", &[]),        (Some(at), Some(why)) => say("synced.stopped", &[("time", &dated_clock(&client, at)), ("why", why)]),        (Some(at), None) => say(if stand.caught_up { "synced.finished" } else { "synced.unfinished" }, &[("time", &dated_clock(&client, at))]),    };    let rows = |n: u64| say("rows", &[("n", &n.to_string())]);    let error = match client.last_trouble() {        Some((words, at)) => say("error.at", &[("words", &words), ("time", &dated_clock(&client, &at))]),        None => say("error.none", &[]),    };    let sent_up = match (client.topping_up(), client.topped_up()) {        (true, _) => Some(say("sent_up.checking", &[])),        (false, Some((0, 0, at))) => Some(say("sent_up.none", &[("time", &dated_clock(&client, &at))])),        (false, Some((sent, 0, at))) => Some(say("sent_up.sent", &[("rows", &rows(sent)), ("time", &dated_clock(&client, &at))])),        (false, Some((sent, refused, at))) => Some(say("sent_up.refused", &[("rows", &rows(sent)), ("refused", &rows(refused)), ("time", &dated_clock(&client, &at))])),        (false, None) => None,    };    let fact = |label: &str, said: String| json!({"id": label, "label": say(&format!("labels.{label}"), &[]), "said": said});    let mut facts = vec![        fact("app", app),        fact("database", database),        fact("synced", synced),        fact("waiting", rows(stand.pending)),        // Said as a count under "Items on this phone" (shared Words: never rows).        fact("here", stand.rows.unwrap_or(0).to_string()),    ];    // What the last sign-in or Back up now sent the object that it lacked.    if let Some(said) = sent_up {        facts.push(fact("sent_up", said));    }    facts.push(fact("error", error));    let mut answer = json!({        "key": ACCOUNT_CARD,        "name": name(),        "line": line_of(&stand),        "stand": home["stand"],        "card": {"title": name(), "subtitle": who, "facts": facts},        "trouble": stand.stopped.is_some() || stand.failed || stand.backup_stopped,        "actions": [],    });    // Your people (14 Nov 2026): the one place connections live, read from the object while signed in.    if stand.signed_in && ask_people {        let people = crate::phone::your_people::part(&client);        if let Some(counts) = crate::methods::shell_settings::people_counts(&people) {            crate::methods::shell_settings::keep_later(&client, |later| later.people = Some(counts));        }        answer["people"] = people;    }    let (actions, tile) = acts(&client)?;    answer["actions"] = json!(actions);    if let Some(tile) = tile {        answer["tile"] = tile;    }    Ok(answer)}/// The account acts standing now, as `tools.acts` answers the Account/// card's view of the kit's one tool, dressed in the tool's tile.fn acts(client: &ClientController) -> Result<(Vec<Value>, Option<Value>), MethodError> {    let unreadable = |why: String| MethodError::new("unreadable", why);    let Some(kit) = AppKit::at(client.layout().root()).map_err(unreadable)? else { return Ok((Vec::new(), None)) };    let Some(tool) = kit.tools.first() else { return Ok((Vec::new(), None)) };    let mut table = None;    client        .read_rows("shell.account", &mut |ctx| {            let tools = cotton_tools::definitions::tool_definitions(ctx).map_err(|failure| failure.to_string())?.definitions;            table = tools.iter().find(|definition| &definition.id == tool).and_then(|definition| definition.tables.first().cloned());            Ok(Value::Null)        })        .map_err(unreadable)?;    let Some(table) = table else { return Ok((Vec::new(), None)) };    // An app whose tool draws no account card (Post: `personal/messages` draws no table of its own) has no account acts    // to add; Settings and Account still stand (POST Android walk, 26 Nov 2026: Storage, Help and About said "No tool    // draws this table" and showed nothing).    let Ok(answer) = crate::phone::tool_acts::acts(client, &json!({"table": table, "view": format!("{tool}/{ACCOUNT_CARD}")})) else {        return Ok((Vec::new(), None));    };    let actions = answer["actions"].as_array().into_iter().flatten().filter(|act| act["id"].as_str().is_some_and(|id| ACCOUNT_ACTS.contains(&id))).cloned().collect();    Ok((actions, answer.get("tile").filter(|tile| !tile.is_null()).cloned()))}#[cfg(test)]mod tests {    use super::*;    /// Signed in, last synced at 13:24 UTC, now 13:30 (invented times).    fn signed_in() -> Standing {        Standing {            signed_in: true,            now_ms: cotton_store::protocol::js::parse_date_ms("2026-11-22T13:30:00.000Z").unwrap(),            synced_at: Some("2026-11-22T13:24:00.000Z".into()),            caught_up: true,            zone: "UTC".into(),            ..Standing::default()        }    }    /// RULE (UNSENT SEEN, 26 Nov 2026): writes this phone has held for a day because it cannot seal them are said as that, with what to do, never as changes on their way or "synced".    #[test]    fn writes_the_phone_cannot_seal_for_a_day_are_said() {        let stuck = Standing { pending: 3, seal_stuck: 8, oldest_pending_ms: Some(signed_in().now_ms - SEAL_STUCK_AFTER_MS), ..signed_in() };        assert_eq!(seen_of(&stuck).0, "waiting");        assert_eq!(line_of(&stuck), "8 changes can't sync: this phone can't lock them yet. Unlock on this phone to send them.");        assert_eq!(line_of(&Standing { seal_stuck: 1, ..stuck.clone() }), "1 change can't sync: this phone can't lock it yet. Unlock on this phone to send it.");        // Unreached, the same: the phone holds them whatever the network does.        assert!(line_of(&Standing { unreached: true, ..stuck }).starts_with("8 changes can't sync"));    }    /// RULE: Account says a time as the lists do ("1:24 pm"), never a 24-hour "13:24" beside the list's "6:55 pm".    #[test]    fn the_glance_says_a_time_as_the_lists_do() {        assert_eq!(line_of(&signed_in()), "Synced at 1:24 pm");    }    /// RULE (the launch walk, 22 Nov 2026, offline; SYNC SEEN, 25 Nov 2026): out of reach, a change waiting is said    /// at once, and with nothing waiting the glance says Cotton is not reached, never that it is synced.    #[test]    fn out_of_reach_the_glance_says_what_waits_and_that_cotton_is_not_reached() {        let offline = Standing { unreached: true, ..signed_in() };        assert_eq!(seen_of(&offline).0, "unreached");        assert!(!line_of(&offline).is_empty() && !line_of(&offline).starts_with("Synced"));        let waiting = Standing { pending: 1, oldest_pending_ms: Some(offline.now_ms - 5_000), ..offline.clone() };        assert_eq!(line_of(&waiting), "1 change waiting to sync");        // In reach, a change made a moment ago is on its way: syncing, not yet said as waiting (owner, 21 Nov 2026),        // and never "synced" while it is unsent (SYNC SEEN).        let on_its_way = Standing { unreached: false, ..waiting };        assert_eq!(seen_of(&on_its_way), ("catching_up", "Syncing…".to_string()));    }    /// RULE (SYNC SEEN, owner 25 Nov 2026): a pass that has not caught up says it is syncing, with how far when the    /// object said; never up to date.    #[test]    fn a_pass_not_caught_up_says_syncing_and_how_far() {        let behind = Standing { caught_up: false, ..signed_in() };        assert_eq!(seen_of(&behind), ("catching_up", "Syncing…".to_string()));        let counted = Standing { done: Some(1_200), total: Some(3_108), ..behind.clone() };        assert_eq!(seen_of(&counted).0, "catching_up");        assert!(line_of(&counted).contains("1,200") && line_of(&counted).contains("3,108"), "{}", line_of(&counted));        let signed_out = Standing { signed_in: false, ..Standing::default() };        assert_eq!(seen_of(&signed_out), ("signed_out", "Signed out".to_string()));        assert_eq!(seen_of(&signed_in()).0, "up_to_date");    }    /// RULE (SYNC SEEN, one line for both phones, 26 Nov 2026): the seen answer carries what VoiceOver and TalkBack    /// say (a catch-up without its ticking count), when the pass began and how long a shell waits before saying it, and    /// how far a counted catch-up has come; a line that is not catching up carries no start.    #[test]    fn the_seen_answer_carries_its_spoken_words_its_start_and_how_far() {        let now = signed_in().now_ms;        let counted = Standing { caught_up: false, done: Some(1_200), total: Some(3_000), pass_started_ms: Some(now - 400), ..signed_in() };        let said = seen_said(&counted);        assert_eq!(said["state"], "catching_up");        assert_eq!(said["spoken"], "Syncing…");        assert_eq!(said["since"], json!(now - 400));        assert_eq!(said["showAfterMs"], json!(SHOW_AFTER_MS));        assert_eq!(said["percent"], json!(40));        let level = seen_said(&Standing { pass_started_ms: Some(now - 400), ..signed_in() });        assert_eq!(level["state"], "up_to_date");        assert_eq!(level["spoken"], level["line"]);        assert!(level.get("since").is_none());    }    /// RULE: the loop is out of reach while it climbs its ladder; a stopped loop is not "out of reach", and no loop    /// is not either.    #[test]    fn out_of_reach_is_a_failing_loop_that_has_not_stopped() {        assert!(unreached(&json!({"loop": {"failures": 2, "stoppedReason": null}})));        assert!(!unreached(&json!({"loop": {"failures": 0, "stoppedReason": null}})));        assert!(!unreached(&json!({"loop": {"failures": 3, "stoppedReason": "device_revoked"}})));        assert!(!unreached(&json!({"loop": null})));    }}