Cotton code
1064 lines · 59.8 KB · RustRaw
//! Post's acts on mail (assets/design/mail/DECISIONS.md "The four acts", and the owner's Archive of 25 Nov 2026).//!//! ```text//! mail.archive { scope, key?, emails? }   → After   one tap: every mail of the scope in the Inbox, out of it, kept//! mail.act     { emails[], act }          → After   read | unread | archive | delete | restore//! mail.undo    { after }                  → After   puts back what that act changed here//! mail.after   { after }                  → After   the same after-state, its mailbox line read again//! ```//!//! **Archive is one tap** (owner, 25 Nov 2026: "all mail text should exist on the device, so counts on the device are//! the same as the actual email counts, and tapping Archive archives all of them, in one tap, no count-first second//! tap, no Try again"). The phone holds every mail, so the count on the button is the count it archives. Each mail is//! archived here at once (`archived_at`) and his mailbox is asked to follow through the outbox: `sender_archive` for a//! whole sender (one row per address), `archive` for each chosen mail.//!//! **Delete is the Bin**: the mail's `trashed_at` here (out of every list but the Bin, kept 30 days) and `trash` in his//! mailbox. Nothing is erased by an act; the Bin's sweep erases after 30 days.//!//! **The after-state** says what really happened, with Undo, and a line for his mailbox from the outbox rows the act//! filed: done once every row is `sent`, waiting while any is queued (the Mac's way says so), failed with the Mac's//! words. Undo puts this copy back; his mailbox has no way back through the outbox yet, and the line says so.use cotton_tools::mcp::handlers::common::update_row;use super::super::*;use super::p;use cotton_core::rules::mail_predicate;use cotton_core::rules::mail_predicate::cuts as mail_cuts;/// Where this phone keeps its recent acts, so Undo and the mailbox line can find them.const AFTERS: &str = "post-afters.json";/// Acts kept for Undo.const KEPT: usize = 20;#[derive(serde::Serialize, serde::Deserialize, Clone)]struct Done {    id: String,    act: String,    at: String,    /// The mails changed, with what each held before (`unread`).    mails: Vec<(String, bool)>,    /// Who it was from, in words.    sender: String,    /// The outbox rows filed for his mailbox: kind and target (the mail's external id, or the sender's address).    filed: Vec<(String, String)>,    /// The mailbox's name for the line ("Gmail").    provider: String,    undone: bool,    /// Acts for a Cotton-fetched account, done by the object itself (`POST /v1/mail/fetch/act`), not yet sent.    #[serde(default, skip_serializing)]    pending: Vec<Value>,    /// What the object answered for each: `sent`, or `failed` with its words.    #[serde(default)]    direct: Vec<(String, Option<String>)>,    /// The archived-sender rows a whole sender's Archive wrote (`email_cut`): Undo deletes them.    #[serde(default)]    cuts: Vec<String>,    /// The Delete rows a whole sender's Delete wrote (`email_bin_cut`, MAIL PREDICATE phase 2): Undo deletes them,    /// until this device began erasing what one covers.    #[serde(default)]    bin_cuts: Vec<String>,    /// The Mark read rows a Mark read of many wrote (`email_read_cut`): Undo deletes them.    #[serde(default)]    read_cuts: Vec<String>,    /// Mail the act names that has no landing time yet: no cut covers it until the backfill brings one (landed.rs).    #[serde(default)]    waiting: usize,}fn afters_path(client: &ClientController) -> std::path::PathBuf {    client.layout().client_dir().join(AFTERS)}fn afters(client: &ClientController) -> Vec<Done> {    std::fs::read(afters_path(client)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()}fn keep(client: &ClientController, done: &Done) -> Result<(), MethodError> {    let mut all = afters(client);    all.retain(|d| d.id != done.id);    all.push(done.clone());    let from = all.len().saturating_sub(KEPT);    let bytes = serde_json::to_vec(&all[from..]).map_err(|e| MethodError::new("unanswerable", e.to_string()))?;    // not a copy: Post's afters list.    std::fs::write(afters_path(client), bytes).map_err(|e| MethodError::new("unwritable", e.to_string()))}/// The mailbox's name, by the address the mail was read from.fn provider_of(account: Option<&str>) -> String {    let domain = account.and_then(|a| a.rsplit_once('@')).map(|(_, d)| d.to_lowercase()).unwrap_or_default();    match domain.as_str() {        "gmail.com" | "googlemail.com" => "Gmail".to_string(),        "icloud.com" | "me.com" | "mac.com" => "iCloud".to_string(),        "fastmail.com" | "fastmail.fm" => "Fastmail".to_string(),        d if d.starts_with("yahoo.") => "Yahoo".to_string(),        "" => "your mailbox".to_string(),        _ => "your mailbox".to_string(),    }}/// The Inbox's mail as an act reads it: its sender as every cut matches it, and when it landed (`_mail_landed`).pub(super) fn inbox_base(know: &Know) -> String {    format!("SELECT id, external_id, {key_fn}(from_email) AS a, from_name, {unread_col} AS unread, sent_at, created_at, (SELECT l.landed_at FROM {landed} l WHERE l.id = cotton_emails.id) AS landed_at, coalesce(account, gmail_account) AS account FROM {EMAILS} WHERE workspace_id = ?{}", super::cuts::inbox(know, ""), unread_col = mail_predicate::unread(""), key_fn = mail_cuts::KEY_FUNCTION, landed = mail_cuts::LANDED)}/// A sender's mail of `base` (`?2` its key): found by the sender index's own expression first, then by the one/// normaliser (PHASE 2 PHONE 2, item 2), so it seeks, never reads every mail.pub(super) fn sender_sql(base: &str) -> String {    format!("{base} AND lower(trim(from_email)) = ?2 AND {key_fn}(from_email) = ?2 ORDER BY sent_at DESC", key_fn = mail_cuts::KEY_FUNCTION)}/// A domain's mail of `base` (`?2` its `@domain`): by `_mail_landed`'s domain index (the mail a domain cut can cover/// has landed by definition). The workspace test is written `+workspace_id` so the planner cannot drive from the/// workspace's own index (every mail he holds) and must seek the domain's ids first.pub(super) fn domain_sql(base: &str) -> String {    let base = base.replacen("WHERE workspace_id = ?", "WHERE +workspace_id = ?", 1);    debug_assert!(base.contains("+workspace_id"), "the domain's mail is found from its ids first");    format!("{base} AND id IN (SELECT l.id FROM {landed} l WHERE l.domain = ?2) ORDER BY sent_at DESC", landed = mail_cuts::LANDED)}/// The scope's mail in the Inbox now, newest first, with its sender, unread and account. A sender or a domain is/// chosen exactly as its cut will match it (MAIL PREDICATE phase 2, rule 5).fn inbox_of(ctx: &mut Ctx<'_>, know: &Know, scope: &str, key: Option<&str>, emails: &[String]) -> Result<Vec<Map<String, Value>>, String> {    let base = inbox_base(know);    match scope {        "select" => rows_in(ctx, &base, "id", emails),        // A conversation: every mail of it in the Inbox (a row's swipe).        "thread" => rows(ctx, &format!("{base} AND thread_id = ? ORDER BY sent_at DESC"), &[ws(ctx), text(key.unwrap_or_default().to_string())]),        "sender" => rows(ctx, &sender_sql(&base), &[ws(ctx), text(mail_cuts::normalise_key(key.unwrap_or_default()))]),        "domain" => rows(ctx, &domain_sql(&base), &[ws(ctx), text(format!("@{}", mail_cuts::normalise_key(key.unwrap_or_default()).trim_start_matches('@')))]),        "group" => {            let kind = key.and_then(|k| super::Kind::ALL.into_iter().find(|g| g.id() == k.trim_start_matches("group:"))).ok_or("no such group")?;            let senders: Vec<String> = super::sender_kinds(ctx, know)?.into_iter().filter(|(_, k)| *k == Some(kind)).map(|(a, _)| mail_cuts::normalise_key(&a)).collect();            let mut found = rows_in(ctx, &base, "lower(trim(from_email))", &senders)?;            found.retain(|r| s(r, "a").is_some_and(|a| senders.contains(&a)));            Ok(found)        }        _ => Err("scope is sender, domain, group, thread or select".into()),    }}fn after_json(done: &Done, line: String, ctx_rows: &[(String, Option<String>)]) -> Value {    let mut states = ctx_rows.to_vec();    states.extend(done.direct.iter().cloned());    let mailbox = mailbox_line(done, &states);    json!({ "after": done.id, "act": done.act, "count": done.mails.len(), "line": line, "mailbox": mailbox, "undo": (!done.undone).then(|| p("act.undo", &[])) })}/// The mailbox's line from the filed rows' states (`status`, `error`), as read now.fn mailbox_line(done: &Done, states: &[(String, Option<String>)]) -> Value {    if done.filed.is_empty() && done.direct.is_empty() {        return Value::Null;    }    let done_word = p(&format!("after.done_words.{}", done.act), &[]);    let provider = done.provider.as_str();    if done.undone {        // Put back here; his mailbox has no way back through the outbox yet, said as what he can do.        return json!({ "state": "here_only", "line": capital(&p(&format!("after.undo_mailbox.{}", done.act), &[("provider", provider)])) });    }    if let Some((_, why)) = states.iter().find(|(s, _)| s == "failed") {        return json!({ "state": "failed", "line": capital(&p("after.mailbox.failed", &[("done", &done_word), ("provider", provider), ("why", why.as_deref().unwrap_or_default())])), "retry": p("act.retry", &[]) });    }    if !states.is_empty() && states.iter().all(|(s, _)| s == "sent") {        return json!({ "state": "done", "line": capital(&p("after.mailbox.done", &[("done", &done_word), ("provider", provider)])) });    }    json!({ "state": "waiting", "line": capital(&p("after.mailbox.waiting", &[("provider", provider)])) })}fn states_of(ctx: &mut Ctx<'_>, done: &Done) -> Result<Vec<(String, Option<String>)>, String> {    let mut out = Vec::new();    for (kind, target) in &done.filed {        let column = if kind.starts_with("sender_") || kind == "unsubscribe" { "\"to\"" } else { "target" };        let found = one(ctx, &format!("SELECT status, error FROM cotton_outbox WHERE workspace_id = ? AND channel = 'mail' AND kind = ? AND {column} = ? AND created_at >= ? ORDER BY created_at DESC LIMIT 1"), &[ws(ctx), text(kind.clone()), text(target.clone()), text(done.at.clone())])            .unwrap_or(None);        if let Some(r) = found {            out.push((s(&r, "status").unwrap_or_default(), s(&r, "error")));        }    }    Ok(out)}fn new_id() -> String {    cotton_chat::fresh_id()}fn now_iso(client: &ClientController) -> String {    client.clock().now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)}// ── mail.archive ───────────────────────────────────────────────────────pub(super) fn archive(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let scope = request.get("scope").and_then(Value::as_str).unwrap_or("select").to_string();    let key = request.get("key").and_then(Value::as_str).map(str::to_string);    let emails: Vec<String> = request.get("emails").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();    if !matches!(scope.as_str(), "sender" | "domain" | "group" | "thread" | "select") {        return Err(bad("scope", "sender, domain, group, thread or select"));    }    if scope != "select" && key.is_none() || scope == "select" && emails.is_empty() {        return Err(bad("key", "the sender, domain, group or thread, or `emails` for select"));    }    public_domain(&scope, key.as_deref())?;    if scope == "domain" {        let k = key.clone().unwrap_or_default();        let n = read(client, "mail.archive.senders", |ctx| domain_senders(ctx, &k))?;        if let Some(sheet) = many_senders(&scope, k.trim_start_matches('@'), n, request) {            return Ok(sheet);        }    }    let at = now_iso(client);    let done = write(client, "mail.archive", |ctx| {        let know = super::cuts::know(ctx)?;        let mut found = inbox_of(ctx, &know, &scope, key.as_deref(), &emails)?;        let whole = matches!(scope.as_str(), "sender" | "domain" | "group");        if whole {            // His own mail is never a whole sender's act (PHASE 2 PHONE 2, low): not counted, not covered.            super::cuts::keep_own(ctx, know.own.iter().map(String::as_str))?;            found.retain(|r| !s(r, "a").is_some_and(|a| know.own.iter().any(|o| mail_cuts::normalise_key(o) == a)));        }        let mut done = Done { id: new_id(), act: "archive".into(), at: at.clone(), mails: Vec::new(), sender: String::new(), filed: Vec::new(), pending: Vec::new(), direct: Vec::new(), cuts: Vec::new(), bin_cuts: Vec::new(), read_cuts: Vec::new(), waiting: 0, provider: provider_of(found.first().and_then(|r| s(r, "account")).as_deref()), undone: false };        let mut senders: Vec<(String, String)> = Vec::new();        // A whole sender, a domain or a group: one archived-sender row each, however many mails (cuts.rs). Chosen        // mail and a conversation: each mail.        for r in &found {            let Some(id) = s(r, "id") else { continue };            if !whole {                update_row(ctx, EMAILS, &id, json!({ "archived_at": at }).as_object().cloned().unwrap_or_default()).map_err(|e| e.to_string())?;            }            done.mails.push((id, truthy(r, "unread")));            let a = s(r, "a").unwrap_or_default();            if !senders.iter().any(|(x, _)| *x == a) {                senders.push((a.clone(), know.name_of(&a).map(str::to_string).or_else(|| s(r, "from_name")).unwrap_or_else(|| a.clone())));            }        }        if whole {            // Each row covers up to its newest mail found, landed by the newest landing among them.            // Keys through the one normaliser; a whole public mail domain is refused (rule 5).            let keys: Vec<String> = if scope == "domain" {                vec![format!("@{}", mail_cuts::normalise_key(key.as_deref().unwrap_or_default()).trim_start_matches('@'))]            } else {                senders.iter().map(|(a, _)| mail_cuts::normalise_key(a)).collect()            };            // Every row planned and checked before the first is written (review of the rules, 5).            let newest = super::cuts::newest_landed(ctx)?;            let made_at = super::cuts::made_at(ctx, &at)?;            let mut planned: Vec<(String, String, String)> = Vec::new();            for k in keys {                if let Some(why) = mail_cuts::refused_key(&k) {                    return Err(format!("archive {k}: {why}"));                }                let domain_of = |a: &str| a.find('@').map(|at| a[at..].to_string());                let mine: Vec<&Map<String, Value>> = found.iter().filter(|r| {                    let a = mail_cuts::normalise_key(&s(r, "a").unwrap_or_default());                    a == k || domain_of(&a).as_deref() == Some(k.as_str())                }).collect();                let Some(before) = mine.iter().filter_map(|r| s(r, "sent_at")).filter_map(|t| mail_cuts::normalise_time(&t)).max() else { continue };                // MAIL PREDICATE phase 2, rules 2 and 3: the moment is the newest SERVER landing among the mails it                // takes, never this phone's clock nor a created_at an import could set. Mail with no landing time yet                // is not covered until the backfill brings it (landed.rs).                let Some(by) = mail_cuts::cut_at(mine.iter().map(|r| r.get("landed_at").and_then(Value::as_str))) else { continue };                if let Some(why) = mail_cuts::check_cut_at(&by, newest.as_deref()) {                    return Err(format!("archive cut at {by}: {why}"));                }                planned.push((k, before, by));            }            for (k, before, by) in planned {                done.cuts.push(super::cuts::cut(ctx, &k, &before, &by, &made_at)?);            }        }        done.sender = match (scope.as_str(), senders.as_slice()) {            ("thread", _) if senders.len() > 1 => String::new(),            ("group", _) => p(&format!("groups.{}", key.as_deref().unwrap_or_default().trim_start_matches("group:")), &[]),            ("domain", _) => key.clone().unwrap_or_default().trim_start_matches('@').to_string(),            (_, [(_, name)]) => name.clone(),            _ => String::new(),        };        // His mailbox follows: a whole sender's Inbox by one row each; chosen mail one by one.        let fetched = fetched_accounts(ctx);        if scope == "select" || scope == "thread" {            for r in &found {                if let Some(account) = s(r, "account").map(|a| a.to_lowercase()).and_then(|a| fetched.get(&a).cloned()) {                    done.pending.push(json!({ "account": account, "kind": "archive", "email": s(r, "id") }));                    continue;                }                if let Some(external) = s(r, "external_id") {                    if let Some(mail) = super::super::acts::mail_of(ctx, &s(r, "id").unwrap_or_default())? {                        if super::super::acts::queue(ctx, &mail, "archive")? {                            done.filed.push(("archive".into(), external));                        }                    }                }            }        } else {            for (address, name) in &senders {                if let Some(account) = sender_account(ctx, address)?.and_then(|a| fetched.get(&a).cloned()) {                    done.pending.push(json!({ "account": account, "kind": "sender_archive", "to": address }));                    continue;                }                if crate::phone::chat_app::senders::wide::file_sender_wide(ctx, "sender_archive", address, name)? {                    done.filed.push(("sender_archive".into(), address.clone()));                }            }        }        Ok(done)    })?;    if done.mails.is_empty() {        // Nothing of it is in the Inbox: said, never "Archived 0".        return Err(MethodError::new("nothing", p("after.nothing_to_archive", &[])));    }    let mut done = done;    run_direct(client, &mut done);    keep(client, &done)?;    let line = if done.mails.len() == 1 { p("after.archived_one", &[]) } else { archived_line(&done) };    Ok(after_json(&done, line, &[]))}// ── mail.act ───────────────────────────────────────────────────────────pub(super) fn act(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let act = cotton_chat::text(request, "act")?.to_string();    if !matches!(act.as_str(), "read" | "unread" | "archive" | "delete" | "restore") {        return Err(bad("act", "read, unread, archive, delete or restore"));    }    if act == "read" && request.get("scope").is_some() {        return read_many(client, request);    }    if let Some(thread) = request.get("thread").and_then(Value::as_str) {        if act == "archive" {            return archive(client, &json!({ "scope": "thread", "key": thread }));        }    }    let ids: Vec<String> = match (request.get("emails").and_then(Value::as_array), request.get("thread").and_then(Value::as_str)) {        (Some(list), _) => list.iter().filter_map(Value::as_str).map(str::to_string).collect(),        (None, Some(thread)) => {            let bin = act == "restore";            let thread = thread.to_string();            read(client, "mail.act.thread", |ctx| {                let found = rows(ctx, &format!("SELECT id FROM {EMAILS} WHERE workspace_id = ? AND thread_id = ? AND {binned_mail} = ?", binned_mail = mail_predicate::binned("")), &[ws(ctx), text(thread.clone()), SqlValue::Integer(bin as i64)])?;                Ok(found.iter().filter_map(|r| s(r, "id")).collect())            })?        }        (None, None) => vec![cotton_chat::text(request, "email")?.to_string()],    };    if ids.is_empty() {        return Err(bad("emails", "at least one mail"));    }    if act == "archive" {        return archive(client, &json!({ "scope": "select", "emails": ids }));    }    let at = now_iso(client);    let done = write(client, "mail.act", |ctx| {        let fetched = fetched_accounts(ctx);        let mut done = Done { id: new_id(), act: act.clone(), at: at.clone(), mails: Vec::new(), sender: String::new(), filed: Vec::new(), pending: Vec::new(), direct: Vec::new(), cuts: Vec::new(), bin_cuts: Vec::new(), read_cuts: Vec::new(), waiting: 0, provider: String::new(), undone: false };        for id in &ids {            let Some(r) = one(ctx, &format!("SELECT id, external_id, from_email, from_name, {unread_col} AS unread, coalesce(account, gmail_account) AS account, trashed_at FROM {EMAILS} WHERE workspace_id = ? AND id = ?", unread_col = mail_predicate::unread("")), &[ws(ctx), text(id.clone())])? else { continue };            if done.provider.is_empty() {                done.provider = provider_of(s(&r, "account").as_deref());                done.sender = s(&r, "from_name").or_else(|| s(&r, "from_email")).unwrap_or_default();            }            let patch = match act.as_str() {                "read" => json!({ "unread": false }),                "unread" => json!({ "unread": true }),                "delete" => json!({ "trashed_at": at }),                _ => json!({ "trashed_at": null, "archived_at": null, "in_inbox": true }),            };            update_row(ctx, EMAILS, id, patch.as_object().cloned().unwrap_or_default()).map_err(|e| e.to_string())?;            // Rule 7: his act on this one mail wins over every cut of that kind that covers it.            if act == "restore" {                super::cuts::keep_out_of(ctx, super::cuts::ARCHIVE, id).map_err(except_full)?;                super::cuts::keep_out_of(ctx, super::cuts::BIN, id).map_err(except_full)?;            }            if act == "unread" {                super::cuts::keep_out_of(ctx, super::cuts::READ, id).map_err(except_full)?;            }            done.mails.push((id.clone(), truthy(&r, "unread")));            let fetched_here = s(&r, "account").map(|a| a.to_lowercase()).and_then(|a| fetched.get(&a).cloned());            if act != "restore" && fetched_here.is_some() {                let kind = match act.as_str() {                    "read" => "mark_read",                    "unread" => "mark_unread",                    _ => "trash",                };                done.pending.push(json!({ "account": fetched_here, "kind": kind, "email": id }));            } else if act != "restore" {                // The act's mail is live again for the outbox's reading of it (a deleted one is read before its move).                let mail = super::super::acts::Mail {                    id: id.clone(),                    thread: String::new(),                    external: s(&r, "external_id"),                    from: s(&r, "from_email").unwrap_or_default().trim().to_lowercase(),                    name: s(&r, "from_name"),                    unread: truthy(&r, "unread"),                    account: s(&r, "account"),                    unsubscribe: false,                    archived: false,                };                if let (Some(external), true) = (mail.external.clone(), super::super::acts::queue(ctx, &mail, &act)?) {                    let kind = match act.as_str() {                        "read" => "mark_read",                        "unread" => "mark_unread",                        _ => "trash",                    };                    done.filed.push((kind.into(), external));                }            }        }        Ok(done)    })?;    if done.mails.is_empty() {        return Err(MethodError::new("not_found", p("act.gone", &[])));    }    let mut done = done;    run_direct(client, &mut done);    keep(client, &done)?;    let n = done.mails.len();    let line = match (act.as_str(), n) {        ("delete", 1) => p("after.deleted_one", &[]),        ("delete", n) => p("after.deleted", &[("n", &n.to_string())]),        ("read", n) => p("after.read", &[("n", &n.to_string())]),        ("unread", _) => p("after.unread", &[]),        (_, n) => p("after.restored", &[("n", &n.to_string())]),    };    Ok(after_json(&done, line, &[]))}/// `mail.act { act: "read", scope, key, count, upto }`: a Mark read of many (a group's, a sender's or a domain's/// unread in the Inbox), one row per address however many mails (MAIL PREDICATE phase 2). Decision 4: the act carries/// the count the list showed and `upto`, the newest server landing among its mails; it covers the unread that landed/// by `upto` (mail that arrived since is not covered and stays unread), and is refused "changed" when what it would/// cover now, with the unread still waiting for a landing time, is not the count shown.fn read_many(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let scope = cotton_chat::text(request, "scope")?.to_string();    if !matches!(scope.as_str(), "sender" | "domain" | "group") {        return Err(bad("scope", "sender, domain or group"));    }    let key = cotton_chat::text(request, "key")?.to_string();    let shown = request.get("count").and_then(Value::as_u64).ok_or_else(|| bad("count", "the count the list showed"))? as usize;    let upto = request.get("upto").and_then(Value::as_str).and_then(mail_cuts::normalise_time).ok_or_else(|| bad("upto", "the newest landing the list showed"))?;    let at = now_iso(client);    let done = write(client, "mail.act.read", |ctx| {        let know = super::cuts::know(ctx)?;        let found = inbox_of(ctx, &know, &scope, Some(&key), &[])?;        let unread: Vec<Map<String, Value>> = found.into_iter().filter(|r| truthy(r, "unread")).collect();        let landed = |r: &Map<String, Value>| r.get("landed_at").and_then(Value::as_str).and_then(mail_cuts::normalise_time);        let seen: Vec<Map<String, Value>> = unread.iter().filter(|r| landed(r).is_none_or(|t| t <= upto)).cloned().collect();        if seen.len() != shown {            return Ok(None);        }        let take: Vec<Map<String, Value>> = seen.iter().filter(|r| landed(r).is_some()).cloned().collect();        let mut addresses: Vec<String> = take.iter().filter_map(|r| s(r, "a")).map(|a| mail_cuts::normalise_key(&a)).collect();        addresses.sort();        addresses.dedup();        super::cuts::keep_own(ctx, know.own.iter().map(String::as_str))?;        let (planned, _) = plan_cuts(ctx, &take, &addresses)?;        let made_at = super::cuts::made_at(ctx, &at)?;        let mut done = Done { id: new_id(), act: "read".into(), at: at.clone(), mails: Vec::new(), sender: String::new(), filed: Vec::new(), pending: Vec::new(), direct: Vec::new(), cuts: Vec::new(), bin_cuts: Vec::new(), read_cuts: Vec::new(), waiting: seen.len() - take.len(), provider: provider_of(take.first().and_then(|r| s(r, "account")).as_deref()), undone: false };        for (k, before, by, covered) in planned {            done.read_cuts.push(super::cuts::cut_in(ctx, super::cuts::READ, &k, &before, &by, &made_at)?);            done.mails.extend(covered.into_iter().map(|m| (m, true)));        }        Ok(Some(done))    })?;    let Some(done) = done else {        return Err(MethodError::new("changed", p("act.changed", &[])));    };    keep(client, &done)?;    let line = with_waiting(client, p("after.read", &[("n", &done.mails.len().to_string())]), done.waiting);    Ok(after_json(&done, line, &[]))}// ── mail.undo, mail.after ──────────────────────────────────────────────fn find(client: &ClientController, request: &Value) -> Result<Done, MethodError> {    let id = cotton_chat::text(request, "after")?.to_string();    afters(client).into_iter().find(|d| d.id == id).ok_or_else(|| MethodError::new("not_found", p("after.gone", &[])))}pub(super) fn undo(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let mut done = find(client, request)?;    if done.undone {        return Ok(after_json(&done, p("after.undone", &[]), &[]));    }    let refused = write(client, "mail.undo", |ctx| {        // A Delete whose erase this device began cannot come back (decision 3): refused, in words, before anything.        for cut in &done.bin_cuts {            if super::cuts::undo_refused(ctx, cut)? {                return Ok(true);            }        }        // A whole sender's act: its rows go, one write each.        for cut in &done.cuts {            super::cuts::uncut(ctx, cut)?;        }        for cut in &done.bin_cuts {            super::cuts::uncut_in(ctx, super::cuts::BIN, cut)?;        }        for cut in &done.read_cuts {            super::cuts::uncut_in(ctx, super::cuts::READ, cut)?;        }        let by_rows = !done.cuts.is_empty() || !done.bin_cuts.is_empty() || !done.read_cuts.is_empty();        for (id, unread) in done.mails.iter().filter(|_| !by_rows) {            let patch = match done.act.as_str() {                // Back in the Inbox here, even where his mailbox moved it out meanwhile (its Trash, or archived),                // so Archive finds it again (walk find, POST iPhone 3).                "archive" => json!({ "archived_at": null, "in_inbox": true }),                "delete" => json!({ "trashed_at": null, "in_inbox": true }),                "read" | "unread" => json!({ "unread": unread }),                _ => continue,            };            update_row(ctx, EMAILS, id, patch.as_object().cloned().unwrap_or_default()).map_err(|e| e.to_string())?;        }        Ok(false)    })?;    if refused {        return Err(MethodError::new("too_late", p("act.too_late", &[])));    }    done.undone = true;    keep(client, &done)?;    Ok(after_json(&done, p("after.undone", &[]), &[]))}pub(super) fn after(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let done = find(client, request)?;    let states = read(client, "mail.after", |ctx| states_of(ctx, &done))?;    let n = done.mails.len();    let line = if done.undone {        p("after.undone", &[])    } else {        match done.act.as_str() {            "archive" if n == 1 => p("after.archived_one", &[]),            "archive" => archived_line(&done),            "delete" if n == 1 => p("after.deleted_one", &[]),            "delete" => p("after.deleted", &[("n", &n.to_string())]),            "read" => p("after.read", &[("n", &n.to_string())]),            "unread" => p("after.unread", &[]),            _ => p("after.restored", &[("n", &n.to_string())]),        }    };    Ok(after_json(&done, line, &states))}/// "Archived 214 from Tiffinly.", or "Archived 2." for chosen mail from several senders.fn archived_line(done: &Done) -> String {    let n = cotton_core::rules::shell_lines::number(done.mails.len() as i64);    if done.sender.is_empty() {        p("after.archived_chosen", &[("n", &n)])    } else {        p("after.archived", &[("n", &n), ("sender", &done.sender)])    }}// ── mail.ask, mail.do: Delete, Unsubscribe and Block, each with one sheet ──/// What a sheet agreed to, handed back by `mail.do` as it came.#[derive(serde::Serialize, serde::Deserialize)]struct Plan {    act: String,    scope: String,    key: String,    count: usize,    /// The newest mail counted when he agreed.    at: String,    /// `unsubscribe` with no one-tap link: Bin new mail instead (a block they aren't told of).    #[serde(default)]    binning: bool,}/// The addresses a sender or a domain names, and how the sheet names them./// A domain's senders (`?` its `@domain`), by `_mail_landed`'s domain index.pub(super) fn domain_senders_sql() -> String {    format!("SELECT DISTINCT \"key\" AS a FROM {} WHERE domain = ?", mail_cuts::LANDED)}fn whole_of(ctx: &mut Ctx<'_>, know: &Know, scope: &str, key: &str) -> Result<(Vec<String>, String), String> {    let key = mail_cuts::normalise_key(key);    let key_fn = mail_cuts::KEY_FUNCTION;    if scope == "domain" {        let domain = key.trim_start_matches('@').to_string();        // The domain's senders by `_mail_landed`'s domain index; his own never among them.        let found = rows(ctx, &domain_senders_sql(), &[text(format!("@{domain}"))])?;        return Ok((found.iter().filter_map(|r| s(r, "a")).filter(|a| !know.own.iter().any(|o| mail_cuts::normalise_key(o) == *a)).collect(), domain));    }    let name = match know.name_of(&key) {        Some(n) => n.to_string(),        None => one(ctx, &format!("SELECT from_name FROM {EMAILS} WHERE workspace_id = ? AND lower(trim(from_email)) = ?2 AND {key_fn}(from_email) = ?2 AND trim(coalesce(from_name, '')) <> '' ORDER BY sent_at DESC LIMIT 1"), &[ws(ctx), text(key.clone())])?.and_then(|r| s(&r, "from_name")).unwrap_or_else(|| key.clone()),    };    Ok((vec![key], name))}/// Their mail not in the Bin (every place), with the thread each belongs to; `before` keeps only what had come by then./// Their mail not in the Bin, as [`held`] reads it; `rows_in` adds the senders by the sender index's own expression.pub(super) fn held_select() -> String {    format!(            "SELECT id, thread_id, sent_at, created_at, (SELECT l.landed_at FROM {landed} l WHERE l.id = cotton_emails.id) AS landed_at, {key_fn}(from_email) AS a, {unread_col} AS unread, archived_at, coalesce(in_inbox, 1) AS in_inbox, coalesce(account, gmail_account) AS account, list_unsubscribe, {covered} AS covered FROM {EMAILS} WHERE workspace_id = ? AND {live_mail}",            live_mail = mail_predicate::live(""),            unread_col = mail_predicate::unread(""),            key_fn = mail_cuts::KEY_FUNCTION,            landed = mail_cuts::LANDED,            covered = mail_cuts::archive_covers(""),        )}fn held(ctx: &mut Ctx<'_>, addresses: &[String], before: Option<&str>) -> Result<Vec<Map<String, Value>>, String> {    // Found by the sender index's own expression first, then by the one normaliser (PHASE 2 PHONE 2, item 2).    let mut found = rows_in(ctx, &held_select(), "lower(trim(from_email))", addresses)?;    found.retain(|r| s(r, "a").is_some_and(|a| addresses.contains(&a)));    if let Some(at) = before {        found.retain(|r| s(r, "sent_at").is_some_and(|t| t.as_str() <= at));    }    Ok(found)}/// How many of `found` are in the Inbox, an archived sender's rows counted (cuts.rs).fn in_inbox(found: &[Map<String, Value>]) -> usize {    found        .iter()        .filter(|r| s(r, "archived_at").is_none() && r.get("in_inbox").and_then(Value::as_i64) != Some(0))        .filter(|r| r.get("covered").and_then(Value::as_i64) != Some(1))        .count()}fn sheet_title(key: &str, n: usize, sender: &str) -> String {    if n == 1 { p(&format!("ask.{key}.title_one"), &[("sender", sender)]) } else { p(&format!("ask.{key}.title"), &[("n", &n.to_string()), ("sender", sender)]) }}pub(super) fn ask(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let act = cotton_chat::text(request, "act")?.to_string();    let scope = request.get("scope").and_then(Value::as_str).unwrap_or("sender").to_string();    let key = cotton_chat::text(request, "key")?.to_string();    if !matches!(act.as_str(), "delete" | "unsubscribe" | "block") {        return Err(bad("act", "delete, unsubscribe or block (Archive is one tap: mail.archive)"));    }    if !matches!(scope.as_str(), "sender" | "domain") {        return Err(bad("scope", "sender or domain"));    }    public_domain(&scope, Some(&key))?;    let at = now_iso(client);    read(client, "mail.ask", |ctx| {        let know = super::cuts::know(ctx)?;        let (addresses, sender) = whole_of(ctx, &know, &scope, &key)?;        if let Some(sheet) = many_senders(&scope, &sender, addresses.len(), request) {            return Ok(sheet);        }        let found = held(ctx, &addresses, None)?;        // A domain's sheet always says how many senders it takes as well as how many mails (review of the rules, 4).        let sender = if scope == "domain" && act != "block" { super::counted_with("ask.domain_senders", addresses.len(), &[("domain", &sender)]) } else { sender };        let provider = provider_of(found.first().and_then(|r| s(r, "account")).as_deref());        let mailbox = super::super::acts::takes(ctx, "sender_trash")?;        let n = found.len();        // "Only the agreed" means the mail counted: up to the newest of them.        let upto = found.iter().filter_map(|r| s(r, "sent_at")).max().unwrap_or_else(|| at.clone());        let mut plan = Plan { act: act.clone(), scope: scope.clone(), key: key.clone(), count: n, at: upto, binning: false };        let cancel = p("ask.cancel", &[]);        let sheet = match act.as_str() {            "delete" => {                if n == 0 {                    return Err(format!("nothing:{}", p("act.gone", &[])));                }                let line = if mailbox { p("ask.delete.line", &[("provider", &provider)]) } else { p("ask.delete.line_cotton_only", &[]) };                json!({ "title": sheet_title("delete", n, &sender), "line": line, "go": p("ask.delete.go", &[("n", &n.to_string())]), "danger": true })            }            "unsubscribe" => {                let one_tap = found.iter().any(|r| s(r, "list_unsubscribe").is_some_and(|v| !v.trim().is_empty()));                let inbox = in_inbox(&found);                if one_tap {                    let also = (inbox > 0).then(|| json!({ "label": p("ask.unsubscribe.also_archive", &[("n", &inbox.to_string())]), "count": inbox, "on": true }));                    json!({ "title": p("ask.unsubscribe.title", &[("sender", &sender)]), "line": p("ask.unsubscribe.line", &[("sender", &sender)]), "go": p("ask.unsubscribe.go", &[]), "also": also })                } else {                    plan.binning = true;                    json!({ "title": p("ask.unsubscribe.none_title", &[("sender", &sender)]), "line": p("ask.unsubscribe.none_line", &[]), "go": p("ask.unsubscribe.none_go", &[("sender", &sender)]) })                }            }            _ => {                let line = if scope == "domain" { p("ask.block.line_domain", &[("domain", &sender)]) } else { p("ask.block.line_address", &[("sender", &sender)]) };                let also = (n > 0).then(|| json!({ "label": p("ask.block.also_delete", &[("n", &n.to_string())]), "count": n, "on": false }));                json!({ "title": p("ask.block.title", &[("sender", &sender)]), "line": line, "go": p("ask.block.go", &[]), "also": also, "danger": true })            }        };        let mut sheet = sheet;        sheet["cancel"] = json!(cancel);        sheet["plan"] = json!(serde_json::to_string(&plan).map_err(|e| e.to_string())?);        Ok(sheet)    })    .map_err(|e| match e.message.strip_prefix("nothing:") {        Some(words) => MethodError::new("nothing", words.to_string()),        None => e,    })}/// Move their mail to the Bin here, and ask his mailbox to follow (one `sender_trash` an address). Answers the Done./// The rows a whole sender's act writes, one per address as the screen grouped them (MAIL PREDICATE phase 2): each/// covers that address's mail sent up to the newest of `found` and landed on the server by the newest landing among/// them, never this phone's clock. All planned and checked before the first is written. Mail of theirs with no/// landing time yet is counted as waiting, not covered.fn plan_cuts(ctx: &mut Ctx<'_>, found: &[Map<String, Value>], addresses: &[String]) -> Result<(Vec<(String, String, String, Vec<String>)>, usize), String> {    let newest = super::cuts::newest_landed(ctx)?;    // His own addresses are never cut (PHASE 2 PHONE 2, low): `_mail_own`, kept by the act before it plans.    let own: Vec<String> = rows(ctx, &format!("SELECT \"key\" FROM {}", mail_cuts::OWN), &[])?.iter().filter_map(|r| s(r, "key")).collect();    let (mut planned, mut waiting) = (Vec::new(), 0);    for address in addresses {        let key = mail_cuts::normalise_key(address);        if own.contains(&key) {            continue;        }        if let Some(why) = mail_cuts::refused_key(&key) {            return Err(format!("cut {key}: {why}"));        }        let mine: Vec<&Map<String, Value>> = found.iter().filter(|r| mail_cuts::normalise_key(&s(r, "a").unwrap_or_default()) == key).collect();        waiting += mine.iter().filter(|r| r.get("landed_at").and_then(Value::as_str).and_then(mail_cuts::normalise_time).is_none()).count();        let Some(before) = mine.iter().filter_map(|r| s(r, "sent_at")).filter_map(|t| mail_cuts::normalise_time(&t)).max() else { continue };        let Some(by) = mail_cuts::cut_at(mine.iter().map(|r| r.get("landed_at").and_then(Value::as_str))) else { continue };        if let Some(why) = mail_cuts::check_cut_at(&by, newest.as_deref()) {            return Err(format!("cut at {by}: {why}"));        }        // What the row will cover, by the predicate's own rule: sent by `before`, landed by `at` (all of `mine` is this        // key's mail).        let covered: Vec<String> = mine            .iter()            .filter(|r| s(r, "sent_at").and_then(|t| mail_cuts::normalise_time(&t)).is_some_and(|t| t <= before) && r.get("landed_at").and_then(Value::as_str).and_then(mail_cuts::normalise_time).is_some_and(|t| t <= by))            .filter_map(|r| s(r, "id"))            .collect();        planned.push((key, before, by, covered));    }    Ok((planned, waiting))}fn bin_all(ctx: &mut Ctx<'_>, know: &Know, found: &[Map<String, Value>], addresses: &[String], sender: &str, at: &str, id: &str) -> Result<Done, String> {    let mut done = Done { id: id.to_string(), act: "delete".into(), at: at.to_string(), mails: Vec::new(), sender: sender.to_string(), filed: Vec::new(), pending: Vec::new(), direct: Vec::new(), cuts: Vec::new(), bin_cuts: Vec::new(), read_cuts: Vec::new(), waiting: 0, provider: provider_of(found.first().and_then(|r| s(r, "account")).as_deref()), undone: false };    // One Delete row per address, however many mails (MAIL PREDICATE phase 2): never a write per mail. Made when he    // tapped (item 1): its 30 days run from then, never from the newest mail it covers.    super::cuts::keep_own(ctx, know.own.iter().map(String::as_str))?;    let (planned, waiting) = plan_cuts(ctx, found, addresses)?;    let made_at = super::cuts::made_at(ctx, at)?;    let unread_of = |mail: &str| found.iter().find(|r| s(r, "id").as_deref() == Some(mail)).is_some_and(|r| truthy(r, "unread"));    for (key, before, by, covered) in planned {        done.bin_cuts.push(super::cuts::cut_in(ctx, super::cuts::BIN, &key, &before, &by, &made_at)?);        done.mails.extend(covered.into_iter().map(|m| { let u = unread_of(&m); (m, u) }));    }    done.waiting = waiting;    let fetched = fetched_accounts(ctx);    for address in addresses {        if let Some(account) = sender_account(ctx, address)?.and_then(|a| fetched.get(&a).cloned()) {            done.pending.push(json!({ "account": account, "kind": "sender_trash", "to": address }));            continue;        }        if crate::phone::chat_app::senders::wide::file_sender_wide(ctx, "sender_trash", address, sender)? {            done.filed.push(("sender_trash".into(), address.clone()));        }    }    Ok(done)}pub(super) fn act_on_plan(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let plan: Plan = serde_json::from_str(cotton_chat::text(request, "plan")?).map_err(|_| bad("plan", "the plan mail.ask answered"))?;    public_domain(&plan.scope, Some(&plan.key))?;    let choice = request.get("choice").and_then(Value::as_str).map(str::to_string);    let also = request.get("also").and_then(Value::as_bool);    let at = now_iso(client);    let id = new_id();    match plan.act.as_str() {        "delete" => {            let mut more: Option<Value> = None;            let done = write(client, "mail.do", |ctx| {                let know = super::cuts::know(ctx)?;                let (addresses, sender) = whole_of(ctx, &know, &plan.scope, &plan.key)?;                let now = held(ctx, &addresses, None)?;                let found = match choice.as_deref() {                    Some("only") => held(ctx, &addresses, Some(&plan.at))?,                    Some("all") => now,                    _ if now.len() == plan.count => now,                    _ => {                        // Delete is the one act he agreed to by its count: more came since, so ask once.                        let (agreed, n) = (plan.count.to_string(), now.len().to_string());                        let word = p("act.delete", &[]);                        more = Some(json!({                            "line": p("ask.more.line", &[("more", &now.len().saturating_sub(plan.count).to_string()), ("sender", &sender), ("done", &p("after.done_words.delete", &[])), ("agreed", &agreed), ("now", &n)]),                            "choices": [                                { "id": "all", "label": p("ask.more.all", &[("act", &word), ("now", &n)]) },                                { "id": "only", "label": p("ask.more.only", &[("act", &word), ("agreed", &agreed)]) },                                { "id": "not_now", "label": p("ask.more.not_now", &[]) },                            ],                        }));                        return Ok(None);                    }                };                Ok(Some(bin_all(ctx, &know, &found, &addresses, &sender, &at, &id)?))            })?;            if let Some(more) = more {                return Ok(json!({ "more": more, "plan": request["plan"] }));            }            let mut done = done.ok_or_else(|| MethodError::new("nothing", p("act.gone", &[])))?;            run_direct(client, &mut done);            keep(client, &done)?;            let line = with_waiting(client, if done.mails.len() == 1 { p("after.deleted_one", &[]) } else { p("after.deleted", &[("n", &done.mails.len().to_string())]) }, done.waiting);            Ok(after_json(&done, line, &[]))        }        "unsubscribe" if !plan.binning => {            let (addresses, sender) = read(client, "mail.do", |ctx| { let know = super::cuts::know(ctx)?; whole_of(ctx, &know, &plan.scope, &plan.key) })?;            for address in &addresses {                crate::phone::chat_app::senders::wide::unsubscribe(client, address)?;            }            let time = Clock::of(client).recent(&at).unwrap_or_default();            let mut answer = json!({ "act": "unsubscribe", "line": p("after.unsubscribed", &[("sender", &sender), ("time", &time)]) });            if also.unwrap_or(true) {                let archived = archive(client, &json!({ "scope": plan.scope, "key": plan.key }))?;                if archived["count"].as_u64().unwrap_or(0) > 0 {                    answer["archived"] = archived;                }            }            Ok(answer)        }        _ => {            // Block, or Bin new mail from a sender with no one-tap unsubscribe: the same rule, said its own way.            let (addresses, sender) = read(client, "mail.do", |ctx| { let know = super::cuts::know(ctx)?; whole_of(ctx, &know, &plan.scope, &plan.key) })?;            for address in &addresses {                crate::phone::chat_app::senders::act(client, &json!({ "key": address, "act": "block" }))?;            }            let key = if plan.binning { "after.binning" } else { "after.blocked" };            let mut answer = json!({ "act": "block", "line": p(key, &[("sender", &sender)]) });            if !plan.binning && also == Some(true) {                let done = write(client, "mail.do", |ctx| {                    let know = super::cuts::know(ctx)?;                    let found = held(ctx, &addresses, None)?;                    bin_all(ctx, &know, &found, &addresses, &sender, &at, &id)                })?;                let mut done = done;                run_direct(client, &mut done);                keep(client, &done)?;                if !done.mails.is_empty() {                    let line = if done.mails.len() == 1 { p("after.deleted_one", &[]) } else { p("after.deleted", &[("n", &done.mails.len().to_string())]) };                    answer["deleted"] = after_json(&done, line, &[]);                }            }            Ok(answer)        }    }}// ── the Bin: 30 days, then gone ────────────────────────────────────────/// How long the Bin keeps a mail.const BIN_DAYS: i64 = 30;/// Mails one sweep erases at most; the next takes the rest.const SWEEP_MAX: usize = 500;/// Erase (ERASES) what has sat in the Bin 30 days, on every device. Answers how many went.pub(super) fn sweep_bin(client: &ClientController) -> Result<usize, MethodError> {    let cut = (client.clock().now() - chrono::Duration::days(BIN_DAYS)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true);    let now = now_iso(client);    write(client, "mail.bin.sweep", |ctx| {        let due = rows(ctx, &format!("SELECT id, thread_id FROM {EMAILS} WHERE workspace_id = ? AND {binned_mail} AND trashed_at <= ? ORDER BY trashed_at LIMIT {SWEEP_MAX}", binned_mail = mail_predicate::binned("")), &[ws(ctx), text(cut.clone())])?;        let mails: Vec<(String, String)> = due.iter().filter_map(|r| Some((s(r, "id")?, s(r, "thread_id").unwrap_or_default()))).collect();        if !mails.is_empty() {            crate::phone::chat_app::senders::erase::erase_mails(ctx, &mails, &now)?;        }        Ok(mails.len())    })}/// What a whole sender's Delete covers, erased 30 days after he made it (decisions 1 and 3; PHASE 2 PHONE 2, items 1/// and 3): never decided by the server, never by the newest mail it covers.////// A Delete row moves live → erasing → erased, each a write of its one row held to the version this copy read, and/// Undo is live → undone the same way: the object's version check makes one of them win. So:/// - a due row (by `made_at`) is first written erasing, and nothing is erased until the object has taken that write;/// - each slice reads the row again and goes on only while it is still erasing or erased;/// - a state this copy wrote that lost (its post refused as moved) takes the winner's, and a lost Undo shows its Undo///   again, refused "already being erased" when tapped;/// - once nothing of it is left and every erase was taken, it is erased, and stays: mail it covers that turns up later///   (opened from the parks, outside keep rules, its arrival time learned late) is erased where it is seen, never///   shown live. A cut only covers mail landed by its `at`, so it never grows./// Answers how many mails this step erased.pub(super) fn erase_cuts(client: &ClientController) -> Result<usize, MethodError> {    let due = (client.clock().now() - chrono::Duration::days(BIN_DAYS)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true);    let now = now_iso(client);    let lost = write(client, "mail.bin.settle", |ctx| super::cuts::merge_states(ctx))?;    reopen_lost_undo(client, &lost)?;    write(client, "mail.bin.erase", |ctx| {        let know = super::cuts::know(ctx)?;        super::cuts::keep_own(ctx, know.own.iter().map(String::as_str))?;        for id in super::cuts::due(ctx, &due)? {            super::cuts::begin_erasing(ctx, &id)?;        }        let mut erased = 0usize;        for (id, state) in super::cuts::erasing_cuts(ctx)? {            if erased >= SWEEP_MAX {                break;            }            // Only once the object has taken this copy's last write of the row, and while the row still says so.            if !super::cuts::taken(ctx, &id)? || !super::cuts::undo_refused(ctx, &id)? {                continue;            }            let covered = super::cuts::bin_covered(ctx, &id, SWEEP_MAX - erased)?;            let mails: Vec<(String, String)> = covered.iter().filter_map(|r| Some((s(r, "id")?, s(r, "thread_id").unwrap_or_default()))).collect();            if !mails.is_empty() {                crate::phone::chat_app::senders::erase::erase_mails(ctx, &mails, &now)?;                erased += mails.len();                continue;            }            let unsent = one(ctx, "SELECT 1 AS one FROM _outbox WHERE tbl IN ('email', 'cotton_emails') LIMIT 1", &[])?.is_some();            if state == "erasing" && !unsent {                super::cuts::mark_erased(ctx, &id)?;            }        }        Ok(erased)    })}/// An Undo this copy made that lost to an erase begun elsewhere: its act shows Undo again, and Undo now says it is too/// late, so he is never left believing mail came back that is being erased.fn reopen_lost_undo(client: &ClientController, lost: &[(String, String, String)]) -> Result<(), MethodError> {    for (id, mine, theirs) in lost {        if mine != "undone" || !matches!(theirs.as_str(), "erasing" | "erased") {            continue;        }        for mut done in afters(client).into_iter().filter(|d| d.undone && d.bin_cuts.contains(id)) {            done.undone = false;            keep(client, &done)?;        }    }    Ok(())}/// `mail.bin.empty { count }` (ERASES): every mail in the Bin, gone for good now, only when `count` is what the Bin/// holds (the sheet's number); else it answers the Bin's count to ask again.pub(super) fn empty_bin(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let count = request.get("count").and_then(Value::as_u64);    let now = now_iso(client);    write(client, "mail.bin.empty", |ctx| {        let all = rows(ctx, &format!("SELECT id, thread_id FROM {EMAILS} WHERE workspace_id = ? AND {binned_mail}", binned_mail = mail_predicate::binned("")), &[ws(ctx)])?;        let n = all.len();        if count != Some(n as u64) {            return Ok(json!({ "ask": { "line": super::counted("bin.empty_ask", n as usize), "go": p("bin.empty_go", &[("n", &n.to_string())]), "cancel": p("ask.cancel", &[]), "count": n } }));        }        let mails: Vec<(String, String)> = all.iter().filter_map(|r| Some((s(r, "id")?, s(r, "thread_id").unwrap_or_default()))).collect();        crate::phone::chat_app::senders::erase::erase_mails(ctx, &mails, &now)?;        Ok(json!({ "emptied": n, "line": p("after.emptied", &[("n", &n.to_string())]) }))    })}/// A line, or a sentence in it, that opens with "your mailbox" opens with a capital.fn capital(line: &str) -> String {    let line = line.replace(". your mailbox", ". Your mailbox");    let mut chars = line.chars();    chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default()}#[cfg(test)]#[test]fn mailbox_lines_open_with_capitals() {    assert_eq!(capital("your mailbox will follow in a moment."), "Your mailbox will follow in a moment.");    assert_eq!(capital("Back in your Inbox here. your mailbox still has it archived."), "Back in your Inbox here. Your mailbox still has it archived.");}// ── a Cotton-fetched account's acts, done by the object ────────────────/// His accounts Cotton fetches: address → the `email_account` id the object knows them by.fn fetched_accounts(ctx: &mut Ctx<'_>) -> HashMap<String, String> {    super::accounts(ctx)        .into_iter()        .filter(|a| a.get("way").and_then(Value::as_str) == Some("cotton"))        .filter_map(|a| Some((a.get("address")?.as_str()?.to_lowercase(), a.get("id")?.as_str()?.to_string())))        .collect()}/// The account a sender's newest mail came to.fn sender_account(ctx: &mut Ctx<'_>, address: &str) -> Result<Option<String>, String> {    Ok(one(ctx, &format!("SELECT lower(coalesce(account, gmail_account)) AS a FROM {EMAILS} WHERE workspace_id = ? AND lower(trim(from_email)) = ? ORDER BY sent_at DESC LIMIT 1"), &[ws(ctx), text(address.to_string())])?.and_then(|r| s(&r, "a")))}/// Do each pending act through `POST /v1/mail/fetch/act` (meetings-comms, row 13): the IMAP work happens inside the/// request and nothing of the act is kept there. A whole sender's move counts first (`sender_count`), then moves/// exactly the set counted. Each answer becomes a state for the mailbox line.fn run_direct(client: &ClientController, done: &mut Done) {    let pending = std::mem::take(&mut done.pending);    if pending.is_empty() {        return;    }    let Some(door) = client.object_door() else {        done.direct.extend(pending.iter().map(|_| ("failed".to_string(), Some(p("after.offline", &[])))));        return;    };    for ask in pending {        let mut ask = ask;        let kind = ask["kind"].as_str().unwrap_or_default().to_string();        if kind == "sender_archive" || kind == "sender_trash" {            match door.send("POST", "/v1/mail/fetch/act", Some(&json!({ "account": ask["account"], "kind": "sender_count", "to": ask["to"] }))) {                Ok(c) if c["ok"].as_bool() == Some(true) => {                    for k in ["count", "uid_validity", "uid_below"] {                        ask[k] = c[k].clone();                    }                }                Ok(c) => {                    done.direct.push(("failed".into(), c["error"].as_str().map(str::to_string)));                    continue;                }                Err(e) => {                    done.direct.push(("failed".into(), Some(e.message)));                    continue;                }            }        }        match door.send("POST", "/v1/mail/fetch/act", Some(&ask)) {            Ok(a) if a["ok"].as_bool() == Some(true) => done.direct.push(("sent".into(), None)),            Ok(a) => done.direct.push(("failed".into(), a["error"].as_str().map(str::to_string))),            Err(e) => done.direct.push(("failed".into(), Some(e.message))),        }    }}/// The after line, with how many of his mails still wait for their landing time (no cut covers them yet)./// The act's line, with the mail it could not cover said truly (PHASE 2 PHONE 2, item 5): while this copy is still/// asking for landing times, that they go once it has caught up; after, that they are not covered.fn with_waiting(client: &ClientController, line: String, waiting: usize) -> String {    if waiting == 0 {        return line;    }    let caught_up = client.with_file(|replica| crate::phone::landed::caught_up(replica.driver.connection())).unwrap_or(false);    format!("{line} {}", super::counted(if caught_up { "after.not_covered" } else { "after.waiting" }, waiting))}/// A whole domain that is a public mail service is never one act's (MAIL PREDICATE phase 2, rule 5): Archive,/// Delete, Unsubscribe and Block of everyone @gmail.com would take strangers' mail with one sender's. Said in words/// before anything is counted or written.fn public_domain(scope: &str, key: Option<&str>) -> Result<(), MethodError> {    if scope != "domain" {        return Ok(());    }    let domain = mail_cuts::normalise_key(key.unwrap_or_default()).trim_start_matches('@').to_string();    if mail_cuts::is_public_domain(&domain) {        return Err(MethodError::new("refused", p("act.public_domain", &[("domain", &domain)])));    }    Ok(())}/// A domain with more than this many different senders here is not taken in one act unless he confirms a second sheet/// that names the count (PHASE 2 PHONE 2, low): an unlisted domain may still be a mail service.pub(super) const MANY_SENDERS: usize = 25;/// The second sheet for a domain of many senders, or None: none once the request carries `senders`, the count named.fn many_senders(scope: &str, domain: &str, senders: usize, request: &Value) -> Option<Value> {    if scope != "domain" || senders <= MANY_SENDERS || request.get("senders").and_then(Value::as_u64) == Some(senders as u64) {        return None;    }    let n = cotton_core::rules::shell_lines::number(senders as i64);    Some(json!({ "confirm": { "line": p("ask.many_senders.line", &[("n", &n), ("domain", domain)]), "go": p("ask.many_senders.go", &[("n", &n)]), "cancel": p("ask.cancel", &[]), "senders": senders } }))}/// How many different senders of a domain this copy holds, by `_mail_landed`'s domain index.fn domain_senders(ctx: &mut Ctx<'_>, key: &str) -> Result<usize, String> {    let domain = format!("@{}", mail_cuts::normalise_key(key).trim_start_matches('@'));    Ok(one(ctx, &format!("SELECT count(DISTINCT \"key\") AS n FROM {} WHERE domain = ?", mail_cuts::LANDED), &[text(domain)])?.and_then(|r| r.get("n").and_then(Value::as_i64)).unwrap_or(0) as usize)}/// A cut's `except` full: said in words, and Undo offered only where it can still be done.fn except_full(why: String) -> String {    match why.as_str() {        super::cuts::EXCEPT_FULL => p("act.except_full", &[]),        super::cuts::ERASING_FULL => p("act.erasing_full", &[]),        _ => why,    }}