Cotton code
932 lines · 70.0 KB · RustRaw
//! Everyone who writes to him, over a phone's own copy (SENDERS.md). Every name, number and address is invented.use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use crate::handle::CottonHandle;use crate::phone::cotton_chat::over;use crate::phone::passwords::tests::phone;const ME: &str = "mira@invented.example";fn answer(handle: &CottonHandle, method: &str, request: Value) -> Value {    over(&handle.client(), method, &request).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message))}fn sql(handle: &CottonHandle, statement: &str, params: &[SqlValue]) {    handle.client().with_writer(|replica| replica.driver.run(statement, params).map(|_| ()).map_err(|e| e.to_string())).expect(statement);}fn workspace(handle: &CottonHandle) -> String {    let found = crate::phone::cotton_chat::read(&handle.client(), "test.ws", |ctx| Ok(json!(ctx.workspace_id))).unwrap();    found.as_str().unwrap().to_string()}fn t(s: &str) -> SqlValue {    SqlValue::Text(s.to_string())}fn iso(minutes_ago: i64) -> String {    (chrono::Utc::now() - chrono::Duration::minutes(minutes_ago)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true)}/// One one-to-one chat on `channel`: `contact` a number (or none, a short code's thread by its title), `ins` from/// them and `outs` from him, each with its words.fn chat(handle: &CottonHandle, id: &str, channel: &str, contact: Option<(&str, &str)>, title: &str, ins: &[&str], outs: &[&str]) {    let ws = workspace(handle);    let contact_id = contact.map(|(number, name)| {        let cid = format!("c-{id}");        sql(handle, "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, created_at, updated_at) VALUES (?, ?, ?, ?, '2026-01-01', '2026-01-01')", &[t(&cid), t(&ws), t(number), t(name)]);        cid    });    let contact_value = contact_id.as_deref().map_or(SqlValue::Null, t);    sql(handle, "INSERT INTO cotton_msg_threads (id, workspace_id, kind, external_key, contact_id, title, last_message_at, read_seq, created_at, updated_at) VALUES (?, ?, 'dm', ?, ?, ?, ?, 0, ?, ?)", &[t(id), t(&ws), t(&format!("{channel}:{id}")), contact_value, t(title), t(&iso(1)), t(&iso(1)), t(&iso(1))]);    let mut seq = 0;    for (out, words) in ins.iter().map(|w| (false, *w)).chain(outs.iter().map(|w| (true, *w))) {        seq += 1;        let at = iso(100 - seq);        sql(            handle,            "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, seq, created_at, external_id) VALUES (?, ?, ?, ?, ?, 'imported', ?, ?, ?, ?, ?)",            &[t(&format!("{id}-{seq}")), t(id), t(&ws), t(if out { "out" } else { "in" }), t(channel), t(words), t(&at), SqlValue::Integer(seq), t(&at), t(&format!("x-{id}-{seq}"))],        );    }}fn email(handle: &CottonHandle, id: &str, thread: &str, from: (&str, &str), to: &str, subject: &str, minutes_ago: i64) {    let ws = workspace(handle);    let at = iso(minutes_ago);    sql(handle, "INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, first_at, last_at, email_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?) ON CONFLICT (id) DO UPDATE SET email_count = email_count + 1", &[t(thread), t(&ws), t(&format!("key-{thread}")), t(subject), t(&at), t(&at), t(&at), t(&at)]);    sql(        handle,        "INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, subject, from_email, from_name, recipients, sent_at, body, snippet, unread, account, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?)",        &[t(id), t(&ws), t(thread), t(&format!("x-{id}")), t(subject), t(from.0), t(from.1), t(&json!([{ "email": to, "kind": "to" }]).to_string()), t(&at), t(subject), t(subject), t(ME), t(&at)],    );}/// Ravi on WhatsApp (he answered him), a bank's two SMS headers, a shop's mail he never answered, Asha's mail he did.fn senders(handle: &CottonHandle) {    chat(handle, "t-ravi", "whatsapp", Some(("15550100002", "Ravi K")), "Ravi K", &["Are you coming?", "Call me", "Lake at six"], &["Yes"]);    chat(handle, "t-bank1", "sms", None, "VM-HDFCBK-S", &["Your OTP is 0000", "Spend alert 1", "Spend alert 2", "Spend alert 3", "Statement ready"], &[]);    chat(handle, "t-bank2", "sms", None, "AD-HDFCBK", &["Offer for you", "Loan offer"], &[]);    for (i, ago) in [(1, 50), (2, 40), (3, 30)] {        email(handle, &format!("e-shop-{i}"), &format!("et-shop-{i}"), ("deals@shop.invented", "Invented Shop"), ME, &format!("Sale {i}"), ago);    }    email(handle, "e-asha", "et-asha", ("asha@invented.example", "Asha Example"), ME, "The lake trip", 20);    email(handle, "e-mira", "et-asha", (ME, "Mira Invented"), "asha@invented.example", "Re: The lake trip", 10);}fn keys(page: &Value) -> Vec<String> {    page["rows"].as_array().unwrap().iter().map(|r| r["key"].as_str().unwrap().to_string()).collect()}/// GOLDEN (owner, 24 Nov 2026): one ranked list across WhatsApp, SMS and mail, a sender by number, address or/// short-code name; how much each sent and whether he replied; never replied and most sent first; chips by channel.#[test]fn everyone_who_writes_to_him_in_one_ranked_list() {    let (_dir, handle) = phone();    senders(&handle);    let page = answer(&handle, "chat.senders", json!({}));    assert_eq!(keys(&page), ["HDFCBK", "deals@shop.invented", "+15550100002", "asha@invented.example"], "{page}");    let bank = &page["rows"][0];    assert_eq!((bank["sent"].as_u64(), bank["sentLine"].as_str(), bank["repliedLine"].as_str(), bank["channelsLine"].as_str()), (Some(7), Some("7 messages"), Some("Never replied"), Some("SMS")));    let ravi = &page["rows"][2];    assert_eq!((ravi["name"].as_str(), ravi["handle"].as_str(), ravi["sent"].as_u64(), ravi["repliedLine"].as_str()), (Some("Ravi K"), Some("+15550100002"), Some(3), Some("You replied")));    assert_eq!(page["rows"][3]["repliedLine"], "You replied", "he wrote to Asha");    let chips: Vec<(&str, Option<u64>)> = page["filters"].as_array().unwrap().iter().map(|c| (c["id"].as_str().unwrap(), c["count"].as_u64())).collect();    // Senders 3: the chips are the three groups, by rule (a number is a person, a bank's short code a notice, the    // shop's sale mail a promotion, Asha a person he writes to).    assert_eq!(chips, [("all", Some(4)), ("people", Some(2)), ("notices", Some(1)), ("promotions", Some(1))]);    assert_eq!(keys(&answer(&handle, "chat.senders", json!({ "filter": "people" }))), ["+15550100002", "asha@invented.example"]);    assert_eq!(page["rows"][0]["group"], "notices");    assert_eq!(page["title"], "Senders");    assert_eq!(keys(&answer(&handle, "chat.senders", json!({ "filter": "mail" }))), ["deals@shop.invented", "asha@invented.example"]);    assert_eq!(page["blocked"]["label"], "Blocked");    // The chat list's People chip gave way to the Senders tab.    let list = answer(&handle, "chat.list", json!({}));    assert_eq!(list["filters"].as_array().unwrap().iter().map(|c| c["id"].as_str().unwrap()).collect::<Vec<_>>(), ["all", "unread", "groups"], "People is the Senders tab now");}/// RULE: Block asks with its count first; a blocked sender then shows nowhere in Comms (the chat list, its search,/// the senders list, Mail) but the one Blocked place, which says when what they sent is erased; Unblock brings them/// back.#[test]fn a_blocked_sender_shows_only_in_blocked_until_unblocked() {    let (_dir, handle) = phone();    senders(&handle);    let ask = answer(&handle, "chat.sender.ask", json!({ "key": "HDFCBK", "act": "block" }));    assert_eq!((ask["title"].as_str(), ask["count"].as_u64()), (Some("Block HDFCBK?"), Some(7)));    assert!(ask["line"].as_str().unwrap().starts_with("7 messages from HDFCBK will go to Blocked"), "{ask}");    let delete = answer(&handle, "chat.sender.ask", json!({ "key": "deals@shop.invented", "act": "delete" }));    assert_eq!((delete["confirm"].as_str(), delete["count"].as_u64()), (Some("Delete 3"), Some(3)));    let said = answer(&handle, "chat.sender.act", json!({ "key": "HDFCBK", "act": "block" }));    assert_eq!(said["said"], "Blocked. HDFCBK shows only in Blocked now.");    answer(&handle, "chat.sender.act", json!({ "key": "deals@shop.invented", "act": "block" }));    assert_eq!(keys(&answer(&handle, "chat.senders", json!({}))), ["+15550100002", "asha@invented.example"]);    let list = answer(&handle, "chat.list", json!({}));    let ids: Vec<&str> = list["rows"].as_array().unwrap().iter().filter_map(|r| r["thread"].as_str()).collect();    assert!(!ids.contains(&"t-bank1") && !ids.contains(&"t-bank2") && ids.contains(&"t-ravi"), "{ids:?}");    let found = answer(&handle, "chat.list", json!({ "search": "offer" }));    assert!(found["rows"].as_array().unwrap().is_empty(), "the bank's words are found nowhere: {found}");    let mail = answer(&handle, "chat.mail", json!({}));    assert!(!mail.to_string().contains("Sale 1"), "the shop's mail is in no list: {mail}");    let blocked = answer(&handle, "chat.senders.blocked", json!({}));    let rows = blocked["rows"].as_array().unwrap();    assert_eq!(rows.len(), 2, "{blocked}");    let bank = rows.iter().find(|r| r["key"] == "HDFCBK").unwrap();    assert_eq!(bank["sentLine"], "7 messages");    assert!(bank["erases"].as_str().unwrap().starts_with("Erased on "), "{bank}");    assert_eq!(answer(&handle, "chat.senders", json!({}))["blocked"]["label"], "Blocked · 2");    answer(&handle, "chat.sender.act", json!({ "key": "HDFCBK", "act": "unblock" }));    answer(&handle, "chat.sender.act", json!({ "key": "deals@shop.invented", "act": "unblock" }));    assert_eq!(keys(&answer(&handle, "chat.senders", json!({}))).len(), 4);    assert!(answer(&handle, "chat.senders.blocked", json!({}))["rows"].as_array().unwrap().is_empty());}fn count(handle: &CottonHandle, sql_text: &str) -> i64 {    let found = crate::phone::cotton_chat::read(&handle.client(), "test.count", |ctx| Ok(crate::phone::cotton_chat::rows(ctx, sql_text, &[])?.first().and_then(|r| r.get("n")).cloned().unwrap_or(json!(0)))).unwrap();    found.as_i64().unwrap_or(0)}/// ERASES. Delete everything runs only with the count its ask showed, then erases what they sent, from the chats and/// from mail; what he wrote stays; a chat left empty leaves the list.#[test]fn delete_everything_erases_what_they_sent_with_the_count_first() {    let (_dir, handle) = phone();    senders(&handle);    let refused = over(&handle.client(), "chat.sender.act", &json!({ "key": "HDFCBK", "act": "delete", "count": 6 })).unwrap_err();    assert_eq!(refused.code, "count_changed");    assert_eq!(count(&handle, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id IN ('t-bank1', 't-bank2')"), 7, "nothing was taken");    assert!(over(&handle.client(), "chat.sender.act", &json!({ "key": "HDFCBK", "act": "delete" })).is_err(), "never without the count");    let done = answer(&handle, "chat.sender.act", json!({ "key": "HDFCBK", "act": "delete", "count": 7 }));    assert_eq!(done["said"], "Deleted 7 from HDFCBK.");    assert_eq!(count(&handle, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id IN ('t-bank1', 't-bank2') AND json_extract(meta, '$.cotton.erased') IS NULL"), 0);    // Each erased text leaves a wordless marker, so reading the phone's store again never brings it back.    assert_eq!(count(&handle, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id IN ('t-bank1', 't-bank2') AND body = '' AND json_extract(meta, '$.cotton.erased') IS NOT NULL"), 7);    let list = answer(&handle, "chat.list", json!({}));    let ids: Vec<&str> = list["rows"].as_array().unwrap().iter().filter_map(|r| r["thread"].as_str()).collect();    assert!(!ids.contains(&"t-bank1") && ids.contains(&"t-ravi"), "{ids:?}");    answer(&handle, "chat.sender.act", json!({ "key": "deals@shop.invented", "act": "delete", "count": 3 }));    assert_eq!(count(&handle, "SELECT COUNT(*) AS n FROM cotton_emails WHERE from_email = 'deals@shop.invented'"), 0);    assert_eq!(count(&handle, "SELECT COUNT(*) AS n FROM cotton_email_threads WHERE id LIKE 'et-shop-%'"), 0, "an emptied conversation goes with its mail");    // Ravi's chat: Delete everything takes his three, never the one Mira wrote.    answer(&handle, "chat.sender.act", json!({ "key": "+15550100002", "act": "delete", "count": 3 }));    assert_eq!(count(&handle, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = 't-ravi' AND direction = 'out'"), 1);    assert_eq!(count(&handle, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = 't-ravi' AND direction = 'in' AND json_extract(meta, '$.cotton.erased') IS NULL"), 0);    assert_eq!(keys(&answer(&handle, "chat.senders", json!({}))), ["asha@invented.example"]);}/// ERASES. A sender whose clock runs ahead of ours: Delete everything still takes their chat off the list (walked on/// emulator-5618, 24 Nov 2026: an emptied chat stood blank with its future time).#[test]fn delete_everything_takes_the_chat_off_the_list_when_their_clock_runs_ahead() {    let (_dir, handle) = phone();    chat(&handle, "t-ahead", "sms", Some(("15550100009", "")), "", &["Your parcel is out for delivery"], &[]);    let ahead = iso(-90);    sql(&handle, "UPDATE cotton_msg_messages SET sent_at = ? WHERE thread_id = 't-ahead'", &[t(&ahead)]);    sql(&handle, "UPDATE cotton_msg_threads SET last_message_at = ? WHERE id = 't-ahead'", &[t(&ahead)]);    answer(&handle, "chat.sender.act", json!({ "key": "+15550100009", "act": "delete", "count": 1 }));    let list = answer(&handle, "chat.list", json!({}));    let ids: Vec<&str> = list["rows"].as_array().unwrap().iter().filter_map(|r| r["thread"].as_str()).collect();    assert!(!ids.contains(&"t-ahead"), "{ids:?}");}/// ERASES. What sits in Blocked is erased 30 days after it came there: what was there at the block, 30 days after the/// block; what came later, 30 days after it came.#[test]fn what_sits_in_blocked_is_erased_after_thirty_days() {    let (_dir, handle) = phone();    senders(&handle);    answer(&handle, "chat.sender.act", json!({ "key": "HDFCBK", "act": "block" }));    let old = (chrono::Utc::now() - chrono::Duration::days(40)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true);    let older = (chrono::Utc::now() - chrono::Duration::days(45)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true);    sql(&handle, "UPDATE cotton_blocked_senders SET created_at = ?", &[t(&old)]);    sql(&handle, "UPDATE cotton_msg_messages SET sent_at = ? WHERE thread_id = 't-bank1'", &[t(&older)]);    let sweep = |h: &CottonHandle| crate::phone::chat_app::senders::erase::sweep_blocked(&h.client()).unwrap();    sweep(&handle);    assert!(count(&handle, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = 't-bank1' AND json_extract(meta, '$.cotton.erased') IS NULL") > 0, "the clock alone erases nothing: one day counted here");    // Thirty days counted on this phone since it first saw the block.    sql(&handle, "UPDATE _blocked_seen SET day = day - 31", &[]);    sweep(&handle);    assert_eq!(count(&handle, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = 't-bank1' AND json_extract(meta, '$.cotton.erased') IS NULL"), 0, "blocked 40 days ago and 31 days counted: erased");    assert_eq!(count(&handle, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = 't-bank2'"), 2, "came minutes ago: 30 days from now");    let blocked = answer(&handle, "chat.senders.blocked", json!({}));    assert_eq!(blocked["rows"][0]["sentLine"], "2 messages", "{blocked}");}/// A copy that has not pulled everything may hold a block he lifted on another phone: it erases nothing from Blocked/// until it knows; the same copy standing on its own again sweeps as before.#[test]fn blocked_erases_nothing_while_the_copy_may_lack_an_unblock() {    let (_dir, handle) = phone();    senders(&handle);    answer(&handle, "chat.sender.act", json!({ "key": "HDFCBK", "act": "block" }));    let old = (chrono::Utc::now() - chrono::Duration::days(40)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true);    let older = (chrono::Utc::now() - chrono::Duration::days(45)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true);    sql(&handle, "UPDATE cotton_blocked_senders SET created_at = ?", &[t(&old)]);    sql(&handle, "UPDATE cotton_msg_messages SET sent_at = ? WHERE thread_id = 't-bank1'", &[t(&older)]);    let path = handle.client().layout().connection_json();    let local = std::fs::read_to_string(&path).unwrap();    assert!(local.contains("\"local\""), "{local}");    // As an account's copy whose pass has not ended caught up.    std::fs::write(&path, local.replace("\"local\"", "\"remote\"")).unwrap();    assert_eq!(crate::phone::chat_app::senders::erase::sweep_blocked(&handle.client()).unwrap(), 0);    let held = "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = 't-bank1' AND json_extract(meta, '$.cotton.erased') IS NULL";    assert!(count(&handle, held) > 0, "kept while an unblock may be missing");    std::fs::write(&path, &local).unwrap();    assert_eq!(crate::phone::chat_app::senders::erase::sweep_blocked(&handle.client()).unwrap(), 0, "first seen today: no days counted yet");    sql(&handle, "UPDATE _blocked_seen SET day = day - 31", &[]);    assert!(crate::phone::chat_app::senders::erase::sweep_blocked(&handle.client()).unwrap() > 0);    assert_eq!(count(&handle, held), 0, "known: erased");}/// RULE (SENDERS.md "DECIDED: Senders 3", Grouping): a domain with two or more senders is one row, opening to its/// addresses; a webmail address stands alone; two senders can be merged by hand into one row and parted again; a/// merge is picked from the list with that sender left out.#[test]fn senders_group_by_domain_then_address_and_merge_by_hand() {    // Comms' own copy: its tool draws the merges' table.    let _dir = tempfile::tempdir().unwrap();    let handle = crate::phone::chat_app::mail::tests::comms(&_dir, cotton_core::flavor::Flavor::Real);    senders(&handle);    email(&handle, "e-orders", "et-orders", ("orders@shop.invented", "Invented Shop"), ME, "Your order has shipped", 25);    email(&handle, "e-gm1", "et-gm1", ("tom.invented@outlook.invented", "Tom"), ME, "Hello", 26);    email(&handle, "e-gm2", "et-gm2", ("lee.invented@outlook.invented", "Lee"), ME, "Hi there", 27);    let page = answer(&handle, "chat.senders", json!({}));    let shop = page["rows"].as_array().unwrap().iter().find(|r| r["key"] == "@shop.invented").unwrap_or_else(|| panic!("{page}"));    assert_eq!((shop["level"].as_str(), shop["name"].as_str(), shop["handle"].as_str(), shop["sent"].as_u64()), (Some("domain"), Some("shop.invented"), Some("2 addresses"), Some(4)));    assert_eq!(shop["open"], json!({ "domain": "shop.invented" }));    assert!(shop["group"].is_null(), "a sale and an order: no one group for the domain");    assert!(!keys(&page).contains(&"deals@shop.invented".to_string()), "its addresses are inside it");    assert!(keys(&page).contains(&"tom.invented@outlook.invented".to_string()) && keys(&page).contains(&"lee.invented@outlook.invented".to_string()), "webmail stands alone");    let inside = answer(&handle, "chat.senders", json!({ "domain": "shop.invented" }));    assert_eq!((inside["title"].as_str(), keys(&inside)), (Some("shop.invented"), vec!["deals@shop.invented".to_string(), "orders@shop.invented".to_string()]));    assert_eq!(inside["rows"][0]["open"], json!({ "sender": "deals@shop.invented" }));    assert_eq!(inside["filters"], json!([]));    // Merge: the bank's SMS name and its mail are one sender.    email(&handle, "e-bank", "et-bank", ("alerts@hdxb.invented", "HDXB Invented"), ME, "Your statement", 15);    let held = answer(&handle, "chat.senders", json!({}));    let mail = held["rows"].as_array().unwrap().iter().find(|r| r["key"] == "alerts@hdxb.invented").unwrap();    assert!(mail["hold"].as_array().unwrap().iter().any(|a| a["id"] == "merge" && a["label"] == "Merge with another sender"), "{mail}");    let picking = answer(&handle, "chat.senders", json!({ "merging": "alerts@hdxb.invented" }));    assert_eq!(picking["picking"]["line"], "Tap who HDXB Invented is the same sender as.");    assert!(!keys(&picking).contains(&"alerts@hdxb.invented".to_string()) && keys(&picking).contains(&"deals@shop.invented".to_string()), "every sender on its own, that one left out");    let said = answer(&handle, "chat.sender.act", json!({ "key": "alerts@hdxb.invented", "act": "merge", "into": "HDFCBK" }));    assert_eq!(said["said"], "HDXB Invented and HDFCBK are one sender now.");    let merged = answer(&handle, "chat.senders", json!({}));    assert!(!keys(&merged).contains(&"alerts@hdxb.invented".to_string()));    let bank = merged["rows"].as_array().unwrap().iter().find(|r| r["key"] == "HDFCBK").unwrap();    assert_eq!((bank["sent"].as_u64(), bank["channelsLine"].as_str(), bank["handle"].as_str()), (Some(8), Some("SMS · Mail"), Some("With alerts@hdxb.invented")));    assert_eq!(bank["merged"], json!(["alerts@hdxb.invented"]));    assert!(bank["hold"].as_array().unwrap().iter().any(|a| a["id"] == "part" && a["label"] == "Undo merge"));    assert_eq!(over(&handle.client(), "chat.sender.act", &json!({ "key": "HDFCBK", "act": "merge", "into": "alerts@hdxb.invented" })).unwrap_err().code, "merge_self");    assert_eq!(answer(&handle, "chat.sender.act", json!({ "key": "HDFCBK", "act": "part" }))["said"], "HDFCBK stands alone again.");    assert!(keys(&answer(&handle, "chat.senders", json!({}))).contains(&"alerts@hdxb.invented".to_string()));}/// RULE (SENDERS.md "A sender's page"): a sender's page lists their mail newest first with select, opens their/// SMS or WhatsApp chat as the chat itself, and holds the whole sender's acts; a domain's page holds all its mail; a/// mail opened names its sender for the page; chosen mails take an act together.#[test]fn a_senders_page_lists_their_mail_with_select_and_opens_their_chats() {    let (_dir, handle) = phone();    senders(&handle);    email(&handle, "e-orders", "et-orders", ("orders@shop.invented", "Invented Shop"), ME, "Your order has shipped", 25);    let page = answer(&handle, "chat.sender.page", json!({ "key": "deals@shop.invented" }));    let subjects: Vec<&str> = page["mail"]["rows"].as_array().unwrap().iter().map(|r| r["subject"].as_str().unwrap()).collect();    assert_eq!(subjects, ["Sale 3", "Sale 2", "Sale 1"], "{page}");    assert_eq!((page["name"].as_str(), page["handle"].as_str(), page["line"].as_str(), page["group"].as_str()), (Some("Invented Shop"), Some("deals@shop.invented"), Some("3 messages · Never replied · Mail"), Some("promotions")));    let acts: Vec<&str> = page["acts"].as_array().unwrap().iter().map(|a| a["id"].as_str().unwrap()).collect();    assert_eq!(acts, ["block", "delete", "archive", "unsubscribe", "merge"]);    assert_eq!(page["mail"]["select"]["acts"].as_array().unwrap().iter().map(|a| a["id"].as_str().unwrap()).collect::<Vec<_>>(), ["read", "unread", "archive"]);    assert_eq!(page["chats"], json!([]));    let domain = answer(&handle, "chat.sender.page", json!({ "key": "@shop.invented" }));    assert_eq!((domain["name"].as_str(), domain["handle"].as_str(), domain["mail"]["rows"].as_array().unwrap().len()), (Some("shop.invented"), Some("2 addresses"), 4));    let bank = answer(&handle, "chat.sender.page", json!({ "key": "HDFCBK" }));    let threads: Vec<&str> = bank["chats"].as_array().unwrap().iter().map(|c| c["thread"].as_str().unwrap()).collect();    assert_eq!((threads.len(), bank["chats"][0]["label"].as_str()), (2, Some("Open the SMS chat")), "{bank}");    assert!(threads.contains(&"t-bank1") && threads.contains(&"t-bank2"));    // Select: two chosen mails read at once.    let said = answer(&handle, "chat.mail.act", json!({ "emails": ["e-shop-3", "e-shop-2"], "act": "read" }));    assert_eq!(said["said"], "Marked read.");    let after = answer(&handle, "chat.sender.page", json!({ "key": "deals@shop.invented" }));    let unread: Vec<bool> = after["mail"]["rows"].as_array().unwrap().iter().map(|r| r["unread"].as_bool().unwrap()).collect();    assert_eq!(unread, [false, false, true]);    // A mail opened names its sender, and Open sender is in its long-press.    let open = answer(&handle, "chat.mail.thread", json!({ "thread": "et-shop-1" }));    assert_eq!(open["messages"][0]["from"]["sender"], "deals@shop.invented");    let hold = answer(&handle, "chat.mail.hold", json!({ "email": "e-shop-1" }));    let sender = hold["acts"].as_array().unwrap().last().unwrap();    assert_eq!((sender["id"].as_str(), sender["label"].as_str(), sender["open"].clone()), (Some("sender"), Some("Open sender"), json!({ "sender": "deals@shop.invented" })));}/// The columns MAIL ALL ON PHONE brings to the phone's store, where this copy lacks them.fn mail_columns(handle: &CottonHandle) {    let have = crate::phone::cotton_chat::read(&handle.client(), "test.columns", |ctx| Ok(json!(crate::phone::cotton_chat::rows(ctx, "SELECT name FROM pragma_table_info('cotton_emails')", &[])?))).unwrap();    let have: Vec<&str> = have.as_array().unwrap().iter().filter_map(|r| r["name"].as_str()).collect();    for column in ["list_unsubscribe", "archived_at"] {        if !have.contains(&column) {            sql(handle, &format!("ALTER TABLE cotton_emails ADD COLUMN {column} TEXT"), &[]);        }    }}fn outbox(handle: &CottonHandle, kind: &str) -> Vec<(String, String)> {    let found = crate::phone::cotton_chat::read(&handle.client(), "test.outbox", |ctx| {        Ok(json!(crate::phone::cotton_chat::rows(ctx, "SELECT \"to\", coalesce(target, '') AS target FROM cotton_outbox WHERE workspace_id = ? AND channel = 'mail' AND kind = ? ORDER BY \"to\"", &[SqlValue::Text(ctx.workspace_id.to_string()), t(kind)])?))    })    .unwrap();    found.as_array().unwrap().iter().map(|r| (r["to"].as_str().unwrap().to_string(), r["target"].as_str().unwrap().to_string())).collect()}fn hold_ids(row: &Value) -> Vec<String> {    row["hold"].as_array().unwrap().iter().map(|a| a["id"].as_str().unwrap().to_string()).collect()}/// RULE (SENDERS.md "Acts", Senders 3 step 5): a whole sender, or a whole domain, is archived, unsubscribed or/// blocked after an ask with its count. Archive takes their mail out of every list here and asks the Mac to take it out/// of the Inbox; Unsubscribe asks the Mac once per address, on the mail that offers it; Block blocks each address; the/// Mac's half shows on the row. A sender who sent no mail has no mail acts.#[test]fn a_whole_sender_or_domain_is_archived_unsubscribed_and_blocked_after_its_count() {    let _dir = tempfile::tempdir().unwrap();    let handle = crate::phone::chat_app::mail::tests::comms(&_dir, cotton_core::flavor::Flavor::Real);    senders(&handle);    mail_columns(&handle);    email(&handle, "e-orders", "et-orders", ("orders@shop.invented", "Invented Shop"), ME, "Your order has shipped", 25);    let page = answer(&handle, "chat.senders", json!({}));    let row = |key: &str| page["rows"].as_array().unwrap().iter().find(|r| r["key"] == key).cloned().unwrap_or_else(|| panic!("{key}: {page}"));    assert_eq!(hold_ids(&row("@shop.invented")), ["block", "delete", "archive", "unsubscribe"]);    assert_eq!(hold_ids(&row("asha@invented.example")), ["block", "delete", "archive", "unsubscribe", "merge"]);    assert_eq!(hold_ids(&row("HDFCBK")), ["block", "delete", "merge"]);    assert_eq!(row("@shop.invented")["hold"][2]["label"], "Archive everything");    // Archive: asked with the mail it takes, then out of every list here, and one row per address for the Mac.    let ask = answer(&handle, "chat.sender.ask", json!({ "key": "@shop.invented", "act": "archive" }));    assert_eq!((ask["title"].as_str(), ask["confirm"].as_str(), ask["count"].as_u64()), (Some("Archive everything from shop.invented?"), Some("Archive 4"), Some(4)));    assert_eq!(ask["line"], "4 messages from shop.invented will leave Comms. Your Mac hasn't counted your Inbox yet, so only the 4 emails here leave your Inbox there. They stay in your mail, in All Mail.");    let said = answer(&handle, "chat.sender.act", json!({ "key": "@shop.invented", "act": "archive", "count": 4 }));    // The page says where they are: archived, not gone (look-ios).    let page = answer(&handle, "chat.sender.page", json!({ "key": "@shop.invented" }));    assert_eq!((page["mail"]["rows"].as_array().map(Vec::len), page["empty"].as_str()), (Some(0), Some("All 4 are archived in Comms.")), "{page}");    assert_eq!(said["said"], "Archived 4 from shop.invented in Comms. Your Mac archives their mail next.");    assert_eq!(count(&handle, "SELECT count(*) AS n FROM cotton_emails WHERE from_email LIKE '%@shop.invented' AND archived_at IS NOT NULL"), 4);    // His Inbox not counted yet: one `archive` a mail here (ARCHIVE COUNT).    assert!(outbox(&handle, "sender_archive").is_empty());    assert_eq!(outbox(&handle, "archive").len(), 4);    let inside = answer(&handle, "chat.senders", json!({ "domain": "shop.invented" }));    assert_eq!(inside["rows"][0]["source"]["line"], "Waiting for your Mac to archive their mail", "{inside}");    // Nothing left to archive: said, never asked "Archive 0" (look-ios, 24 Nov 2026).    assert_eq!(over(&handle.client(), "chat.sender.ask", &json!({ "key": "@shop.invented", "act": "archive" })).unwrap_err().code, "not_found");    // Unsubscribe: once per address, on the mail that offers it, else their newest. (Set here: this copy's store has    // no such column of its own, and the archive's write above keeps only the store's columns.)    sql(&handle, "UPDATE cotton_emails SET list_unsubscribe = '<https://shop.invented/u>' WHERE id = 'e-shop-2'", &[]);    let ask = answer(&handle, "chat.sender.ask", json!({ "key": "@shop.invented", "act": "unsubscribe" }));    assert_eq!((ask["title"].as_str(), ask["confirm"].as_str()), (Some("Unsubscribe from shop.invented?"), Some("Unsubscribe")));    assert_eq!(answer(&handle, "chat.sender.act", json!({ "key": "@shop.invented", "act": "unsubscribe" }))["said"], "Unsubscribing from shop.invented…");    assert_eq!(outbox(&handle, "unsubscribe"), [("deals@shop.invented".to_string(), "x-e-shop-2".to_string()), ("orders@shop.invented".to_string(), "x-e-orders".to_string())]);    let inside = answer(&handle, "chat.senders", json!({ "domain": "shop.invented" }));    assert_eq!(inside["rows"][0]["source"]["line"], "Waiting for your Mac to unsubscribe");    // A sender who sent no mail has none of it.    assert_eq!(over(&handle.client(), "chat.sender.act", &json!({ "key": "HDFCBK", "act": "archive" })).unwrap_err().message, "HDFCBK sent you no mail.");    // Block: every address at the domain, after its count.    let ask = answer(&handle, "chat.sender.ask", json!({ "key": "@shop.invented", "act": "block" }));    assert_eq!((ask["title"].as_str(), ask["count"].as_u64()), (Some("Block shop.invented?"), Some(4)));    answer(&handle, "chat.sender.act", json!({ "key": "@shop.invented", "act": "block" }));    let blocked = answer(&handle, "chat.senders.blocked", json!({}));    let names: Vec<&str> = blocked["rows"].as_array().unwrap().iter().filter_map(|r| r["key"].as_str()).collect();    assert!(names.contains(&"deals@shop.invented") && names.contains(&"orders@shop.invented"), "{blocked}");    assert!(!keys(&answer(&handle, "chat.senders", json!({}))).contains(&"@shop.invented".to_string()));}/// ERASES. RULE (SENDERS.md "Acts"): Delete everything at a domain erases what every address there sent, after its/// count, and asks the Mac to move each address's mail to Trash; the row then shows the Mac's half.#[test]fn a_whole_domain_is_deleted_after_its_count_and_its_mail_goes_to_trash() {    let _dir = tempfile::tempdir().unwrap();    let handle = crate::phone::chat_app::mail::tests::comms(&_dir, cotton_core::flavor::Flavor::Real);    senders(&handle);    email(&handle, "e-orders", "et-orders", ("orders@shop.invented", "Invented Shop"), ME, "Your order has shipped", 25);    let ask = answer(&handle, "chat.sender.ask", json!({ "key": "@shop.invented", "act": "delete" }));    assert_eq!((ask["title"].as_str(), ask["confirm"].as_str()), (Some("Delete everything from shop.invented?"), Some("Delete 4")));    // His mailbox not counted yet: only the four here go to Trash there, each by its own id (DELETE FAST).    assert_eq!(ask["line"], "4 messages from shop.invented will be erased from Cotton on all your devices. This can't be undone. Your Mac hasn't counted your mail from them yet, so only the 4 emails here go to Trash there.");    assert!(ask["mailbox"].is_null(), "{ask}");    assert_eq!(over(&handle.client(), "chat.sender.act", &json!({ "key": "@shop.invented", "act": "delete", "count": 3 })).unwrap_err().code, "count_changed");    assert_eq!(answer(&handle, "chat.sender.act", json!({ "key": "@shop.invented", "act": "delete", "count": 4 }))["said"], "Deleted 4 from shop.invented in Comms. Your Mac moves their mail to Trash next.");    assert_eq!(count(&handle, "SELECT count(*) AS n FROM cotton_emails WHERE from_email LIKE '%@shop.invented'"), 0);    assert!(outbox(&handle, "sender_trash").is_empty());    let mut trashed: Vec<String> = outbox(&handle, "trash").into_iter().map(|(_, target)| target).collect();    trashed.sort();    assert_eq!(trashed, ["x-e-orders", "x-e-shop-1", "x-e-shop-2", "x-e-shop-3"]);    assert_eq!(outbox(&handle, "sender_count").len(), 2, "the ask asked the Mac to count each address");    // An SMS sender's ask says nothing of mail.    let bank = answer(&handle, "chat.sender.ask", json!({ "key": "HDFCBK", "act": "delete" }));    assert!(!bank["line"].as_str().unwrap().contains("mail"), "{bank}");}/// RULE: A sender's page grows by the (sent_at, id) cursor of the last mail it drew, never a page by number: every mail of/// the sender comes once, newest first, across pages, and the last page has no `next`.#[test]fn a_sender_s_page_walks_all_their_mail_by_its_cursor() {    let _dir = tempfile::tempdir().unwrap();    let handle = crate::phone::chat_app::mail::tests::comms(&_dir, cotton_core::flavor::Flavor::Real);    // Two mails a minute apart, and two sharing one minute, so the id breaks the tie.    for i in 0..130_i64 {        email(&handle, &format!("e-news-{i:03}"), &format!("et-news-{i:03}"), ("news@paper.invented", "The Invented Paper"), ME, "This week", i / 2);    }    let (mut seen, mut after, mut pages) = (Vec::new(), Value::Null, 0);    loop {        let page = answer(&handle, "chat.sender.page", json!({ "key": "news@paper.invented", "after": after }));        pages += 1;        seen.extend(page["mail"]["rows"].as_array().unwrap().iter().map(|row| row["email"].as_str().unwrap().to_string()));        after = page["mail"]["next"].clone();        if after.is_null() || pages > 5 {            break;        }    }    assert_eq!(pages, 3, "60, 60 and 10");    let mut expected: Vec<String> = (0..130).map(|i| format!("e-news-{i:03}")).collect();    // Newest first: minutes ago ascending, and within a minute the larger id first.    expected.sort_by(|a, b| {        let (na, nb): (i64, i64) = (a[7..].parse().unwrap(), b[7..].parse().unwrap());        (na / 2).cmp(&(nb / 2)).then(b.cmp(a))    });    assert_eq!(seen, expected);}/// SENDERS 3 WALKED (24 Nov 2026): the Senders tab, a sender's page, Delete all's count and a merge, timed over an/// invented account as large as the owner's (100,000 mails from 2,000 senders at 400 domains). Run by hand:/// `cargo test -p cotton-ffi --lib -- senders_at_scale --ignored --nocapture`.#[test]#[ignore]fn senders_at_scale() {    let _dir = tempfile::tempdir().unwrap();    let handle = crate::phone::chat_app::mail::tests::comms(&_dir, cotton_core::flavor::Flavor::Real);    let ws = workspace(&handle);    let started = std::time::Instant::now();    sql(&handle, "WITH RECURSIVE n(x) AS (SELECT 0 UNION ALL SELECT x + 1 FROM n WHERE x < 29999)        INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, first_at, last_at, email_count, created_at, updated_at)        SELECT 't' || x, ?1, 'k' || x, 'Offer', '2026-01-01T00:00:00Z', '2026-11-20T00:00:00Z', 3, '2026-11-20T00:00:00Z', '2026-11-20T00:00:00Z' FROM n", &[t(&ws)]);    sql(&handle, "WITH RECURSIVE n(x) AS (SELECT 0 UNION ALL SELECT x + 1 FROM n WHERE x < 99999)        INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, subject, from_email, from_name, recipients, sent_at, body, snippet, unread, account, created_at)        SELECT 'e' || x, ?1, 't' || (x % 30000), 'x' || x, 'Offer ' || x, 'news' || (x % 2000) || '@shop' || (x % 2000 % 400) || '.invented', 'Shop ' || (x % 2000),               '[{\"email\":\"mira@invented.example\",\"kind\":\"to\"}]', strftime('%Y-%m-%dT%H:%M:%SZ', '2026-11-20', '-' || x || ' minutes'), replace(printf('%.200c', '~'), '~', 'Your weekly offer is here with more to read. ') || x, 'Words ' || x, x % 5 = 0, 'mira@invented.example', '2026-11-20T00:00:00Z' FROM n", &[t(&ws)]);    eprintln!("SCALE seeded in {:?}", started.elapsed());    // The seed's write-ahead log folded in now, so no act below pays for it.    handle.client().with_writer(|replica| replica.driver.all("PRAGMA wal_checkpoint(TRUNCATE)", &[]).map(|_| ()).map_err(|e| e.to_string())).unwrap();    let time = |what: &str, method: &str, request: Value| {        let at = std::time::Instant::now();        let out = answer(&handle, method, request);        eprintln!("SCALE {what}: {:?}", at.elapsed());        out    };    {        let parts = |what: &str, f: &dyn Fn(&mut cotton_tools::mcp::dispatch::Ctx<'_>) -> Result<(), String>| {            let at = std::time::Instant::now();            crate::phone::cotton_chat::read(&handle.client(), "scale.part", |ctx| f(ctx).map(|_| json!(null))).unwrap();            eprintln!("SCALE part {what}: {:?}", at.elapsed());        };        parts("know", &|ctx| crate::phone::chat_app::mail::Know::read(ctx).map(|_| ()));        parts("mail_tallies", &|ctx| super::mail_tallies(ctx, None).map(|_| ()));        parts("chat_shares", &|ctx| super::chat_shares(ctx).map(|_| ()));        parts("sender_groups", &|ctx| crate::phone::chat_app::mail::sender_groups(ctx).map(|_| ()));        parts("source_states", &|ctx| super::source_states(ctx).map(|_| ()));    }    let page = time("chat.senders (tab)", "chat.senders", json!({}));    eprintln!("SCALE rows {} first {}", page["rows"].as_array().map_or(0, Vec::len), page["rows"][0]["key"]);    time("chat.senders (a domain)", "chat.senders", json!({ "domain": "shop7.invented" }));    time("chat.senders (notices)", "chat.senders", json!({ "filter": "notices" }));    time("chat.sender.page (address)", "chat.sender.page", json!({ "key": "news7@shop7.invented" }));    time("chat.sender.page (domain)", "chat.sender.page", json!({ "key": "@shop7.invented" }));    let ask = time("chat.sender.ask (delete, domain)", "chat.sender.ask", json!({ "key": "@shop7.invented", "act": "delete" }));    eprintln!("SCALE count {}", ask["count"]);    time("chat.sender.act (merge)", "chat.sender.act", json!({ "key": "news8@shop8.invented", "act": "merge", "into": "news9@shop9.invented" }));    time("chat.senders (after merge)", "chat.senders", json!({}));    time("chat.sender.act (delete, domain)", "chat.sender.act", json!({ "key": "@shop7.invented", "act": "delete", "count": ask["count"] }));    time("chat.mail (tab)", "chat.mail", json!({}));}/// RULE (look-ios's walk, 24 Nov 2026): a sender with nothing of theirs left is not asked "Archive 0" or "Delete 0":/// the ask is refused in words; and Blocked is the tab's place, not a domain page's.#[test]fn nothing_left_is_said_and_blocked_stands_on_the_tab_only() {    let (_dir, handle) = phone();    email(&handle, "e-arch", "et-arch", ("deals@shop.invented", "Invented Shop"), ME, "Sale", 5);    sql(&handle, "UPDATE cotton_emails SET archived_at = '2026-11-24T00:00:00Z' WHERE id = 'e-arch'", &[]);    let refused = over(&handle.client(), "chat.sender.ask", &json!({ "key": "deals@shop.invented", "act": "archive" })).unwrap_err();    assert_eq!((refused.code.as_str(), refused.message.as_str()), ("not_found", "Nothing from them is here."));    assert!(answer(&handle, "chat.senders", json!({}))["blocked"]["label"].is_string());    assert!(answer(&handle, "chat.senders", json!({ "domain": "shop.invented" }))["blocked"].is_null());}/// RULE (ACTS TRUTH, owner's Comms 31, 24 Nov 2026): Comms never says a mailbox act is done before the Mac says so./// Delete everything says what Comms erased and that the Mac moves their mail next; the sender, with nothing left here,/// stands on in the tab and keeps a page under their name, waiting for the Mac; a Mac that refuses ("Count first, then/// move.", a Mac whose Cotton does not take the act yet) is said plainly, with Try again, which files it again; once the/// Mac has done it the sender goes. One mail's Archive and Delete say the same of their half.#[test]fn a_mailbox_act_is_never_said_done_before_the_mac_does_it() {    let _dir = tempfile::tempdir().unwrap();    let handle = crate::phone::chat_app::mail::tests::comms(&_dir, cotton_core::flavor::Flavor::Real);    let ws = workspace(&handle);    for i in 0..3 {        email(&handle, &format!("e-deals-{i}"), &format!("et-deals-{i}"), ("deals@shop.invented", "Invented Shop"), ME, "Sale", 10 + i);    }    // His mailbox counted by the Mac first, so the move is the set it counted (DELETE FAST).    answer(&handle, "chat.sender.ask", json!({ "key": "deals@shop.invented", "act": "delete" }));    sql(&handle, "UPDATE cotton_outbox SET status = 'sent', count = 3, uid_validity = 42, uid_below = 9000 WHERE workspace_id = ? AND kind = 'sender_count'", &[t(&ws)]);    let ask = answer(&handle, "chat.sender.ask", json!({ "key": "deals@shop.invented", "act": "delete" }));    let done = answer(&handle, "chat.sender.act", json!({ "key": "deals@shop.invented", "act": "delete", "count": ask["count"], "mailbox": ask["mailbox"] }));    assert_eq!(done["said"], "Deleted 3 from Invented Shop in Comms. Your Mac moves their mail to Trash next.");    let row = |page: &Value| page["rows"].as_array().unwrap().iter().find(|r| r["key"] == "deals@shop.invented").cloned();    // Waiting: the sender stands on, by name, with the Mac's half.    let tab = answer(&handle, "chat.senders", json!({}));    let waiting = row(&tab).unwrap_or_else(|| panic!("the sender stands on while the Mac works: {tab}"));    assert_eq!(waiting["name"], "Invented Shop", "{waiting}");    assert_eq!(waiting["source"]["line"], "Waiting for your Mac to move those 3 to Trash", "{waiting}");    let page = answer(&handle, "chat.sender.page", json!({ "key": "deals@shop.invented" }));    assert_eq!((page["name"].as_str(), page["line"].as_str()), (Some("Invented Shop"), Some("Nothing from them is left in Comms.")), "{page}");    assert_eq!(page["acts"], json!([{ "id": "block", "label": "Block" }]), "{page}");    assert!(page["empty"].is_null(), "said once, by `line`: {page}");    assert_eq!(page["source"]["state"], "queued", "{page}");    // Refused by a Mac that cannot do it yet: said plainly, with Try again, on the row and the page.    sql(&handle, "UPDATE cotton_outbox SET status = 'failed', error = 'Count first, then move.' WHERE workspace_id = ? AND kind = 'sender_trash'", &[t(&ws)]);    let failed = row(&answer(&handle, "chat.senders", json!({}))).unwrap();    assert_eq!((failed["source"]["line"].as_str(), failed["source"]["retry"].as_str()), (Some("Not moved to Trash in your mail: your Mac can't do this yet"), Some("Try again")), "{failed}");    assert_eq!(answer(&handle, "chat.sender.page", json!({ "key": "deals@shop.invented" }))["source"]["retry"], "Try again");    answer(&handle, "chat.sender.act", json!({ "key": "deals@shop.invented", "act": "retry" }));    assert_eq!(row(&answer(&handle, "chat.senders", json!({}))).unwrap()["source"]["state"], "queued");    // Done by the Mac: nothing of theirs is left anywhere, and the sender goes.    sql(&handle, "UPDATE cotton_outbox SET status = 'sent' WHERE workspace_id = ? AND kind = 'sender_trash'", &[t(&ws)]);    assert!(row(&answer(&handle, "chat.senders", json!({}))).is_none());    // Its page, still open on the phone, keeps their name (SENDERS TRUE walk on emulator-5618).    let page = answer(&handle, "chat.sender.page", json!({ "key": "deals@shop.invented" }));    assert_eq!((page["name"].as_str(), page["handle"].as_str(), page["source"]["state"].as_str()), (Some("Invented Shop"), Some("deals@shop.invented"), Some("sent")), "{page}");    // One mail: Comms' half done, the mailbox's half the Mac's.    email(&handle, "e-news", "et-news", ("news@paper.invented", "The Invented Paper"), ME, "News", 3);    email(&handle, "e-news2", "et-news2", ("news@paper.invented", "The Invented Paper"), ME, "More news", 2);    let archived = answer(&handle, "chat.mail.act", json!({ "email": "e-news", "act": "archive" }));    assert_eq!(archived["said"], "Archived in Comms. Your Mac archives it in your mail next.");    let deleted = answer(&handle, "chat.mail.act", json!({ "email": "e-news2", "act": "delete" }));    assert_eq!(deleted["said"], "Deleted in Comms. Your Mac moves it to Trash in your mail next.");    let paper = row(&answer(&handle, "chat.senders", json!({}))).is_none();    assert!(paper);    let news = answer(&handle, "chat.senders", json!({}))["rows"].as_array().unwrap().iter().find(|r| r["key"] == "news@paper.invented").cloned().unwrap();    assert_eq!(news["source"]["line"], "Waiting for your Mac to move their mail to Trash", "{news}");}/// RULE (SENDERS INDEX, schema 153): the Senders tab's tally and each sender's newest mail read/// `idx_cotton_emails_sender` alone, for the whole account, an address and a domain: never a pass over the mail rows,/// which are mostly their bodies (the tab was cut off at 20 s over 100,000 mails on emulator-5618).#[test]fn the_senders_tally_reads_the_sender_index_alone() {    let (_dir, handle) = phone();    let only = |keys: &[&str]| keys.iter().map(|k| k.to_string()).collect::<Vec<_>>();    let plans = crate::phone::cotton_chat::read(&handle.client(), "test.plans", |ctx| {        let mut out = Vec::new();        for scope in [None, Some(only(&["deals@shop.invented"])), Some(only(&["@shop.invented"]))] {            let (clause, mut params) = super::mail_where(scope.as_deref());            let mut all = vec![crate::phone::cotton_chat::ws(ctx)];            all.append(&mut params);            let tally = crate::phone::cotton_chat::rows(ctx, &format!("EXPLAIN QUERY PLAN {}", super::tally_sql(&clause)), &all)?;            let newest = crate::phone::cotton_chat::rows(ctx, &format!("EXPLAIN QUERY PLAN {}", crate::phone::chat_app::mail::newest_sql("id", &clause)), &all)?;            out.push(json!({ "tally": tally.iter().map(|r| r["detail"].clone()).collect::<Vec<_>>(), "newest": newest.iter().map(|r| r["detail"].clone()).collect::<Vec<_>>() }));        }        Ok(json!(out))    })    .unwrap();    for plan in plans.as_array().unwrap() {        let tally: Vec<&str> = plan["tally"].as_array().unwrap().iter().filter_map(Value::as_str).collect();        assert!(tally.iter().any(|d| d.contains("COVERING INDEX idx_cotton_emails_sender")), "{plan}");        assert!(!tally.iter().any(|d| d.starts_with("SCAN cotton_emails") && !d.contains("COVERING")), "{plan}");        let newest: Vec<&str> = plan["newest"].as_array().unwrap().iter().filter_map(Value::as_str).collect();        assert!(newest.iter().any(|d| d.contains("COVERING INDEX idx_cotton_emails_sender")), "{plan}");    }}/// ERASES. RULE (DELETE FAST, owner via the coordinator, 24 Nov 2026: he was shown Delete 13, the phone holding 90/// days, and the Mac moved all 23 in his mailbox): Delete everything moves in his mailbox exactly what its ask showed./// Opening their page asks the Mac to count his mailbox, once while it counts. Not counted yet, the ask says so and/// only the mail here goes, each by its own id. Counted, the ask says his mailbox's own number and the act carries/// the set that count fixed; a number he did not see is refused, so the ask is shown again.#[test]fn delete_everything_moves_in_his_mailbox_only_what_it_showed() {    let _dir = tempfile::tempdir().unwrap();    let handle = crate::phone::chat_app::mail::tests::comms(&_dir, cotton_core::flavor::Flavor::Real);    let ws = workspace(&handle);    let shop = "deals@shop.invented";    for i in 0..3 {        email(&handle, &format!("e-deals-{i}"), &format!("et-deals-{i}"), (shop, "Invented Shop"), ME, "Sale", 10 + i);    }    answer(&handle, "chat.sender.page", json!({ "key": shop }));    answer(&handle, "chat.sender.page", json!({ "key": shop }));    assert_eq!(outbox(&handle, "sender_count").into_iter().filter(|(_, place)| place.is_empty()).collect::<Vec<_>>(), [(shop.to_string(), String::new())], "asked once while the Mac counts");    let ask = answer(&handle, "chat.sender.ask", json!({ "key": shop, "act": "delete" }));    assert!(ask["line"].as_str().unwrap().ends_with("Your Mac hasn't counted your mail from them yet, so only the 3 emails here go to Trash there."), "{ask}");    assert!(ask["mailbox"].is_null(), "{ask}");    // The Mac counts 23 from them in his mailbox.    sql(&handle, "UPDATE cotton_outbox SET status = 'sent', count = 23, uid_validity = 42, uid_below = 9000 WHERE workspace_id = ? AND kind = 'sender_count' AND target IS NULL", &[t(&ws)]);    let ask = answer(&handle, "chat.sender.ask", json!({ "key": shop, "act": "delete" }));    assert_eq!((ask["count"].clone(), ask["mailbox"].clone()), (json!(3), json!(23)), "{ask}");    assert!(ask["line"].as_str().unwrap().ends_with("Your mail holds 23 emails from them, and your Mac moves those 23 to Trash."), "{ask}");    assert_eq!(outbox(&handle, "sender_count").into_iter().filter(|(_, place)| place.is_empty()).count(), 1, "a count within the hour is not asked again");    assert_eq!(over(&handle.client(), "chat.sender.act", &json!({ "key": shop, "act": "delete", "count": 3, "mailbox": 13 })).unwrap_err().code, "count_changed");    answer(&handle, "chat.sender.act", json!({ "key": shop, "act": "delete", "count": 3, "mailbox": 23 }));    let moves = crate::phone::cotton_chat::read(&handle.client(), "test.moves", |ctx| {        Ok(json!(crate::phone::cotton_chat::rows(ctx, "SELECT \"to\", count, uid_validity, uid_below FROM cotton_outbox WHERE workspace_id = ? AND kind = 'sender_trash'", &[t(&ws)])?))    })    .unwrap();    assert_eq!(moves, json!([{ "to": shop, "count": 23, "uid_validity": 42, "uid_below": 9000 }]), "exactly the set he was shown");    assert!(outbox(&handle, "trash").is_empty(), "{:?}", outbox(&handle, "trash"));}/// ERASES. RULE (DELETE FAST, coordinator, 24 Nov 2026): Delete everything takes their mail out of Comms at once,/// deleting from the search indexes plainly (never securely: that rewrote every word's list a mail at a time, minutes/// on a phone). Each index is then due a background purge, which merges it whole and is finished once its row is/// gone; `an_erase_leaves_its_words_and_its_file_nowhere` reads every page for the words after it.#[test]fn delete_everything_is_at_once_and_its_words_go_in_the_background_purge() {    let _dir = tempfile::tempdir().unwrap();    let handle = crate::phone::chat_app::mail::tests::comms(&_dir, cotton_core::flavor::Flavor::Real);    let ws = workspace(&handle);    // A copy that deleted securely before this.    sql(&handle, "INSERT INTO fts_emails(fts_emails, rank) VALUES ('secure-delete', 1)", &[]);    for i in 0..3 {        email(&handle, &format!("e-deals-{i}"), &format!("et-deals-{i}"), ("deals@shop.invented", "Invented Shop"), ME, "Sale", 10 + i);    }    let ask = answer(&handle, "chat.sender.ask", json!({ "key": "deals@shop.invented", "act": "delete" }));    answer(&handle, "chat.sender.act", json!({ "key": "deals@shop.invented", "act": "delete", "count": ask["count"] }));    assert_eq!(count(&handle, "SELECT count(*) AS n FROM cotton_emails WHERE from_email = 'deals@shop.invented'"), 0);    let _ = ws;    assert_eq!(count(&handle, "SELECT count(*) AS n FROM fts_emails_config WHERE k = 'secure-delete' AND CAST(v AS INTEGER) = 1"), 0, "deleted plainly");    assert!(count(&handle, "SELECT count(*) AS n FROM _fts_purge WHERE fts = 'fts_emails'") == 1, "due a purge");    assert!(crate::phone::mail_index::purge_now(&handle.client(), std::time::Duration::from_secs(60)).unwrap() >= 1);    assert_eq!(count(&handle, "SELECT count(*) AS n FROM _fts_purge"), 0, "purged whole");}/// RULE (SENDERS TRUE, coordinator, 24 Nov 2026; mac-import found Gmail ignores a label change made in an open Inbox/// and still answers OK): Archive everything is said done in his mail only when the Mac read his Inbox back. A `sent`/// without the read-back is said as unchecked, with Try again; read back, the row says how many left his Inbox; what/// Gmail kept is a refusal in the Mac's words, with Try again.#[test]fn an_archive_is_done_in_his_mail_only_when_the_mac_reads_it_back() {    let _dir = tempfile::tempdir().unwrap();    let handle = crate::phone::chat_app::mail::tests::comms(&_dir, cotton_core::flavor::Flavor::Real);    let ws = workspace(&handle);    let shop = "deals@shop.invented";    for i in 0..3 {        email(&handle, &format!("e-deals-{i}"), &format!("et-deals-{i}"), (shop, "Invented Shop"), ME, "Sale", 10 + i);    }    // His Inbox counted first (ARCHIVE COUNT), so the act carries that set.    answer(&handle, "chat.sender.ask", json!({ "key": shop, "act": "archive" }));    sql(&handle, "UPDATE cotton_outbox SET status = 'sent', count = 3, uid_validity = 42, uid_below = 9000 WHERE workspace_id = ? AND kind = 'sender_count' AND target = 'inbox'", &[t(&ws)]);    let ask = answer(&handle, "chat.sender.ask", json!({ "key": shop, "act": "archive" }));    answer(&handle, "chat.sender.act", json!({ "key": shop, "act": "archive", "count": ask["count"], "mailbox": ask["mailbox"] }));    let source = |handle: &CottonHandle| answer(handle, "chat.sender.page", json!({ "key": shop }))["source"].clone();    assert_eq!(source(&handle)["line"], "Waiting for your Mac to archive those 3");    let mac = |set: &str| sql(&handle, &format!("UPDATE cotton_outbox SET {set} WHERE workspace_id = ? AND kind = 'sender_archive'"), &[t(&ws)]);    // A Mac before the read-back: OK, unchecked.    mac("status = 'sent', moved = 3");    let unchecked = source(&handle);    assert_eq!((unchecked["state"].as_str(), unchecked["line"].as_str(), unchecked["retry"].as_str()), (Some("unchecked"), Some("Your Mac archived their mail but didn't check your Inbox after"), Some("Try again")), "{unchecked}");    answer(&handle, "chat.sender.act", json!({ "key": shop, "act": "retry" }));    assert_eq!(source(&handle)["state"], "queued");    // Gmail kept some: the Mac's words, with Try again.    mac("status = 'failed', moved = 1, error = 'Gmail kept 2 of them in your Inbox.'");    let kept = source(&handle);    assert_eq!((kept["line"].as_str(), kept["retry"].as_str()), (Some("Not archived in your mail: Gmail kept 2 of them in your Inbox."), Some("Try again")), "{kept}");    answer(&handle, "chat.sender.act", json!({ "key": shop, "act": "retry" }));    // Read back: done, with how many.    mac("status = 'sent', moved = 3, error = NULL, sent_external_id = 'read_back'");    let done = source(&handle);    assert_eq!((done["state"].as_str(), done["line"].as_str()), (Some("sent"), Some("3 archived in your mail")), "{done}");    assert!(done["retry"].is_null(), "{done}");}/// RULE (SENDERS TRUE, coordinator, 24 Nov 2026): Senders end to end against a Mac on Gmail (`developer.fakeMac`, the/// walk's own fake on Comms Dev). Delete everything shows his mailbox's count, refuses a count that changed between/// ask and act, and stays waiting through a move cut half way until the Mac is done; Archive everything is done only/// once read back, through Gmail keeping some and an unchecked OK; a refused move and a refused unsubscribe are said/// in the Mac's words with Try again, and a second try goes through.#[test]fn senders_end_to_end_against_a_mac_on_gmail() {    let _dir = tempfile::tempdir().unwrap();    let handle = crate::phone::chat_app::mail::tests::comms(&_dir, cotton_core::flavor::Flavor::Dev);    let mac = |behave: Value| crate::methods::dispatch(&handle, "developer.fakeMac", &behave).unwrap_or_else(|e| panic!("developer.fakeMac: {} {}", e.code, e.message));    let shop = "deals@shop.invented";    for i in 0..3 {        email(&handle, &format!("e-deals-{i}"), &format!("et-deals-{i}"), (shop, "Invented Shop"), ME, "Sale", 10 + i);    }    let source = |key: &str| answer(&handle, "chat.sender.page", json!({ "key": key }))["source"].clone();    let in_tab = |key: &str| answer(&handle, "chat.senders", json!({}))["rows"].as_array().unwrap().iter().find(|r| r["key"] == key).cloned();    // Delete everything: counted by the Mac (20 more than the phone's 90 days).    answer(&handle, "chat.sender.page", json!({ "key": shop }));    mac(json!({ "older": 20 }));    let ask = answer(&handle, "chat.sender.ask", json!({ "key": shop, "act": "delete" }));    assert_eq!(ask["mailbox"], 23, "{ask}");    // Mail came between the ask and the act: asked again with the new number.    mac(json!({ "recount": 1 }));    assert_eq!(over(&handle.client(), "chat.sender.act", &json!({ "key": shop, "act": "delete", "count": ask["count"], "mailbox": 23 })).unwrap_err().code, "count_changed");    let ask = answer(&handle, "chat.sender.ask", json!({ "key": shop, "act": "delete" }));    assert!(ask["line"].as_str().unwrap().ends_with("Your mail holds 24 emails from them, and your Mac moves those 24 to Trash."), "{ask}");    answer(&handle, "chat.sender.act", json!({ "key": shop, "act": "delete", "count": ask["count"], "mailbox": ask["mailbox"] }));    // Cut half way: still waiting, the sender stands on.    mac(json!({ "trash": "partial" }));    assert_eq!(source(shop)["line"], "Waiting for your Mac to move those 24 to Trash");    assert!(in_tab(shop).is_some());    mac(json!({}));    assert!(in_tab(shop).is_none(), "done at the Mac: nothing of theirs is left anywhere");    // Archive everything: Gmail keeps some, then an unchecked OK, then read back.    let paper = "news@paper.invented";    for i in 0..4 {        email(&handle, &format!("e-news-{i}"), &format!("et-news-{i}"), (paper, "The Invented Paper"), ME, "News", 5 + i);    }    answer(&handle, "chat.sender.ask", json!({ "key": paper, "act": "archive" }));    mac(json!({}));    let ask = answer(&handle, "chat.sender.ask", json!({ "key": paper, "act": "archive" }));    assert_eq!(ask["mailbox"], 4, "{ask}");    answer(&handle, "chat.sender.act", json!({ "key": paper, "act": "archive", "count": ask["count"], "mailbox": ask["mailbox"] }));    mac(json!({ "archive": "gmail_keeps" }));    assert_eq!(source(paper)["line"], "Not archived in your mail: Gmail kept 2 of them in your Inbox.");    answer(&handle, "chat.sender.act", json!({ "key": paper, "act": "retry" }));    mac(json!({ "archive": "unchecked" }));    assert_eq!(source(paper)["state"], "unchecked");    answer(&handle, "chat.sender.act", json!({ "key": paper, "act": "retry" }));    mac(json!({}));    assert_eq!(source(paper)["line"], "4 archived in your mail");    // A refused move, not counted: only the mail here, said in the Mac's words, then through on Try again.    let club = "hello@club.invented";    for i in 0..3 {        email(&handle, &format!("e-club-{i}"), "et-club", (club, "Invented Club"), ME, "Welcome", 4 + i);    }    let ask = answer(&handle, "chat.sender.ask", json!({ "key": club, "act": "delete" }));    mac(json!({ "refuse": ["sender_count"] }));    answer(&handle, "chat.sender.act", json!({ "key": club, "act": "delete", "count": ask["count"] }));    mac(json!({ "refuse": ["trash"] }));    let refused = source(club);    assert_eq!((refused["line"].as_str(), refused["retry"].as_str()), (Some("Not moved to Trash in your mail: This mail server can't move mail without erasing it, so nothing was moved."), Some("Try again")), "{refused}");    // One of three moved on the Mac's next run, two refused again: still refused, never "Moved".    let rows = crate::phone::cotton_chat::read(&handle.client(), "test.rows", |ctx| Ok(json!(crate::phone::cotton_chat::rows(ctx, "SELECT id FROM cotton_outbox WHERE kind = 'trash' ORDER BY id", &[])?))).unwrap();    let first = rows[0]["id"].as_str().unwrap().to_string();    sql(&handle, "UPDATE cotton_outbox SET status = 'sent', error = NULL WHERE id = ?", &[t(&first)]);    assert_eq!(source(club)["state"], "failed", "one of three moved is not all moved");    answer(&handle, "chat.sender.act", json!({ "key": club, "act": "retry" }));    let queued = crate::phone::cotton_chat::read(&handle.client(), "test.rows", |ctx| Ok(json!(crate::phone::cotton_chat::rows(ctx, "SELECT count(*) AS n FROM cotton_outbox WHERE kind = 'trash' AND status = 'queued'", &[])?))).unwrap();    assert_eq!(queued[0]["n"], 2, "Try again takes every refused row");    mac(json!({}));    assert!(in_tab(club).is_none());    // Unsubscribe: their link refuses, then the one-click goes through.    let store = "offers@store.invented";    email(&handle, "e-store", "et-store", (store, "Invented Store"), ME, "Offer", 3);    sql(&handle, "UPDATE cotton_emails SET list_unsubscribe = '<https://store.invented/u>', list_unsubscribe_post = 'List-Unsubscribe=One-Click' WHERE id = 'e-store'", &[]);    answer(&handle, "chat.sender.act", json!({ "key": store, "act": "unsubscribe" }));    mac(json!({ "unsubscribe": "refuse" }));    let refused = source(store);    assert_eq!((refused["state"].as_str(), refused["retry"].as_str()), (Some("failed"), Some("Try again")), "{refused}");    assert!(refused["line"].as_str().unwrap().ends_with("Their unsubscribe link didn't answer."), "{refused}");    answer(&handle, "chat.sender.act", json!({ "key": store, "act": "retry" }));    mac(json!({ "unsubscribe": "one_click" }));    let done = source(store);    assert_eq!((done["state"].as_str(), done["line"].as_str()), (Some("sent"), Some("Unsubscribed")), "{done}");    // One that offers no one-click: their arrivals go to Trash, and the row says so.    let shop2 = "promo@other.invented";    email(&handle, "e-promo", "et-promo", (shop2, "Other Shop"), ME, "Promo", 2);    answer(&handle, "chat.sender.act", json!({ "key": shop2, "act": "unsubscribe" }));    mac(json!({ "unsubscribe": "trash_on_arrival" }));    assert_eq!(source(shop2)["line"], "They offer no one-click unsubscribe, so your Mac moves what they send to Trash");    // One-click offered, but their server refuses the click, or leads it to a page: the Mac falls back to Trash on    // arrival with its why in `error`, and the row says which (UNSUBSCRIBE WORDS, 25 Nov 2026).    for (who, how, said) in [        ("news@refuses.invented", "sender_refused", "They didn't take the unsubscribe, so your Mac moves what they send to Trash"),        ("news@page.invented", "page", "Their unsubscribe opens a web page instead, so your Mac moves what they send to Trash"),    ] {        let id = format!("e-{how}");        email(&handle, &id, &format!("et-{how}"), (who, "Invented News"), ME, "News", 1);        sql(&handle, &format!("UPDATE cotton_emails SET list_unsubscribe = '<https://x.invented/u>', list_unsubscribe_post = 'List-Unsubscribe=One-Click' WHERE id = '{id}'"), &[]);        answer(&handle, "chat.sender.act", json!({ "key": who, "act": "unsubscribe" }));        mac(json!({ "unsubscribe": how }));        let row = source(who);        assert_eq!((row["state"].as_str(), row["line"].as_str(), row["retry"].as_str()), (Some("sent"), Some(said), None), "{row}");    }    // The real Cotton refuses the fake by name.    let real_dir = tempfile::tempdir().unwrap();    let real = crate::phone::chat_app::mail::tests::comms(&real_dir, cotton_core::flavor::Flavor::Real);    assert_eq!(crate::methods::dispatch(&real, "developer.fakeMac", &json!({})).unwrap_err().code, "not_dev");}/// RULE (ARCHIVE COUNT, coordinator, 25 Nov 2026; ACTS CHECK, Mac 9): the owner's Archive everything from build 8 takes/// two taps of Try again to finish, and each tap's words say what happens next. Unchecked, Try again. Waiting while/// the Mac counts his Inbox. The Mac's count, with "Archive those 14". Waiting for that set. Then done, read back.#[test]fn an_old_archive_finishes_in_two_taps_each_saying_what_comes_next() {    let _dir = tempfile::tempdir().unwrap();    let handle = crate::phone::chat_app::mail::tests::comms(&_dir, cotton_core::flavor::Flavor::Dev);    let mac = |behave: Value| crate::methods::dispatch(&handle, "developer.fakeMac", &behave).unwrap_or_else(|e| panic!("developer.fakeMac: {} {}", e.code, e.message));    let paper = "news@paper.invented";    for i in 0..3 {        email(&handle, &format!("e-news-{i}"), &format!("et-news-{i}"), (paper, "The Invented Paper"), ME, "News", 5 + i);    }    mac(json!({ "old_archive": paper }));    let source = || answer(&handle, "chat.sender.page", json!({ "key": paper }))["source"].clone();    let said = |s: &Value| (s["state"].as_str().unwrap_or_default().to_string(), s["line"].as_str().unwrap_or_default().to_string(), s["retry"].as_str().map(str::to_string));    assert_eq!(said(&source()), ("unchecked".into(), "Your Mac archived their mail but didn't check your Inbox after".into(), Some("Try again".into())));    // Tap 1: the Mac counts his Inbox first.    assert_eq!(answer(&handle, "chat.sender.act", json!({ "key": paper, "act": "retry" }))["said"], "Your Mac counts their mail in your Inbox first, and Comms shows you the number before anything moves.");    assert_eq!(said(&source()), ("queued".into(), "Waiting for your Mac to count their mail in your Inbox".into(), None));    mac(json!({ "inbox": 11 }));    assert_eq!(said(&source()), ("counted".into(), "14 emails from them are still in your Inbox".into(), Some("Archive those 14".into())));    // Tap 2: exactly those 14.    assert_eq!(answer(&handle, "chat.sender.act", json!({ "key": paper, "act": "retry" }))["said"], "Your Mac archives those 14 next.");    assert_eq!(said(&source()), ("queued".into(), "Waiting for your Mac to archive those 14".into(), None));    mac(json!({}));    assert_eq!(said(&source()), ("sent".into(), "14 archived in your mail".into(), None));}/// RULE (ARCHIVE COUNT, coordinator, 25 Nov 2026): Archive everything's ask shows his Inbox's own count before he/// agrees (`sender_count` with `target: "inbox"`, asked when their page opens), and the act carries the set that count/// fixed, so one tap archives exactly it; a count answered since asks again; not counted yet, only the mail here/// leaves his Inbox, one by one.#[test]fn archive_everything_shows_his_inbox_count_before_he_agrees() {    let _dir = tempfile::tempdir().unwrap();    let handle = crate::phone::chat_app::mail::tests::comms(&_dir, cotton_core::flavor::Flavor::Dev);    let mac = |behave: Value| crate::methods::dispatch(&handle, "developer.fakeMac", &behave).unwrap_or_else(|e| panic!("developer.fakeMac: {} {}", e.code, e.message));    let shop = "deals@shop.invented";    for i in 0..3 {        email(&handle, &format!("e-deals-{i}"), &format!("et-deals-{i}"), (shop, "Invented Shop"), ME, "Sale", 10 + i);    }    // Not counted yet.    let ask = answer(&handle, "chat.sender.ask", json!({ "key": shop, "act": "archive" }));    assert_eq!(ask["line"], "3 messages from Invented Shop will leave Comms. Your Mac hasn't counted your Inbox yet, so only the 3 emails here leave your Inbox there. They stay in your mail, in All Mail.");    assert!(ask["mailbox"].is_null(), "{ask}");    // Counted: 8 in his Inbox.    mac(json!({ "inbox": 5 }));    let ask = answer(&handle, "chat.sender.ask", json!({ "key": shop, "act": "archive" }));    assert_eq!((ask["mailbox"].clone(), ask["line"].as_str().map(|l| l.ends_with("Your Inbox holds 8 emails from them, and your Mac archives those 8. They stay in your mail, in All Mail."))), (json!(8), Some(true)), "{ask}");    // Recounted in between: asked again.    mac(json!({ "recount": 1 }));    assert_eq!(over(&handle.client(), "chat.sender.act", &json!({ "key": shop, "act": "archive", "count": 3, "mailbox": 8 })).unwrap_err().code, "count_changed");    let ask = answer(&handle, "chat.sender.ask", json!({ "key": shop, "act": "archive" }));    answer(&handle, "chat.sender.act", json!({ "key": shop, "act": "archive", "count": ask["count"], "mailbox": ask["mailbox"] }));    let page = answer(&handle, "chat.sender.page", json!({ "key": shop }));    assert_eq!(page["source"]["line"], "Waiting for your Mac to archive those 9", "{page}");    mac(json!({}));    assert_eq!(answer(&handle, "chat.sender.page", json!({ "key": shop }))["source"]["line"], "9 archived in your mail");}/// RULE (COMMS WITHOUT MAIL): Senders left Comms, so Blocked, where a blocked sender's texts wait their 30 days, is/// reached from You: a "blocked" row stands under You only while Blocked holds someone, and goes once they are/// unblocked.#[test]fn you_reaches_blocked_while_it_holds_someone() {    let (_dir, handle) = phone();    senders(&handle);    let you = |handle: &CottonHandle| crate::methods::dispatch(handle, "chat.you", &json!({})).unwrap();    let row = |answer: &Value| answer["rows"].as_array().unwrap().iter().find(|r| r["id"] == "blocked").cloned();    assert_eq!(row(&you(&handle)), None, "nobody blocked: no row");    answer(&handle, "chat.sender.act", json!({ "key": "HDFCBK", "act": "block" }));    let blocked = row(&you(&handle)).expect("a Blocked row once someone is blocked");    assert_eq!((blocked["label"].as_str(), blocked["line"].as_str()), (Some("Blocked"), Some("1 sender blocked")), "{blocked}");    assert_eq!(answer(&handle, "chat.senders.blocked", json!({}))["rows"].as_array().map(Vec::len), Some(1), "the row opens the Blocked place");    answer(&handle, "chat.sender.act", json!({ "key": "HDFCBK", "act": "unblock" }));    assert_eq!(row(&you(&handle)), None, "unblocked: the row goes");}/// Blocked's day count counts a calendar day once: a clock set back and then forward again counts nothing twice/// (ABSENCE 6, M3).#[test]fn blocked_days_count_once_when_the_date_goes_back_and_forth() {    let (_dir, handle) = phone();    senders(&handle);    answer(&handle, "chat.sender.act", json!({ "key": "HDFCBK", "act": "block" }));    let days = |h: &CottonHandle| count(h, "SELECT CAST(v AS INTEGER) AS n FROM _blocked_clock WHERE k = 'days'");    for day in ["2026-12-01", "2026-11-01", "2026-12-01", "2026-11-15", "2026-12-01"] {        crate::phone::chat_app::senders::erase::TODAY.with(|t| *t.borrow_mut() = Some(day.to_string()));        crate::phone::chat_app::senders::erase::sweep_blocked(&handle.client()).unwrap();    }    assert_eq!(days(&handle), 1, "one day counted");    crate::phone::chat_app::senders::erase::TODAY.with(|t| *t.borrow_mut() = Some("2026-12-02".to_string()));    crate::phone::chat_app::senders::erase::sweep_blocked(&handle.client()).unwrap();    assert_eq!(days(&handle), 2, "a later day counts");    crate::phone::chat_app::senders::erase::TODAY.with(|t| *t.borrow_mut() = None);}