Cotton code
673 lines · 32.9 KB · RustRaw
//! `shell.settings {commit?}`, `shell.report {commit?}`, `shell.freeUp//! {expected}` — ONE SETTINGS SHAPE IN EVERY APP (owner, 21 Nov 2026), each//! app drawing it in its own look://!//! ```json//! { "account": <shell.account's answer>,//!   "storage": { "title", "line", "total_bytes",//!                "parts": [{ "id": "data|files|downloads|other", "label", "line"?, "bytes", "said" }],//!                "free_up": { "label", "bytes", "line", "ask"?, "ask_body"?, "confirm"? } },//!   "help":    { "title", "share": { "label", "line" }, "links": [{ "id": "privacy|support", "label", "url" }] },//!   "about":   { "title", "version", "facts": [{ "id", "label", "said" }] },//!   "sections": ["account", "storage", "help", "about"],//!   "rows":    [{ "id": "sync|claude|privacy|notifications|storage|help|about", "label", "line"?, "later"?, "group": "keep|behave|help" }],//!   "profile": { "signed_in", "name"?, "line"? },//!   "sync":    { "title", "last"?, "trouble" },//!   "pages":   { "storage_kept", "notifications_phone_line" },//!   "loading": <shell.home's `bringing`, or null> }//! ```//!//! - **Quick and whole** (owner, build 24: the card drew, the rows one to two//!   seconds later, in all four apps). `shell.settings.now` answers the same//!   shape from this phone alone, with no network and no walk of the app's//!   folder, for the list's first frame; `shell.settings` is the whole answer//!   (Your people asked of the server, the folder measured) and keeps what//!   took time ([`Later`]) for the next quick one, across launches. On a phone//!   that never had a whole answer the quick one marks Privacy and Storage//!   `later` (no line), leaves out `storage` and `account.people`; the phone//!   draws the row at its full height and the whole answer fills it in place.//!//! - **Rows** are Settings' top level as Comms' You draws it (23 Nov 2026)://!   under the profile card, each row saying how it stands and opening its//!   own page, a gap where `group` changes. Which stand is [`row_ids`]; the//!   app's own rows (Words' look and type, Days' calendar, Story's text//!   size) stand above them, drawn by the app (assets/design/shared/DECISIONS.md//!   "Settings"). `notifications` in the request is whether the phone lets//!   the app notify, which only the phone knows.//!//! - **Account** is the Account card's answer whole (name, Sync now, Sign//!   out, Your people); its internal facts (database, rows, the last error)//!   are said only under About.//! - **Storage** is what this app keeps on this phone, in a person's words://!   Your data (the database file and its log), Photos and files, Downloads//!   (films, books, songs, audio kept for offline; only in an app that keeps//!   them, Books, Music, Cinemas, Podcasts or the all-in-one app: elsewhere a//!   sound or a film a person attached is one of their files, and Words,//!   Days or Story never shows a Downloads row) and Other (thumbnails,//!   caches, the search index: everything else in the app's folder). Free up//!   space takes only files the person's account already holds (`_media`//!   state `synced`), never one kept for offline (pinned), one this phone//!   made and has not given to the account, or a thumbnail; each comes back//!   when it is opened. Its amount is said before it is asked.//! - **Help and feedback** offers Share a report: `shell.report` answers the//!   text, which the phone SHOWS the person whole before its share sheet//!   sends it. It holds the app's version, the phone's platform, how sync//!   stands, the storage figures and recent errors, and NOTHING personal: no//!   titles, names, numbers or message text (errors pass [`impersonal`]).use std::path::Path;use serde_json::{json, Value};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::shell::client::ClientController;use cotton_core::rules::shell_lines::resolve;const SET: &str = "settings";/// Cotton's public site: the privacy policy and the help page every app links to.pub const SITE: &str = "https://cottondb.com";fn say(key: &str, fills: &[(&str, &str)]) -> String {    resolve(SET, key, &[], fills).unwrap_or_default()}/// Bytes as a person reads them: "0.4 MB", "12 MB", "1.3 GB".pub fn size_said(bytes: u64) -> String {    const MB: f64 = 1_000_000.0;    let mb = bytes as f64 / MB;    if bytes > 0 && mb < 0.1 {        return say("sizes.small", &[]);    }    if mb >= 1000.0 {        let gb = mb / 1000.0;        let n = if gb < 10.0 { format!("{:.1}", gb) } else { format!("{:.0}", gb) };        return say("sizes.gigabytes", &[("n", &n)]);    }    let n = if mb < 10.0 { format!("{:.1}", mb) } else { format!("{:.0}", mb) };    say("sizes.megabytes", &[("n", n.trim_end_matches(".0"))])}/// What this app keeps on this phone, by the four parts a person knows.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]pub struct Kept {    pub data: u64,    pub files: u64,    pub downloads: u64,    pub other: u64,    /// Of `files` and `downloads`, what Free up space may take.    pub freeable: u64,    /// Whether this app keeps downloads at all: Storage shows the Downloads    /// part only where it does (owner's Words walk, 22 Nov 2026).    pub keeps_downloads: bool,}impl Kept {    pub fn total(&self) -> u64 {        self.data + self.files + self.downloads + self.other    }    /// The parts a person reads, in order: Downloads only in an app that keeps them.    pub fn parts(&self) -> Vec<(&'static str, u64)> {        let mut parts = vec![("data", self.data), ("files", self.files)];        if self.keeps_downloads {            parts.push(("downloads", self.downloads));        }        parts.push(("other", self.other));        parts    }}/// Whether an app of kit `kit` keeps downloads: one of the download kits, or/// the all-in-one app (no kit), which holds them all.fn keeps_downloads(kit: Option<&str>) -> bool {    kit.is_none_or(|kit| DOWNLOAD_KITS.contains(&kit))}/// The kits whose files are what the person keeps for offline.const DOWNLOAD_KITS: [&str; 3] = ["books", "music", "cinemas"];/// Whether a file of `content_type` is a download (a film, a book, a song),/// in an app of kit `kit`. Never in an app that keeps no downloads.fn a_download(content_type: &str, kit: Option<&str>) -> bool {    if !keeps_downloads(kit) {        return false;    }    kit.is_some_and(|kit| DOWNLOAD_KITS.contains(&kit))        || content_type.starts_with("audio/")        || content_type.starts_with("video/")        || content_type == "application/epub+zip"}/// What Free up space may take: an original or display file here, already/// in the person's account, not kept for offline, not one this phone made.pub const FREEABLE: &str = "local_path IS NOT NULL AND state = 'synced' AND pinned = 0 AND captured_here = 0 AND tier IN ('original','display')";/// Every file under `dir`, summed; a folder that cannot be read counts nothing.fn folder_bytes(dir: &Path) -> u64 {    let Ok(entries) = std::fs::read_dir(dir) else { return 0 };    entries        .filter_map(Result::ok)        .map(|entry| match entry.file_type() {            Ok(kind) if kind.is_dir() => folder_bytes(&entry.path()),            Ok(kind) if kind.is_file() => entry.metadata().map(|meta| meta.len()).unwrap_or(0),            _ => 0,        })        .sum()}/// Measure what this app keeps: the database file and its log, the files the/// ledger names here, and the rest of the app's folder as Other.pub fn kept(client: &ClientController) -> Kept {    let kit = cotton_core::kit::AppKit::at(client.layout().root()).ok().flatten().map(|kit| kit.id);    let database = client.current_database().ok();    let data = database.as_deref().map_or(0, |database| {        let replica = client.layout().replica(database);        let mut wal = replica.as_os_str().to_owned();        wal.push("-wal");        [replica.clone(), std::path::PathBuf::from(wal)].iter().filter_map(|path| std::fs::metadata(path).ok()).map(|meta| meta.len()).sum()    });    let mut out = Kept { data, keeps_downloads: keeps_downloads(kit.as_deref()), ..Kept::default() };    let _ = client.with_file(|file| {        let sql = format!(            "SELECT content_type, COALESCE(tier, '') AS tier, SUM(size_bytes) AS bytes, SUM(CASE WHEN {FREEABLE} THEN size_bytes ELSE 0 END) AS free \               FROM _media WHERE local_path IS NOT NULL AND state <> 'delete_pending' GROUP BY content_type, tier"        );        for row in file.driver.all(&sql, &[]).map_err(|error| error.to_string())? {            let bytes = u64::try_from(row.int("bytes").unwrap_or(0)).unwrap_or(0);            let free = u64::try_from(row.int("free").unwrap_or(0)).unwrap_or(0);            let tier = row.text("tier").unwrap_or_default();            let content_type = row.text("content_type").unwrap_or_default();            if tier == "thumb" {                out.other += bytes;            } else if a_download(content_type, kit.as_deref()) {                out.downloads += bytes;            } else {                out.files += bytes;            }            out.freeable += free;        }        Ok(())    });    // Other: the app's folder less what is counted above (never below none).    let folder = folder_bytes(client.layout().root());    out.other = out.other.max(folder.saturating_sub(out.data + out.files + out.downloads));    out}/// The Storage section's line: what this phone keeps, and, once the/// database on the server is 80% full or more (the last pass's `room`), how/// full it is, before writes are refused (owner, 22 Nov 2026).fn storage_line(handle: &CottonHandle, kept: &Kept) -> String {    let line = say("storage.line", &[("name", handle.app_name()), ("size", &size_said(kept.total()))]);    let state = handle.client().sync_progress().map(|progress| progress.state());    let room = state.as_ref().and_then(|s| s.room);    let space = state.as_ref().and_then(|s| s.space);    let mut line = match room {        Some(room) if room.used >= 1.0 => format!("{line} {}", say("storage.server_full", &[])),        Some(room) => format!("{line} {}", say("storage.server_filling", &[("percent", &format!("{}", (room.used * 100.0).floor() as u64))])),        None => line,    };    // The space for photos and files (SPACE.md), once the account's rules hold and it is 80% used or more.    if let Some(space) = space {        line = match space_words(space.used) {            Some(words) => format!("{line} {words}"),            None => line,        };    }    line}/// What the Storage line adds for the space for photos and files: full from all of it, else how full from 80%.fn space_words(used: f64) -> Option<String> {    if used >= 1.0 {        Some(say("storage.space_full", &[]))    } else if used >= 0.8 {        Some(say("storage.space_filling", &[("percent", &format!("{}", (used * 100.0).floor() as u64))]))    } else {        None    }}fn storage(handle: &CottonHandle, kept: &Kept) -> Value {    let part = |id: &str, bytes: u64| {        let mut part = json!({"id": id, "label": say(&format!("storage.{id}"), &[]), "bytes": bytes, "said": size_said(bytes)});        if id == "downloads" {            part["line"] = json!(say("storage.downloads_line", &[]));        }        part    };    let freed = size_said(kept.freeable);    let mut free_up = json!({"label": say("storage.free_up", &[]), "bytes": kept.freeable});    if kept.freeable > 0 {        free_up["line"] = json!(say("storage.free_up_line", &[("size", &freed)]));        free_up["ask"] = json!(say("storage.free_up_ask", &[("size", &freed)]));        free_up["ask_body"] = json!(say("storage.free_up_ask_body", &[]));        free_up["confirm"] = json!(say("storage.free_up_confirm", &[]));    } else {        free_up["line"] = json!(say("storage.free_up_none", &[]));    }    json!({        "title": say("sections.storage", &[]),        "line": storage_line(handle, kept),        "total_bytes": kept.total(),        // The whole in a person's words ("1.4 GB"), for a page that says it large over the four (Comms' You).        "said": size_said(kept.total()),        "parts": kept.parts().into_iter().map(|(id, bytes)| part(id, bytes)).collect::<Vec<_>>(),        "free_up": free_up,    })}/// The kits whose app tells the person something while it is closed (Comms'/// messages and calls, Days' alerts): only they show Notifications.const NOTIFYING_KITS: [&str; 2] = ["messages", "days"];/// SETTINGS' TOP LEVEL, AS COMMS' YOU SHOWS IT (you-grouped.html, the/// owner's review of 22 Nov 2026, and "Comms' settings are well organised/// now", 23 Nov 2026): the rows an app of kit `kit` shows, in the one order,/// each with the group it stands in (a gap between groups). Your Claude and/// Privacy (Your people) stand only while signed in, where they hold/// something; Notifications only in an app that notifies. Sync, Storage,/// Help and feedback and About stand in every app, signed in or not.pub fn row_ids(kit: Option<&str>, signed_in: bool) -> Vec<(&'static str, &'static str)> {    let mut ids = vec![("sync", "keep")];    if signed_in {        ids.extend([("claude", "keep"), ("privacy", "behave")]);    }    if kit.is_some_and(|kit| NOTIFYING_KITS.contains(&kit)) {        ids.push(("notifications", "behave"));    }    ids.extend([("storage", "behave"), ("help", "help"), ("about", "help")]);    ids}/// How many of Your people there are: `(asking, connected)`, or nothing when/// the server did not answer them (`unreachable`).pub(crate) fn people_counts(people: &Value) -> Option<(usize, usize)> {    if people.is_null() || people.get("unreachable").is_some() {        return None;    }    let count = |id: &str| people["sections"].as_array().into_iter().flatten().find(|section| section["id"] == id).and_then(|section| section["rows"].as_array().map(Vec::len)).unwrap_or(0);    // Someone he added who has not added him back is one of his people too: Privacy said "No one added yet" over a    // page that listed them under Waiting (seen on emulator-5600 against dev, 24 Nov 2026).    Some((count("asking"), count("people") + count("waiting")))}/// Privacy's glance: how many of Your people there are, and who asks.fn people_said((asking, connected): (usize, usize)) -> String {    if asking > 0 {        say("top.people_asking", &[("n", &asking.to_string())])    } else if connected > 0 {        say("top.people", &[("n", &connected.to_string())])    } else {        say("top.people_none", &[])    }}/// The top level's rows (`rows`), each `{id, label, line?, group}`; the/// words are Comms' own You rows (`chat` set `app.you.rows`, `.glance`).fn rows(handle: &CottonHandle, request: &Value, account: &Value, kept: Option<&Kept>, people: Option<(usize, usize)>) -> Vec<Value> {    let client = handle.client();    let kit = cotton_core::kit::AppKit::at(client.layout().root()).ok().flatten().map(|kit| kit.id);    let signed_in = signed_in(account);    let chat = |row: &str, fills: &[(&str, &str)]| resolve("chat", &format!("app.you.{row}"), &[], fills).unwrap_or_default();    row_ids(kit.as_deref(), signed_in)        .into_iter()        .map(|(id, group)| {            let line = match id {                "sync" => crate::methods::shell_account::sync_said(&client)["title"].as_str().map(str::to_string),                "claude" => crate::phone::assistants::call_on(&client, "assistant.screen", &json!({})).ok().and_then(|screen| screen["reading"]["row"].as_str().map(str::to_string)),                "privacy" => people.map(people_said),                "notifications" => request.get("notifications").and_then(Value::as_bool).map(|on| chat(if on { "glance.notifications_on" } else { "glance.notifications_off" }, &[])),                "storage" => kept.map(|kept| chat("glance.storage", &[("size", &size_said(kept.total()))])),                "help" => Some(chat("glance.help", &[])),                _ => Some(chat("glance.about", &[("version", handle.app_version())])),            };            let mut row = json!({ "id": id, "label": chat(&format!("rows.{id}"), &[]), "group": group });            if let Some(line) = line.filter(|line| !line.is_empty()) {                row["line"] = json!(line);            } else if LATER_ROWS.contains(&id) {                // Not known on this phone yet: the row stands now, its line comes with the whole answer.                row["later"] = json!(true);            }            row        })        .collect()}/// The card at the top: who is signed in (the name on this phone's copy,/// when one is set), or, signed out, what signing in does.fn profile(handle: &CottonHandle, account: &Value) -> Value {    let name = if signed_in(account) {        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))    } else {        None    };    profile_of(account, name)}/// Whether the card stands for someone signed in: Your people answered, or/// the phone connected, connecting or saving its data for the first time./// While the first sync saves (`backing_up`) the account has no people yet,/// and the card said "Signed in" over what signing in does (Words on the/// emulator, 23 Nov 2026).fn signed_in(account: &Value) -> bool {    account.get("people").is_some() || matches!(account["stand"].as_str(), Some("connected" | "connecting" | "backing_up"))}/// The card from the account and the copy's own name.fn profile_of(account: &Value, name: Option<String>) -> Value {    if !signed_in(account) {        // A sign-in whose first sync stopped says so (its data is safe here, Sign in goes on); else what signing in does.        let stopped = resolve("boot", "account.who.backup_stopped", &[], &[]).unwrap_or_default();        let line = if account["card"]["subtitle"] == stopped.as_str() { stopped } else { say("top.signed_out_line", &[]) };        return json!({ "signed_in": false, "line": line });    }    let mut profile = json!({ "signed_in": true });    if let Some(name) = name {        profile["name"] = json!(name);    }    profile}/// `shell.settings` — the whole answer: Your people asked of the server and/// this app's folder measured, as it always was. What took time is kept for/// the next quick answer ([`now`]), on this phone, across launches.pub fn call(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let client = handle.client();    let account = crate::methods::shell_account::call(handle, request)?;    let kept = kept(&client);    keep_later(&client, |later| later.kept = Some(kept));    let people = people_counts(&account["people"]);    answered(handle, request, account, Some(kept), people)}/// `shell.settings.now` — THE LIST ON ITS FIRST FRAME (owner, build 24: the/// card drew, and the rows one to two seconds later, in all four apps). The/// same shape as the whole answer, from this phone alone: no network and no/// walk of the app's folder. How many of Your people there are and what this/// app keeps are as the last whole answer found them, across launches/// ([`Later`]); on a phone that has never had one, those rows stand with/// `later: true` and no line, `storage` is absent, and the whole answer/// fills them in place. `account` carries no `people` (the Privacy page's/// list is the whole answer's).pub fn now(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let client = handle.client();    let account = crate::methods::shell_account::answer(handle, request, false)?;    let later = later(&client);    answered(handle, request, account, later.kept, later.people)}/// The rows whose line takes time to know: Privacy (Your people, the/// server's) and Storage (the app's folder, walked).pub const LATER_ROWS: [&str; 2] = ["privacy", "storage"];fn answered(handle: &CottonHandle, request: &Value, account: Value, kept: Option<Kept>, people: Option<(usize, usize)>) -> Result<Value, MethodError> {    let client = handle.client();    let home = crate::methods::shell_home::call(handle, &json!({}))?;    let version = handle.app_version().to_string();    let facts = account["card"]["facts"].clone();    let mut answer = json!({        "sections": ["account", "storage", "help", "about"],        "rows": rows(handle, request, &account, kept.as_ref(), people),        "profile": profile(handle, &account),        // The Sync page: the state line, when it last synced while the line says something else, and whether        // Cotton is out of reach (as Comms' `chat.you` answers it).        "sync": crate::methods::shell_account::sync_said(&client),        "pages": {            "storage_kept": say("top.storage_kept", &[("name", handle.app_name())]),            "notifications_phone_line": say("top.notifications_phone_line", &[("name", handle.app_name())]),        },        "account": account,        "help": {            "title": say("sections.help", &[]),            "share": {"label": say("help.share", &[]), "line": say("help.share_line", &[]),                      "preview_title": say("help.preview_title", &[]), "preview_share": say("help.preview_share", &[]), "preview_close": say("help.preview_close", &[])},            // The privacy policy and the way to reach us, inside every app (both stores ask; store pass, 24 Nov 2026).            "links": [                {"id": "privacy", "label": say("help.privacy", &[]), "url": format!("{SITE}/privacy")},                {"id": "support", "label": say("help.support", &[]), "url": format!("{SITE}/support")},            ],        },        "about": {"title": say("sections.about", &[]), "version": {"label": say("about.version", &[]), "said": version}, "facts": facts},        "loading": home["bringing"],    });    if let Some(kept) = kept {        answer["storage"] = storage(handle, &kept);    }    Ok(answer)}/// WHAT TAKES TIME, KEPT (coordinator, 23 Nov 2026: the owner's case is a/// cold launch): how many of Your people there are and who asks (the/// server's), how many people are blocked (Comms, the server's), and what/// this app keeps on this phone (its folder walked), as the last whole/// answer found them, so a quick answer says them on its first frame even on/// a cold launch. One small file beside the chat preferences, for the/// database it was found in: counts and byte figures only, nothing personal.#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]pub struct Later {    #[serde(default)]    pub database: Option<String>,    /// `(asking, connected)`.    #[serde(default)]    pub people: Option<(usize, usize)>,    #[serde(default)]    pub blocked: Option<usize>,    #[serde(default)]    pub kept: Option<Kept>,}const LATER_FILE: &str = "settings-later.json";/// One keeper at a time: four threads answer the phone, and two whole answers finishing together must not lose a figure.static KEEPING: std::sync::Mutex<()> = std::sync::Mutex::new(());fn later_path(client: &ClientController) -> std::path::PathBuf {    client.layout().client_dir().join(LATER_FILE)}/// What the last whole answer found, for the database this phone stands on now (nothing for another's).pub fn later(client: &ClientController) -> Later {    let database = client.current_database().ok();    std::fs::read(later_path(client))        .ok()        .and_then(|bytes| serde_json::from_slice::<Later>(&bytes).ok())        .filter(|later| later.database.is_some() && later.database == database)        .unwrap_or_default()}/// Keep what a whole answer found ([`Later`]); a file that cannot be written leaves the quick answer saying less, never wrong.pub fn keep_later(client: &ClientController, change: impl FnOnce(&mut Later)) {    let _one = KEEPING.lock().unwrap_or_else(|held| held.into_inner());    let Ok(database) = client.current_database() else { return };    let mut later = later(client);    later.database = Some(database);    change(&mut later);    let path = later_path(client);    let Ok(text) = serde_json::to_vec(&later) else { return };    if let Some(parent) = path.parent() {        let _ = std::fs::create_dir_all(parent);    }    let fresh = path.with_extension("json.new");    // not a copy: settings file.    if std::fs::write(&fresh, text).is_ok() {        // not a copy: settings file.        let _ = std::fs::rename(&fresh, &path);    }}/// A line with nothing personal left in it: anything quoted, any run of five/// or more digits (a number, an id), any email address and anything that/// looks like a record id goes, and the shared secret rules run over it.pub fn impersonal(line: &str) -> String {    let line = cotton_core::device::reported_state::redact_line(line);    // Words first: an email address and anything that looks like an id go whole.    let line = line        .split_whitespace()        .map(|word| if word.contains('@') || (word.len() >= 20 && word.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')) { "…" } else { word })        .collect::<Vec<_>>()        .join(" ");    let mut out = String::with_capacity(line.len());    let mut quoted: Option<char> = None;    let mut held = String::new();    // A run of digits, with the spaces, dashes and dots a number is written    // with: a phone number or an id once it holds five digits or more.    let flush = |held: &mut String, out: &mut String| {        let trailing: String = held.chars().rev().take_while(|c| !c.is_ascii_digit()).collect::<Vec<_>>().into_iter().rev().collect();        let number = &held[..held.len() - trailing.len()];        if number.chars().filter(char::is_ascii_digit).count() >= 5 {            out.push('…');        } else {            out.push_str(number);        }        out.push_str(&trailing);        held.clear();    };    for c in line.chars() {        if let Some(close) = quoted {            if c == close {                quoted = None;                out.push('…');                out.push(close);            }            continue;        }        let closing = match c {            '"' => Some('"'),            '“' => Some('”'),            '\'' if out.ends_with(' ') || out.is_empty() => Some('\''),            '‘' => Some('’'),            '«' => Some('»'),            _ => None,        };        if c.is_ascii_digit() || (!held.is_empty() && matches!(c, ' ' | '-' | '.')) {            held.push(c);            continue;        }        flush(&mut held, &mut out);        if let Some(close) = closing {            out.push(c);            quoted = Some(close);            continue;        }        out.push(c);    }    flush(&mut held, &mut out);    if quoted.is_some() {        out.push('…');    }    out}/// `shell.report` — `{ title, file_name, text }`.pub fn report(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let client = handle.client();    let account = crate::methods::shell_account::call(handle, request)?;    let home = crate::methods::shell_home::call(handle, &json!({}))?;    let kept = kept(&client);    let zone = client.time_zone().unwrap_or("UTC").to_string();    let now = client.clock().now_iso();    let local = |iso: &str, format: &str| cotton_core::kit::local_clock(iso, &zone, format).unwrap_or_else(|| iso.to_string());    let name = handle.app_name().to_string();    let app = account["card"]["facts"].as_array().into_iter().flatten().find(|fact| fact["id"] == "app").and_then(|fact| fact["said"].as_str()).map(str::to_string)        .unwrap_or_else(|| format!("{name} {}", handle.app_version()));    let platform = format!("{:?}", crate::phone::commands::THIS_BUILDS_PLATFORM).to_lowercase();    let signed_in = home["stand"] == "connected" || home["stand"] == "backing_up";    let mut lines = vec![        say("report.app", &[("app", &impersonal(&app))]),        say("report.phone", &[("platform", &platform)]),        say("report.made", &[("time", &local(&now, "%-d %b %Y %H:%M %Z"))]),        String::new(),        format!("## {}", say("report.sync", &[])),        say("report.signed_in", &[("yes", &say(if signed_in { "report.yes" } else { "report.no" }, &[]))]),        say("report.stand", &[("line", &impersonal(account["line"].as_str().unwrap_or_default()))]),    ];    let synced = account["card"]["facts"].as_array().into_iter().flatten().find(|fact| fact["id"] == "synced").and_then(|fact| fact["said"].as_str()).map(str::to_string);    lines.push(say("report.synced", &[("time", &synced.map_or_else(|| say("report.never", &[]), |said| impersonal(&said)))]));    let pending = client.sync_status()["pending"].as_u64().unwrap_or(0);    lines.push(say("report.waiting", &[("n", &pending.to_string())]));    if let Some(loading) = home["bringing"]["words"].as_str() {        lines.push(say("report.loading", &[("line", loading)]));    }    lines.push(String::new());    lines.push(format!("## {}", say("report.storage", &[])));    for (id, bytes) in kept.parts() {        lines.push(say("report.part", &[("label", &say(&format!("storage.{id}"), &[])), ("size", &size_said(bytes))]));    }    lines.push(say("report.freeable", &[("size", &size_said(kept.freeable))]));    lines.push(String::new());    lines.push(format!("## {}", say("report.errors", &[])));    let mut errors = Vec::new();    if let Some((words, at)) = client.last_trouble() {        errors.push(say("report.error", &[("time", &local(&at, "%-d %b %H:%M")), ("words", &impersonal(&words))]));    }    if let Some(why) = client.sync_status()["loop"]["stoppedReason"].as_str() {        errors.push(say("report.error", &[("time", &local(&now, "%-d %b %H:%M")), ("words", &impersonal(why))]));    }    if errors.is_empty() {        errors.push(say("report.no_errors", &[]));    }    lines.extend(errors);    let title = say("report.title", &[("name", &name), ("time", &local(&now, "%-d %b %H:%M"))]);    let file_name = say("report.file", &[("name", &name), ("date", &local(&now, "%Y-%m-%d %H%M"))]);    let text = format!("{title}\n\n{}\n", lines.join("\n"));    Ok(json!({"title": title, "file_name": file_name, "text": text}))}/// `shell.freeUp {expected}` — take off this phone the files Free up space/// said it would, after the person agreed to `expected` bytes. Refused when/// more would go than was said (Storage changed: open it again).pub fn free_up(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let expected = request["expected"].as_u64().ok_or_else(|| MethodError::new("bad_request", "shell.freeUp takes the bytes the person agreed to free, `expected`"))?;    free_within(&handle.client(), expected, None)}/// Free up space, over every file it may take, or (`within`, a key prefix:/// one chat's folder, `chat.storage.free`) over those under it alone. The/// same rule either way: only [`FREEABLE`], refused when more would go than/// the person agreed to, answered in the kit's words.pub fn free_within(client: &ClientController, expected: u64, within: Option<&str>) -> Result<Value, MethodError> {    let device = client.self_device_id().ok_or_else(|| MethodError::new("not_ready", "this phone has not joined yet"))?;    let now = client.clock().now().timestamp_millis();    let mut ids = cotton_client::seams::op_ids(client.random());    let layout = client.layout().clone();    let (workspace, freed) = client        .with_writer(|file| {            let (scope, params) = match within {                Some(prefix) => (" AND substr(key, 1, length(?1)) = ?1", vec![rusqlite::types::Value::Text(prefix.to_string())]),                None => ("", Vec::new()),            };            let freeable: Vec<(String, i64)> = file                .driver                .all(&format!("SELECT key, size_bytes FROM _media WHERE {FREEABLE}{scope} ORDER BY key"), &params)                .map_err(|error| error.to_string())?                .iter()                .map(|row| (row.text("key").unwrap_or_default().to_string(), row.int("size_bytes").unwrap_or(0)))                .collect();            let would: u64 = freeable.iter().map(|(_, bytes)| u64::try_from(*bytes).unwrap_or(0)).sum();            if would > expected {                return Err("storage_changed".to_string());            }            let mut freed = 0u64;            for (media, _) in &freeable {                match cotton_client::media::storage::evict_one(                    file.driver, file.workspace_id, &device, &layout, &cotton_client::media::SystemEvictDisk, media, now, &mut ids,                    crate::phone::storage::held(file),                ) {                    Ok(bytes) => freed += bytes,                    Err(why) => tracing::warn!("free up kept {media}: {why}"),                }            }            Ok((file.workspace_id.to_string(), freed))        })        .map_err(|why| if why == "storage_changed" { MethodError::new("storage_changed", say("storage.changed", &[])) } else { MethodError::new("refused", why) })?;    client.emit_data(&workspace, vec!["_media".into(), "cotton_media_holdings".into()], "local");    client.nudge_sync();    let said = if freed == 0 { say("storage.freed_nothing", &[]) } else { say("storage.freed", &[("size", &size_said(freed))]) };    Ok(json!({"freed_bytes": freed, "said": said}))}#[cfg(test)]#[path = "shell_settings_tests.rs"]mod tests;