Cotton code
1630 lines · 89.6 KB · RustRaw
//! Mail in Comms (assets/design/chat/MAIL.md, 21 Nov 2026), answered from the//! phone's own copy of `email_thread` and `email`://!//! ```text//! chat.mail        { filter?: all|people|unread, after?, text? } → the Mail tab//! chat.mail.thread { thread }                                    → a conversation of mail, whole; read here//! chat.mail.file   { email, index, dir }                         → { path, mime, name }   refused not_kept, file_offline//! chat.mail.free   { dir? }                                      → { freed, said }//! ```//!//! and the mail a chat's person and the person sent each other, woven by time//! into `chat.thread`'s page ([`weave`]). Who wrote is//! `cotton_core::mail::who`, over the facts this copy holds ([`Know`]). Every//! word is the kit's (`chat` set, `app.mail.*`).use std::collections::{HashMap, HashSet};use cotton_core::mail::group::{self as grouping, Group, Headers};use cotton_core::mail::who::{self as rule, Facts, Who};use cotton_core::rules::mail_predicate;use super::*;const EMAILS: &str = "cotton_emails";const MAIL_THREADS: &str = "cotton_email_threads";/// Rows of the Mail tab a page answers.const PAGE: usize = 40;/// Mail a chat's page weaves in at most./// Where this phone keeps the keys of the attachments it fetched (`chat.mail.free` frees them).const OPENED: &str = "chat-mail-opened.json";/// Every method this module answers.pub const METHODS: [&str; 15] = ["chat.mail", "chat.mail.act", "chat.mail.compose", "chat.mail.countSender", "chat.mail.discard", "chat.mail.file", "chat.mail.free", "chat.mail.page", "chat.mail.hold", "chat.mail.save", "chat.mail.send", "chat.mail.sender", "chat.mail.thread", "chat.mail.trashSender", "chat.sender.page"];#[path = "chat_mail_write.rs"]mod writing;#[path = "chat_mail_sender.rs"]mod sender;#[path = "chat_mail_acts.rs"]pub(crate) mod acts;#[path = "chat_mail_post.rs"]pub(crate) mod post;#[path = "chat_mail_sender_page.rs"]mod sender_page;pub(super) fn answer(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "chat.mail" => list(client, request),        "chat.mail.thread" => thread(client, request),        "chat.mail.file" => file(client, request),        "chat.mail.page" => page(client, request),        "chat.mail.free" => free(client, request),        "chat.mail.compose" => writing::compose(client, request),        "chat.mail.save" => writing::save(client, request),        "chat.mail.discard" => writing::discard(client, request),        "chat.mail.send" => writing::send(client, request),        "chat.mail.sender" => sender::page(client, request),        "chat.mail.countSender" => sender::count(client, request),        "chat.mail.trashSender" => sender::trash(client, request),        "chat.mail.hold" => acts::hold(client, request),        "chat.mail.act" => acts::act(client, request),        "chat.sender.page" => sender_page::page(client, request),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a mail method"))),    }}/// Each mail sender's group (Senders 3), by address in lower case: the rule over the newest mail they sent here and/// what the copy knows of them; `None` for junk.pub(crate) fn sender_groups(ctx: &mut Ctx<'_>) -> Result<HashMap<String, Option<Group>>, String> {    sender_groups_in(ctx, None)}/// The groups of only the senders `only` covers (`senders::mail_where`)./// Each sender's newest mail, its `columns`: found over `idx_cotton_emails_sender` alone (their `sent_at`, then the/// rowid every index holds), then only those rows read (schema 153, SENDERS INDEX).pub(crate) fn newest_sql(columns: &str, clause: &str) -> String {    format!("SELECT {columns} FROM {EMAILS} WHERE rowid IN (SELECT CAST(substr(newest, instr(newest, char(31)) + 1) AS INTEGER) FROM (SELECT MAX(COALESCE(sent_at, '') || char(31) || printf('%020d', rowid)) AS newest FROM {EMAILS} WHERE workspace_id = ? AND {live_mail} AND {clause} GROUP BY lower(trim(from_email))))", live_mail = mail_predicate::live(""))}pub(crate) fn sender_groups_in(ctx: &mut Ctx<'_>, only: Option<&[String]>) -> Result<HashMap<String, Option<Group>>, String> {    let know = Know::read(ctx)?;    let columns = know.mail_columns();    let (clause, mut scoped) = crate::phone::chat_app::senders::mail_where(only);    let mut params = vec![ws(ctx)];    params.append(&mut scoped);    let found = rows(        ctx,        // Each sender's newest mail found in one grouped pass over `idx_cotton_emails_sender` alone (schema 153: its        // `sent_at`, then its rowid, which every index holds, so on a tie the later-landed), then only those rows read whole: the window over every whole mail        // took seconds on an account of 100,000 (SENDERS 3 WALKED).        &newest_sql(&columns, &clause),        &params,    )?;    let mut out = HashMap::new();    for mail in found {        let Some(address) = lower(s(&mail, "from_email")) else { continue };        if know.is_own(&address) {            continue;        }        let group = know.group(&address, None, Some(&mail));        out.insert(address, group);    }    Ok(out)}// ── what the copy knows of senders ─────────────────────────────────────/// The facts the rule reads, gathered once per answer.#[derive(Debug, Default, Clone)]pub(super) struct Know {    /// The person's own addresses: the mailboxes their mail was read from.    own: HashSet<String>,    /// An email handle of someone in People → that person.    people: HashMap<String, String>,    /// An email handle of someone in People → their name there.    named: HashMap<String, String>,    /// A person in People → their one-to-one chat here.    chatted: HashMap<String, String>,    /// Addresses the person sent mail to (To).    written: HashSet<String>,    blocked: HashSet<String>,    /// The person's own verdict on a sender.    verdicts: HashMap<String, String>,    /// The conversations holding mail the person sent (the Sent chip).    sent: HashSet<String>,    /// Post's archived senders (`email_cut`), read by Post alone (`post::cuts::know`); empty for Comms.    cuts: Vec<post::cuts::Cut>,}fn lower(value: Option<String>) -> Option<String> {    value.map(|v| v.trim().to_lowercase()).filter(|v| !v.is_empty())}/// A row's value from a table this copy may not hold: none when it does not.fn maybe(ctx: &mut Ctx<'_>, sql: &str) -> Vec<Map<String, Value>> {    let params = [ws(ctx)];    rows(ctx, sql, &params).unwrap_or_default()}/// The `to` addresses of a recipients list, lower-cased.fn to_of(recipients: &Value) -> Vec<(String, Option<String>)> {    let list = match recipients {        Value::String(text) => serde_json::from_str::<Value>(text).unwrap_or(Value::Null),        other => other.clone(),    };    list.as_array()        .into_iter()        .flatten()        .filter(|r| r.get("kind").and_then(Value::as_str).unwrap_or("to") == "to")        .filter_map(|r| Some((r.get("email")?.as_str()?.trim().to_lowercase(), r.get("name").and_then(Value::as_str).map(str::to_string))))        .collect()}/// Every recipient of a list as (address, name, kind).fn recipients_of(recipients: &Value) -> Vec<(String, Option<String>, String)> {    let list = match recipients {        Value::String(text) => serde_json::from_str::<Value>(text).unwrap_or(Value::Null),        other => other.clone(),    };    list.as_array()        .into_iter()        .flatten()        .filter_map(|r| {            Some((                r.get("email")?.as_str()?.trim().to_lowercase(),                r.get("name").and_then(Value::as_str).map(str::to_string).filter(|n| !n.is_empty()),                r.get("kind").and_then(Value::as_str).unwrap_or("to").to_string(),            ))        })        .collect()}impl Know {    /// The name in People of whoever holds `address`, when someone does.    pub(super) fn name_of(&self, address: &str) -> Option<&str> {        self.named.get(&address.trim().to_lowercase()).map(String::as_str)    }    pub(super) fn read(ctx: &mut Ctx<'_>) -> Result<Know, String> {        let mut know = Know::default();        // The mailboxes his mail was read from: each mail's `account`, else its `gmail_account`, word for word the        // expression `idx_cotton_emails_account_live` holds, so it is read from that index alone (37 ms over 110,000        // mails, where reading `gmail_account` off the rows read every mail's body: 200 ms, 26 Nov 2026).        let accounts = rows(            ctx,            &format!("SELECT DISTINCT lower(coalesce(account, gmail_account)) AS a FROM {EMAILS} WHERE workspace_id = ? AND lower(coalesce(account, gmail_account)) IS NOT NULL"),            &[ws(ctx)],        )?;        know.own.extend(accounts.into_iter().filter_map(|r| lower(s(&r, "a"))));        for r in maybe(ctx, "SELECT google_email AS a FROM cotton_google_accounts WHERE workspace_id = ?") {            know.own.extend(lower(s(&r, "a")));        }        for r in maybe(ctx, "SELECT reaches AS a FROM cotton_connections WHERE workspace_id = ? AND kind IN ('google', 'mail')") {            know.own.extend(lower(s(&r, "a")));        }        for r in maybe(ctx, "SELECT h.normalised AS a, h.person_id AS p, p.full_name AS n FROM cotton_person_handles h JOIN cotton_people p ON p.id = h.person_id WHERE h.workspace_id = ? AND h.kind = 'email' AND h.trashed_at IS NULL AND p.trashed_at IS NULL") {            if let (Some(a), Some(p)) = (lower(s(&r, "a")), s(&r, "p")) {                if let Some(n) = s(&r, "n").map(|n| n.trim().to_string()).filter(|n| !n.is_empty()) {                    know.named.insert(a.clone(), n);                }                know.people.insert(a, p);            }        }        // A person's chat: one whose contact is them, or (a contact never tied to People, as most are) whose number        // is one of their phone handles. Seen on an emulator (22 Nov 2026): Ada in People with her number, a chat        // with that number, and her mail stood in the Mail tab, not in her chat.        let chats = format!(            "SELECT p, t FROM (SELECT {person} AS p, t.id AS t, t.last_message_at AS at \             FROM {THREADS} t JOIN cotton_msg_contacts c ON c.id = t.contact_id \             WHERE t.workspace_id = ? AND t.trashed_at IS NULL AND coalesce(t.kind, '') <> 'group') WHERE p IS NOT NULL ORDER BY at ASC",            person = cotton_store::protocol::who::contact_person_sql(cotton_store::protocol::who::shared_held(ctx.db()), "c"),        );        for r in maybe(ctx, &chats) {            if let (Some(p), Some(t)) = (s(&r, "p"), s(&r, "t")) {                know.chatted.insert(p, t);            }        }        for r in maybe(ctx, "SELECT address AS a FROM cotton_blocked_senders WHERE workspace_id = ?") {            know.blocked.extend(lower(s(&r, "a")));        }        for r in maybe(ctx, "SELECT address AS a FROM cotton_email_senders WHERE workspace_id = ? AND written_to = 1") {            know.written.extend(lower(s(&r, "a")));        }        for r in maybe(ctx, "SELECT address AS a, verdict AS v FROM cotton_email_senders WHERE workspace_id = ? AND decided_by = 'owner' AND verdict IS NOT NULL") {            if let (Some(a), Some(v)) = (lower(s(&r, "a")), s(&r, "v")) {                know.verdicts.insert(a, v);            }        }        if !know.own.is_empty() {            let own: Vec<String> = know.own.iter().cloned().collect();            let sent = rows_in(ctx, &format!("SELECT recipients, thread_id FROM {EMAILS} WHERE workspace_id = ? AND {live_mail}", live_mail = mail_predicate::live("")), "from_email", &own)?;            for r in sent {                know.sent.extend(s(&r, "thread_id"));                for (address, _) in to_of(r.get("recipients").unwrap_or(&Value::Null)) {                    if !know.own.contains(&address) {                        know.written.insert(address);                    }                }            }        }        Ok(know)    }    /// Whether the person ever wrote to `address` (sent it mail, or the sender's row says so).    pub(super) fn wrote_to(&self, address: &str) -> bool {        self.written.contains(address)    }    pub(super) fn is_own(&self, address: &str) -> bool {        self.own.contains(address)    }    /// The person's own address a new mail is from: the first of theirs, in order.    pub(super) fn own_first(&self) -> Option<String> {        let mut own: Vec<&String> = self.own.iter().collect();        own.sort();        own.first().map(|a| a.to_string())    }    /// What the rule says `address` is, the thread's stored kind beside it, and `mail`, the newest it sent (its    /// name, subject, words and recipients), when there is one.    pub(super) fn who(&self, address: &str, stored: Option<&str>, mail: Option<&Map<String, Value>>) -> Who {        self.judged(address, stored, mail).0    }    /// Its group (Senders 3: People, Notices, Promotions; none for junk), by `grouping::group` over the same facts and    /// the headers the Mac kept of that mail.    pub(super) fn group(&self, address: &str, stored: Option<&str>, mail: Option<&Map<String, Value>>) -> Option<Group> {        self.judged(address, stored, mail).1    }    fn judged(&self, address: &str, stored: Option<&str>, mail: Option<&Map<String, Value>>) -> (Who, Option<Group>) {        let name = mail.and_then(|m| s(m, "from_name"));        let subject = mail.and_then(|m| s(m, "subject"));        let words = mail.and_then(|m| s(m, "body").or_else(|| s(m, "snippet")));        let precedence = mail.and_then(|m| lower(s(m, "precedence")));        let category = mail.and_then(|m| lower(s(m, "gmail_category")));        let facts = Facts {            address,            blocked: self.blocked.contains(address),            owner_verdict: self.verdicts.get(address).map(String::as_str),            in_people: self.people.contains_key(address),            written_to: self.written.contains(address),            stored_kind: stored,            name: name.as_deref(),            subject: subject.as_deref(),            text: words.as_deref(),            to_a_list: mail.is_some_and(|m| self.to_a_list(m)),        };        let headers = Headers {            list_unsubscribe: mail.and_then(|m| s(m, "list_unsubscribe")).is_some_and(|v| !v.trim().is_empty()),            precedence: precedence.as_deref(),            gmail_category: category.as_deref(),        };        (rule::who(&facts).0, grouping::group(&facts, &headers).map(|(g, _)| g))    }    /// The columns a mail row is read with, the headers the Mac keeps with them (schema 152).    fn mail_columns(&self) -> String {        format!("{MAIL_COLUMNS}, {HEADER_COLUMNS}")    }    /// Whether `mail` went to a list and not to the person: a list's address in its To or Cc, and none of theirs.    fn to_a_list(&self, mail: &Map<String, Value>) -> bool {        let to = recipients_of(mail.get("recipients").unwrap_or(&Value::Null));        to.iter().any(|(a, _, _)| rule::is_list_address(a)) && !to.iter().any(|(a, _, _)| self.is_own(a))    }    /// The chat `address`'s mail stands in, when it is a person's with a chat here.    pub(super) fn chat_of(&self, address: &str, stored: Option<&str>, mail: Option<&Map<String, Value>>) -> Option<&String> {        (self.who(address, stored, mail) == Who::Person).then(|| self.people.get(address).and_then(|p| self.chatted.get(p))).flatten()    }}// ── one conversation of mail as the list reads it ──────────────────────/// A thread of mail: its row and what its messages say about it.struct Conv {    id: String,    last_at: String,    subject: Option<String>,    count: i64,    stored: Option<String>,    /// The other side: who wrote to the person, or whom the person wrote to.    address: String,    name: Option<String>,    newest: Option<Map<String, Value>>,    /// The newest mail the other side sent in it, when they wrote: what the rule reads of them.    theirs: Option<Map<String, Value>>,    unread: bool,}impl Conv {    fn who(&self, know: &Know) -> Who {        know.who(&self.address, self.stored.as_deref(), self.theirs.as_ref())    }    fn group(&self, know: &Know) -> Option<Group> {        know.group(&self.address, self.stored.as_deref(), self.theirs.as_ref())    }    fn chat<'k>(&self, know: &'k Know) -> Option<&'k String> {        know.chat_of(&self.address, self.stored.as_deref(), self.theirs.as_ref())    }}const MAIL_COLUMNS: MailColumns = MailColumns;/// [`MAIL_COLUMNS`], said into a statement: `unread` through the shared mail predicate (MAIL PREDICATE).#[derive(Clone, Copy)]struct MailColumns;impl std::fmt::Display for MailColumns {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        write!(f, "id, thread_id, subject, from_email, from_name, recipients, sent_at, body, snippet, attachments, {} AS unread", mail_predicate::unread(""))    }}/// What the Mac keeps of a mail's headers (Senders 3, CONTRACT "Senders 3: what the Mac keeps"), read where held.const HEADER_COLUMNS: &str = "list_unsubscribe, precedence, gmail_category";/// A thread of mail from its row and its messages (`oldest` first, a few), `newest` and whether any is unread./// The sender is the row's stored address, else who first wrote to the person in it; when the person wrote every/// message, the first they wrote to.fn conv_with(know: &Know, t: &Map<String, Value>, oldest: &[Map<String, Value>], newest: Option<Map<String, Value>>, unread: bool) -> Option<Conv> {    let id = s(t, "id")?;    if oldest.is_empty() && newest.is_none() {        return None;    }    let first = oldest.first().or(newest.as_ref());    let (address, name) = match lower(s(t, "sender_address")) {        Some(a) => {            let name = oldest.iter().chain(newest.iter()).find(|m| lower(s(m, "from_email")).as_deref() == Some(a.as_str())).and_then(|m| s(m, "from_name"));            (a, name)        }        None => match oldest.iter().chain(newest.iter()).find(|m| lower(s(m, "from_email")).is_some_and(|f| !know.is_own(&f))) {            Some(m) => (lower(s(m, "from_email")).unwrap_or_default(), s(m, "from_name")),            None => {                let to = first.map(|m| to_of(m.get("recipients").unwrap_or(&Value::Null))).unwrap_or_default();                match to.into_iter().find(|(a, _)| !know.is_own(a)) {                    Some((a, name)) => (a, name),                    None => (lower(first.and_then(|m| s(m, "from_email"))).unwrap_or_default(), None),                }            }        },    };    let theirs = newest.iter().chain(oldest.iter().rev()).find(|m| lower(s(m, "from_email")).as_deref() == Some(address.as_str())).cloned();    Some(Conv {        id,        last_at: s(t, "last_at").or_else(|| newest.as_ref().and_then(|m| s(m, "sent_at"))).unwrap_or_default(),        subject: s(t, "subject").or_else(|| first.and_then(|m| s(m, "subject"))),        count: n(t, "email_count").max(oldest.len() as i64),        stored: s(t, "sender_kind"),        address,        name,        newest,        theirs,        unread,    })}fn conv_of(ctx: &mut Ctx<'_>, know: &Know, t: &Map<String, Value>) -> Result<Option<Conv>, String> {    let Some(id) = s(t, "id") else { return Ok(None) };    let columns = know.mail_columns();    // Archived here (Senders 3: Archive) is out of every list, kept.    let live = " AND archived_at IS NULL";    let oldest = rows(ctx, &format!("SELECT {columns} FROM {EMAILS} WHERE thread_id = ? AND {live_mail}{live} ORDER BY sent_at ASC, id ASC LIMIT 8", live_mail = mail_predicate::live("")), &[text(id.clone())])?;    if oldest.is_empty() {        return Ok(None);    }    let newest = one(ctx, &format!("SELECT {columns} FROM {EMAILS} WHERE thread_id = ? AND {live_mail}{live} ORDER BY sent_at DESC, id DESC LIMIT 1", live_mail = mail_predicate::live("")), &[text(id.clone())])?;    let unread = one(ctx, &format!("SELECT 1 AS u FROM {EMAILS} WHERE thread_id = ? AND {live_mail}{live} AND {unread_mail} LIMIT 1", unread_mail = mail_predicate::unread(""), live_mail = mail_predicate::live("")), &[text(id.clone())])?.is_some();    Ok(conv_with(know, t, &oldest, newest, unread))}// ── beyond the window: the object's older mail, opened here ────────────/// The object's answer to `GET /v1/older?<query>` (MAIL.md): a dated table's rows older than this copy's window,/// sealed as it stores them, each opened here with the database's key. Only clear columns are asked about.fn from_object(client: &ClientController, table: &str, query: &str) -> Result<Vec<Map<String, Value>>, MethodError> {    let lines = list::lines();    let database = client.current_database().map_err(|why| MethodError::new("not_attached", why))?;    let keys: std::sync::Arc<dyn cotton_client::seal::DataKeyStore> = client.data_keys().clone();    let sealer = cotton_client::seal::Sealer::new(database, keys);    let door = client.object_door().ok_or_else(|| MethodError::new("file_offline", say(&lines, "app.mail.older_offline", &[])))?;    let answer = door        .send("GET", &format!("/v1/older?table={table}&{query}"), None)        .map_err(|refused| older_said(&lines, table, refused))?;    let mut out = Vec::new();    for row in answer.get("rows").and_then(Value::as_array).into_iter().flatten() {        let (Some(id), Some(data)) = (row.get("id").and_then(Value::as_str), row.get("data").and_then(Value::as_object)) else { continue };        // A row that does not open is left out of the page, said in the log, never drawn blank.        match sealer.open(table, id, data) {            Ok(mut open) => {                open.insert("id".into(), Value::from(id));                out.push(open);            }            Err(error) => tracing::warn!("chat.mail: {table} {id} from the object did not open ({})", error.code()),        }    }    Ok(out)}/// Whatever kept the object's older mail away (offline, a Worker that does not page yet, a refusal), the person/// is told in the kit's words, never the transport's; the cause goes to the log. Seen on an emulator (22 Nov 2026):/// an empty Mail tab said "nothing answers GET /v1/older".fn older_said(lines: &LineSet, table: &str, refused: MethodError) -> MethodError {    tracing::warn!("chat.mail: the object's older {table} did not come ({}: {})", refused.code, refused.message);    MethodError::new("file_offline", say(lines, "app.mail.older_offline", &[]))}fn part(value: &str) -> String {    url::form_urlencoded::byte_serialize(value.as_bytes()).collect()}fn newest_first(mut mail: Vec<Map<String, Value>>) -> Vec<Map<String, Value>> {    mail.sort_by(|a, b| (s(b, "sent_at"), s(b, "id")).cmp(&(s(a, "sent_at"), s(a, "id"))));    mail}/// Threads older than `before` from the object, with their mail in the same span, as the Mail tab draws them.fn older_listed(client: &ClientController, know: &Know, filter: &str, before: (String, String), want: usize) -> Result<Found, MethodError> {    let mut out = Vec::new();    let mut cursor = before;    for _ in 0..4 {        let threads = from_object(client, "email_thread", &format!("before={}&id={}&limit=60", part(&cursor.0), part(&cursor.1)))?;        if threads.is_empty() {            return Ok((out, None));        }        let newest_at = threads.iter().filter_map(|t| s(t, "last_at")).max().unwrap_or_default();        let oldest_at = threads.iter().filter_map(|t| s(t, "last_at")).min().unwrap_or_default();        // Each thread's newest mail was sent at its last_at: one ask holds every one of them.        let mail = from_object(client, "email", &format!("from={}&to={}&limit=1000", part(&oldest_at), part(&newest_at)))?;        let mut by_thread: HashMap<String, Vec<Map<String, Value>>> = HashMap::new();        for m in mail.into_iter().filter(|m| m.get("trashed_at").is_none_or(Value::is_null) && m.get("archived_at").is_none_or(Value::is_null)) {            by_thread.entry(s(&m, "thread_id").unwrap_or_default()).or_default().push(m);        }        for t in &threads {            cursor = (s(t, "last_at").unwrap_or_default(), s(t, "id").unwrap_or_default());            if t.get("trashed_at").is_some_and(|v| !v.is_null()) {                continue;            }            let mine = newest_first(by_thread.remove(&cursor.1).unwrap_or_default());            let unread = mine.iter().any(|m| truthy(m, "unread"));            let mut oldest = mine.clone();            oldest.reverse();            let Some(c) = conv_with(know, t, &oldest, mine.first().cloned(), unread) else { continue };            if shown(know, &c, filter) {                out.push(c);                if out.len() == want {                    return Ok((out, Some(object_cursor(&cursor))));                }            }        }        if threads.len() < 60 {            return Ok((out, None));        }    }    Ok((out, Some(object_cursor(&cursor))))}const OBJECT: &str = "object";fn object_cursor(at: &(String, String)) -> String {    format!("{OBJECT}\u{1f}{}\u{1f}{}", at.0, at.1)}/// Whether the Mail tab shows a thread: not junk, not a person's who has a chat here, by the filter.fn shown(know: &Know, c: &Conv, filter: &str) -> bool {    let who = c.who(know);    who != Who::Junk        && c.chat(know).is_none()        && match filter {            "people" | "notices" | "promotions" => c.group(know).map(Group::as_str) == Some(filter),            "unread" => c.unread,            "sent" => know.sent.contains(&c.id),            _ => true,        }}/// Mail beyond the window holding the search, by its words' blind tokens (`GET /v1/blind`, MAIL.md): the object/// is asked by tokens alone, and each hit is opened and held to the words here. Its threads, newest first.fn searched_beyond(client: &ClientController, know: &Know, words: &str, held: &HashSet<String>) -> Result<Vec<Conv>, MethodError> {    let database = client.current_database().map_err(|why| MethodError::new("not_attached", why))?;    let keys: std::sync::Arc<dyn cotton_client::seal::DataKeyStore> = client.data_keys().clone();    let sealer = cotton_client::seal::Sealer::new(database, keys);    let Some(door) = client.object_door() else { return Ok(Vec::new()) };    let tables = cotton_client::transport::object::ObjectTables::personal();    let Some(spec) = tables.object("email").and_then(|stored| stored.seal.clone()) else { return Ok(Vec::new()) };    let mut get = |path: &str| door.send("GET", path, None).map_err(|error| format!("{}: {}", error.code, error.message));    let local = |id: &str| held.contains(id);    // Whatever keeps the object's history away is said in the kit's words, the cause in the log (seen on an emulator,    // 22 Nov 2026: a search's foot said "internal_error: the business did not answer").    let found = cotton_client::seal::search::search_beyond(&sealer, "email", &spec, Some("sent_at"), words, PAGE * 3, &local, &mut get)        .map_err(|why| older_said(&list::lines(), "email", MethodError::new("file_offline", why)))?;    let mut by_thread: Vec<(String, Vec<Map<String, Value>>)> = Vec::new();    for hit in found.hits {        let thread = s(&hit.row, "thread_id").unwrap_or_default();        let mut row = hit.row;        row.insert("id".into(), Value::from(hit.id));        match by_thread.iter_mut().find(|(t, _)| *t == thread) {            Some((_, mail)) => mail.push(row),            None => by_thread.push((thread, vec![row])),        }    }    let mut out = Vec::new();    for (thread, mail) in by_thread {        let mail = newest_first(mail);        let t = json!({ "id": thread }).as_object().cloned().unwrap_or_default();        let mut oldest = mail.clone();        oldest.reverse();        let unread = mail.iter().any(|m| truthy(m, "unread"));        if let Some(c) = conv_with(know, &t, &oldest, mail.first().cloned(), unread) {            if c.who(know) != Who::Junk {                out.push(c);            }        }        if out.len() == PAGE {            break;        }    }    Ok(out)}fn attachments_of(m: &Map<String, Value>) -> Vec<Value> {    match m.get("attachments") {        Some(Value::String(text)) => serde_json::from_str::<Vec<Value>>(text).unwrap_or_default(),        Some(Value::Array(list)) => list.clone(),        _ => Vec::new(),    }}fn attachments_line(lines: &LineSet, count: usize) -> Option<String> {    match count {        0 => None,        1 => Some(say(lines, "app.mail.one_attachment", &[])),        n => Some(say(lines, "app.mail.attachments", &[("n", &n.to_string())])),    }}/// A mail's first words on one line.fn line_of(m: &Map<String, Value>) -> Option<String> {    let words = s(m, "snippet").or_else(|| s(m, "body"))?;    let flat: String = words.split_whitespace().collect::<Vec<_>>().join(" ");    let cut: String = flat.chars().take(140).collect();    (!cut.is_empty()).then(|| if flat.chars().count() > 140 { format!("{cut}…") } else { cut })}fn shown_name(name: Option<&str>, address: &str) -> String {    name.map(str::trim).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| address.split('@').next().unwrap_or(address).to_string())}fn subject_or(lines: &LineSet, subject: Option<String>) -> String {    subject.map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| say(lines, "app.mail.no_subject", &[]))}fn row_json(lines: &LineSet, clock: &Clock, know: &Know, c: &Conv) -> Value {    let who = c.who(know);    let name = shown_name(c.name.as_deref(), &c.address);    let newest = c.newest.as_ref();    let attachments = newest.map(attachments_of).map_or(0, |a| a.len());    json!({        "thread": c.id,        "from": { "name": name, "address": c.address, "picture": picture(&c.address, &name, None) },        "who": who.as_str(),        "subject": subject_or(lines, c.subject.clone().or_else(|| newest.and_then(|m| s(m, "subject")))),        "line": newest.and_then(line_of),        "when": clock.recent(&c.last_at),        "unread": c.unread,        "count": c.count,        "attachments": attachments_line(lines, attachments),        "group": c.group(know).map(Group::as_str),        // One act a side (SENDERS.md "swipes everywhere"): right Read or Unread, left Archive, by `chat.mail.act        // { thread, act }`; the rest is the long-press (`chat.mail.hold { thread }`).        "swipe": {            "right": if c.unread { json!({ "id": "read", "label": say(lines, "app.swipe.read", &[]) }) } else { json!({ "id": "unread", "label": say(lines, "app.swipe.unread", &[]) }) },            "left": { "id": "archive", "label": say(lines, "app.swipe.archive", &[]) },        },    })}// ── chat.mail: the Mail tab ────────────────────────────────────────────fn list(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let filter = request.get("filter").and_then(Value::as_str).unwrap_or("all").to_string();    if !matches!(filter.as_str(), "all" | "people" | "notices" | "promotions" | "unread" | "sent" | "drafts") {        return Err(bad("filter", "all, people, notices, promotions, unread, sent or drafts"));    }    let words = request.get("text").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()).map(str::to_string);    // A search reads every mail, wherever it is drawn, whatever chip stands on: the Drafts chip lists drafts only    // while nothing is asked.    if filter == "drafts" && words.is_none() {        return drafts_page(client);    }    let asked = request.get("after").and_then(Value::as_str).map(str::to_string);    // A cursor past this copy's window pages the object's older mail.    if let Some(rest) = asked.as_deref().and_then(|c| c.strip_prefix(&format!("{OBJECT}\u{1f}"))) {        let (at, id) = rest.split_once('\u{1f}').map(|(a, b)| (a.to_string(), b.to_string())).unwrap_or_default();        return object_page(client, &filter, (at, id));    }    let after = asked.as_deref().and_then(|c| c.split_once('\u{1f}')).map(|(a, b)| (a.to_string(), b.to_string()));    let (know, mut found, mut next, held, oldest) = read(client, "chat.mail", |ctx| {        let know = Know::read(ctx)?;        let (found, next) = match &words {            Some(words) => searched(ctx, &know, words, after.as_ref())?,            None => listed(ctx, &know, &filter, after.as_ref())?,        };        // What this copy holds, and where its mail ends: the window's edge.        let held: HashSet<String> = if words.is_some() { rows(ctx, &format!("SELECT id FROM {EMAILS} WHERE workspace_id = ?"), &[ws(ctx)])?.iter().filter_map(|r| s(r, "id")).collect() } else { HashSet::new() };        let oldest = one(ctx, &format!("SELECT last_at, id FROM {MAIL_THREADS} WHERE workspace_id = ? ORDER BY coalesce(last_at, '') ASC, id ASC LIMIT 1"), &[ws(ctx)])?            .map(|r| (s(&r, "last_at").unwrap_or_default(), s(&r, "id").unwrap_or_default()));        Ok((know, found, next, held, oldest))    })?;    // Past the window: the object's older mail fills the page, and a search reaches its whole history.    let mut older_unreached = None;    // Only for a phone on its object: a phone signed out holds every mail it has.    if words.is_none() && next.is_none() && found.len() < PAGE && client.object_door().is_some() && !crate::methods::shell_home::first_pull_running(client) {        let edge = oldest.unwrap_or_else(|| (Clock::of(client).now_iso(), String::new()));        match older_listed(client, &know, &filter, edge, PAGE - found.len()) {            Ok((more, cursor)) => {                found.extend(more);                next = cursor;            }            Err(refused) => older_unreached = Some(refused.message),        }    }    if let (Some(words), None) = (&words, &after) {        match searched_beyond(client, &know, words, &held) {            Ok(more) => {                let shown: HashSet<String> = found.iter().map(|c| c.id.clone()).collect();                found.extend(more.into_iter().filter(|c| !shown.contains(&c.id)));                found.sort_by(|a, b| b.last_at.cmp(&a.last_at));            }            Err(refused) => older_unreached = Some(refused.message),        }    }    let mut page = page_json(client, &know, &found, next, words.as_deref(), &filter, older_unreached);    // The drafts the words find stand first, on a search's first page.    if let (Some(words), None) = (&words, &after) {        let drafts = drafts_found(client, &know, words)?;        if !drafts.is_empty() {            let mut rows = drafts;            rows.extend(page["rows"].as_array().cloned().unwrap_or_default());            page["rows"] = json!(rows);            page["empty"] = Value::Null;        }    }    Ok(page)}/// The drafts whose subject, words, To or the name of whom it goes to hold `words` (any case), drawn as the/// Drafts chip draws them.fn drafts_found(client: &ClientController, know: &Know, words: &str) -> Result<Vec<Value>, MethodError> {    if !writes(client) {        return Ok(Vec::new());    }    let lines = list::lines();    let clock = Clock::of(client);    let drafts = read(client, "chat.mail", writing::drafts_of)?;    let asked = words.to_lowercase();    Ok(drafts        .iter()        .filter(|d| {            let to = writing::addresses(d.get("to"));            let mut said = vec![s(d, "subject").unwrap_or_default(), s(d, "body").unwrap_or_default()];            said.extend(to.iter().cloned());            said.extend(to.iter().filter_map(|a| know.name_of(a).map(str::to_string)));            said.iter().any(|f| f.to_lowercase().contains(&asked))        })        .map(|d| writing::draft_row(&lines, &clock, know, d))        .collect())}/// A page of the Mail tab past this copy's window: the object's older threads.fn object_page(client: &ClientController, filter: &str, before: (String, String)) -> Result<Value, MethodError> {    let know = read(client, "chat.mail", Know::read)?;    let (found, next) = older_listed(client, &know, filter, before, PAGE)?;    Ok(page_json(client, &know, &found, next, None, filter, None))}/// The Mail tab's Drafts: every mail the person wrote here and kept, newest saved first, each said not sent.fn drafts_page(client: &ClientController) -> Result<Value, MethodError> {    let lines = list::lines();    let clock = Clock::of(client);    let (know, drafts) = read(client, "chat.mail", |ctx| Ok((Know::read(ctx)?, writing::drafts_of(ctx)?)))?;    let mut page = page_json(client, &know, &[], None, None, "drafts", None);    page["rows"] = json!(drafts.iter().map(|d| writing::draft_row(&lines, &clock, &know, d)).collect::<Vec<_>>());    if !drafts.is_empty() {        page["empty"] = Value::Null;    }    Ok(page)}/// Whether the copy holds a draft: the Drafts chip stands only then.fn any_drafts(client: &ClientController) -> bool {    writes(client) && read(client, "chat.mail", |ctx| Ok(!writing::drafts_of(ctx)?.is_empty())).unwrap_or(false)}/// Whether this copy draws Comms' drafts (`email_draft`), so a mail can be written here. A copy made before the/// table shipped holds no definition of it until its object serves one (the Worker carries it from its next/// deploy), and an app whose kit reads mail without it (Keys, in the tests and Chat Dev's fixture) never does:/// there Comms offers no writing at all (only the phone's mail app) rather than a writer whose Save is refused.fn keeps_drafts(client: &ClientController) -> Result<bool, MethodError> {    read(client, "chat.mail", |ctx| Ok(!cotton_tools::definitions::definition_rows(ctx, Some(writing::DRAFTS)).map_err(|e| e.to_string())?.is_empty()))}/// [`keeps_drafts`] for a page that cannot refuse: a read that fails offers no writing, and says why in the log.fn writes(client: &ClientController) -> bool {    keeps_drafts(client).unwrap_or_else(|refused| {        tracing::warn!("chat.mail: whether drafts are drawn was not read ({}: {})", refused.code, refused.message);        false    })}#[allow(clippy::too_many_arguments)]fn page_json(client: &ClientController, know: &Know, found: &[Conv], next: Option<String>, words: Option<&str>, filter: &str, older: Option<String>) -> Value {    let lines = list::lines();    let clock = Clock::of(client);    let rows: Vec<Value> = found.iter().map(|c| row_json(&lines, &clock, know, c)).collect();    let arriving = crate::methods::shell_home::first_pull_running(client).then(|| say(&lines, "app.mail.arriving", &[]));    let empty = rows.is_empty().then(|| match (words, filter) {        (Some(text), _) => say(&lines, "app.mail.none_found", &[("text", text)]),        (None, "people") => say(&lines, "app.mail.empty_people", &[]),        (None, "notices") => say(&lines, "app.mail.empty_notices", &[]),        (None, "promotions") => say(&lines, "app.mail.empty_promotions", &[]),        (None, "unread") => say(&lines, "app.mail.empty_unread", &[]),        (None, "drafts") => say(&lines, "app.mail.empty_drafts", &[]),        (None, "sent") => say(&lines, "app.mail.empty_sent", &[]),        _ => say(&lines, "app.mail.empty", &[]),    });    // Senders 3 (owner, 24 Nov 2026): All, People, Notices, Promotions, Unread, Sent (and Drafts while any is kept).    let mut chips = vec!["all", "people", "notices", "promotions", "unread"];    if filter == "sent" || !know.sent.is_empty() {        chips.push("sent");    }    if filter == "drafts" || any_drafts(client) {        chips.push("drafts");    }    let label = |f: &str| match f {        "sent" => "app.mail.sent_chip".to_string(),        other => format!("app.mail.{other}"),    };    let filters: Vec<Value> = chips.iter().map(|f| json!({ "id": f, "label": say(&lines, &label(f), &[]), "on": *f == filter })).collect();    json!({        "title": say(&lines, "app.mail.title", &[]),        "rows": rows,        "filters": filters,        "after": next,        "arriving": arriving,        "older": older,        "empty": empty,        "words": { "search": say(&lines, "app.mail.search", &[]), "tab": say(&lines, "app.mail.tab", &[]) },        "write": writes(client).then(|| json!({ "label": say(&lines, "app.mail.new", &[]) })),        "history": history(client, &lines),    })}/// The quiet line at the top of Mail and Senders while all his mail is still coming to this phone (MAIL ALL ON PHONE;/// SENDERS.md "While history arrives"): `{ line, paused? }`, or null once it is all here (or the phone keeps a window).pub(crate) fn history(client: &ClientController, lines: &cotton_core::rules::shell_lines::LineSet) -> Value {    crate::phone::mail_history::mail_history(client).map_or(Value::Null, |h| history_words(lines, &h))}/// The history's facts in words: "Mail back to March 2019 · 41,200 of 111,422", and why it stands, when it does.pub(crate) fn history_words(lines: &cotton_core::rules::shell_lines::LineSet, h: &crate::phone::mail_history::History) -> Value {    let held = cotton_core::rules::shell_lines::number(h.held as i64);    let total = cotton_core::rules::shell_lines::number(h.total as i64);    let month = h.back_to.as_deref().and_then(|m| chrono::NaiveDate::parse_from_str(&format!("{m}-01"), "%Y-%m-%d").ok()).map(|d| d.format("%B %Y").to_string());    let line = match &month {        Some(month) => say(lines, "app.mail.history.line", &[("month", month), ("held", &held), ("total", &total)]),        None => say(lines, "app.mail.history.coming", &[("held", &held), ("total", &total)]),    };    let paused = h.paused.as_ref().map(|p| match p {        crate::phone::mail_history::Paused::Offline => say(lines, "app.mail.history.offline", &[]),        crate::phone::mail_history::Paused::MacOffline => say(lines, "app.mail.history.mac_offline", &[]),        crate::phone::mail_history::Paused::Mac(_) => say(lines, "app.mail.history.mac_full", &[]),    });    json!({ "line": line, "paused": paused })}type Found = (Vec<Conv>, Option<String>);/// The Mail tab's page: threads newest first, the ones not in a chat and not junk, by the filter.fn listed(ctx: &mut Ctx<'_>, know: &Know, filter: &str, after: Option<&(String, String)>) -> Result<Found, String> {    let mut out = Vec::new();    let mut cursor = after.cloned();    let mut next = None;    'pages: loop {        let (cut, params) = match &cursor {            Some((at, id)) => (" AND (coalesce(last_at, ''), id) < (?, ?)", vec![ws(ctx), text(at.clone()), text(id.clone())]),            None => ("", vec![ws(ctx)]),        };        let batch = rows(ctx, &format!("SELECT id, subject, last_at, email_count, sender_address, sender_kind FROM {MAIL_THREADS} WHERE workspace_id = ? AND {live_thread}{cut} ORDER BY coalesce(last_at, '') DESC, id DESC LIMIT 120", live_thread = mail_predicate::live_thread("")), &params)?;        if batch.is_empty() {            break;        }        for t in &batch {            cursor = Some((s(t, "last_at").unwrap_or_default(), s(t, "id").unwrap_or_default()));            let Some(c) = conv_of(ctx, know, t)? else { continue };            if shown(know, &c, filter) {                out.push(c);                if out.len() == PAGE {                    next = cursor.as_ref().map(|(a, b)| format!("{a}\u{1f}{b}"));                    break 'pages;                }            }        }        if batch.len() < 120 {            break;        }    }    Ok((out, next))}/// How many conversations of hits one batch of a search reads.const SEARCH_BATCH: usize = PAGE * 2;/// How many batches one page of a search reads at most: past them (hits mostly from blocked senders) the page ends/// short with its next cursor, and the next page reads on from there; but a page with no conversation yet reads on/// (a shell that sends no `after` would show nothing though matches exist), until [`SEARCH_TIME`].const SEARCH_BATCHES: usize = 4;/// How long a page with no conversation yet keeps reading batches before it ends empty with its cursor.const SEARCH_TIME: std::time::Duration = std::time::Duration::from_millis(400);/// A search's conversations, newest first by their key (the newest matching mail's `sent_at`, then the thread),/// one page of [`PAGE`]. `batch` answers the next [`SEARCH_BATCH`] keys below the cursor, grouped by conversation in/// SQL before the cut (`HAVING (max(sent_at), thread_id) < cursor`), so a conversation with hits on both sides of a/// cursor is on one page only. Blocked and junk senders are skipped here; the next cursor is None only when the/// source has no more keys, never because what was skipped left the page short.fn keyed_conversations(    ctx: &mut Ctx<'_>,    know: &Know,    after: Option<&(String, String)>,    mut batch: impl FnMut(&mut Ctx<'_>, Option<&(String, String)>) -> Result<Vec<Map<String, Value>>, String>,) -> Result<Found, String> {    let key = |(at, id): (String, String)| format!("{at}\u{1f}{id}");    let mut out = Vec::new();    let mut cursor = after.cloned();    let began = std::time::Instant::now();    let mut batches = 0;    while batches < SEARCH_BATCHES || out.is_empty() && began.elapsed() < SEARCH_TIME {        batches += 1;        let hits = batch(ctx, cursor.as_ref())?;        let full = hits.len() == SEARCH_BATCH;        for (n, h) in hits.iter().enumerate() {            let Some(id) = s(h, "thread_id") else { continue };            cursor = Some((s(h, "at").unwrap_or_default(), id.clone()));            let Some(t) = one(ctx, &format!("SELECT id, subject, last_at, email_count, sender_address, sender_kind FROM {MAIL_THREADS} WHERE workspace_id = ? AND id = ? AND {live_thread}", live_thread = mail_predicate::live_thread("")), &[ws(ctx), text(id)])? else { continue };            let Some(c) = conv_of(ctx, know, &t)? else { continue };            if c.who(know) == Who::Junk {                continue;            }            out.push(c);            if out.len() == PAGE {                let more = n + 1 < hits.len() || full;                return Ok((out, if more { cursor.map(key) } else { None }));            }        }        if !full {            return Ok((out, None));        }    }    Ok((out, cursor.map(key)))}/// The `HAVING` cut below a search cursor, and its parameters.fn below(after: Option<&(String, String)>, on: &str) -> (String, Vec<SqlValue>) {    match after {        Some((at, id)) => (format!(" HAVING (max({on}sent_at), {on}thread_id) < (?, ?)"), vec![text(at.clone()), text(id.clone())]),        None => (String::new(), Vec::new()),    }}/// Mail whose sender, subject or words hold the search, its conversations newest first: before this device's wide/// index is filled (mail_index.rs). The words go through `fts_emails` (or the wide index, once filled), every word's/// start; sender and subject through LIKE; both in one query, grouped by conversation before the cut.fn searched(ctx: &mut Ctx<'_>, know: &Know, words: &str, after: Option<&(String, String)>) -> Result<Found, String> {    let like = format!("%{}%", words.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_"));    let index = if cotton_store::fts_fill::filling(ctx.db(), crate::phone::mail_index::INDEX).map_or(true, |fill| fill.is_some()) { "fts_emails" } else { crate::phone::mail_index::INDEX };    let phrase: Vec<String> = words.split_whitespace().map(|w| format!("\"{}\"*", w.replace('"', ""))).collect();    let phrase = phrase.join(" ");    // A phrase the index refuses still searches by sender and subject.    let mut words_too = !phrase.is_empty();    keyed_conversations(ctx, know, after, |ctx, cursor| {        let (having, cut) = below(cursor, "");        let run = |ctx: &mut Ctx<'_>, with_words: bool| {            let mut params = vec![ws(ctx), text(like.clone()), text(like.clone()), text(like.clone())];            let words_clause = if with_words {                params.push(text(phrase.clone()));                format!(" OR rowid IN (SELECT rowid FROM {index} WHERE {index} MATCH ?)")            } else {                String::new()            };            params.extend(cut.iter().cloned());            rows(                ctx,                &format!(                    "SELECT thread_id, max(sent_at) AS at FROM {EMAILS} WHERE workspace_id = ? AND {live_mail} AND thread_id IS NOT NULL AND (from_name LIKE ? ESCAPE '\\' OR from_email LIKE ? ESCAPE '\\' OR subject LIKE ? ESCAPE '\\'{words_clause}) GROUP BY thread_id{having} ORDER BY at DESC, thread_id DESC LIMIT {SEARCH_BATCH}",                    live_mail = mail_predicate::live("")                ),                &params,            )        };        if words_too {            match run(ctx, true) {                Ok(hits) => return Ok(hits),                Err(_) => words_too = false,            }        }        run(ctx, false)    })}// ── chat.mail.thread: a conversation of mail, whole ────────────────────fn names_line(lines: &LineSet, line: &str, people: &[(String, Option<String>)], know: &Know) -> Option<String> {    let names: Vec<String> = people.iter().map(|(a, n)| if know.is_own(a) { say(lines, "app.mail.me", &[]) } else { shown_name(n.as_deref(), a) }).collect();    (!names.is_empty()).then(|| say(lines, line, &[("names", &names.join(", "))]))}fn thread(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    thread_knowing(client, request, Know::read)}/// [`thread`] with the facts of senders read by `know_of`: Post passes the ones it keeps while the copy is unchanged.fn thread_knowing(client: &ClientController, request: &Value, know_of: fn(&mut Ctx<'_>) -> Result<Know, String>) -> Result<Value, MethodError> {    let id = cotton_chat::text(request, "thread")?.to_string();    let lines = list::lines();    let clock = Clock::of(client);    let found = read(client, "chat.mail.thread", |ctx| {        let know = know_of(ctx)?;        let Some(t) = one(ctx, &format!("SELECT id, subject, last_at, email_count, sender_address, sender_kind FROM {MAIL_THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(id.clone())])? else { return Ok(None) };        let Some(c) = conv_of(ctx, &know, &t)? else { return Ok(None) };        let mut mail = rows(ctx, &format!("SELECT {MAIL_COLUMNS} FROM {EMAILS} WHERE thread_id = ? AND {live_mail} ORDER BY sent_at DESC, id DESC LIMIT 100", live_mail = mail_predicate::live("")), &[text(id.clone())])?;        mail.reverse();        Ok(Some((know, c, mail)))    })?;    let (know, c, mail, held) = match found {        Some((know, c, mail)) => (know, c, mail, true),        // Past this copy's window: its mail from the object, opened here (`GET /v1/older`, one conversation).        None => {            let know = read(client, "chat.mail.thread", Know::read)?;            let mail = newest_first(from_object(client, "email", &format!("eq={}&limit=100", part(&format!("thread_id:{id}"))))?);            let mut oldest = mail.clone();            oldest.reverse();            let t = json!({ "id": id }).as_object().cloned().unwrap_or_default();            let unread = mail.iter().any(|m| truthy(m, "unread"));            let Some(c) = conv_with(&know, &t, &oldest, mail.first().cloned(), unread) else {                return Err(MethodError::new("not_found", say(&lines, "app.mail.gone", &[])));            };            (know, c, oldest, false)        }    };    let you = say(&lines, "app.mail.you", &[]);    let messages: Vec<Value> = mail        .iter()        .map(|m| {            let from = lower(s(m, "from_email")).unwrap_or_default();            let mine = know.is_own(&from);            let all = recipients_of(m.get("recipients").unwrap_or(&Value::Null));            let pick = |kind: &str| all.iter().filter(|(_, _, k)| k == kind).map(|(a, n, _)| (a.clone(), n.clone())).collect::<Vec<_>>();            let at = s(m, "sent_at").unwrap_or_default();            let (time, heading, _) = clock.slip(&at);            let attachments: Vec<Value> = attachments_of(m)                .iter()                .enumerate()                .map(|(index, a)| {                    json!({                        "index": index,                        "name": a.get("name").and_then(Value::as_str).unwrap_or_default(),                        "mime": a.get("mime").and_then(Value::as_str),                        "size": a.get("size").and_then(Value::as_i64).map(|b| cotton_core::records::page::bytes_words(b as f64)),                        "can": a.get("key").and_then(Value::as_str).is_some(),                        "kept": a.get("key").and_then(Value::as_str).is_some_and(|k| opened_keys(client).iter().any(|o| o == k) && held_here(client, k)),                    })                })                .collect();            let text = s(m, "body").or_else(|| s(m, "snippet")).unwrap_or_default();            // Its links, where each stands, so a tap opens the page inside Comms.            let links = cotton_core::messages::links::links_at(&text);            json!({                "email": s(m, "id"),                "mine": mine,                // A tap on the sender opens their page (`chat.sender.page { key: sender }`).                "from": { "name": if mine { you.clone() } else { shown_name(s(m, "from_name").as_deref(), &from) }, "address": from, "sender": (!mine).then(|| from.clone()) },                "to": names_line(&lines, "app.mail.to", &pick("to"), &know),                "cc": names_line(&lines, "app.mail.cc", &pick("cc"), &know),                "when": format!("{heading}, {time}"),                "subject": subject_or(&lines, s(m, "subject")),                "text": text,                "links": links,                "unread": truthy(m, "unread"),                "attachments": attachments,            })        })        .collect();    // Read here: what was unread is marked read in the person's own copy (their other phones follow by sync).    // Mail past the window is not in the copy: it is read there, and stays as the mailbox has it.    let unread: Vec<String> = if held { mail.iter().filter(|m| truthy(m, "unread")).filter_map(|m| s(m, "id")).collect() } else { Vec::new() };    if !unread.is_empty() {        write(client, "chat.mail.thread", |ctx| {            for id in &unread {                update_row(ctx, EMAILS, id, json!({ "unread": false }).as_object().cloned().unwrap_or_default()).map_err(|e| e.to_string())?;                // Read in his mailbox too, through the Mac (SENDERS.md "To Gmail through the Mac").                if let Some(mail) = acts::mail_of(ctx, id)? {                    acts::queue(ctx, &mail, "read")?;                }            }            Ok(())        })?;    }    let drawn = keeps_drafts(client)?;    let drafts: Vec<Value> = if drawn { read(client, "chat.mail.thread", writing::drafts_of)? } else { Vec::new() }        .iter()        .filter(|d| s(d, "thread_id").as_deref() == Some(c.id.as_str()))        .map(|d| writing::draft_row(&lines, &clock, &know, d))        .collect();    let name = shown_name(c.name.as_deref(), &c.address);    let subject = subject_or(&lines, c.subject.clone());    let reply_subject = if subject.to_lowercase().starts_with("re:") { subject.clone() } else { format!("Re: {subject}") };    let mailto = format!("mailto:{}?subject={}", c.address, url::form_urlencoded::byte_serialize(reply_subject.as_bytes()).collect::<String>().replace('+', "%20"));    Ok(json!({        "thread": c.id,        "subject": subject,        "with": { "name": name, "address": c.address, "picture": picture(&c.address, &name, None) },        "who": c.who(&know).as_str(),        "chat": c.chat(&know),        "messages": messages,        "reply": { "label": say(&lines, "app.mail.reply", &[]), "note": say(&lines, "app.mail.reply_note", &[]), "mailto": mailto },        "write": drawn.then(|| json!({ "label": say(&lines, "app.mail.write", &[]), "note": say(&lines, "app.mail.not_sent", &[]) })),        "drafts": drafts,    }))}// ── attachments: fetched when opened, and freed ────────────────────────fn opened_path(client: &ClientController) -> std::path::PathBuf {    client.layout().client_dir().join(OPENED)}/// Whether this phone holds the bytes of `key` (Free up space may have taken them since it was opened).fn held_here(client: &ClientController, key: &str) -> bool {    client        .with_file(|f| f.driver.get("SELECT 1 AS here FROM _media WHERE key = ? AND local_path IS NOT NULL", &[text(key.to_string())]).map(|row| row.is_some()).map_err(|e| e.to_string()))        .unwrap_or(false)}fn opened_keys(client: &ClientController) -> Vec<String> {    std::fs::read(opened_path(client)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()}fn keep_opened(client: &ClientController, keys: &[String]) -> Result<(), MethodError> {    // not a copy: mail files.    std::fs::write(opened_path(client), serde_json::to_vec(keys).unwrap_or_default()).map_err(|e| MethodError::new("unwritable", e.to_string()))}fn file(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let email = cotton_chat::text(request, "email")?.to_string();    let index = request.get("index").and_then(Value::as_u64).unwrap_or(0) as usize;    let dir = std::path::PathBuf::from(cotton_chat::text(request, "dir")?);    let lines = list::lines();    let row = read(client, "chat.mail.file", |ctx| one(ctx, &format!("SELECT id, attachments FROM {EMAILS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(email.clone())]))?;    let Some(row) = row else { return Err(MethodError::new("not_found", say(&lines, "app.mail.gone", &[]))) };    let all = attachments_of(&row);    let a = all.get(index).ok_or_else(|| MethodError::new("not_found", say(&lines, "app.mail.gone", &[])))?;    let name = a.get("name").and_then(Value::as_str).unwrap_or("attachment").to_string();    let mime = a.get("mime").and_then(Value::as_str).unwrap_or("application/octet-stream").to_string();    // Mail the Mac reads keeps no attachment's bytes, only its name, until it is opened: then the Mac is asked to    // bring the message's page and files (`mail_page`, mac-import's Mac 10) and the phone is told it is coming. Where    // the outbox does not take that yet, the file stays in the mailbox.    let Some(media) = a.get("key").and_then(Value::as_str).map(str::to_string) else {        let asked = write(client, "chat.mail.file", |ctx| {            let Some(mail) = acts::mail_of(ctx, &email)? else { return Ok(json!(false)) };            if acts::page_asked(ctx, &mail)? {                return Ok(json!(true));            }            // His Mac already answered: what it could bring is here, and this file is not (over its size), or it            // refused the mail in its own words. Asking again on every tap would bring nothing more (launch-ios).            if let Some(said) = acts::page_answered(ctx, &mail)? {                return Ok(said.map(Value::from).unwrap_or(json!(false)));            }            Ok(json!(mail.external.is_some() && acts::queue(ctx, &mail, "page")?))        })?;        if asked == json!(true) {            return Err(MethodError::new("file_coming", say(&lines, "app.mail.coming", &[])));        }        if let Some(said) = asked.as_str() {            return Err(MethodError::new("not_kept", said.to_string()));        }        return Err(MethodError::new("not_kept", say(&lines, "app.mail.not_kept", &[])));    };    // A phone that says it has no network is told at once that a file not on it waits for one, never left waiting    // on a fetch that cannot go (seen on emulator-5554 in airplane mode, 22 Nov 2026: the tap said nothing for    // minutes, until the media ceiling ran out).    if request.get("online").and_then(Value::as_bool) == Some(false) && !held_here(client, &media) {        return Err(MethodError::new("file_offline", say(&lines, "app.mail.offline", &[])));    }    let landed = super::super::media::land(client, media.clone(), super::super::media::Tier::Original, super::super::media::Asker::Person)        .map_err(|refused| if refused.code == "unreadable" { refused } else { MethodError::new("file_offline", say(&lines, "app.mail.offline", &[])) })?;    // An attachment opened here is a file of the person's own that the object holds: You → Storage's Free up space    // may take it off this phone, as it takes an opened picture (seen on emulator-5554, 22 Nov 2026: a fetched PDF    // counted in "Photos and files" while Storage said "Nothing to free up", its ledger row bearing no tier).    client        .with_writer(|f| f.driver.run("UPDATE _media SET tier = 'original' WHERE key = ? AND tier IS NULL AND captured_here = 0", &[text(media.clone())]).map(|_| ()).map_err(|e| e.to_string()))        .map_err(|why| MethodError::new("unwritable", why))?;    let safe: String = name.chars().map(|c| if c == '/' || c == '\\' || c.is_control() { '_' } else { c }).collect();    let folder = dir.join(format!("{:x}", sha2::Digest::finalize(<sha2::Sha256 as sha2::Digest>::new_with_prefix(media.as_bytes())))[..16].to_string());    std::fs::create_dir_all(&folder).map_err(|e| MethodError::new("unwritable", e.to_string()))?;    let path = folder.join(if safe.is_empty() { "attachment".to_string() } else { safe });    if !path.exists() {        // not a copy: mail files.        std::fs::copy(&landed.path, &path).map_err(|e| MethodError::new("unwritable", e.to_string()))?;    }    let mut keys = opened_keys(client);    if !keys.contains(&media) {        keys.push(media);        keep_opened(client, &keys)?;    }    let mut opened = json!({ "path": path.to_string_lossy(), "mime": mime, "name": name });    super::super::chat_files::with_view(&mut opened);    Ok(opened)}/// The email as it was sent (Mac 10, CONTRACT "A mail's page and files"): the designed page his Mac brought, landed/// here like an attachment, `{ path, pictures }` (`pictures` the words of the control that loads its pictures from the/// web, which stay off until he taps it). Not brought yet: his Mac is asked once (`mail_page`, as opening an attachment/// asks it) and `{ coming }` says so; the text stays meanwhile. A mail written as plain text, or a copy whose outbox/// does not take the ask, answers `{}`: the text is the mail.fn page(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let email = cotton_chat::text(request, "email")?.to_string();    let dir = std::path::PathBuf::from(cotton_chat::text(request, "dir")?);    let lines = list::lines();    let row = read(client, "chat.mail.page", |ctx| one(ctx, &format!("SELECT id, media FROM {EMAILS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(email.clone())]))?;    let Some(row) = row else { return Err(MethodError::new("not_found", say(&lines, "app.mail.gone", &[]))) };    let media = match row.get("media") {        Some(Value::String(text)) => serde_json::from_str::<Vec<Value>>(text).unwrap_or_default(),        Some(Value::Array(list)) => list.clone(),        _ => Vec::new(),    };    let designed = media.iter().find(|m| m.get("name").and_then(Value::as_str) == Some("page.html") || m.get("contentType").and_then(Value::as_str) == Some("text/html"));    let Some(key) = designed.and_then(|m| m.get("key")).and_then(Value::as_str).map(str::to_string) else {        let coming = write(client, "chat.mail.page", |ctx| {            let Some(mail) = acts::mail_of(ctx, &email)? else { return Ok(json!(false)) };            if acts::page_asked(ctx, &mail)? {                return Ok(json!(true));            }            // A copy that keeps no outbox (a Keys phone) asks nothing, and has no outbox to read (launch-ios, SITES 6).            if !acts::takes(ctx, "mail_page")? {                return Ok(json!(false));            }            // His Mac already answered: it brought the mail and found no page (written as plain text), or refused it as            // too large (`failed`). Asking again on every open would bring nothing more.            if let Some(external) = mail.external.clone() {                if one(ctx, "SELECT 1 AS brought FROM cotton_outbox WHERE workspace_id = ? AND channel = 'mail' AND kind = 'mail_page' AND target = ? AND status IN ('sent', 'failed') LIMIT 1", &[ws(ctx), text(external)])?.is_some() {                    return Ok(json!(false));                }            }            Ok(json!(mail.external.is_some() && acts::queue(ctx, &mail, "page")?))        })?;        return Ok(if coming == json!(true) { json!({ "coming": say(&lines, "app.mail.page_coming", &[]) }) } else { json!({}) });    };    if request.get("online").and_then(Value::as_bool) == Some(false) && !held_here(client, &key) {        return Err(MethodError::new("file_offline", say(&lines, "app.mail.offline", &[])));    }    let landed = super::super::media::land(client, key.clone(), super::super::media::Tier::Original, super::super::media::Asker::Person)        .map_err(|refused| if refused.code == "unreadable" { refused } else { MethodError::new("file_offline", say(&lines, "app.mail.offline", &[])) })?;    let folder = dir.join(format!("{:x}", sha2::Digest::finalize(<sha2::Sha256 as sha2::Digest>::new_with_prefix(key.as_bytes())))[..16].to_string());    std::fs::create_dir_all(&folder).map_err(|e| MethodError::new("unwritable", e.to_string()))?;    let path = folder.join("page.html");    if !path.exists() {        // not a copy: mail files.        std::fs::copy(&landed.path, &path).map_err(|e| MethodError::new("unwritable", e.to_string()))?;    }    // A page landed here is a file the object holds, like an opened attachment: You → Storage's Free up space takes it.    client        .with_writer(|f| f.driver.run("UPDATE _media SET tier = 'original' WHERE key = ? AND tier IS NULL AND captured_here = 0", &[text(key.clone())]).map(|_| ()).map_err(|e| e.to_string()))        .map_err(|why| MethodError::new("unwritable", why))?;    let mut keys = opened_keys(client);    if !keys.contains(&key) {        keys.push(key.clone());        keep_opened(client, &keys)?;    }    Ok(json!({ "path": path.to_string_lossy(), "pictures": say(&lines, "app.mail.show_pictures", &[]) }))}fn free(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let lines = list::lines();    let keys = opened_keys(client);    let mut freed: u64 = 0;    if let Some(dir) = request.get("dir").and_then(Value::as_str) {        let dir = std::path::Path::new(dir);        for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {            let path = entry.path();            for file in std::fs::read_dir(&path).into_iter().flatten().flatten() {                freed += file.metadata().map(|m| m.len()).unwrap_or(0);            }            // not a copy: mail files.            let _ = std::fs::remove_dir_all(&path);        }    }    let device = client.self_device_id();    let now = client.clock().now().timestamp_millis();    let mut ids = cotton_client::seams::op_ids(client.random());    let mut kept = Vec::new();    for key in &keys {        let taken = match &device {            Some(device) => client                .with_writer(|f| {                    Ok(cotton_client::media::storage::evict_one(f.driver, f.workspace_id, device, client.layout(), &cotton_client::media::SystemEvictDisk, key, now, &mut ids, super::super::storage::held(f)))                })                .map_err(|reason| MethodError::new("unwritable", reason))?,            None => Err(cotton_client::media::storage::EvictOneError::NotBackedUp),        };        match taken {            Ok(bytes) => freed += bytes,            // A file not yet synced up stays: this phone may hold its only copy.            Err(_) => kept.push(key.clone()),        }    }    keep_opened(client, &kept)?;    client.nudge_sync();    let said = if freed == 0 && keys.is_empty() { say(&lines, "app.mail.nothing_to_free", &[]) } else { say(&lines, "app.mail.freed", &[("size", &cotton_core::records::page::bytes_words(freed as f64))]) };    Ok(json!({ "freed": freed, "said": said, "label": say(&lines, "app.mail.free", &[]) }))}// ── Cotton Dev only: invented mail ─────────────────────────────────────/// A small PDF that says `words` on one page: an invented attachment a viewer opens.pub(crate) fn invented_pdf(words: &str) -> Vec<u8> {    let words: String = words.chars().filter(|c| c.is_ascii() && !matches!(c, '(' | ')' | '\\')).collect();    let stream = format!("BT /F1 18 Tf 60 720 Td ({words}) Tj ET");    let objects = [        "<< /Type /Catalog /Pages 2 0 R >>".to_string(),        "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),        "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".to_string(),        format!("<< /Length {} >>\nstream\n{stream}\nendstream", stream.len()),        "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_string(),    ];    let mut out = b"%PDF-1.4\n".to_vec();    let mut offsets = Vec::new();    for (i, body) in objects.iter().enumerate() {        offsets.push(out.len());        out.extend(format!("{} 0 obj\n{body}\nendobj\n", i + 1).bytes());    }    let xref = out.len();    out.extend(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).bytes());    for at in offsets {        out.extend(format!("{at:010} 00000 n \n").bytes());    }    out.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).bytes());    out}/// Invented senders a generated mailbox is written from.const MACHINES: &[(&str, &str, &str)] = &[    ("receipts@shop.invented", "Invented Shop", "Your receipt"),    ("news@paper.invented", "The Invented Paper", "This week in the paper"),    ("alerts@bank.invented", "Invented Bank", "Your statement is ready"),    ("no-reply@air.invented", "Invented Air", "Your booking"),    ("notifications@code.invented", "Invented Code", "New activity"),    ("hello@startup.invented", "Invented Startup", "What's new"),    ("orders@grocer.invented", "Invented Grocer", "Your order is on its way"),    ("billing@cloud.invented", "Invented Cloud", "Your invoice"),];const SENTENCES: &[&str] = &[    "Thank you for writing.", "Here is everything in one place.", "The details are below.", "Nothing needs doing today.",    "Reply to this mail if anything looks wrong.", "We kept a copy for you.", "The next one comes next week.",    "Saturday works for us.", "Bring the map and the kite.", "The lake is quiet in the morning.", "Lunch is at one.",];/// One invented message as rows are made of it.struct Said {    thread: String,    subject: String,    from: (String, String),    to: Vec<(String, String)>,    at: String,    body: String,    unread: bool,    files: Vec<(String, String)>,    /// Its attachments' bytes are here (the default); `false`, only their names until his Mac brings them.    brought: bool,    /// Written as plain text: his Mac finds no designed page when it brings it.    plain: bool,}fn word(v: &Value, k: &str) -> String {    v.get(k).and_then(Value::as_str).unwrap_or_default().to_string()}fn party(v: &Value) -> (String, String) {    (word(v, "address").to_lowercase(), word(v, "name"))}fn object_of(value: Value) -> Map<String, Value> {    value.as_object().cloned().unwrap_or_default()}/// `developer.inventMail { me, people?, mail?, generate? }` — COTTON DEV ONLY:/// invented mail written into this phone's copy as the Mac's reader would/// land it, so Comms' mail can be looked at on an emulator and an invented/// account made as large as the owner's. `me` is the invented mailbox;/// `people` invented people in People with an email (and a phone, which/// links their chat); `mail` each message by hand (`id`, `thread`, `subject`,/// `from`, `to`, `at`, `body`, `unread`, `attachments: [{ name, text }]`, an/// attachment an invented PDF saying `text`, kept as the person's own file so/// another phone fetches it when it is opened; `brought: false` keeps only/// their names, as the Mac's reader lands them, until `developer.fakeMac`/// brings them; `plain: true` a mail written as plain text, which the fake/// Mac finds no designed page for); `generate` writes `emails`/// invented messages in `threads` conversations from `from` on (runs side by/// side each take their own `from`), one every `step` minutes before `end`;/// with `senders` and `domains`, the machines' mail comes from that many/// invented addresses over that many invented domains (a Senders walk)./// Ids come from each message's place, so asking again writes the same rows./// The real Cotton refuses it by name.pub fn invent(handle: &crate::handle::CottonHandle, request: &Value) -> Result<Value, MethodError> {    if handle.flavor() != cotton_core::flavor::Flavor::Dev {        return Err(MethodError::new("not_dev", "developer.inventMail answers only in Cotton Dev"));    }    let client = handle.client();    let me = request.get("me").and_then(|m| m.get("address")).and_then(Value::as_str).unwrap_or("mira@invented.example").to_lowercase();    let mut said: Vec<(String, Said)> = Vec::new();    for (i, m) in request.get("mail").and_then(Value::as_array).cloned().unwrap_or_default().iter().enumerate() {        said.push((            // Its own id when given: a place's id an earlier walk deleted is erased for good, and refuses the write.            m.get("id").and_then(Value::as_str).filter(|id| !id.is_empty()).map(str::to_string).unwrap_or_else(|| format!("dev-mail-{i}")),            Said {                thread: word(m, "thread"),                subject: word(m, "subject"),                from: m.get("from").map(party).unwrap_or_default(),                to: m.get("to").and_then(Value::as_array).map(|to| to.iter().map(party).collect()).unwrap_or_else(|| vec![(me.clone(), String::new())]),                at: word(m, "at"),                body: word(m, "body"),                unread: m.get("unread").and_then(Value::as_bool).unwrap_or(false),                files: m.get("attachments").and_then(Value::as_array).map(|a| a.iter().map(|f| (word(f, "name"), word(f, "text"))).collect()).unwrap_or_default(),                brought: m.get("brought").and_then(Value::as_bool).unwrap_or(true),                plain: m.get("plain").and_then(Value::as_bool).unwrap_or(false),            },        ));    }    let people: Vec<Value> = request.get("people").and_then(Value::as_array).cloned().unwrap_or_default();    // A generated conversation's whole span (first, last, count) over all `total` messages, not only this run's:    // runs side by side (and the big account's batches of a thousand) each write the conversations of their own    // messages, and the last to land must not leave one dated by its own part (the window is by `last_at`).    let mut spans: HashMap<String, (String, String, i64)> = HashMap::new();    if let Some(g) = request.get("generate") {        let count = |k: &str, d: u64| g.get(k).and_then(Value::as_u64).unwrap_or(d) as usize;        let (emails, threads, from, step) = (count("emails", 1000), count("threads", 700).max(1), count("from", 0), count("step", 57) as i64);        let total = count("total", (from + emails) as u64);        let end = chrono::DateTime::parse_from_rfc3339(g.get("end").and_then(Value::as_str).unwrap_or("2026-11-21T09:00:00Z")).map_err(|_| bad("end", "an RFC 3339 time"))?;        let at_of = |x: usize| (end - chrono::Duration::minutes(total.saturating_sub(x) as i64 * step)).to_rfc3339_opts(chrono::SecondsFormat::Secs, true);        for x in from..from + emails {            let thread = x % threads;            let at = at_of(x);            if x < total && !spans.contains_key(&format!("g{thread}")) {                // Conversation t holds messages t, t + threads, t + 2·threads… below total, the oldest first.                let more = (total - 1 - thread) / threads;                spans.insert(format!("g{thread}"), (at_of(thread), at_of(thread + more * threads), more as i64 + 1));            }            // One conversation in nine is with an invented person; the rest from machines.            let person = (thread % 9 == 0 && !people.is_empty()).then(|| &people[thread / 9 % people.len()]);            let (from_party, subject) = match person {                Some(p) => ((word(p, "email").to_lowercase(), word(p, "name")), format!("About the trip, part {}", thread / 9 + 1)),                None => {                    let (a, n, sub) = MACHINES[thread % MACHINES.len()];                    match (count("senders", 0), count("domains", 0)) {                        // A Senders walk's account (SENDERS 3 WALKED): `senders` invented addresses spread over                        // `domains` invented domains, each address its conversations' sender.                        (senders, domains) if senders > 0 && domains > 0 => {                            let k = thread % senders;                            let local = a.split('@').next().unwrap_or("news");                            ((format!("{local}{k}@shop{}.invented", k % domains), format!("{n} {k}")), format!("{sub} ({})", thread + 1))                        }                        _ => ((a.to_string(), n.to_string()), format!("{sub} ({})", thread + 1)),                    }                }            };            let lead: Vec<&str> = (0..24).map(|k| SENTENCES[(x * 7 + k * 3) % SENTENCES.len()]).collect();            let lead = lead.join(" ");            let body = format!("{lead}\n\n{}", [lead.as_str(); 3].join(" "));            said.push((format!("dev-mail-g{x}"), Said { thread: format!("g{thread}"), subject, from: from_party, to: vec![(me.clone(), String::new())], at, body, unread: x % 5 == 0, files: Vec::new(), brought: true, plain: false }));        }    }    // The attachments' bytes, made before any row names them.    let layout = client.layout().clone();    let mut files: HashMap<String, Vec<(String, std::path::PathBuf, usize)>> = HashMap::new();    for (id, m) in said.iter().filter(|(_, m)| m.brought) {        for (n, (name, words)) in m.files.iter().enumerate() {            let bytes = invented_pdf(if words.is_empty() { name } else { words });            let scratch = layout.client_dir().join(format!("{id}-{n}.pdf"));            // not a copy: mail files.            std::fs::write(&scratch, &bytes).map_err(|e| MethodError::new("unwritable", e.to_string()))?;            files.entry(id.clone()).or_default().push((name.clone(), scratch, bytes.len()));        }    }    let written = said.len();    let now = client.clock().now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);    write(&client, "developer.inventMail", |ctx| {        for (i, p) in people.iter().enumerate() {            let pid = format!("dev-mail-person-{i}");            let (name, address, phone) = (word(p, "name"), word(p, "email").to_lowercase(), word(p, "phone"));            insert_row(ctx, "cotton_people", &pid, object_of(json!({ "full_name": name, "created_at": now, "updated_at": now }))).map_err(|e| e.to_string())?;            insert_row(ctx, "cotton_person_handles", &format!("{pid}-email"), object_of(json!({ "person_id": pid, "kind": "email", "value": address, "normalised": address, "source": "manual", "created_at": now, "updated_at": now }))).map_err(|e| e.to_string())?;            let number: String = phone.chars().filter(char::is_ascii_digit).collect();            if !number.is_empty() {                insert_row(ctx, "cotton_person_handles", &format!("{pid}-phone"), object_of(json!({ "person_id": pid, "kind": "phone", "value": phone, "normalised": number, "source": "manual", "created_at": now, "updated_at": now }))).map_err(|e| e.to_string())?;            }            // Their chat: a contact with their number, or (an imported chat, which has no number) their name.            let params = [ws(ctx), text(number.clone()), text(name.clone())];            let contacts = rows(ctx, "SELECT id FROM cotton_msg_contacts WHERE workspace_id = ? AND ((? <> '' AND replace(phone_e164, '+', '') = ?2) OR display_name = ?)", &params)?;            for c in contacts.iter().filter_map(|c| s(c, "id")) {                update_row(ctx, "cotton_msg_contacts", &c, object_of(json!({ "person_id": pid }))).map_err(|e| e.to_string())?;            }        }        // THE CONVERSATIONS FIRST (seen on the dev server, 22 Nov 2026): the queue goes up in the order it was written,        // and the object takes an email only once its conversation is there. Written after their mail, every invented        // email was refused once and parked; most were offered again, and 40 of 110,000 never were.        let mut threads: HashMap<String, (String, String, String, String, i64)> = HashMap::new();        for (_, m) in &said {            let entry = threads.entry(format!("dev-mail-thread-{}", m.thread)).or_insert_with(|| (m.thread.clone(), m.subject.clone(), m.at.clone(), m.at.clone(), 0));            if m.at < entry.2 {                entry.2 = m.at.clone();            }            if m.at > entry.3 {                entry.3 = m.at.clone();            }            entry.4 += 1;        }        for (thread_id, (origin, subject, first, last, count)) in &threads {            let (first, last, count) = spans.get(origin).map(|(f, l, c)| (f, l, c)).unwrap_or((first, last, count));            insert_row(ctx, MAIL_THREADS, thread_id, object_of(json!({                "external_key": format!("invented:{origin}"), "subject": subject, "first_at": first, "last_at": last, "email_count": count, "created_at": now, "updated_at": now,            })))            .map_err(|e| e.to_string())?;        }        for (id, m) in &said {            let thread_id = format!("dev-mail-thread-{}", m.thread);            let mut attachments = Vec::new();            for (n, (name, scratch, size)) in files.get(id).into_iter().flatten().enumerate() {                let key = keep_invented(ctx, &layout, scratch, &format!("{id}-{n}"), ("pdf", "application/pdf"), &now)?;                attachments.push(json!({ "name": name, "mime": "application/pdf", "size": size, "key": key }));            }            // Not brought yet: the attachment is a name in the row, as the Mac's reader lands it, until his Mac            // brings it when it is opened (`developer.fakeMac` stands in for the Mac).            for (name, _) in m.files.iter().filter(|_| !m.brought) {                let size = invented_pdf(name).len();                attachments.push(json!({ "name": name, "mime": "application/pdf", "size": size }));            }            let recipients: Vec<Value> = m.to.iter().map(|(a, n)| if n.is_empty() { json!({ "email": a, "kind": "to" }) } else { json!({ "email": a, "name": n, "kind": "to" }) }).collect();            let snippet: String = m.body.chars().take(200).collect();            let from_name = if m.from.1.is_empty() { Value::Null } else { Value::from(m.from.1.clone()) };            insert_row(ctx, EMAILS, id, object_of(json!({                "thread_id": thread_id, "external_id": invented_external(id, m.plain), "subject": m.subject, "from_email": m.from.0,                "from_name": from_name, "recipients": Value::Array(recipients), "sent_at": m.at, "body": m.body, "snippet": snippet,                "attachments": Value::Array(attachments), "unread": m.unread, "starred": false, "in_inbox": true, "account": me, "created_at": now,            })))            .map_err(|e| e.to_string())?;        }        Ok(())    })?;    client.nudge_sync();    Ok(json!({ "written": written }))}/// An invented mail's Message-ID. One written as plain text says so in it, the one thing `developer.fakeMac` reads/// to find no designed page, as the real Mac finds none in such a message.fn invented_external(id: &str, plain: bool) -> String {    if plain {        format!("<{id}.plain@invented.example>")    } else {        format!("<{id}@invented.example>")    }}/// Puts the file at `scratch` in this phone's media store as the person's own file (taken from the scratch place),/// queued to go up so his other phones fetch it when it is opened. Its key.fn keep_invented(ctx: &mut Ctx<'_>, layout: &cotton_client::layout::Layout, scratch: &std::path::Path, stem: &str, (ext, content_type): (&str, &str), now: &str) -> Result<String, String> {    let ws_id = ctx.workspace_id.to_string();    let stored = cotton_client::media::store::put_media_file(layout, &ws_id, scratch, ext).map_err(|e| e.to_string())?;    let key = cotton_core::media::keys::document_original_key(ctx.file.id(), stem, ext);    cotton_store::media_ledger::enqueue_media(        ctx.db(),        &cotton_store::media_ledger::MediaEnqueueInput {            key: key.clone(),            workspace_id: ws_id,            sha256: stored.sha256.clone(),            content_type: content_type.into(),            size_bytes: stored.size_bytes as i64,            local_path: Some(stored.path.to_string_lossy().to_string()),            state: None,            after: None,            after_row_id: None,            tier: Some(cotton_store::media_holdings::Tier::Original),            captured_here: true,            now: now.to_string(),        },    )    .map_err(|e| e.to_string())?;    // not a copy: mail files.    let _ = std::fs::remove_file(scratch);    Ok(key)}fn escaped(words: &str) -> String {    words.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")}/// An invented designed page for a mail: its subject and words as a sender's HTML would lay them, with one picture/// from the web (on a host that does not resolve: it shows only that loads wait for Show pictures) and one link.pub(crate) fn invented_page(from: &str, subject: &str, body: &str) -> String {    let paragraphs: String = body.split("\n\n").filter(|p| !p.trim().is_empty()).map(|p| format!("<p>{}</p>", escaped(p.trim()).replace('\n', "<br>"))).collect();    format!(        "<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\<style>body{{margin:0;background:#efe9df;font-family:Georgia,serif;color:#2a2620}}.card{{max-width:560px;margin:0 auto;background:#fffdf8}}\.top{{background:#1f4d46;color:#f7f1e6;padding:18px 24px;font:600 15px sans-serif;letter-spacing:.04em}}h1{{font-size:26px;margin:24px 24px 12px}}\img{{display:block;width:100%;height:auto;min-height:120px;background:#d9cfbf}}p{{font-size:17px;line-height:1.55;margin:0 24px 16px}}\a.button{{display:inline-block;margin:8px 24px 28px;padding:12px 20px;background:#c4572e;color:#fff;border-radius:6px;text-decoration:none;font:600 15px sans-serif}}\.foot{{padding:16px 24px;color:#7a7266;font:13px sans-serif;border-top:1px solid #e5ddd0}}</style></head>\<body><div class=\"card\"><div class=\"top\">{from}</div><h1>{subject}</h1>\<img src=\"https://picsum.invented.example/a.png\" alt=\"A picture from the web\" width=\"560\" height=\"240\">\{paragraphs}<a class=\"button\" href=\"https://example.com/\">Read more</a>\<div class=\"foot\">An invented letter, laid out as its sender designed it.</div></div></body></html>",        from = escaped(from),        subject = escaped(subject),    )}/// `mail_page` as his Mac answers it (CONTRACT "A mail's page and files, brought when he opens it"), for/// `developer.fakeMac`: the mail whose Message-ID is `target` gains its designed page in `media` (`page.html`,/// `text/html`, kept as a file with a key; none for a mail written as plain text) and every attachment not brought/// yet its file (an invented PDF saying its name) beside its name. The row's answer, with `page` and `files`.pub(crate) fn dev_bring_page(ctx: &mut Ctx<'_>, layout: &cotton_client::layout::Layout, target: &str, now: &str) -> Result<Value, String> {    let found = rows(ctx, &format!("SELECT id, subject, body, from_name, from_email, attachments, media FROM {EMAILS} WHERE workspace_id = ? AND external_id = ?"), &[ws(ctx), text(target.to_string())])?;    let Some(row) = found.into_iter().next() else {        return Ok(json!({ "status": "failed", "error": "This email is no longer in your mail." }));    };    let id = s(&row, "id").unwrap_or_default();    let list = |k: &str| match row.get(k) {        Some(Value::String(text)) => serde_json::from_str::<Vec<Value>>(text).unwrap_or_default(),        Some(Value::Array(list)) => list.clone(),        _ => Vec::new(),    };    let scratch_of = |name: &str| layout.client_dir().join(format!("fake-mac-{}-{name}", id.replace(['/', '\\'], "_")));    let mut patch = Map::new();    let mut media = list("media");    let had_page = media.iter().any(|m| m.get("name").and_then(Value::as_str) == Some("page.html"));    let plain = target.contains(".plain@");    if !had_page && !plain {        let from = s(&row, "from_name").or_else(|| s(&row, "from_email")).unwrap_or_default();        let html = invented_page(&from, &s(&row, "subject").unwrap_or_default(), &s(&row, "body").unwrap_or_default());        let scratch = scratch_of("page.html");        // not a copy: mail files.        std::fs::write(&scratch, html.as_bytes()).map_err(|e| e.to_string())?;        let key = keep_invented(ctx, layout, &scratch, &format!("{id}-page"), ("html", "text/html"), now)?;        media.push(json!({ "key": key, "contentType": "text/html", "size": html.len(), "name": "page.html" }));        // A file column holds its list as JSON text (as the Mac writes it back when it came so).        patch.insert("media".into(), Value::from(serde_json::to_string(&media).unwrap_or_default()));    }    let mut attachments = list("attachments");    let mut files = 0;    for (n, a) in attachments.iter_mut().enumerate() {        let Some(entry) = a.as_object_mut() else { continue };        if entry.contains_key("key") {            continue;        }        let name = entry.get("name").and_then(Value::as_str).unwrap_or("attachment").to_string();        let scratch = scratch_of(&format!("{n}.pdf"));        // not a copy: mail files.        std::fs::write(&scratch, invented_pdf(&name)).map_err(|e| e.to_string())?;        let key = keep_invented(ctx, layout, &scratch, &format!("{id}-brought-{n}"), ("pdf", "application/pdf"), now)?;        entry.insert("key".into(), json!(key));        files += 1;    }    if files > 0 {        patch.insert("attachments".into(), Value::Array(attachments));    }    if !patch.is_empty() {        update_row(ctx, EMAILS, &id, patch).map_err(|e| e.to_string())?;    }    Ok(json!({ "status": "sent", "sent_at": now, "error": null, "page": had_page || !plain, "files": files }))}#[cfg(test)]#[path = "chat_mail_tests.rs"]pub(crate) mod tests;