//! A mail's own acts (SENDERS.md "On any mail, and swipes everywhere"; owner, 24 Nov 2026). Each changes the mail//! here at once and, where the served outbox offers it, files one `mail` outbox row for the Mac to do the same in his//! mailbox (CONTRACT "Senders 3: what the Mac keeps, and the mail acts it carries out").//!//! - `chat.mail.hold { email }` → `{ email, acts: [{ id, label }] }`: `read` or `unread`, `archive`, `delete`,//! `delete_sender`, `unsubscribe` (only when the mail offers it), `block`, `sender`, in that order.//! - `chat.mail.act { email, act }` → `{ email, said }`://! - `read` / `unread`: the mail's `unread` here, and `mark_read` / `mark_unread` for the Mac;//! - `archive`: `archived_at` here (out of every list, kept), and `archive` for the Mac (out of the Inbox);//! - `unsubscribe`: `unsubscribe` for the Mac (one-click, else its arrivals to Trash), nothing here;//! - `block`: People's block of the sender (`chat.sender.act`).//! - `delete` (ERASES): erased from Cotton on every device, and `trash` for the Mac;//! - `delete_sender` (ERASES): with no `count`, answers `{ ask }` (Delete everything's, with its count); with the//! count he saw, Delete everything from the sender (`chat.sender.act`), their mail to Trash at the Mac.use cotton_tools::mcp::handlers::{common::update_row, tables};usesuper::*;use cotton_core::rules::mail_predicate;const OUTBOX: &str = "outbox";const CHANNEL: &str = "mail";/// The kinds a mail act files, by act.fn kind_of(act: &str) -> Option<&'static str> {Some(match act {"read" => "mark_read","unread" => "mark_unread","archive" => "archive","delete" => "trash","unsubscribe" => "unsubscribe",// Opening a mail's file the Mac has not brought: it brings the page and every file (mac-import, Mac 9)."page" => "mail_page", _ => returnNone, })}/// Whether the served outbox takes `kind` on the mail channel: a Worker not yet deployed with it serves the outbox of/// before, and the act is then done here alone.pub(crate) fn takes(ctx: &mutCtx<'_>, kind: &str) -> Result<bool, String> {let rows = cotton_tools::definitions::definition_rows(ctx, Some(OUTBOX)).map_err(|e| e.to_string())?;Ok(rows.iter().any(|row| {let definition: Value = serde_json::from_str(&row.definition).unwrap_or(Value::Null);let offers = |key: &str, value: &str| { definition["columns"].as_array().into_iter().flatten().filter(|c| c["key"] == key).flat_map(|c| c["choices"].as_array().into_iter().flatten()).any(|c| c.as_str().or_else(|| c["value"].as_str()) == Some(value)) }; offers("channel", CHANNEL) && offers("kind", kind) }))}/// One mail as the acts read it.pub(crate) structMail {pub(crate) id: String,pub(crate) thread: String,pub(crate) external: Option<String>,pub(crate) from: String,pub(crate) name: Option<String>,pub(crate) unread: bool,pub(crate) account: Option<String>,pub(crate) unsubscribe: bool,pub(crate) archived: bool,}pub(crate) fn mail_of(ctx: &mutCtx<'_>, id: &str) -> Result<Option<Mail>, String> {letSome(r) = one(ctx, &format!("SELECT id, thread_id, external_id, from_email, from_name, {unread_col} AS unread, coalesce(account, gmail_account) AS account, list_unsubscribe, archived_at FROM {EMAILS} WHERE workspace_id = ? AND id = ? AND {live_mail}", live_mail = mail_predicate::live(""), unread_col = mail_predicate::unread("")), &[ws(ctx), text(id.to_string())])? else {returnOk(None); };Ok(Some(Mail { id: id.to_string(), thread: s(&r, "thread_id").unwrap_or_default(), external: s(&r, "external_id"), from: s(&r, "from_email").unwrap_or_default().trim().to_lowercase(), name: s(&r, "from_name").filter(|n| !n.trim().is_empty()), unread: truthy(&r, "unread"), account: s(&r, "account"), unsubscribe: s(&r, "list_unsubscribe").is_some_and(|v| !v.trim().is_empty()), archived: s(&r, "archived_at").is_some(), }))}/// Whether the Mac is already asked to bring `mail`'s page and files (a `mail_page` row queued or under way).pub(crate) fn page_asked(ctx: &mutCtx<'_>, mail: &Mail) -> Result<bool, String> {letSome(external) = mail.external.clone() else { returnOk(false) };// A copy whose outbox does not take it (or that keeps no outbox at all, a Keys phone) has asked nothing.if !takes(ctx, "mail_page")? {returnOk(false); }Ok(one(ctx, "SELECT 1 AS asked FROM cotton_outbox WHERE workspace_id = ? AND channel = 'mail' AND kind = 'mail_page' AND target = ? AND status IN ('queued', 'sending') LIMIT 1", &[ws(ctx), text(external)])?.is_some())}/// Whether his Mac already answered for `mail`'s page and files: `Some` once a `mail_page` row is `sent` (it brought/// what it could) or `failed` (too large, or gone: a connection's failure stays queued on the Mac), holding the/// failure's words. Asking again would bring nothing more.pub(crate) fn page_answered(ctx: &mutCtx<'_>, mail: &Mail) -> Result<Option<Option<String>>, String> {letSome(external) = mail.external.clone() else { returnOk(None) };if !takes(ctx, "mail_page")? {returnOk(None); }let found = one(ctx, "SELECT status, error FROM cotton_outbox WHERE workspace_id = ? AND channel = 'mail' AND kind = 'mail_page' AND target = ? AND status IN ('sent', 'failed') ORDER BY CASE status WHEN 'failed' THEN 0 ELSE 1 END LIMIT 1", &[ws(ctx), text(external)])?;Ok(found.map(|row| row.get("error").and_then(Value::as_str).map(str::trim).filter(|e| !e.is_empty() && row.get("status").and_then(Value::as_str) == Some("failed")).map(str::to_string)))}/// Files the Mac's row for `act` on `mail`, when the outbox takes it. Whether it did.pub(crate) fn queue(ctx: &mutCtx<'_>, mail: &Mail, act: &str) -> Result<bool, String> {letSome(kind) = kind_of(act) else { returnOk(false) };if !takes(ctx, kind)? {returnOk(false); }letmut data = json!({ "channel": CHANNEL, "kind": kind, "target": mail.external, "account": mail.account, "status": "queued" });// `to` is the outbox's own required column: the sender, which the Mac's unsubscribe reads and the rest name. data["to"] = json!(mail.from);// The sender's name as Comms showed it, for their row while the Mac works (`body`: see wide::file_sender_wide). data["body"] = json!(mail.name.clone().unwrap_or_else(|| mail.from.clone())); tables::create_produced_record(ctx, &json!({ "table": OUTBOX, "data": data }).as_object().cloned().unwrap_or_default()).map_err(|f| f.to_string())?;Ok(true)}fn email_of(request: &Value) -> Result<String, MethodError> {Ok(cotton_chat::text(request, "email")?.to_string())}/// What a request names: one mail (`email`), or a conversation (`thread`), every mail in it.enumNamed {Email(String),Thread(String),/// Several mails chosen on a sender's page (select).Emails(Vec<String>),}fn named(request: &Value) -> Result<Named, MethodError> {ifletSome(list) = request.get("emails").and_then(Value::as_array) {let ids: Vec<String> = list.iter().filter_map(Value::as_str).map(str::to_string).collect();if ids.is_empty() {returnErr(MethodError::new("bad_request", "`emails` names at least one mail")); }returnOk(Named::Emails(ids)); }match request.get("thread").and_then(Value::as_str) {Some(thread) if !thread.is_empty() => Ok(Named::Thread(thread.to_string())), _ => Ok(Named::Email(email_of(request)?)), }}/// The mails `name` names, newest first; for a conversation, its live mail (not archived).fn mails_of(ctx: &mutCtx<'_>, name: &Named) -> Result<Vec<Mail>, String> {match name {Named::Email(id) => Ok(mail_of(ctx, id)?.into_iter().collect()),Named::Emails(ids) => {letmut out = Vec::new();for id in ids { out.extend(mail_of(ctx, id)?); }Ok(out) }Named::Thread(thread) => {let ids = rows(ctx, &format!("SELECT id FROM {EMAILS} WHERE workspace_id = ? AND thread_id = ? AND {live_mail} AND archived_at IS NULL ORDER BY sent_at DESC, id DESC", live_mail = mail_predicate::live("")), &[ws(ctx), text(thread.clone())])?;letmut out = Vec::new();for id in ids.iter().filter_map(|r| s(r, "id")) { out.extend(mail_of(ctx, &id)?); }Ok(out) } }}fn found(client: &ClientController, name: &Named) -> Result<Vec<Mail>, MethodError> {letmut out = Vec::new(); cotton_chat::read(client, "chat.mail.mails", |ctx| { out = mails_of(ctx, name)?;Ok(Value::Null) })?;if out.is_empty() {returnErr(not_found()); }Ok(out)}fn echo(name: &Named) -> Value {match name {Named::Email(id) => json!({ "email": id }),Named::Thread(id) => json!({ "thread": id }),Named::Emails(ids) => json!({ "emails": ids }), }}fn not_found() -> MethodError {MethodError::new("not_found", say(&list::lines(), "app.mail.acts.not_found", &[]))}/// The sender's name as the acts say it: their name, else their address.pub(super) fn shown_name(mail: &Mail) -> String { mail.name.clone().unwrap_or_else(|| mail.from.clone())}/// Whose mail `mails` (newest first) are: the newest not his own (a mail read from his own mailbox's address is his/// reply), else the newest.fn theirs(mails: &[Mail]) -> String { mails.iter().find(|m| is_theirs(m)).or(mails.first()).map(|m| m.from.clone()).unwrap_or_default()}/// Not his own: a mail read from his own mailbox's address is his.fn is_theirs(mail: &Mail) -> bool { mail.account.as_deref().is_none_or(|a| !a.trim().eq_ignore_ascii_case(&mail.from))}pub(super) fn hold(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let name = named(request)?;let lines = list::lines();let mails = found(client, &name)?;// Their page is the sender's: the newest mail not his own (a mail read from his own mailbox's address is his reply),// else the newest (seen by look-ios on Comms Dev's seed, 24 Nov 2026: Open sender on a conversation he answered// opened his own page).let theirs_mail = mails.iter().find(|m| is_theirs(m)).or(mails.first());let sender_name = theirs_mail.map(shown_name).unwrap_or_default();let theirs = theirs(&mails);// A conversation reads as its newest mail, and as unread when any of it is.let mail = mails.into_iter().fold(None::<Mail>, |held, m| match held {None => Some(m),Some(mut first) => { first.unread |= m.unread;Some(first) } }).ok_or_else(not_found)?;let act = |id: &str, fills: &[(&str, &str)]| json!({ "id": id, "label": say(&lines, &format!("app.mail.acts.{id}"), fills) });letmut acts = vec![act(if mail.unread { "read" } else { "unread" }, &[])];if !mail.archived { acts.push(act("archive", &[])); } acts.push(act("delete", &[])); acts.push(act("delete_sender", &[("name", &sender_name)]));if mail.unsubscribe { acts.push(act("unsubscribe", &[])); } acts.push(act("block", &[]));// Their page (`chat.sender.page`), from any mail.letmut sender = act("sender", &[]); sender["open"] = json!({ "sender": theirs }); acts.push(sender);letmut out = echo(&name); out["acts"] = json!(acts);Ok(out)}pub(super) fn act(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let name = named(request)?;let what = cotton_chat::text(request, "act")?.to_string();let lines = list::lines();match what.as_str() {"delete_sender" => {// Delete everything from the sender (ERASES): asked first with its count, then run with the count he saw.let sender = theirs(&found(client, &name)?);letmut out = echo(&name);match request.get("count").and_then(Value::as_u64) {None => out["ask"] = crate::phone::chat_app::senders::ask(client, &json!({ "key": sender, "act": "delete" }))?,Some(count) => out["said"] = crate::phone::chat_app::senders::act(client, &json!({ "key": sender, "act": "delete", "count": count, "mailbox": request.get("mailbox") }))?["said"].clone(), }returnOk(out); }"delete" => {// ERASES: the mail is erased from Cotton on every device, and goes to Trash in his mailbox (`trash`).let now = cotton_chat::iso(cotton_chat::now_ms(client));letmut filed = false; cotton_chat::write(client, "chat.mail.delete", |ctx| {let mails = mails_of(ctx, &name)?;if mails.is_empty() {returnErr(say(&lines, "app.mail.acts.not_found", &[])); } filed = false;for mail in &mails { filed |= queue(ctx, mail, "delete")?; }let doomed: Vec<(String, String)> = mails.iter().map(|m| (m.id.clone(), m.thread.clone())).collect();crate::phone::chat_app::senders::erase::erase_mails(ctx, &doomed, &now)?;Ok(Value::Null) })?;letmut out = echo(&name);// Erased in Comms; Trash in his mailbox waits for the Mac (ACTS TRUTH): never said done before it is. out["said"] = json!(say(&lines, if filed { "app.mail.acts.said.deleted_mail" } else { "app.mail.acts.said.deleted" }, &[]));returnOk(out); }"block" => {let sender = theirs(&found(client, &name)?);let done = crate::phone::chat_app::senders::act(client, &json!({ "key": sender, "act": "block" }))?;letmut out = echo(&name); out["said"] = done["said"].clone();returnOk(out); }"read" | "unread" | "archive" | "unsubscribe" => {} _ => returnErr(MethodError::new("bad_act", format!("act: read, unread, archive, delete, delete_sender, unsubscribe or block, not {what}"))), }let now = cotton_chat::iso(cotton_chat::now_ms(client));let said = cotton_chat::write(client, "chat.mail.act", |ctx| {letmut filed = false;let mails = mails_of(ctx, &name)?;letSome(newest) = mails.first() else { returnErr(say(&lines, "app.mail.acts.not_found", &[])) };let sender = shown_name(newest);if what == "unsubscribe" {// One unsubscribe for the sender: the newest mail that offers it.letSome(offering) = mails.iter().find(|m| m.unsubscribe) else { returnErr(say(&lines, "app.mail.acts.no_unsubscribe", &[])) };if !queue(ctx, offering, &what)? {returnErr(say(&lines, "app.mail.acts.not_yet", &[])); }returnOk(json!(say(&lines, "app.mail.acts.said.unsubscribing", &[("name", &sender)]))); }for mail in &mails {// Only what changes: a read mail is not marked read again, at the Mac either.let (column, value, changes) = match what.as_str() {"read" => ("unread", json!(false), mail.unread),"unread" => ("unread", json!(true), !mail.unread), _ => ("archived_at", json!(now), !mail.archived), };if !changes {continue; }letmut patch = Map::new(); patch.insert(column.into(), value); update_row(ctx, EMAILS, &mail.id, patch).map_err(|f| f.to_string())?; filed |= queue(ctx, mail, &what)?; }// What Comms did, and that his mailbox follows when the Mac does it (ACTS TRUTH, 24 Nov 2026).let key = match (what.as_str(), filed) { ("archive", true) => "app.mail.acts.said.archived_mail", ("archive", false) => "app.mail.acts.said.archived", ("read", true) => "app.mail.acts.said.read_mail", ("read", false) => "app.mail.acts.said.read", (_, true) => "app.mail.acts.said.unread_mail", _ => "app.mail.acts.said.unread", };Ok(json!(say(&lines, key, &[("name", &sender)]))) })?;letmut out = echo(&name); out["said"] = said;Ok(out)}