//! Everyone who writes to him, on this phone's copy (owner, 24 Nov 2026; `assets/design/chat/SENDERS.md`). The//! rules and words are `cotton_core::messages::app::senders`; this reads the copy and writes his choices.//!//! - `chat.senders {filter?, after?}`: one ranked list of the senders of his WhatsApp and SMS one-to-one chats and//! of his mail, by number, address or short-code name; a blocked sender is not in it.//! - `chat.sender.ask {key, act}`: what Block or Delete everything takes, with its count, before it runs.//! - `chat.sender.act {key, act: block | unblock | delete, count?}`: the choice; delete ERASES ([`erase`]) and runs//! only with the count its ask showed. A block is a row of `cotton_blocked_senders`//! (synced to his other phones), keyed by the sender's key in lower case; a mail address is blocked through the//! mail's own `block_sender`, so its mail files into Junk as before.//! - `chat.senders.blocked`: the one Blocked place.//!//! A blocked sender shows nowhere else in Comms: [`hidden_threads`] takes their chats out of the chat list and its//! search, and their mail is Junk, which Mail and a person's chat never show. Only Cotton chat makes notices, and//! a Cotton chat's own block is the Worker's (`chat.block`), so these senders make none already.use std::collections::{HashMap, HashSet};use rusqlite::types::ValueasSqlValue;use serde_json::{json, Map, Value};use cotton_core::messages::app::senders::{selfas rule, KeyKind, SenderKey, Tally};use cotton_core::messages::app::list::{self, say};use cotton_tools::mcp::dispatch::Ctx;usesuper::whatsapp_send::SourceAct;usesuper::cotton_chat::{rows, ws, MESSAGES, THREADS};usesuper::{n, read, s};usecrate::methods::MethodError;usecrate::shell::client::ClientController;use cotton_core::rules::mail_predicate;const CONTACTS: &str = "cotton_msg_contacts";const BLOCKED: &str = "cotton_blocked_senders";/// The senders he joined by hand (kit table `sender_merge`).const MERGES: &str = "sender_merge";const EMAILS: &str = "cotton_emails";/// Rows a page of the list holds.const PAGE: usize = 80;/// The senders he blocked: each key in lower case, with when (ms).#[derive(Debug, Default, Clone)]pub(crate) structBlocked { since: HashMap<String, i64>,}implBlocked {pub(crate) fn read(ctx: &mutCtx<'_>) -> Result<Blocked, String> {letmut since = HashMap::new();let found = rows(ctx, &format!("SELECT address, created_at FROM {BLOCKED} WHERE workspace_id = ?"), &[ws(ctx)]).unwrap_or_default();for r in found {ifletSome(a) = s(&r, "address") { since.insert(a.trim().to_lowercase(), s(&r, "created_at").map_or(0, |at| super::ms(&at))); } }Ok(Blocked { since }) }pub(crate) fn has(&self, key: &SenderKey) -> bool {self.since.contains_key(&key.key.to_lowercase()) }pub(crate) fn since(&self, key: &SenderKey) -> Option<i64> {self.since.get(&key.key.to_lowercase()).copied() }pub(crate) fn is_empty(&self) -> bool {self.since.is_empty() }/// The blocked keys, as stored.pub(crate) fn keys(&self) -> implIterator<Item = (&String, &i64)> {self.since.iter() }}/// The key of a stored blocked row, by its shape: an address holds `@`, a number leads with `+`, else a name.pub(crate) fn stored_key(stored: &str) -> SenderKey {let kind = if stored.contains('@') {KeyKind::Address } elseif stored.starts_with('+') {KeyKind::Number } else {KeyKind::Name };SenderKey { key: if kind == KeyKind::Name { stored.to_uppercase() } else { stored.to_string() }, kind }}/// A one-to-one chat's sender: its contact's number, else its title (an SMS short code's name), else its key.pub(crate) fn chat_key(phone: Option<&str>, title: Option<&str>, external: Option<&str>) -> Option<SenderKey> { phone .and_then(rule::key_of_sender) .or_else(|| title.and_then(rule::key_of_sender)) .or_else(|| external.filter(|k| !k.starts_with("cotton:")).and_then(rule::key_of_sender))}/// One one-to-one chat's share, by channel.#[derive(Debug, Clone)]pub(crate) structChatShare {pub(crate) thread: String,pub(crate) key: SenderKey,pub(crate) channel: String,pub(crate) name: Option<String>,pub(crate) sent: u32,pub(crate) replied: bool,pub(crate) last_at: Option<String>,/// The chat's own title as it came (an SMS short code with its `VM-…-P` marks).pub(crate) title: Option<String>,}/// Names in People by number: who(handle)'s rule (`cotton_store::protocol::who`): the stored match form, a person/// not in the bin (archived still counts), a handle not in the bin.fn people_by_number(ctx: &mutCtx<'_>) -> HashMap<String, String> {let found = rows(ctx, "SELECT h.normalised AS value, h.person_id AS p, p.full_name AS name FROM cotton_person_handles h JOIN cotton_people p ON p.id = h.person_id WHERE h.workspace_id = ? AND h.kind = 'phone' AND h.trashed_at IS NULL AND p.trashed_at IS NULL", &[ws(ctx)]).unwrap_or_default();letmut by: HashMap<String, (String, Option<String>, bool)> = HashMap::new();for r in found {let (Some(value), Some(p)) = (s(&r, "value"), s(&r, "p")) else { continue };letSome(key) = rule::key_of_sender(&value).filter(|k| k.kind == KeyKind::Number) else { continue };match by.get_mut(&key.key) {Some((held, _, two)) if *held != p => *two = true,Some(_) => {}None => { by.insert(key.key, (p, s(&r, "name"), false)); } } } by.into_iter().filter(|(_, (_, _, two))| !two).filter_map(|(k, (_, name, _))| Some((k, name?))).collect()}/// Every WhatsApp and SMS one-to-one chat's sender and how much each side wrote, by channel. Cotton's own chats/// are not here: a Cotton chat has its own block (`chat.block`).pub(crate) fn chat_shares(ctx: &mutCtx<'_>) -> Result<Vec<ChatShare>, String> {let found = rows( ctx, &format!("SELECT t.id AS thread, t.title AS title, t.external_key AS external, c.phone_e164 AS phone, c.display_name AS shown, m.channel AS channel, SUM(CASE WHEN m.direction = 'in' THEN 1 ELSE 0 END) AS sent, MAX(CASE WHEN m.direction = 'out' THEN 1 ELSE 0 END) AS replied, MAX(CASE WHEN m.direction = 'in' THEN m.sent_at END) AS last_at FROM {THREADS} t LEFT JOIN {CONTACTS} c ON c.id = t.contact_id JOIN {MESSAGES} m ON m.thread_id = t.id WHERE t.workspace_id = ? AND t.trashed_at IS NULL AND coalesce(t.kind, '') <> 'group' AND coalesce(t.external_key, '') NOT LIKE 'cotton:%' AND m.channel IN ('whatsapp', 'sms') AND m.trashed_at IS NULL AND m.hidden_at IS NULL AND json_extract(m.meta, '$.system') IS NULL AND json_extract(m.meta, '$.cotton.erased') IS NULL GROUP BY t.id, m.channel" ), &[ws(ctx)], )?;let named = people_by_number(ctx);Ok(found .into_iter() .filter_map(|r| {let key = chat_key(s(&r, "phone").as_deref(), s(&r, "title").as_deref(), s(&r, "external").as_deref())?;let name = named.get(&key.key).cloned().or_else(|| s(&r, "shown")).or_else(|| s(&r, "title")).filter(|t| rule::key_of_sender(t).as_ref() != Some(&key));Some(ChatShare { thread: s(&r, "thread")?, key, channel: s(&r, "channel")?, name, sent: n(&r, "sent").max(0) as u32, replied: n(&r, "replied") > 0, last_at: s(&r, "last_at"), title: s(&r, "title") }) }) .collect())}/// The mail a set of sender keys covers, as a clause over `from_email` and its values: an address itself, every/// address at an `@domain`; keys that are no address (a number, a short code) cover no mail. `None` is every sender./// Reading one sender's facts over only their own mail keeps a page or an act from tallying the whole account/// (SENDERS 3 WALKED: 100,000 mails from 2,000 senders).pub(crate) fn mail_where(only: Option<&[String]>) -> (String, Vec<SqlValue>) {letSome(keys) = only else { return ("1".into(), Vec::new()) };letmut clauses = Vec::new();letmut params = Vec::new();for k in keys.iter().map(|k| k.trim().to_lowercase()) {ifletSome(domain) = k.strip_prefix('@') { clauses.push("lower(trim(from_email)) LIKE ?".to_string()); params.push(SqlValue::Text(format!("%@{domain}"))); } elseif k.contains('@') { clauses.push("lower(trim(from_email)) = ?".to_string()); params.push(SqlValue::Text(k)); } }if clauses.is_empty() {return ("0".into(), params); } (format!("({})", clauses.join(" OR ")), params)}/// Each sender's tally over the mail `clause` covers (`mail_where`): every column it reads is in/// `idx_cotton_emails_sender` (schema 153), whose sender is this expression word for word, so it reads that index alone/// and never a mail's row, which is mostly its body (SENDERS INDEX: the tab cut off at 20 s over 100,000 mails).pub(crate) fn tally_sql(clause: &str) -> String { format!("SELECT lower(trim(from_email)) AS address, COUNT(*) AS sent, MAX(sent_at) AS last_at, MAX(CASE WHEN from_name IS NOT NULL THEN COALESCE(sent_at, '') || char(31) || from_name END) AS named FROM {EMAILS} WHERE workspace_id = ? AND {live_mail} AND {clause} GROUP BY lower(trim(from_email))", live_mail = mail_predicate::live(""))}/// Every mail sender who is not him (or those `only` covers): how many they sent and whether he ever wrote to them.fn mail_tallies(ctx: &mutCtx<'_>, only: Option<&[String]>) -> Result<Vec<Tally>, String> {let know = super::mail::Know::read(ctx)?;let (clause, mut scoped) = mail_where(only);letmut params = vec![ws(ctx)]; params.append(&mut scoped);let found = rows(ctx, &tally_sql(&clause), ¶ms)?;Ok(found .into_iter() .filter_map(|r| {let address = s(&r, "address")?;if know.is_own(&address) {returnNone; }let key = rule::key_of_address(&address)?;// The name on their newest mail that carries one, from the same pass (`sent_at`, a unit separator, the// name): one scan of the mail however many senders there are (SENDERS 3 WALKED, 100,000 mails).let named = s(&r, "named").and_then(|v| v.split_once('\u{1f}').map(|(_, name)| name.to_string()));let name = know.name_of(&address).map(str::to_string).or(named);Some(Tally { replied: know.wrote_to(&address), key, channel: "mail".into(), name, sent: n(&r, "sent").max(0) as u32, last_at: s(&r, "last_at") }) }) .collect())}/// Every WhatsApp one-to-one chat's sender, whether or not anything of theirs is left here (a source act's state/// stands on them after Delete everything).fn whatsapp_chat_keys(ctx: &mutCtx<'_>) -> Result<Vec<(String, SenderKey, Option<String>)>, String> {let found = rows( ctx, &format!("SELECT t.id AS thread, t.title AS title, t.external_key AS external, c.phone_e164 AS phone, c.display_name AS shown FROM {THREADS} t LEFT JOIN {CONTACTS} c ON c.id = t.contact_id WHERE t.workspace_id = ? AND t.trashed_at IS NULL AND coalesce(t.kind, '') <> 'group' AND coalesce(t.external_key, '') NOT LIKE 'cotton:%' AND EXISTS (SELECT 1 FROM {MESSAGES} m WHERE m.thread_id = t.id AND m.channel = 'whatsapp')"), &[ws(ctx)], )?;Ok(found .into_iter() .filter_map(|r| Some((s(&r, "thread")?, chat_key(s(&r, "phone").as_deref(), s(&r, "title").as_deref(), s(&r, "external").as_deref())?, s(&r, "shown")))) .collect())}/// The WhatsApp chats of `key`.pub(crate) fn whatsapp_threads_of(ctx: &mutCtx<'_>, key: &SenderKey) -> Result<Vec<String>, String> {Ok(whatsapp_chat_keys(ctx)?.into_iter().filter(|(_, k, _)| k.key.eq_ignore_ascii_case(&key.key)).map(|(t, _, _)| t).collect())}/// Each sender's newest act on his WhatsApp (block, unblock, delete the chat), by key in lower case, with a name.fn source_states(ctx: &mutCtx<'_>) -> Result<HashMap<String, (SourceAct, SenderKey, Option<String>)>, String> {let acts = super::whatsapp_send::newest_source_acts(ctx)?;if acts.is_empty() {returnOk(HashMap::new()); }letmut out: HashMap<String, (SourceAct, SenderKey, Option<String>)> = HashMap::new();for (thread, key, name) in whatsapp_chat_keys(ctx)? {letSome(act) = acts.get(&thread) else { continue };let k = key.key.to_lowercase();let newer = out.get(&k).is_none_or(|(held, _, _)| (&held.written_at, &held.id) < (&act.written_at, &act.id));if newer { out.insert(k, (act.clone(), key, name)); } }Ok(out)}/// A source act as a row says it: its line, and Retry when it failed or stuck.pub(crate) fn source_json(lines: &cotton_core::rules::shell_lines::LineSet, act: &SourceAct, now_ms: i64) -> Value {// An archive the Mac did not read back is said as unchecked, with Try again (SENDERS TRUE).// The Mac counted first and asks him (Mac 9): his count to confirm, with the pill saying what the tap does.ifletSome(n) = act.counted() {let one = n == 1;let line = say(lines, &format!("app.senders.source.{}_counted{}", act.kind, if one { "_one" } else { "" }), &[("n", &n.to_string())]);let retry = say(lines, &format!("app.senders.source.{}_go{}", act.kind, if one { "_one" } else { "" }), &[("n", &n.to_string())]);return json!({ "kind": act.kind, "state": "counted", "line": line, "retry": retry }); }let state = match act.status.as_str() {"sent"if act.unchecked() => "unchecked","sent" => "sent","failed" => "failed", _ => "queued", };// A Mac whose Cotton does not take this act yet answers in its own words ("Not something mail can do.", "Count// first, then move."): said plainly to him (ACTS TRUTH, owner's Comms 31, 24 Nov 2026).let why = match act.error.as_deref() {None => say(lines, "app.senders.source.no_why", &[]),Some("Not something mail can do.") | Some("Count first, then move.") => say(lines, "app.senders.source.mac_not_yet", &[]),Some(other) => other.to_string(), };// A sender's Archive everything read back says how many left his Inbox.let line = match (act.kind.as_str(), state, act.moved) {// Waiting, said as what the Mac does next: count first (no set on the row), or move the set he confirmed. ("sender_archive" | "sender_trash", "queued", _) if !act.fixed => say(lines, &format!("app.senders.source.{}_counting", act.kind), &[]), ("sender_archive" | "sender_trash", "queued", _) if act.count.is_some_and(|n| n > 0) => {let n = act.count.unwrap_or(0); say(lines, &format!("app.senders.source.{}_going{}", act.kind, if n == 1 { "_one" } else { "" }), &[("n", &n.to_string())]) } ("sender_archive", "sent", Some(0)) => say(lines, "app.senders.source.sender_archive_sent_none", &[]), ("sender_archive", "sent", Some(1)) => say(lines, "app.senders.source.sender_archive_sent_one", &[]), ("sender_archive", "sent", Some(n)) => say(lines, "app.senders.source.sender_archive_sent_n", &[("n", &n.to_string())]),// Not unsubscribed there: the Mac moves their arrivals to Trash from now on. Why, in words: no one-click// offered (the mail here says), the click led to a page, or their server refused it (the Mac's `error`). ("unsubscribe", "sent", _) if act.proof.as_deref() == Some("trash_on_arrival") => {let page = act.error.as_deref().is_some_and(|e| e.contains("redirected the click to a page"));let source_line = match (act.offered, page) { (_, true) => "unsubscribe_sent_trash_page", (true, false) => "unsubscribe_sent_trash_refused", (false, false) => "unsubscribe_sent_trash", }; say(lines, &format!("app.senders.source.{source_line}"), &[]) } _ => say(lines, &format!("app.senders.source.{}_{state}", act.kind), &[("why", &why)]), };let retry = super::whatsapp_send::source_retryable(act, now_ms).then(|| say(lines, "app.senders.source.retry", &[])); json!({ "kind": act.kind, "state": state, "line": line, "retry": retry })}/// Every sender, ranked, blocked ones with them.fn everyone(ctx: &mutCtx<'_>) -> Result<Vec<rule::Sender>, String> { everyone_in(ctx, None)}/// The senders `only` covers (see [`mail_where`]); chats are few and read whole either way.pub(crate) fn everyone_in(ctx: &mutCtx<'_>, only: Option<&[String]>) -> Result<Vec<rule::Sender>, String> {letmut tallies: Vec<Tally> = chat_shares(ctx)? .into_iter() .map(|c| Tally { key: c.key, channel: c.channel, name: c.name, sent: c.sent, replied: c.replied, last_at: c.last_at }) .collect(); tallies.extend(mail_tallies(ctx, only)?);Ok(rule::senders_of(tallies))}/// The one-to-one chats of blocked senders, which stand nowhere but Blocked.pub(crate) fn hidden_threads(ctx: &mutCtx<'_>) -> Result<HashSet<String>, String> {let blocked = Blocked::read(ctx)?;if blocked.is_empty() {returnOk(HashSet::new()); }Ok(chat_shares(ctx)?.into_iter().filter(|c| blocked.has(&c.key)).map(|c| c.thread).collect())}fn key_of_request(request: &Value) -> Result<SenderKey, MethodError> {let raw = request.get("key").and_then(Value::as_str).map(str::trim).filter(|k| !k.is_empty()).ok_or_else(|| MethodError::new("bad_request", "`key` names the sender"))?;Ok(stored_key(raw))}/// `chat.senders`: the Senders tab (SENDERS.md "DECIDED: Senders 3"). `filter` is all, people, notices or/// promotions (a channel, as People asked, still answers); `domain` lists one domain's addresses; `merging` is the/// list a sender is merged from, every sender on its own and that one left out.pub(crate) fn page(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let lines = list::lines();let now = super::cotton_chat::now_ms(client);let wanted = |f: &&str| *f == "all" || rule::CHANNELS.contains(f) || rule::GROUPS.iter().any(|g| g.as_str() == *f);let filter = request.get("filter").and_then(Value::as_str).filter(wanted).unwrap_or("all").to_string();let after = request.get("after").and_then(Value::as_str).and_then(|a| a.parse::<usize>().ok()).unwrap_or(0);let domain = request.get("domain").and_then(Value::as_str).map(|d| d.trim().trim_start_matches('@').to_lowercase()).filter(|d| !d.is_empty());let merging = request.get("merging").and_then(Value::as_str).map(|k| k.trim().to_lowercase()).filter(|k| !k.is_empty());let merges = merges(client); read(client, "chat.senders", |ctx| {let blocked = Blocked::read(ctx)?;let states = source_states(ctx)?;let (all, groups, members) = tab(ctx, &blocked, &states, &merges)?;let kept: Vec<Option<rule::Group>> = all.iter().map(|s| groups.get(&s.key.key.to_lowercase()).copied().flatten()).collect();let shown: Vec<&rule::Sender> = all .iter() .filter(|s| match rule::GROUPS.iter().find(|g| g.as_str() == filter) {Some(g) => groups.get(&s.key.key.to_lowercase()).copied().flatten() == Some(*g),None => rule::keeps(&filter, s), }) .filter(|s| domain.as_ref().is_none_or(|d| rule::domain_of(&s.key).as_ref() == Some(d))) .filter(|s| merging.as_ref().is_none_or(|m| s.key.key.to_lowercase() != *m)) .collect();let rows = rule::tab_rows(&lines, &shown, &groups, &members, domain.is_none() && merging.is_none());let mail_states = wide::mail_states(ctx)?;let page: Vec<Value> = rows .iter() .skip(after) .take(PAGE) .map(|built| {letmut row = serde_json::to_value(built).unwrap_or(Value::Null);ifletSome((act, _, _)) = states.get(&built.row.key.to_lowercase()) { row["source"] = source_json(&lines, act, now); } else {// The Mac's sender-wide mail acts: on the sender and those merged into them, or on any address at// the domain.let keys: Vec<String> = if built.level == "domain" { all.iter().filter(|s| rule::domain_of(&s.key).as_deref() == Some(built.row.name.as_str())).map(|s| s.key.key.clone()).collect() } else { std::iter::once(built.row.key.clone()).chain(built.merged.iter().cloned()).collect() };ifletSome(act) = wide::newest_of(&mail_states, keys) { row["source"] = source_json(&lines, act, now); } }// A domain opens to its addresses; a sender to their page (`chat.sender.page`). row["open"] = if built.level == "domain" { json!({ "domain": built.row.name }) } else { json!({ "sender": built.row.key }) }; row }) .collect();let next = (after + PAGE < rows.len()).then(|| (after + PAGE).to_string());let count = blocked.since.len();let picking = merging.as_ref().map(|m| {let name = all.iter().find(|s| s.key.key.to_lowercase() == *m).map(rule::name_of).unwrap_or_else(|| m.clone()); json!({ "key": m, "line": say(&lines, "app.senders.picking", &[("name", &name)]), "cancel": say(&lines, "app.senders.picking_cancel", &[]) }) });Ok(json!({"filter": filter,"domain": domain,"title": domain.clone().unwrap_or_else(|| say(&lines, "app.senders.title", &[])),"line": if domain.is_some() { Value::Null } else { json!(say(&lines, "app.senders.line", &[])) },"filters": if domain.is_some() || merging.is_some() { json!([]) } else { json!(rule::group_filters(&lines, &kept, &filter)) },"picking": picking,"rows": page,"next": next,"empty": if all.is_empty() { say(&lines, "app.senders.empty", &[]) } else { say(&lines, "app.senders.empty_filter", &[]) },"history": crate::phone::chat_app::mail::history(client, &lines),// Blocked is the tab's place, not a domain's page's (look-ios, 24 Nov 2026)."blocked": if domain.is_some() { Value::Null } else { json!({ "label": if count == 0 { say(&lines, "app.senders.blocked.place", &[]) } else { say(&lines, "app.senders.blocked.place_count", &[("n", &count.to_string())]) }, "count": count }) }, })) })}/// The merges he made by hand (`sender_merge`): `(id, member, into)`, in lower case, read in the copy itself (never/// through `records.*`, which borrows the phone's key: seen on emulator-5618, 24 Nov 2026, `chat.senders` waiting on/// the main thread for ever). None where the copy has no such table yet.fn merge_rows(ctx: &mutCtx<'_>) -> Vec<(String, String, String)> {letmut args = Map::new(); args.insert("table".into(), json!(MERGES)); args.insert("page".into(), json!(0)); args.insert("limit".into(), json!(1000));letOk(listed) = cotton_tools::mcp::handlers::tables::list_records(ctx, &args) else { returnVec::new() }; listed["records"] .as_array() .into_iter() .flatten() .filter_map(|r| Some((r["id"].as_str()?.to_string(), r["data"]["key"].as_str()?.to_lowercase(), r["data"]["into"].as_str()?.to_lowercase()))) .collect()}/// The merges as `(member, into)`, read inside a reading (Post's Senders).pub(crate) fn merges_in(ctx: &mutCtx<'_>) -> Vec<(String, String)> { merge_rows(ctx).into_iter().map(|(_, m, i)| (m, i)).collect()}/// The merges as `(member, into)`.pub(crate) fn merges(client: &ClientController) -> Vec<(String, String)> { read(client, "chat.senders.merges", |ctx| Ok(json!(merge_rows(ctx).into_iter().map(|(_, m, i)| [m, i]).collect::<Vec<_>>()))) .ok() .and_then(|v| v.as_array().cloned()) .unwrap_or_default() .into_iter() .filter_map(|p| Some((p[0].as_str()?.to_string(), p[1].as_str()?.to_string()))) .collect()}/// Every sender not blocked, merged by hand and ranked, with each kept key's group and its members.#[allow(clippy::type_complexity)]typeTab = (Vec<rule::Sender>, HashMap<String, Option<rule::Group>>, HashMap<String, Vec<String>>);pub(crate) fn tab(ctx: &mutCtx<'_>, blocked: &Blocked, states: &HashMap<String, (SourceAct, SenderKey, Option<String>)>, merges: &[(String, String)]) -> Result<Tab, String> { tab_in(ctx, blocked, states, merges, None)}/// The tab over only the senders `only` covers (a sender's page: the sender and those merged into them, or a domain).pub(crate) fn tab_in(ctx: &mutCtx<'_>, blocked: &Blocked, states: &HashMap<String, (SourceAct, SenderKey, Option<String>)>, merges: &[(String, String)], only: Option<&[String]>) -> Result<Tab, String> {letmut all: Vec<rule::Sender> = everyone_in(ctx, only)?.into_iter().filter(|s| !blocked.has(&s.key)).collect();// A sender whose WhatsApp chat is still being deleted there (or failed to be) stands on, with nothing left here,// so the state and its Retry have a row.for (k, (act, key, name)) in states {if act.kind == "delete_chat" && act.status != "sent" && !blocked.has(key) && !all.iter().any(|s| s.key.key.to_lowercase() == *k) { all.push(rule::Sender { key: key.clone(), name: name.clone(), channels: vec!["whatsapp".into()], sent: 0, replied: false, last_at: None }); } }// A mail sender with nothing left here whose act the Mac has not done, or refused, stands on with that state and// its Try again (ACTS TRUTH, owner's Comms 31, 24 Nov 2026: Delete everything said done, the Mac refused, and the// sender vanished with the refusal).for (address, act) in wide::mail_states(ctx)? {let covered = only.is_none_or(|keys| keys.iter().any(|k| *k == address || k.strip_prefix('@').is_some_and(|d| address.ends_with(&format!("@{d}")))));let key = stored_key(&address);if !act.done() && covered && !blocked.has(&key) && !all.iter().any(|s| s.key.key.to_lowercase() == address) { all.push(rule::Sender { key, name: act.name.clone(), channels: vec!["mail".into()], sent: 0, replied: false, last_at: None }); } }// Each sender's own group: mail by the rule over their newest mail, a chat by its key.let mail = crate::phone::chat_app::mail::sender_groups_in(ctx, only)?;letmut own: HashMap<String, Option<rule::Group>> = HashMap::new();for c in chat_shares(ctx)? {let k = c.key.key.to_lowercase();let g = rule::chat_group(&c.key, c.title.as_deref()); own.entry(k).and_modify(|held| *held = rule::group_with(*held, &[Some(g)])).or_insert(Some(g)); }for s in &all {let k = s.key.key.to_lowercase();ifletSome(g) = mail.get(&k) { own.insert(k, *g); } }let (all, members) = rule::merged(all, merges);let groups = all .iter() .map(|s| {let k = s.key.key.to_lowercase();let theirs: Vec<Option<rule::Group>> = members.get(&k).into_iter().flatten().map(|m| own.get(m).copied().flatten()).collect(); (k.clone(), rule::group_with(own.get(&k).copied().flatten(), &theirs)) }) .collect();Ok((all, groups, members))}fn delete_merge(ctx: &mutCtx<'_>, id: &str) -> Result<(), String> {let gone = json!({ "table": MERGES, "id": id }); cotton_tools::mcp::handlers::tables::delete_record(ctx, gone.as_object().unwrap_or(&Map::new())).map(|_| ()).map_err(|f| f.to_string())}/// `chat.sender.act { act: merge, key, into }`: `key`'s row joins `into`'s, and so do any joined to `key` before./// `{ act: part, key }` parts every sender joined to `key`, or `key` from the row it joined.fn merge(client: &ClientController, key: &SenderKey, into: Option<&str>, lines: &cotton_core::rules::shell_lines::LineSet) -> Result<Value, MethodError> {let member = key.key.to_lowercase();let into = into.map(|i| i.trim().to_lowercase()).filter(|i| !i.is_empty()).ok_or_else(|| MethodError::new("bad_request", "`into` names the sender to merge with"))?;let held = merges(client);// Into the row `into` itself joined, if it joined one.let root = held.iter().find(|(m, _)| *m == into).map(|(_, i)| i.clone()).unwrap_or(into);if root == member {returnErr(MethodError::new("merge_self", say(lines, "app.senders.refused.merge_self", &[]))); }let names = read(client, "chat.sender.names", |ctx| {let all = everyone_in(ctx, Some(&[member.clone(), root.clone()]))?;let name = |k: &str| all.iter().find(|s| s.key.key.to_lowercase() == k).map(rule::name_of).unwrap_or_else(|| k.to_string());Ok(json!([name(&member), name(&root)])) })?;letmut joining = vec![member.clone()]; joining.extend(held.iter().filter(|(_, i)| *i == member).map(|(m, _)| m.clone()));super::cotton_chat::write(client, "chat.sender.merge", |ctx| {// One row per sender: what any of them joined before goes first (the key is sealed, so the id is random).for (id, k, _) in merge_rows(ctx) {if joining.contains(&k) { delete_merge(ctx, &id)?; } }for m in &joining {let made = json!({ "table": MERGES, "data": { "key": m, "into": root } }); cotton_tools::mcp::handlers::tables::create_record(ctx, made.as_object().unwrap_or(&Map::new())).map_err(|f| f.to_string())?; }Ok(Value::Null) })?;let (a, b) = (names[0].as_str().unwrap_or_default(), names[1].as_str().unwrap_or_default());Ok(json!({ "key": root, "said": say(lines, "app.senders.said.merged", &[("name", a), ("other", b)]) }))}fn part(client: &ClientController, key: &SenderKey, lines: &cotton_core::rules::shell_lines::LineSet) -> Result<Value, MethodError> {let k = key.key.to_lowercase();letmut parted = 0;super::cotton_chat::write(client, "chat.sender.part", |ctx| {for (id, m, i) in merge_rows(ctx) {if m == k || i == k { delete_merge(ctx, &id)?; parted += 1; } }Ok(Value::Null) })?;if parted == 0 {returnErr(MethodError::new("not_merged", say(lines, "app.senders.refused.not_found", &[]))); }let name = read(client, "chat.sender.name", |ctx| Ok(json!(one_sender(ctx, key)?.map(|s| rule::name_of(&s)).unwrap_or_else(|| key.key.clone()))))?;Ok(json!({ "key": key.key, "said": say(lines, "app.senders.said.parted", &[("name", name.as_str().unwrap_or_default())]) }))}/// One sender, blocked or not.fn one_sender(ctx: &mutCtx<'_>, key: &SenderKey) -> Result<Option<rule::Sender>, String> {let wanted = key.key.to_lowercase();Ok(everyone_in(ctx, Some(std::slice::from_ref(&wanted)))?.into_iter().find(|s| s.key.key.to_lowercase() == wanted))}/// `chat.sender.ask`: what an act takes, its count first. `key` is a sender (with those merged into them) or a domain/// (`@domain`), as the Senders tab's rows are.pub(crate) fn ask(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let key = key_of_request(request)?;let act = request.get("act").and_then(Value::as_str).filter(|a| rule::ASKED.contains(a)).ok_or_else(|| MethodError::new("bad_request", "`act` is block, delete, archive or unsubscribe"))?.to_string();let lines = list::lines();if act == "delete" || act == "archive" {// His mailbox's own number (all his mail; his Inbox for Archive everything), asked of the Mac for the next// time if it has none (DELETE FAST, ARCHIVE COUNT). wide::want_counts(client, &key.key, act == "archive")?; }let asked = read(client, "chat.sender.ask", |ctx| {let whole = wide::whole(ctx, &key.key)?;let count = if act == "archive" { wide::archive_count(ctx, &whole)? } else { whole.sent };// Nothing of theirs left to act on (look-ios's walk, 24 Nov 2026: "Archive 0"): said, never asked.if count == 0 && act != "block" {returnOk(json!({ "refused": say(&lines, "app.senders.refused.not_found", &[]) })); }letmut asked = rule::ask(&lines, &act, &key.key, &whole.name, count, whole.sms && cfg!(target_os = "ios"));// Delete everything takes their mail to Trash in his mailbox too, and says how much: the Mac's own count of// his mailbox, carried to the act as `mailbox`, so exactly that set moves; with no count yet, only the mail// here, as many as it says (DELETE FAST: he was shown 13 and the Mac moved 23).letmut mailbox = Value::Null;let addresses = whole.addresses();if act == "archive" && !addresses.is_empty() {// His Inbox's own number for Archive everything (ARCHIVE COUNT): the act carries the set it fixed.let counts = wide::mailbox_counts(ctx, true)?;let words = match counts.over(&addresses) {Some(0) => say(&lines, "app.senders.ask.archive_inbox_none", &[]),Some(1) => say(&lines, "app.senders.ask.archive_inbox_one", &[]),Some(m) => say(&lines, "app.senders.ask.archive_inbox", &[("m", &m.to_string())]),None => match count {1 => say(&lines, "app.senders.ask.archive_inbox_shown_one", &[]), n => say(&lines, "app.senders.ask.archive_inbox_shown", &[("n", &n.to_string())]), }, }; mailbox = counts.over(&addresses).map_or(Value::Null, |m| json!(m)); asked.line = format!("{} {}", asked.line, words); }if act == "delete" && !addresses.is_empty() {let counts = wide::mailbox_counts(ctx, false)?;let words = match counts.over(&addresses) {Some(0) => say(&lines, "app.senders.ask.delete_mail_none", &[]),Some(1) => say(&lines, "app.senders.ask.delete_mail_counted_one", &[]),Some(m) => say(&lines, "app.senders.ask.delete_mail_counted", &[("m", &m.to_string())]),None => match erase::held_mail(ctx, &addresses)?.len() {1 => say(&lines, "app.senders.ask.delete_mail_shown_one", &[]), n => say(&lines, "app.senders.ask.delete_mail_shown", &[("n", &n.to_string())]), }, }; mailbox = counts.over(&addresses).map_or(Value::Null, |m| json!(m)); asked.line = format!("{} {}", asked.line, words); }letmut asked = serde_json::to_value(asked).unwrap_or(Value::Null);if (act == "delete" || act == "archive") && !addresses.is_empty() { asked["mailbox"] = mailbox; }Ok(asked) })?;match asked.get("refused").and_then(Value::as_str) {Some(line) => Err(MethodError::new("not_found", line)),None => Ok(asked), }}/// `chat.sender.act`: block or unblock.pub(crate) fn act(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let key = key_of_request(request)?;let lines = list::lines();let name = read(client, "chat.sender.name", |ctx| Ok(one_sender(ctx, &key)?.map(|s| rule::name_of(&s)).unwrap_or_else(|| key.key.clone())))?;match request.get("act").and_then(Value::as_str) {Some("block") => {// A whole sender: each of their keys (those merged into them, or each address at a domain).let keys = read(client, "chat.sender.whole", |ctx| Ok(json!(wide::whole(ctx, &key.key)?.keys.iter().map(|k| k.key.clone()).collect::<Vec<_>>())))?;let keys: Vec<SenderKey> = keys.as_array().into_iter().flatten().filter_map(Value::as_str).map(stored_key).collect();for k inif keys.is_empty() { vec![key.clone()] } else { keys } { block(client, &k, true)?; }Ok(json!({ "key": key.key, "blocked": true, "said": say(&lines, "app.senders.said.blocked", &[("name", &name)]) })) }Some("unblock") => { block(client, &key, false)?;Ok(json!({ "key": key.key, "blocked": false, "said": say(&lines, "app.senders.said.unblocked", &[("name", &name)]) })) }Some("retry") => {let now = super::cotton_chat::now_ms(client);letmut retried = false;// What the Mac does next, said at the tap (ARCHIVE COUNT): count first, or move the set he confirmed.letmut next: Option<(String, Option<u64>)> = None;super::cotton_chat::write(client, "chat.sender.retry", |ctx| {ifletSome((act, _, _)) = source_states(ctx)?.get(&key.key.to_lowercase()) {ifsuper::whatsapp_send::source_retryable(act, now) {super::whatsapp_send::retry_source(ctx, &act.id)?; retried = true; } }// The Mac's mail acts on any of their addresses.let whole = wide::whole(ctx, &key.key)?;// Every row of their newest act that may go again, not one of them.let batches = wide::newest_batches(ctx)?;for address in whole.addresses() {for act in batches.get(&address).into_iter().flatten().filter(|a| super::whatsapp_send::source_retryable(a, now)) {if next.is_none() && matches!(act.kind.as_str(), "sender_archive" | "sender_trash") { next = Some((act.kind.clone(), act.counted().or(act.count.filter(|_| act.fixed)))); }super::whatsapp_send::retry_source(ctx, &act.id)?; retried = true; } }Ok(Value::Null) })?;if !retried {returnErr(MethodError::new("nothing_to_retry", say(&lines, "app.senders.refused.not_found", &[]))); }let said = match &next {Some((kind, None)) => say(&lines, &format!("app.senders.said.retried_{kind}_count"), &[]),Some((kind, Some(1))) => say(&lines, &format!("app.senders.said.retried_{kind}_one"), &[]),Some((kind, Some(n))) => say(&lines, &format!("app.senders.said.retried_{kind}"), &[("n", &n.to_string())]),None => say(&lines, "app.senders.said.retried", &[]), };Ok(json!({ "key": key.key, "said": said })) }Some("archive") => wide::archive(client, &key.key, request.get("mailbox").and_then(Value::as_u64)),Some("unsubscribe") => wide::unsubscribe(client, &key.key),Some("delete") => erase::delete_everything(client, &key, request.get("count").and_then(Value::as_u64), request.get("mailbox").and_then(Value::as_u64)),Some("merge") => merge(client, &key, request.get("into").and_then(Value::as_str), &lines),Some("part") => part(client, &key, &lines), _ => Err(MethodError::new("bad_request", "`act` is block, unblock, delete, archive, unsubscribe, retry, merge or part")), }}/// Block or unblock one key: a mail address through the mail's own act (its mail files into Junk and back), any/// other key as its own row.fn block(client: &ClientController, key: &SenderKey, on: bool) -> Result<(), MethodError> {let stored = key.key.to_lowercase();super::cotton_chat::write(client, if on { "chat.sender.block" } else { "chat.sender.unblock" }, |ctx| {// On his WhatsApp too, through the Mac (CONTRACT "Blocking a WhatsApp sender…"): one row per chat of theirs,// where the served outbox takes it.if key.kind == KeyKind::Number {for thread in whatsapp_threads_of(ctx, key)? {super::whatsapp_send::queue_block_if(ctx, &thread, on)?; } }if key.kind == KeyKind::Address {letmut args = Map::new(); args.insert("address".into(), json!(stored));let done = if on { cotton_tools::mcp::handlers::emails::senders::block_sender(ctx, &args) } else { cotton_tools::mcp::handlers::emails::senders::unblock_sender(ctx, &args) }; done.map_err(|f| f.to_string())?;returnOk(Value::Null); }let id = cotton_store::protocol::derived_id::blocked_sender_id(ctx.file.namespace(), &stored);if on {let held = rows(ctx, &format!("SELECT id FROM {BLOCKED} WHERE id = ?"), &[SqlValue::Text(id.clone())])?;if held.is_empty() {letmut patch = Map::new(); patch.insert("address".into(), json!(stored)); patch.insert("workspace_id".into(), json!(ctx.workspace_id.to_string())); cotton_tools::mcp::handlers::common::insert_row(ctx, BLOCKED, &id, patch).map_err(|f| f.to_string())?; } } else { ctx.writer().map_err(|f| f.to_string())?.retract(BLOCKED, &id, cotton_tools::mcp::writer::Retract::Relation); }Ok(Value::Null) })?;Ok(())}/// When what `key` sent leaves Blocked for good: 30 days after its newest arrived or the block, whichever is later.fn erased_on(blocked_ms: i64, last_ms: i64) -> String {let at = rule::erased_at(blocked_ms, last_ms); chrono::DateTime::from_timestamp_millis(at).map(|d| d.format("%-d %B %Y").to_string()).unwrap_or_default()}/// `chat.senders.blocked`: the one Blocked place, newest block first./// How many senders the Blocked place holds, for You's Blocked row (COMMS WITHOUT MAIL: Senders left Comms, and/// Blocked, where a blocked sender's texts wait 30 days, is reached from You). None while the copy cannot be read.pub(crate) fn blocked_count(client: &ClientController) -> Option<usize> { read(client, "chat.you.blocked", |ctx| Ok(Blocked::read(ctx)?.keys().count())).ok()}pub(crate) fn blocked_place(client: &ClientController) -> Result<Value, MethodError> {let lines = list::lines();let now = super::cotton_chat::now_ms(client); read(client, "chat.senders.blocked", |ctx| {let blocked = Blocked::read(ctx)?;let senders: HashMap<String, rule::Sender> = everyone(ctx)?.into_iter().map(|s| (s.key.key.to_lowercase(), s)).collect();let states = source_states(ctx)?;letmut held: Vec<(&String, &i64)> = blocked.keys().collect(); held.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));let rows: Vec<Value> = held .into_iter() .map(|(stored, since)| {let key = stored_key(stored);let sender = senders.get(stored);let name = sender.map(rule::name_of).unwrap_or_else(|| key.key.clone());let sent = sender.map_or(0, |s| s.sent);let last = sender.and_then(|s| s.last_at.as_deref()).map_or(0, super::ms); json!({"key": key.key,"kind": key.kind.id(),"name": name,"sent": sent,"sentLine": rule::sent_line(&lines, sent),"erases": (sent > 0).then(|| say(&lines, "app.senders.blocked.erases", &[("date", &erased_on(*since, last))])),"unblock": say(&lines, "app.senders.blocked.unblock", &[]),"source": states.get(stored.as_str()).map(|(act, _, _)| source_json(&lines, act, now)), }) }) .collect();Ok(json!({"title": say(&lines, "app.senders.blocked.title", &[]),"line": say(&lines, "app.senders.blocked.line", &[]),"empty": say(&lines, "app.senders.blocked.empty", &[]),"rows": rows, })) })}#[path = "chat_senders_erase.rs"]pub(crate) mod erase;#[path = "chat_senders_wide.rs"]pub(crate) mod wide;#[cfg(test)]#[path = "chat_senders_tests.rs"]mod tests;