Cotton code
998 lines · 68.1 KB · RustRaw
//! Mail in Comms over a phone's own copy (MAIL.md). Every name, address and//! line 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 ASHA_CHAT: &str = "11111111-1111-4111-8111-0000000000a1";const ME: &str = "mira@invented.example";const ASHA: &str = "asha@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)}/// Asha in People with a phone and an email, her Cotton chat (two messages), and Mira's mailbox.fn asha(handle: &CottonHandle) {    let ws = workspace(handle);    sql(handle, "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES ('p-asha', ?, 'Asha Example', '2026-01-01', '2026-01-01')", &[t(&ws)]);    sql(handle, "INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, created_at, updated_at) VALUES ('h-asha', ?, 'p-asha', 'email', ?, ?, 'manual', '2026-01-01', '2026-01-01')", &[t(&ws), t(ASHA), t(ASHA)]);    sql(handle, "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, person_id, created_at, updated_at) VALUES ('c-asha', ?, '15550100001', 'Asha Example', 'p-asha', '2026-01-01', '2026-01-01')", &[t(&ws)]);    sql(handle, "INSERT INTO cotton_msg_threads (id, workspace_id, kind, external_key, contact_id, last_message_at, read_seq, created_at, updated_at) VALUES (?, ?, 'dm', 'cotton:+15550100001', 'c-asha', ?, 0, ?, ?)", &[t(ASHA_CHAT), t(&ws), t(&iso(5)), t(&iso(5)), t(&iso(5))]);    for (id, out, body, at, seq) in [("m-1", true, "Are we still on?", iso(300), 1), ("m-2", false, "Yes, at the lake", iso(5), 2)] {        sql(            handle,            "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, seq, created_at, external_id) VALUES (?, ?, ?, ?, 'cotton', 'live', ?, ?, ?, ?, ?)",            &[t(id), t(ASHA_CHAT), t(&ws), t(if out { "out" } else { "in" }), t(body), t(&at), SqlValue::Integer(seq), t(&at), t(&format!("x-{id}"))],        );    }}#[allow(clippy::too_many_arguments)]fn email(handle: &CottonHandle, id: &str, thread: &str, from: (&str, &str), to: &str, subject: &str, body: &str, at: &str, unread: bool, attachments: Value) {    let ws = workspace(handle);    let (address, name) = from;    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 last_at = max(last_at, excluded.last_at), 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, attachments, unread, account, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",        &[t(id), t(&ws), t(thread), t(&format!("x-{id}")), t(subject), t(address), t(name), t(&json!([{ "email": to, "kind": "to" }]).to_string()), t(at), t(body), t(body), t(&attachments.to_string()), SqlValue::Integer(unread as i64), t(ME), t(at)],    );}/// Asha's mail and Mira's to her, a shop's receipt, a newsletter, and a stranger./// The columns the Mac keeps since Senders 3 (CONTRACT "what the Mac keeps"), on this test's copy where it lacks them:/// Comms' kit makes them, a bare copy's fixed store gains them with MAIL ALL ON PHONE.fn with_headers(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", "list_unsubscribe_post", "list_id", "precedence", "auto_submitted", "gmail_category", "archived_at"] {        if !have.contains(&column) {            sql(handle, &format!("ALTER TABLE cotton_emails ADD COLUMN {column} TEXT"), &[]);        }    }}fn mailbox(handle: &CottonHandle) {    email(handle, "e-asha-1", "et-trip", (ASHA, "Asha Example"), ME, "The lake trip", "Here is the plan for Saturday.", &iso(120), true, json!([{ "name": "plan.pdf", "mime": "application/pdf", "size": 2048 }]));    email(handle, "e-mira-1", "et-trip", (ME, "Mira Invented"), ASHA, "Re: The lake trip", "Looks good to me.", &iso(60), false, json!([]));    email(handle, "e-shop", "et-shop", ("receipts@shop.invented", "Invented Shop"), ME, "Your receipt", "Order 1234, ₹499 paid.", &iso(30), true, json!([]));    email(handle, "e-news", "et-news", ("news@paper.invented", "The Invented Paper"), ME, "This week", "Five stories.", &iso(20), false, json!([]));    email(handle, "e-new", "et-new", ("ravi.k@elsewhere.invented", "Ravi K"), ME, "Hello", "We met at the fair.", &iso(10), true, json!([]));}fn subjects(page: &Value) -> Vec<String> {    page["rows"].as_array().unwrap().iter().map(|r| r["subject"].as_str().unwrap().to_string()).collect()}/// RULE (MAIL.md): mail from a person who has a chat stands in that chat, never in the Mail tab;/// every other mail is in the Mail tab, newest first; People holds the people the rule calls people.#[test]fn a_persons_mail_is_in_their_chat_and_the_rest_in_the_mail_tab() {    let (_dir, handle) = phone();    asha(&handle);    mailbox(&handle);    let mail = answer(&handle, "chat.mail", json!({}));    assert_eq!(subjects(&mail), ["Hello", "This week", "Your receipt"], "Asha's trip is in her chat, not here: {mail}");    assert_eq!(mail["rows"][0]["who"], "person", "a stranger who writes as a person waits in the Mail tab, under People");    assert_eq!(mail["rows"][2]["unread"], true);    assert_eq!(mail["title"], "Mail");    let people = answer(&handle, "chat.mail", json!({ "filter": "people" }));    assert_eq!(subjects(&people), ["Hello"], "{people}");    let unread = answer(&handle, "chat.mail", json!({ "filter": "unread" }));    assert_eq!(subjects(&unread), ["Hello", "Your receipt"]);}/// RULE (who_corpus.txt): the rule reads the newest mail a sender wrote, its name, subject, words and recipients:/// a newsletter from a personal-looking address, a post to a list and a calendar's invitation are a machine's; a/// friend at a webmail the person never wrote to is a person, in the Mail tab under People.#[test]fn the_rule_reads_the_mail_a_sender_wrote() {    let (_dir, handle) = phone();    asha(&handle);    email(&handle, "e-pat", "et-pat", ("pat@patkelly.invented", "Pat Kelly"), ME, "Monthly letter", "Hi all, here's my month. If you'd rather not get these, unsubscribe below.", &iso(40), false, json!([]));    email(&handle, "e-list", "et-list", ("ravi.menon@ymail.com", "Ravi Menon"), "hiking@googlegroups.com", "[hiking] Saturday", "Ridge route this Saturday?", &iso(30), false, json!([]));    email(&handle, "e-cal", "et-cal", ("jlee@work.invented", "Jennifer Lee"), ME, "Invitation: Q4 planning @ Tue 3pm", "Join with Google Meet. Invitation from Google Calendar.", &iso(20), false, json!([]));    email(&handle, "e-tom", "et-tom", ("tom.fischer@icloud.com", "Tom Fischer"), ME, "moving", "We're moving next month, would love to see you before.", &iso(10), false, json!([]));    let mail = answer(&handle, "chat.mail", json!({}));    let who: Vec<(String, String)> = mail["rows"].as_array().unwrap().iter().map(|r| (r["subject"].as_str().unwrap().to_string(), r["who"].as_str().unwrap().to_string())).collect();    assert_eq!(        who,        [("moving", "person"), ("Invitation: Q4 planning @ Tue 3pm", "machine"), ("[hiking] Saturday", "machine"), ("Monthly letter", "machine")].map(|(a, b)| (a.to_string(), b.to_string())),        "{mail}"    );}/// RULE: a conversation of mail opens whole, oldest first, and is read here; an attachment/// whose bytes Cotton never kept is said so.#[test]fn a_conversation_of_mail_opens_whole_and_is_read() {    // A copy that draws no drafts (a Keys phone here; a Comms copy made before the table shipped, until its object    // serves it) still opens its mail, and offers only the phone's mail app: no writer whose Save would be refused.    let (_dir, handle) = phone();    asha(&handle);    mailbox(&handle);    let open = answer(&handle, "chat.mail.thread", json!({ "thread": "et-trip" }));    let messages = open["messages"].as_array().unwrap();    assert_eq!(messages.iter().map(|m| m["email"].as_str().unwrap()).collect::<Vec<_>>(), ["e-asha-1", "e-mira-1"]);    assert_eq!(messages[0]["from"]["name"], "Asha Example");    assert_eq!(messages[0]["to"], "To me");    assert_eq!(messages[1]["from"]["name"], "You");    assert_eq!(messages[0]["text"], "Here is the plan for Saturday.");    assert_eq!(messages[0]["attachments"][0]["name"], "plan.pdf");    assert_eq!(messages[0]["attachments"][0]["can"], false);    assert_eq!(open["chat"], ASHA_CHAT, "the conversation knows her chat");    assert!(open["reply"]["mailto"].as_str().unwrap().starts_with(&format!("mailto:{ASHA}?subject=Re%3A")), "{}", open["reply"]);    assert!(open["write"].is_null() && open["drafts"] == json!([]), "{open}");    assert!(answer(&handle, "chat.mail", json!({}))["write"].is_null(), "no pen where nothing could be kept");    let again = answer(&handle, "chat.mail.thread", json!({ "thread": "et-trip" }));    assert_eq!(again["messages"][0]["unread"], false, "opened is read");    let refused = over(&handle.client(), "chat.mail.file", &json!({ "email": "e-asha-1", "index": 0, "dir": _dir.path().join("open").to_string_lossy() })).unwrap_err();    assert_eq!((refused.code.as_str(), refused.message.as_str()), ("not_kept", "This attachment stays in your mailbox. Open it there."));}/// RULE: search finds mail by sender, subject or words, any mail but junk.#[test]fn search_finds_mail_by_sender_subject_and_words() {    let (_dir, handle) = phone();    asha(&handle);    mailbox(&handle);    assert_eq!(subjects(&answer(&handle, "chat.mail", json!({ "text": "receipt" }))), ["Your receipt"]);    assert_eq!(subjects(&answer(&handle, "chat.mail", json!({ "text": "Invented Paper" }))), ["This week"]);    assert_eq!(subjects(&answer(&handle, "chat.mail", json!({ "text": "Saturday" }))), ["The lake trip"]);    let none = answer(&handle, "chat.mail", json!({ "text": "zebra" }));    assert_eq!(none["empty"], "No mail matches “zebra”.");}/// A Comms phone of this flavour (Cotton Dev, or the real Cotton) with its own database./// Comms itself, whose kit lays the drafts table a conversation of mail reads and writes (a Keys phone keeps mail's/// tables for the reads above, but not Comms' own drafts).fn comms_phone() -> (tempfile::TempDir, CottonHandle) {    let dir = tempfile::tempdir().unwrap();    let handle = comms(&dir, cotton_core::flavor::Flavor::Real);    (dir, handle)}pub(crate) fn comms(dir: &tempfile::TempDir, flavor: cotton_core::flavor::Flavor) -> CottonHandle {    let manifest = json!({        "genesis": "personal", "flavour": "messages", "name": "Cotton Comms", "databases": "single", "database": "personal",        "fan": {"home": false, "tools": false, "opens": "messages"}, "kit": "messages",    });    let handle = CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: Some(crate::fixture::paired_secret()),        vault_secret: None,        flavor,        manifest: Some(manifest),    })    .expect("an open core");    crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started");    handle}/// RULE (Cotton Dev only): invented mail lands as the Mac's reader lands mail, so Comms' mail/// can be looked at on an emulator: by hand (an invented person, their attachment a file of/// the person's own) and generated; asked twice it writes the same rows. The real Cotton refuses it.#[test]fn invented_mail_lands_in_cotton_dev_only() {    let dir = tempfile::tempdir().unwrap();    let real = comms(&dir, cotton_core::flavor::Flavor::Real);    let ask = json!({ "mail": [] });    assert_eq!(crate::methods::dispatch(&real, "developer.inventMail", &ask).unwrap_err().code, "not_dev");    drop(real);    let dir = tempfile::tempdir().unwrap();    let dev = comms(&dir, cotton_core::flavor::Flavor::Dev);    let invented = json!({        "me": { "address": ME },        "people": [{ "name": "Asha Example", "email": ASHA, "phone": "+15550100001" }],        "mail": [{ "thread": "trip", "subject": "The lake trip", "from": { "address": ASHA, "name": "Asha Example" }, "at": iso(120),                   "body": "Here is the plan.", "unread": true, "attachments": [{ "name": "plan.pdf", "text": "The invented plan" }] }],        "generate": { "emails": 30, "threads": 12, "step": 60, "end": iso(1) },    });    for _ in 0..2 {        crate::methods::dispatch(&dev, "developer.inventMail", &invented).expect("invented");    }    let mail = answer(&dev, "chat.mail", json!({}));    let rows = mail["rows"].as_array().unwrap();    assert!(rows.len() >= 10, "the generated conversations, once each: {mail}");    let ids: std::collections::HashSet<&str> = rows.iter().map(|r| r["thread"].as_str().unwrap()).collect();    assert_eq!(ids.len(), rows.len(), "nothing twice");    let open = answer(&dev, "chat.mail.thread", json!({ "thread": "dev-mail-thread-trip" }));    let file = &open["messages"][0]["attachments"][0];    assert_eq!((file["name"].as_str(), file["can"].as_bool()), (Some("plan.pdf"), Some(true)), "{open}");    let opened = answer(&dev, "chat.mail.file", json!({ "email": "dev-mail-0", "index": 0, "dir": dir.path().join("open").to_string_lossy() }));    let bytes = std::fs::read(opened["path"].as_str().unwrap()).unwrap();    assert!(bytes.starts_with(b"%PDF-1.4"), "a PDF a viewer opens");    assert_eq!(opened["name"], "plan.pdf");}/// Seen making the big invented account (22 Nov 2026): the generator runs in parts (batches of a thousand, and/// copies side by side, each from its own place), and each part wrote the conversations of its own messages dated/// by that part only, so whichever part landed last left a conversation's last_at at its own message and its count/// at one. A generated conversation is now dated by its whole span, whichever part writes it.#[test]fn invented_mail_in_parts_dates_each_conversation_by_its_whole_span() {    let dir = tempfile::tempdir().unwrap();    let dev = comms(&dir, cotton_core::flavor::Flavor::Dev);    // 30 messages in 12 conversations: conversation 3 holds messages 3, 15 and 27. The newest part lands first.    for from in [20, 10, 0] {        let ask = json!({ "me": { "address": ME }, "generate": { "emails": 10, "threads": 12, "from": from, "total": 30, "step": 60, "end": "2026-11-21T09:00:00Z" } });        crate::methods::dispatch(&dev, "developer.inventMail", &ask).expect("invented");    }    let found = crate::phone::cotton_chat::read(&dev.client(), "test.span", |ctx| {        let params = [super::ws(ctx)];        let rows = super::rows(ctx, "SELECT first_at, last_at, email_count FROM cotton_email_threads WHERE workspace_id = ? AND id = 'dev-mail-thread-g3'", &params)?;        Ok(json!(rows))    })    .unwrap();    let row = &found[0];    // Message x is dated (30 - x) hours before the end.    assert_eq!((row["first_at"].as_str(), row["last_at"].as_str(), row["email_count"].as_i64()), (Some("2026-11-20T06:00:00.000Z"), Some("2026-11-21T06:00:00.000Z"), Some(3)), "{found}");}/// Seen on an emulator (22 Nov 2026): an empty Mail tab said "nothing answers GET /v1/older" (a Worker that did/// not page yet). Whatever keeps older mail away is said in the kit's words.#[test]fn older_mail_out_of_reach_is_said_in_the_kits_words() {    let lines = super::list::lines();    let said = super::older_said(&lines, "email_thread", crate::methods::MethodError::new("not_found", "nothing answers GET /v1/older"));    assert_eq!((said.code.as_str(), said.message.as_str()), ("file_offline", "Older mail comes when you're online."));}const NOT_SENT: &str = "Not sent yet: sending from Comms is not set up.";/// RULE (MAIL.md "Writing, and sending"): Reply in Comms opens a form to the other side, "Re:" the subject, their/// words quoted, from the mailbox it came to, and says plainly it will not be sent.#[test]fn a_reply_is_formed_to_the_other_side_with_their_words_quoted() {    let (_dir, handle) = comms_phone();    asha(&handle);    mailbox(&handle);    let form = answer(&handle, "chat.mail.compose", json!({ "thread": "et-trip" }));    assert_eq!(form["to"], json!([ASHA]), "{form}");    assert_eq!(form["subject"], "Re: The lake trip");    assert_eq!(form["from"], ME);    assert_eq!(form["replyTo"], "e-asha-1");    let quoted = form["quoted"].as_str().unwrap();    assert!(quoted.contains("Asha Example wrote:") && quoted.ends_with("> Here is the plan for Saturday."), "{quoted}");    assert_eq!(form["note"], NOT_SENT);    assert_eq!(form["words"]["save"], "Save draft");    let fresh = answer(&handle, "chat.mail.compose", json!({}));    assert_eq!((fresh["to"].clone(), fresh["subject"].clone(), fresh["title"].clone()), (json!([]), json!(""), json!("New mail")));    let open = answer(&handle, "chat.mail.thread", json!({ "thread": "et-trip" }));    assert_eq!((open["write"]["label"].as_str(), open["write"]["note"].as_str()), (Some("Reply"), Some(NOT_SENT)));}/// RULE: Save keeps the mail as a draft in the person's own copy, never as mail waiting to go: it stands in the/// Mail tab's Drafts and at the foot of its conversation, opens again as it was, can be handed to the phone's mail/// app whole (to, cc, subject, the words and the quote), and can be discarded.#[test]fn a_draft_is_kept_shown_handed_on_and_discarded() {    let (_dir, handle) = comms_phone();    asha(&handle);    mailbox(&handle);    let before = answer(&handle, "chat.mail", json!({}));    assert!(before["filters"].as_array().unwrap().iter().all(|f| f["id"] != "drafts"), "no Drafts chip with no drafts");    let form = answer(&handle, "chat.mail.compose", json!({ "thread": "et-trip" }));    let saved = answer(        &handle,        "chat.mail.save",        json!({ "to": form["to"], "cc": "ravi.k@elsewhere.invented", "subject": form["subject"], "body": "Saturday works.", "thread": "et-trip", "replyTo": form["replyTo"], "quoted": form["quoted"] }),    );    let draft = saved["draft"].as_str().unwrap().to_string();    assert_eq!(saved["said"], format!("Saved as a draft. {NOT_SENT}"));    let mailto = saved["mailto"].as_str().unwrap();    assert!(mailto.starts_with(&format!("mailto:{ASHA}?cc=ravi.k%40elsewhere.invented&subject=Re%3A%20The%20lake%20trip&body=Saturday%20works.%0A%0AOn%20")), "{mailto}");    let drafts = answer(&handle, "chat.mail", json!({ "filter": "drafts" }));    let row = &drafts["rows"][0];    assert_eq!((row["draft"].as_str(), row["subject"].as_str(), row["line"].as_str(), row["note"].as_str()), (Some(draft.as_str()), Some("Re: The lake trip"), Some("Saturday works."), Some(NOT_SENT)), "{drafts}");    assert!(answer(&handle, "chat.mail", json!({}))["filters"].as_array().unwrap().iter().any(|f| f["id"] == "drafts" && f["label"] == "Drafts"));    assert_eq!(answer(&handle, "chat.mail.thread", json!({ "thread": "et-trip" }))["drafts"][0]["draft"], draft.as_str());    let again = answer(&handle, "chat.mail.compose", json!({ "draft": draft }));    assert_eq!((again["body"].as_str(), again["cc"].clone(), again["title"].as_str()), (Some("Saturday works."), json!(["ravi.k@elsewhere.invented"]), Some("Reply")));    answer(&handle, "chat.mail.save", json!({ "draft": draft, "to": [ASHA], "subject": "Re: The lake trip", "body": "Saturday works, see you at 9." }));    assert_eq!(answer(&handle, "chat.mail", json!({ "filter": "drafts" }))["rows"].as_array().unwrap().len(), 1, "saved again, still one draft");    assert_eq!(answer(&handle, "chat.mail.discard", json!({ "draft": draft }))["said"], "Draft discarded.");    let gone = answer(&handle, "chat.mail", json!({ "filter": "drafts" }));    assert_eq!((gone["rows"].as_array().unwrap().len(), gone["empty"].as_str()), (0, Some("No drafts.")));}/// RULE: a draft with no one to go to, or an address that is not one, is refused in plain words.#[test]fn a_draft_without_a_proper_address_is_refused_plainly() {    let (_dir, handle) = comms_phone();    let refused = over(&handle.client(), "chat.mail.save", &json!({ "to": [], "body": "Hi" })).unwrap_err();    assert_eq!((refused.code.as_str(), refused.message.as_str()), ("no_recipient", "Add who this mail is to."));    let refused = over(&handle.client(), "chat.mail.save", &json!({ "to": "asha@invented.example, ravi at home", "body": "Hi" })).unwrap_err();    assert_eq!((refused.code.as_str(), refused.message.as_str()), ("bad_address", "“ravi” isn't an email address."));}/// Seen on the dev server (22 Nov 2026): of 110,000 invented emails written by 40 phones side by side, 40 were/// refused for good, "email.thread_id names no email_thread", each one email of a phone's last write while its/// conversation was taken. The object takes an email only once its conversation is there, and the queue goes up in/// the order it was written: every email of a write is queued after its conversation.#[test]fn invented_mail_queues_each_conversation_before_its_mail() {    let dir = tempfile::tempdir().unwrap();    let dev = comms(&dir, cotton_core::flavor::Flavor::Dev);    let ask = json!({ "me": { "address": ME }, "generate": { "emails": 750, "threads": 600, "from": 0, "total": 750, "step": 60, "end": "2026-11-21T09:00:00Z" } });    crate::methods::dispatch(&dev, "developer.inventMail", &ask).expect("invented");    // Each row's stamp is the one its write goes up under, and the queue goes up in stamp order.    let found = crate::phone::cotton_chat::read(&dev.client(), "test.order", |ctx| {        let params = [super::ws(ctx)];        let all = super::rows(ctx, "SELECT COUNT(*) AS n FROM cotton_emails WHERE workspace_id = ?", &params)?;        let early = super::rows(            ctx,            "SELECT e.id, e._hlc AS email, t._hlc AS thread FROM cotton_emails e JOIN cotton_email_threads t ON t.id = e.thread_id WHERE e.workspace_id = ? AND e._hlc < t._hlc ORDER BY e._hlc",            &params,        )?;        Ok(json!({ "all": all, "early": early }))    })    .unwrap();    assert_eq!(found["all"][0]["n"].as_i64(), Some(750), "{found}");    let early = found["early"].as_array().unwrap();    assert!(early.is_empty(), "{} of 750 emails go up before their conversation: {:?}", early.len(), &early[..early.len().min(3)]);}/// A file the object hands over when asked, as the bucket would.#[derive(Debug)]struct Delivers(Vec<u8>);impl crate::phone::media::MediaFetch for Delivers {    fn fetch_to(&self, _database: &str, _key: &str, dest: &std::path::Path) -> Result<(), crate::phone::media::NotFetched> {        std::fs::write(dest, &self.0).map_err(|error| error.to_string().into())    }}/// A fetch that must not happen: the test fails if it is asked.#[derive(Debug)]struct NeverAsked;impl crate::phone::media::MediaFetch for NeverAsked {    fn fetch_to(&self, _database: &str, key: &str, _dest: &std::path::Path) -> Result<(), crate::phone::media::NotFetched> {        panic!("{key} was fetched with no network");    }}/// Seen on emulator-5554 (22 Nov 2026, Comms on an invented account): Ada's PDF, opened from her mail, counted in You →/// Storage's "Photos and files", and Free up space said "Nothing to free up". An attachment opened here is the/// person's own file the object holds: Storage frees it, and the mail no longer marks it kept.#[test]fn an_opened_attachment_is_freed_from_storage() {    let (dir, handle) = comms_phone();    asha(&handle);    let key = crate::phone::cotton_chat::read(&handle.client(), "test.key", |ctx| Ok(json!(cotton_core::media::keys::document_original_key(ctx.file.id(), "plan-0", "pdf")))).unwrap();    let key = key.as_str().unwrap().to_string();    let pdf = b"%PDF-1.4 an invented plan".to_vec();    email(&handle, "e-plan", "et-plan", (ASHA, "Asha Example"), ME, "The plan", "Attached.", &iso(30), false, json!([{ "name": "plan.pdf", "mime": "application/pdf", "size": pdf.len(), "key": key }]));    handle.client().set_media_fetch(Some(std::sync::Arc::new(Delivers(pdf.clone()))));    let storage = |h: &CottonHandle| crate::methods::dispatch(h, "shell.settings", &json!({"commit": "abc1234"})).expect("shell.settings")["storage"].clone();    assert_eq!(storage(&handle)["free_up"]["bytes"], 0, "nothing opened yet");    let opened = answer(&handle, "chat.mail.file", json!({ "email": "e-plan", "index": 0, "dir": dir.path().join("open").to_string_lossy() }));    assert!(std::fs::read(opened["path"].as_str().unwrap()).unwrap().starts_with(b"%PDF"));    // Comms' own viewer draws it (owner, 24 Nov 2026): a PDF page by page.    assert_eq!(opened["view"], "pdf");    assert_eq!(answer(&handle, "chat.mail.thread", json!({ "thread": "et-plan" }))["messages"][0]["attachments"][0]["kept"], true);    let before = storage(&handle);    assert_eq!(before["free_up"]["bytes"], pdf.len(), "the opened PDF is offered to Free up space: {before}");    let freed = crate::methods::dispatch(&handle, "shell.freeUp", &json!({"expected": pdf.len()})).expect("freed");    assert_eq!(freed["freed_bytes"], pdf.len(), "{freed}");    assert_eq!(storage(&handle)["free_up"]["bytes"], 0);    assert_eq!(answer(&handle, "chat.mail.thread", json!({ "thread": "et-plan" }))["messages"][0]["attachments"][0]["kept"], false, "no longer on this phone");    // With no network, one not on the phone is said at once, without asking; one on the phone still opens.    handle.client().set_media_fetch(Some(std::sync::Arc::new(NeverAsked)));    let offline = over(&handle.client(), "chat.mail.file", &json!({ "email": "e-plan", "index": 0, "dir": dir.path().join("open").to_string_lossy(), "online": false })).unwrap_err();    assert_eq!((offline.code.as_str(), offline.message.as_str()), ("file_offline", "Connect to the internet to open this attachment."));    handle.client().set_media_fetch(Some(std::sync::Arc::new(Delivers(pdf.clone()))));    // Opened again, it comes back.    answer(&handle, "chat.mail.file", json!({ "email": "e-plan", "index": 0, "dir": dir.path().join("open").to_string_lossy() }));    assert_eq!(answer(&handle, "chat.mail.thread", json!({ "thread": "et-plan" }))["messages"][0]["attachments"][0]["kept"], true);    handle.client().set_media_fetch(Some(std::sync::Arc::new(NeverAsked)));    let kept = answer(&handle, "chat.mail.file", json!({ "email": "e-plan", "index": 0, "dir": dir.path().join("open").to_string_lossy(), "online": false }));    assert!(std::fs::read(kept["path"].as_str().unwrap()).unwrap().starts_with(b"%PDF"), "on the phone, it opens offline");}/// Seen on emulator-5554 (22 Nov 2026): a new mail to Ada Invented's address, saved, stood in Drafts as "ada". A draft/// to someone in People is named as People names them; an address no one holds keeps its own first part.#[test]fn a_draft_is_named_as_people_name_whom_it_goes_to() {    let (_dir, handle) = comms_phone();    asha(&handle);    mailbox(&handle);    answer(&handle, "chat.mail.save", json!({ "to": ASHA.to_uppercase(), "subject": "Ferry times", "body": "Shall we take the early ferry?" }));    answer(&handle, "chat.mail.save", json!({ "to": "nobody@else.invented", "subject": "Hello" }));    let drafts = answer(&handle, "chat.mail", json!({ "filter": "drafts" }));    let names: std::collections::HashSet<&str> = drafts["rows"].as_array().unwrap().iter().map(|r| r["from"]["name"].as_str().unwrap()).collect();    assert_eq!(names, ["Asha Example", "nobody"].into_iter().collect(), "{drafts}");}/// Seen on emulator-5554 (22 Nov 2026, Comms at the largest text): a chat a year old said "Tue 18 Nov 2025" in the/// Chats list, squeezing its name and its last line. A list says only the month and year of a day outside the/// reader's year; the Mail tab's rows the same.#[test]fn a_list_says_an_item_of_another_year_by_its_month() {    let (_dir, handle) = phone();    asha(&handle);    let year_ago = iso(400 * 24 * 60);    let ws = workspace(&handle);    sql(&handle, "UPDATE cotton_msg_threads SET last_message_at = ? WHERE workspace_id = ?", &[t(&year_ago), t(&ws)]);    sql(&handle, "UPDATE cotton_msg_messages SET sent_at = ?, created_at = ? WHERE workspace_id = ?", &[t(&year_ago), t(&year_ago), t(&ws)]);    email(&handle, "e-old", "et-old", ("ravi.k@elsewhere.invented", "Ravi K"), ME, "Long ago", "From last year.", &year_ago, false, json!([]));    let at = chrono::Utc::now() - chrono::Duration::minutes(400 * 24 * 60);    let said = format!("{} {}", at.format("%b"), at.format("%Y"));    let chats = answer(&handle, "chat.list", json!({}));    assert_eq!(chats["rows"][0]["when"], json!(said), "{chats}");    let mail = answer(&handle, "chat.mail", json!({}));    assert_eq!(mail["rows"][0]["when"], json!(said), "{mail}");}/// Seen on emulator-5554 (22 Nov 2026, Comms on an invented account): with the Drafts chip on, searching for the/// lake trip, which stands in Ada's chat, found only drafts. A search reads every mail, wherever it is drawn and/// whatever chip stands on, with the drafts its words find first; what it finds opens.#[test]fn a_search_finds_every_mail_whatever_chip_stands_on() {    let (_dir, handle) = comms_phone();    asha(&handle);    mailbox(&handle);    answer(&handle, "chat.mail.save", json!({ "to": ASHA, "subject": "Ferry times", "body": "Shall we take the early ferry?" }));    for filter in ["all", "people", "unread", "drafts"] {        let found = answer(&handle, "chat.mail", json!({ "filter": filter, "text": "Saturday" }));        assert_eq!(subjects(&found), ["The lake trip"], "{filter}: {found}");        let opened = answer(&handle, "chat.mail.thread", json!({ "thread": found["rows"][0]["thread"] }));        assert_eq!(opened["messages"][0]["text"], "Here is the plan for Saturday.", "{filter}: {opened}");        let draft = answer(&handle, "chat.mail", json!({ "filter": filter, "text": "ferry" }));        assert_eq!(subjects(&draft), ["Ferry times"], "{filter}: {draft}");        assert!(draft["rows"][0]["draft"].is_string(), "{filter}: the draft opens in the writer: {draft}");        assert_eq!(subjects(&answer(&handle, "chat.mail", json!({ "filter": filter, "text": "asha" })))[0], "Ferry times", "{filter}: by whom it goes to");    }}/// RULE (COMMS WITHOUT MAIL, mail CONTRACT row 21): Mail is Cotton Post's. Comms' places are Chats, Calls and You/// whatever the copy holds, and a chat weaves no mail among its messages, even for a shell that asks (`mail: true`)./// The mail itself stays in the copy, untouched: Post reads it there.#[test]fn comms_has_no_mail_place_and_weaves_no_mail_even_with_mail_held() {    let (_dir, handle) = phone();    asha(&handle);    mailbox(&handle);    let ids = |answer: &Value| answer["places"].as_array().unwrap().iter().map(|p| p["id"].as_str().unwrap().to_string()).collect::<Vec<_>>();    let list = answer(&handle, "chat.list", json!({}));    assert_eq!(ids(&list), vec!["chats", "calls", "you"], "{list}");    assert_eq!(list["places"][0]["label"], "Chats");    let asked = answer(&handle, "chat.thread", json!({ "thread": ASHA_CHAT, "mail": true }));    assert!(asked["items"].as_array().unwrap().iter().all(|i| i["item"] != "mail"), "no mail woven: {asked}");    let held = handle.client().with_file(|file| file.driver.get("SELECT COUNT(*) AS n FROM cotton_emails WHERE id = 'e-asha-1'", &[]).map_err(|error| error.to_string())).unwrap();    assert_eq!(held.and_then(|row| row.int("n")), Some(1), "her mail is still in the copy, for Post");}// ── Sending from the person's own domain (OWN-MAIL.md "Sending") ───────────────────────────────────────────────────fn mail_door(handle: &CottonHandle, replies: impl IntoIterator<Item = cotton_client::transport::scripted::Reply>) -> std::sync::Arc<cotton_client::transport::scripted::ScriptedExchange> {    let exchange = cotton_client::transport::scripted::ScriptedExchange::new(replies);    let door = crate::phone::personal_object::ObjectDoor {        address: cotton_client::transport::object::ObjectAddress::open("https://cottondb.example.test").expect("an address"),        exchange: exchange.clone(),        credential: "ctd_11111111-1111-4111-8111-111111111111_test-credential".to_string(),    };    handle.client().set_object_door(Some(std::sync::Arc::new(door)));    exchange}fn sending_settings(sending: bool) -> cotton_client::transport::scripted::Reply {    cotton_client::transport::scripted::Reply::ok(        &json!({ "domains": [{ "domain": "invented.example", "proved": true }], "addresses": [{ "address": ME, "isDefault": true, "forwardTo": null }], "sending": sending }).to_string(),    )}fn reply_draft(handle: &CottonHandle) -> String {    let form = answer(handle, "chat.mail.compose", json!({ "thread": "et-trip" }));    let saved = answer(handle, "chat.mail.save", json!({ "to": form["to"], "subject": form["subject"], "body": "Saturday works.", "thread": "et-trip", "replyTo": form["replyTo"], "quoted": form["quoted"] }));    saved["draft"].as_str().unwrap().to_string()}fn draft_status(handle: &CottonHandle, draft: &str) -> (Option<String>, Option<String>) {    let row = crate::phone::cotton_chat::read(&handle.client(), "test.draft", |ctx| {        let listed = cotton_tools::mcp::handlers::tables::list_records(ctx, json!({ "table": "email_draft", "where": {}, "limit": 50 }).as_object().unwrap()).map_err(|e| e.to_string())?;        Ok(listed["records"].as_array().unwrap().iter().find(|r| r["id"] == draft).map(|r| r["data"].clone()).unwrap_or(Value::Null))    })    .unwrap();    (row["status"].as_str().map(str::to_string), row["error"].as_str().map(str::to_string))}/// RULE: Send hands the draft to the object once, from the person's own address, as a reply to the mail it answers;/// the draft then says Sent and a second tap sends nothing more.#[test]fn a_draft_is_sent_from_the_persons_own_address_once() {    let (_dir, handle) = comms_phone();    asha(&handle);    mailbox(&handle);    let draft = reply_draft(&handle);    let exchange = mail_door(&handle, [sending_settings(true), cotton_client::transport::scripted::Reply::ok(&json!({ "draft": draft, "state": "sent", "messageId": "<cf-1@invented.example>", "email": "sent-email-1" }).to_string())]);    let sent = answer(&handle, "chat.mail.send", json!({ "draft": draft }));    assert_eq!((sent["state"].as_str(), sent["said"].as_str(), sent["email"].as_str()), (Some("sent"), Some("Sent."), Some("sent-email-1")));    let ask: Value = serde_json::from_slice(&exchange.nth(1).body).unwrap();    assert_eq!(exchange.nth(1).path, "/v1/mail/send");    assert_eq!((ask["from"].as_str(), ask["to"].clone(), ask["thread"].as_str()), (Some(ME), json!([ASHA]), Some("et-trip")));    assert_eq!(ask["subject"], "Re: The lake trip");    assert!(ask["text"].as_str().unwrap().starts_with("Saturday works.\n\nOn "), "the quote goes under the words: {ask}");    assert_eq!(draft_status(&handle, &draft).0.as_deref(), Some("sent"));    assert_eq!(answer(&handle, "chat.mail", json!({ "filter": "drafts" }))["rows"].as_array().unwrap().len(), 0, "a sent draft leaves Drafts");    let again = answer(&handle, "chat.mail.send", json!({ "draft": draft }));    assert_eq!(again["state"], "sent");    assert_eq!(exchange.calls(), 2, "a sent draft asks nothing more");}/// RULE: with no address of their own set up for sending, Send is refused in words and nothing goes.#[test]fn send_is_refused_where_sending_is_not_set_up() {    let (_dir, handle) = comms_phone();    asha(&handle);    mailbox(&handle);    let draft = reply_draft(&handle);    let exchange = mail_door(&handle, [sending_settings(false)]);    let refused = over(&handle.client(), "chat.mail.send", &json!({ "draft": draft })).unwrap_err();    assert_eq!((refused.code.as_str(), refused.message.as_str()), ("no_sender", "Sending from Comms needs your own domain, set up in You › Mail."));    assert_eq!(exchange.calls(), 1);    handle.client().set_object_door(None);    let offline = over(&handle.client(), "chat.mail.send", &json!({ "draft": draft })).unwrap_err();    assert_eq!((offline.code.as_str(), offline.message.as_str()), ("offline", "You're offline. Nothing was sent."));    assert_eq!(draft_status(&handle, &draft).0.as_deref(), Some("draft"), "a refused send leaves the draft a draft");}/// RULE: a send Cloudflare refused says why on the draft, and Retry (the same call, the person's own tap) sends it.#[test]fn a_refused_send_says_why_and_retry_sends_it() {    let (_dir, handle) = comms_phone();    asha(&handle);    mailbox(&handle);    let draft = reply_draft(&handle);    let refused = json!({ "draft": draft, "state": "failed", "code": "E_DAILY_LIMIT_EXCEEDED", "said": "Too much mail has gone from here today. Try again later." });    let sent = json!({ "draft": draft, "state": "sent", "messageId": "<cf-2@invented.example>" });    use cotton_client::transport::scripted::Reply;    mail_door(&handle, [sending_settings(true), Reply::ok(&refused.to_string()), sending_settings(true), Reply::ok(&sent.to_string())]);    let first = answer(&handle, "chat.mail.send", json!({ "draft": draft }));    assert_eq!((first["state"].as_str(), first["said"].as_str()), (Some("failed"), Some("Not sent: Too much mail has gone from here today. Try again later.")));    assert_eq!(draft_status(&handle, &draft), (Some("failed".into()), Some("Too much mail has gone from here today. Try again later.".into())));    assert_eq!(answer(&handle, "chat.mail.send", json!({ "draft": draft }))["state"], "sent");    assert_eq!(draft_status(&handle, &draft).0.as_deref(), Some("sent"));}/// RULE (OWN-MAIL.md): the Sent chip holds the conversations the person wrote in, and stands only once there are any.#[test]fn the_sent_chip_holds_what_the_person_wrote() {    let (_dir, handle) = comms_phone();    mailbox(&handle);    let sent = answer(&handle, "chat.mail", json!({ "filter": "sent" }));    let threads: Vec<&str> = sent["rows"].as_array().unwrap().iter().filter_map(|r| r["thread"].as_str()).collect();    assert_eq!(threads, vec!["et-trip"], "{sent}");    assert!(sent["filters"].as_array().unwrap().iter().any(|f| f["id"] == "sent" && f["label"] == "Sent" && f["on"] == true));}fn fail(handle: &CottonHandle, method: &str, request: Value) -> crate::methods::MethodError {    over(&handle.client(), method, &request).expect_err(method)}/// The Mac's answer to the newest mail row of the outbox about `address`, as its drain writes it (cotton-mac/// src/mail/trash.rs).fn mac_answers(handle: &CottonHandle, kind: &str, patch: Value) {    let ws = workspace(handle);    let id = crate::phone::cotton_chat::read(&handle.client(), "test.outbox", |ctx| {        let rows = crate::phone::cotton_chat::rows(ctx, "SELECT id FROM cotton_outbox WHERE workspace_id = ? AND kind = ? ORDER BY created_at DESC, rowid DESC LIMIT 1", &[SqlValue::Text(ctx.workspace_id.to_string()), t(kind)])?;        Ok(json!(rows[0]["id"]))    })    .unwrap();    for (key, value) in patch.as_object().unwrap() {        let value = match value {            Value::String(s) => t(s),            Value::Number(n) => SqlValue::Integer(n.as_i64().unwrap()),            _ => SqlValue::Null,        };        sql(handle, &format!("UPDATE cotton_outbox SET \"{key}\" = ? WHERE id = ? AND workspace_id = ?"), &[value, t(id.as_str().unwrap()), t(&ws)]);    }}/// RULE (coordinator, 23 Nov 2026): the owner moves all of a sender's mail to Trash from the phone: the Mac counts/// first, he sees the number, and the move carries what that count fixed; each step reads in plain words.#[test]fn a_senders_mail_goes_to_trash_after_a_count_the_owner_sees() {    let (_dir, handle) = comms_phone();    mailbox(&handle);    let shop = "news@paper.invented";    // Senders 3: the Senders tab no longer offers it (Delete everything moves their mail to Trash too); the Mac's    // count-first move below stands for the phones that still ask it.    let page = answer(&handle, "chat.mail.sender", json!({ "address": " News@Paper.Invented " }));    assert_eq!(page["address"], shop);    assert_eq!(page["trash"], json!({ "line": null, "act": { "id": "count", "label": "Move all their mail to Trash" } }));    assert_eq!(fail(&handle, "chat.mail.trashSender", json!({ "address": shop })).code, "not_counted");    let asked = answer(&handle, "chat.mail.countSender", json!({ "address": shop }));    assert_eq!(asked["trash"], json!({ "line": "Your Mac is counting their mail…" }));    let ws = workspace(&handle);    let queued = crate::phone::cotton_chat::read(&handle.client(), "test.outbox", |ctx| {        Ok(json!(crate::phone::cotton_chat::rows(ctx, "SELECT channel, kind, \"to\", status FROM cotton_outbox WHERE workspace_id = ?", &[SqlValue::Text(ctx.workspace_id.to_string())])?))    })    .unwrap();    assert_eq!(queued, json!([{ "channel": "mail", "kind": "sender_count", "to": shop, "status": "queued" }]), "{ws}");    mac_answers(&handle, "sender_count", json!({ "status": "sent", "count": 1204, "uid_validity": 42, "uid_below": 9000 }));    let counted = answer(&handle, "chat.mail.sender", json!({ "address": shop }));    assert_eq!(counted["trash"], json!({ "line": "1204 emails from news@paper.invented", "act": { "id": "confirm", "label": "Move 1204 emails to Trash" } }));    let moving = answer(&handle, "chat.mail.trashSender", json!({ "address": shop }));    assert_eq!(moving["trash"]["line"], "1204 emails will go to Trash when your Mac is on");    let held = crate::phone::cotton_chat::read(&handle.client(), "test.outbox", |ctx| {        Ok(json!(crate::phone::cotton_chat::rows(ctx, "SELECT \"to\", count, uid_validity, uid_below, moved, status FROM cotton_outbox WHERE workspace_id = ? AND kind = 'sender_trash'", &[SqlValue::Text(ctx.workspace_id.to_string())])?))    })    .unwrap();    assert_eq!(held, json!([{ "to": shop, "count": 1204, "uid_validity": 42, "uid_below": 9000, "moved": 0, "status": "queued" }]));    mac_answers(&handle, "sender_trash", json!({ "status": "sending", "moved": 400 }));    assert_eq!(answer(&handle, "chat.mail.sender", json!({ "address": shop }))["trash"]["line"], "Moving to Trash: 400 of 1204");    mac_answers(&handle, "sender_trash", json!({ "status": "sent", "moved": 1204 }));    let done = answer(&handle, "chat.mail.sender", json!({ "address": shop }));    assert_eq!(done["trash"], json!({ "line": "Moved 1204 emails to Trash. You can take them back from Trash in your mail account until Trash is emptied." }));    // A count of none offers no move; a failure says why and offers a count again.    answer(&handle, "chat.mail.countSender", json!({ "address": "ravi.k@elsewhere.invented" }));    mac_answers(&handle, "sender_count", json!({ "status": "sent", "count": 0, "uid_validity": 42, "uid_below": 9000 }));    assert_eq!(fail(&handle, "chat.mail.trashSender", json!({ "address": "ravi.k@elsewhere.invented" })).code, "nothing_to_move");    answer(&handle, "chat.mail.countSender", json!({ "address": "receipts@shop.invented" }));    mac_answers(&handle, "sender_count", json!({ "status": "failed", "error": "This mail server can't move mail without erasing it, so nothing was moved." }));    let failed = answer(&handle, "chat.mail.sender", json!({ "address": "receipts@shop.invented" }));    assert_eq!(failed["trash"]["line"], "Not moved: This mail server can't move mail without erasing it, so nothing was moved.");    assert_eq!(failed["trash"]["act"]["id"], "count");    assert_eq!(fail(&handle, "chat.mail.countSender", json!({ "address": "not an address" })).code, "bad_address");}/// RULE (seen on emulator-5612, 24 Nov 2026): a Worker not yet deployed with the `mail` channel serves the outbox of/// before; there People offers no Move to Trash, the sheet offers nothing to ask, and a count asked anyway is refused/// in words, never as the definition's own refusal.#[test]fn an_outbox_of_before_offers_no_mail_to_trash() {    let (_dir, handle) = comms_phone();    mailbox(&handle);    let ws = workspace(&handle);    let held = handle.client().with_writer(|replica| replica.driver.all("SELECT definition FROM cotton_table_definitions WHERE workspace_id = ? AND id = 'outbox'", &[t(&ws)]).map_err(|e| e.to_string())).unwrap();    let mut before: Value = serde_json::from_str(held[0].text("definition").unwrap()).unwrap();    for column in before["columns"].as_array_mut().unwrap() {        if column["key"] == "channel" {            column["choices"] = json!(["whatsapp", "instagram"]);        }    }    sql(&handle, "UPDATE cotton_table_definitions SET definition = ? WHERE workspace_id = ? AND id = 'outbox'", &[t(&before.to_string()), t(&ws)]);    let people = answer(&handle, "chat.senders", json!({ "filter": "mail" }));    let row = people["rows"].as_array().unwrap().iter().find(|r| r["key"] == "news@paper.invented").unwrap();    assert!(row["hold"].as_array().unwrap().iter().all(|a| a["id"] != "trash"), "{row}");    let page = answer(&handle, "chat.mail.sender", json!({ "address": "news@paper.invented" }));    assert_eq!(page["trash"]["act"]["id"], "count", "the sheet still draws, from nothing asked");    let refused = fail(&handle, "chat.mail.countSender", json!({ "address": "news@paper.invented" }));    assert_eq!(refused.message, "Moving mail to Trash isn't available on this phone yet.");}/// RULE (SENDERS.md "DECIDED: Senders 3"): the Mail tab's chips are All, People, Notices, Promotions, Unread and Sent./// A receipt is a Notice; a paper with a List-Unsubscribe header the Mac kept is Promotions; the stranger who writes/// as a person is People. Every rule, no AI.#[test]fn mail_falls_into_people_notices_and_promotions() {    let (_dir, handle) = phone();    asha(&handle);    with_headers(&handle);    mailbox(&handle);    sql(&handle, "UPDATE cotton_emails SET list_unsubscribe = '<https://paper.invented/u>', precedence = 'bulk' WHERE id = 'e-news'", &[]);    let mail = answer(&handle, "chat.mail", json!({}));    let chips: Vec<&str> = mail["filters"].as_array().unwrap().iter().filter_map(|f| f["id"].as_str()).collect();    assert_eq!(chips, ["all", "people", "notices", "promotions", "unread", "sent"]);    assert_eq!(mail["filters"][2]["label"], "Notices");    assert_eq!(subjects(&answer(&handle, "chat.mail", json!({ "filter": "people" }))), ["Hello"]);    assert_eq!(subjects(&answer(&handle, "chat.mail", json!({ "filter": "notices" }))), ["Your receipt"]);    assert_eq!(subjects(&answer(&handle, "chat.mail", json!({ "filter": "promotions" }))), ["This week"]);    // Without the header (mail the Mac read before it kept headers), the paper's plain "Five stories." says nothing    // of marketing: an automatic message, a Notice.    sql(&handle, "UPDATE cotton_emails SET list_unsubscribe = NULL, precedence = NULL WHERE id = 'e-news'", &[]);    assert_eq!(subjects(&answer(&handle, "chat.mail", json!({ "filter": "notices" }))), ["This week", "Your receipt"]);    let empty = answer(&handle, "chat.mail", json!({ "filter": "promotions" }));    assert_eq!(empty["empty"], "No promotions.");}/// The mail rows of the outbox, as (kind, target, to, account, status).fn mail_rows(handle: &CottonHandle) -> Vec<(String, String, String, String, String)> {    let found = crate::phone::cotton_chat::read(&handle.client(), "test.outbox", |ctx| {        Ok(json!(crate::phone::cotton_chat::rows(ctx, "SELECT kind, target, \"to\", account, status FROM cotton_outbox WHERE workspace_id = ? AND channel = 'mail' ORDER BY created_at, rowid", &[SqlValue::Text(ctx.workspace_id.to_string())])?))    })    .unwrap();    let text = |r: &Value, k: &str| r[k].as_str().unwrap_or_default().to_string();    found.as_array().unwrap().iter().map(|r| (text(r, "kind"), text(r, "target"), text(r, "to"), text(r, "account"), text(r, "status"))).collect()}/// RULE (SENDERS.md "On any mail"): a mail's long-press offers read or unread, Archive, Unsubscribe only when the/// mail offers it, and Block; each changes the mail here at once and files one row for the Mac to do the same in his/// mailbox (CONTRACT "Senders 3"): mark_read, mark_unread, archive, unsubscribe (to the sender).#[test]fn a_mails_acts_change_it_here_and_go_to_the_mac() {    let (_dir, handle) = comms_phone();    with_headers(&handle);    mailbox(&handle);    sql(&handle, "UPDATE cotton_emails SET list_unsubscribe = '<https://paper.invented/u>' WHERE id = 'e-news'", &[]);    let hold = answer(&handle, "chat.mail.hold", json!({ "email": "e-shop" }));    let ids: Vec<&str> = hold["acts"].as_array().unwrap().iter().filter_map(|a| a["id"].as_str()).collect();    assert_eq!(ids, ["read", "archive", "delete", "delete_sender", "block", "sender"], "the receipt is unread and offers no unsubscribe: {hold}");    assert_eq!(hold["acts"][3]["label"], "Delete all from Invented Shop");    let news: Vec<String> = answer(&handle, "chat.mail.hold", json!({ "email": "e-news" }))["acts"].as_array().unwrap().iter().filter_map(|a| a["id"].as_str().map(str::to_string)).collect();    assert_eq!(news, ["unread", "archive", "delete", "delete_sender", "unsubscribe", "block", "sender"]);    // A conversation he answered last opens the other's page, never his own (look-ios on Comms Dev's seed).    let trip = answer(&handle, "chat.mail.hold", json!({ "thread": "et-trip" }));    assert_eq!(trip["acts"].as_array().unwrap().last().unwrap()["open"], json!({ "sender": ASHA }), "{trip}");    assert_eq!(answer(&handle, "chat.mail.act", json!({ "email": "e-shop", "act": "read" }))["said"], "Marked read. Your Mac marks it read in your mail next.");    assert!(subjects(&answer(&handle, "chat.mail", json!({ "filter": "unread" }))).iter().all(|s| s != "Your receipt"));    answer(&handle, "chat.mail.act", json!({ "email": "e-shop", "act": "unread" }));    assert_eq!(answer(&handle, "chat.mail.act", json!({ "email": "e-shop", "act": "archive" }))["said"], "Archived in Comms. Your Mac archives it in your mail next.");    assert!(!subjects(&answer(&handle, "chat.mail", json!({}))).contains(&"Your receipt".to_string()), "archived is out of every list");    assert_eq!(answer(&handle, "chat.mail.act", json!({ "email": "e-news", "act": "unsubscribe" }))["said"], "Unsubscribing from The Invented Paper…");    let refused = fail(&handle, "chat.mail.act", json!({ "email": "e-shop", "act": "unsubscribe" }));    assert!(refused.message.contains("This email offers no way to unsubscribe."), "{}", refused.message);    let rows: Vec<(String, String, String, String)> = mail_rows(&handle).into_iter().map(|(k, t, to, a, s)| (k, t, to, s + &if a == ME { "" } else { "?" }.to_string())).collect();    assert_eq!(        rows,        [            ("mark_read".to_string(), "x-e-shop".to_string(), "receipts@shop.invented".to_string(), "queued".to_string()),            ("mark_unread".to_string(), "x-e-shop".to_string(), "receipts@shop.invented".to_string(), "queued".to_string()),            ("archive".to_string(), "x-e-shop".to_string(), "receipts@shop.invented".to_string(), "queued".to_string()),            ("unsubscribe".to_string(), "x-e-news".to_string(), "news@paper.invented".to_string(), "queued".to_string()),        ]    );    // Block is People's: the sender is blocked, and their mail goes from the list.    answer(&handle, "chat.mail.act", json!({ "email": "e-news", "act": "block" }));    assert!(!subjects(&answer(&handle, "chat.mail", json!({}))).contains(&"This week".to_string()));}/// RULE (CONTRACT "A mail's page and files, brought when he opens it"): a file the Mac never brought asks the Mac to/// bring the mail's page and files, once, and he is told it is coming; asking again files nothing more.#[test]fn a_file_not_brought_asks_the_mac_once_and_says_it_is_coming() {    let (dir, handle) = comms_phone();    with_headers(&handle);    mailbox(&handle);    let open = json!({ "email": "e-asha-1", "index": 0, "dir": dir.path().join("open").to_string_lossy() });    for _ in 0..2 {        let coming = fail(&handle, "chat.mail.file", open.clone());        assert_eq!((coming.code.as_str(), coming.message.as_str()), ("file_coming", "Your Mac is bringing this from your mailbox. Try again in a moment."));    }    let rows: Vec<(String, String, String)> = mail_rows(&handle).into_iter().map(|(k, t, _, _, s)| (k, t, s)).collect();    assert_eq!(rows, [("mail_page".to_string(), "x-e-asha-1".to_string(), "queued".to_string())]);    // His Mac brought the mail, and this file was over what it keeps: it stays in the mailbox, asked no more.    sql(&handle, "UPDATE cotton_outbox SET status = 'sent' WHERE kind = 'mail_page'", &[]);    let stays = fail(&handle, "chat.mail.file", open.clone());    assert_eq!((stays.code.as_str(), stays.message.as_str()), ("not_kept", "This attachment stays in your mailbox. Open it there."));    // Or it refused the mail: its own words, and still asked no more (launch-ios: no refiling on every tap).    sql(&handle, "UPDATE cotton_outbox SET status = 'failed', error = 'This email is too large to bring. Open it in your mail.' WHERE kind = 'mail_page'", &[]);    let refused = fail(&handle, "chat.mail.file", open);    assert_eq!((refused.code.as_str(), refused.message.as_str()), ("not_kept", "This email is too large to bring. Open it in your mail."));    assert_eq!(mail_rows(&handle).len(), 1, "answered once, asked no more");}/// RULE (CONTRACT "A mail's page and files", the designed page): `chat.mail.page` asks his Mac for the page once and/// says it is coming; a mail the Mac brought with no page is plain text (`{}`); a page brought lands here like a file,/// with the words of the control that loads its pictures.#[test]fn a_mails_own_page_is_asked_once_then_opens_as_it_was_sent() {    let (dir, handle) = comms_phone();    with_headers(&handle);    mailbox(&handle);    let open = json!({ "email": "e-asha-1", "dir": dir.path().join("pages").to_string_lossy() });    for _ in 0..2 {        assert_eq!(answer(&handle, "chat.mail.page", open.clone()), json!({ "coming": "Your Mac is bringing this email as it was sent." }));    }    let rows: Vec<(String, String, String)> = mail_rows(&handle).into_iter().map(|(k, t, _, _, s)| (k, t, s)).collect();    assert_eq!(rows, [("mail_page".to_string(), "x-e-asha-1".to_string(), "queued".to_string())]);    // The Mac brought it and found the mail written as plain text: the text is the mail, and nothing is asked again.    sql(&handle, "UPDATE cotton_outbox SET status = 'sent' WHERE kind = 'mail_page'", &[]);    assert_eq!(answer(&handle, "chat.mail.page", open.clone()), json!({}));    assert_eq!(mail_rows(&handle).len(), 1);    // A page brought: landed here as `page.html`, pictures from the web left to his tap.    let key = crate::phone::cotton_chat::read(&handle.client(), "test.key", |ctx| Ok(json!(cotton_core::media::keys::document_original_key(ctx.file.id(), "page-asha", "html")))).unwrap();    let html = b"<html><body><h1>An invented letter</h1><img src=\"https://pictures.invented/a.png\"></body></html>".to_vec();    let media = json!([{ "key": key, "contentType": "text/html", "size": html.len(), "name": "page.html" }]);    sql(&handle, "UPDATE cotton_emails SET media = ? WHERE id = 'e-asha-1'", &[SqlValue::Text(media.to_string())]);    handle.client().set_media_fetch(Some(std::sync::Arc::new(Delivers(html.clone()))));    let page = answer(&handle, "chat.mail.page", open);    assert!(page["path"].as_str().unwrap().ends_with("/page.html"), "{page}");    assert_eq!(std::fs::read(page["path"].as_str().unwrap()).unwrap(), html);    assert_eq!(page["pictures"], "Show pictures");}/// RULE (CONTRACT "A mail's page and files, brought when he opens it"; Mac 10 walk, 25 Nov 2026): Comms Dev's fake Mac/// answers `mail_page` as his Mac does, so the designed page and a file brought when opened can be walked on an/// emulator. Asked by opening the mail and by tapping a file it never brought, once; then the page stands, made of/// the mail's own subject and words with a picture from the web and a link, and the file opens. A mail written as/// plain text is its text, with nothing coming, and asking again sends the Mac nothing more.#[test]fn the_fake_mac_brings_a_mails_page_and_files_as_his_mac_does() {    let dir = tempfile::tempdir().unwrap();    let handle = comms(&dir, cotton_core::flavor::Flavor::Dev);    with_headers(&handle);    let asha = json!({ "address": ASHA, "name": "Asha Example" });    let invented = json!({ "me": { "address": ME }, "mail": [        { "thread": "letter", "subject": "The garden letter", "from": asha, "at": iso(90), "body": "Here is the plan.\n\nBring <boots>.", "brought": false, "attachments": [{ "name": "plan.pdf" }] },        { "id": "dev-mail-1", "thread": "plain", "subject": "Just words", "from": asha, "at": iso(60), "body": "Only text.", "plain": true },    ]});    crate::methods::dispatch(&handle, "developer.inventMail", &invented).expect("invented");    let mac = || crate::methods::dispatch(&handle, "developer.fakeMac", &json!({})).unwrap_or_else(|e| panic!("developer.fakeMac: {} {}", e.code, e.message));    let pages = dir.path().join("pages").to_string_lossy().to_string();    let open = |email: &str| json!({ "email": email, "dir": pages });    let tap = json!({ "email": "dev-mail-0", "index": 0, "dir": dir.path().join("open").to_string_lossy() });    // Never brought: the file is a name only, and its tap and the mail's page ask his Mac once between them.    let letter = answer(&handle, "chat.mail.thread", json!({ "thread": "dev-mail-thread-letter" }));    assert_eq!(letter["messages"][0]["attachments"][0]["can"], false, "{letter}");    assert_eq!(over(&handle.client(), "chat.mail.file", &tap).unwrap_err().code, "file_coming");    let coming = json!({ "coming": "Your Mac is bringing this email as it was sent." });    assert_eq!(answer(&handle, "chat.mail.page", open("dev-mail-0")), coming);    assert_eq!(answer(&handle, "chat.mail.page", open("dev-mail-1")), coming);    assert_eq!(mail_rows(&handle).iter().filter(|r| r.0 == "mail_page").count(), 2, "{:?}", mail_rows(&handle));    let answered = mac();    let mut said: Vec<(String, bool, u64)> = answered["answered"].as_array().unwrap().iter().filter(|a| a["kind"] == "mail_page").map(|a| (a["status"].as_str().unwrap().to_string(), a["page"].as_bool().unwrap(), a["files"].as_u64().unwrap())).collect();    said.sort();    assert_eq!(said, [("sent".to_string(), false, 0), ("sent".to_string(), true, 1)], "{answered}");    // The page as it was sent: its own subject and words, a picture left to his tap, a link.    let page = answer(&handle, "chat.mail.page", open("dev-mail-0"));    assert_eq!(page["pictures"], "Show pictures", "{page}");    let html = std::fs::read_to_string(page["path"].as_str().unwrap()).unwrap();    for part in ["<h1>The garden letter</h1>", "<p>Bring &lt;boots&gt;.</p>", "<img src=\"https://picsum.invented.example/a.png\"", "href=\"https://example.com/\""] {        assert!(html.contains(part), "{part} in {html}");    }    // The file it brought opens.    let opened = answer(&handle, "chat.mail.file", tap);    assert!(std::fs::read(opened["path"].as_str().unwrap()).unwrap().starts_with(b"%PDF-1.4"));    assert_eq!(opened["name"], "plan.pdf");    // Plain text: the text is the mail, and nothing more is asked of his Mac.    assert_eq!(answer(&handle, "chat.mail.page", open("dev-mail-1")), json!({}));    assert!(mac()["answered"].as_array().unwrap().iter().all(|a| a["kind"] != "mail_page"));}/// RULE (SENDERS.md "swipes everywhere"): a mail row swipes one act a side, right Read (or Unread) and left Archive,/// on the whole conversation; its long-press is the conversation's.#[test]fn a_mail_row_swipes_one_act_a_side_on_the_whole_conversation() {    let (_dir, handle) = comms_phone();    with_headers(&handle);    mailbox(&handle);    let row = |page: &Value, subject: &str| page["rows"].as_array().unwrap().iter().find(|r| r["subject"] == subject).cloned().unwrap_or_else(|| panic!("{page}"));    let shop = row(&answer(&handle, "chat.mail", json!({})), "Your receipt");    assert_eq!(shop["swipe"], json!({ "right": { "id": "read", "label": "Read" }, "left": { "id": "archive", "label": "Archive" } }));    let thread = shop["thread"].as_str().unwrap().to_string();    assert_eq!(answer(&handle, "chat.mail.hold", json!({ "thread": thread }))["acts"][0]["id"], "read");    answer(&handle, "chat.mail.act", json!({ "thread": thread, "act": "read" }));    assert_eq!(row(&answer(&handle, "chat.mail", json!({})), "Your receipt")["swipe"]["right"]["id"], "unread");    answer(&handle, "chat.mail.act", json!({ "thread": thread, "act": "archive" }));    assert!(answer(&handle, "chat.mail", json!({}))["rows"].as_array().unwrap().iter().all(|r| r["thread"] != thread.as_str()));    let kinds: Vec<String> = mail_rows(&handle).into_iter().map(|r| r.0).collect();    assert_eq!(kinds, ["mark_read", "archive"]);}/// ERASES. RULE (SENDERS.md "On any mail"): Delete on a mail erases it from Cotton on every device and asks the Mac to/// move it to Trash; Delete all from this sender asks first with the count, then erases everything from them and asks/// the Mac to move all their mail to Trash.#[test]fn a_mail_is_deleted_and_all_from_its_sender_after_the_count() {    let (_dir, handle) = comms_phone();    with_headers(&handle);    mailbox(&handle);    email(&handle, "e-shop-2", "et-shop-2", ("receipts@shop.invented", "Invented Shop"), ME, "Your second receipt", "Order 1235.", &iso(25), true, json!([]));    let gone = |id: &str| {        let found = crate::phone::cotton_chat::read(&handle.client(), "test.mail", |ctx| Ok(json!(crate::phone::cotton_chat::rows(ctx, "SELECT id FROM cotton_emails WHERE id = ?", &[t(id)])?.len()))).unwrap();        found == json!(0)    };    assert_eq!(answer(&handle, "chat.mail.act", json!({ "email": "e-news", "act": "delete" }))["said"], "Deleted in Comms. Your Mac moves it to Trash in your mail next.");    assert!(gone("e-news"), "erased, not hidden");    assert!(mail_rows(&handle).iter().any(|(kind, target, _, _, _)| kind == "trash" && target == "x-e-news"), "{:?}", mail_rows(&handle));    let asked = answer(&handle, "chat.mail.act", json!({ "email": "e-shop", "act": "delete_sender" }));    let ask = &asked["ask"];    assert_eq!((ask["title"].as_str(), ask["confirm"].as_str(), ask["count"].as_u64()), (Some("Delete everything from Invented Shop?"), Some("Delete 2"), Some(2)), "{asked}");    assert!(ask["line"].as_str().unwrap().ends_with("Your Mac hasn't counted your mail from them yet, so only the 2 emails here go to Trash there."), "{ask}");    assert_eq!(fail(&handle, "chat.mail.act", json!({ "email": "e-shop", "act": "delete_sender", "count": 1 })).code, "count_changed");    assert_eq!(answer(&handle, "chat.mail.act", json!({ "email": "e-shop", "act": "delete_sender", "count": 2 }))["said"], "Deleted 2 from Invented Shop in Comms. Your Mac moves their mail to Trash next.");    assert!(gone("e-shop") && gone("e-shop-2"));    // Not counted: only the two here, each by its own id (DELETE FAST).    assert!(["x-e-shop", "x-e-shop-2"].iter().all(|x| mail_rows(&handle).iter().any(|(kind, target, _, _, _)| kind == "trash" && target == x)), "{:?}", mail_rows(&handle));    assert!(!mail_rows(&handle).iter().any(|(kind, _, _, _, _)| kind == "sender_trash"), "{:?}", mail_rows(&handle));}/// RULE (SENDERS.md "While history arrives"; MAIL ALL ON PHONE): a quiet line says how far back his mail reaches and/// how many of how many are here, and why it stands when it does; with no history coming (as here, the switch off),/// Mail and Senders carry none.#[test]fn the_history_line_says_how_far_back_and_how_many() {    use crate::phone::mail_history::{History, Paused};    let lines = cotton_core::messages::app::list::lines();    let coming = super::history_words(&lines, &History { back_to: Some("2019-03".into()), held: 41_200, total: 111_422, paused: None });    assert_eq!(coming, json!({ "line": "Mail back to March 2019 · 41,200 of 111,422", "paused": null }));    let offline = super::history_words(&lines, &History { back_to: None, held: 0, total: 96_000, paused: Some(Paused::Offline) });    assert_eq!(offline, json!({ "line": "Mail coming in · 0 of 96,000", "paused": "Paused: this phone is offline" }));    // The Mac's walk: it stands when the Mac is away, and when the Mac stopped it at size.    let away = super::history_words(&lines, &History { back_to: Some("2015-03".into()), held: 41_200, total: 98_000, paused: Some(Paused::MacOffline) });    assert_eq!(away["paused"], "Paused: your Mac is asleep or offline");    let full = super::history_words(&lines, &History { back_to: Some("2015-03".into()), held: 41_200, total: 98_000, paused: Some(Paused::Mac("full".into())) });    assert_eq!(full["paused"], "Paused: your Cotton is nearly full");    let (_dir, handle) = comms_phone();    mailbox(&handle);    assert!(answer(&handle, "chat.mail", json!({}))["history"].is_null());    assert!(answer(&handle, "chat.senders", json!({}))["history"].is_null());}/// RULE (launch-ios, SITES 6): a page his Mac refused (too large, `failed`) is not asked again on every open, and a/// page landed here is counted with the opened files that You → Storage's Free up space takes.#[test]fn a_refused_page_is_not_asked_again_and_a_landed_one_is_freed_with_the_files() {    let (dir, handle) = comms_phone();    with_headers(&handle);    mailbox(&handle);    let ask = |id: &str| json!({ "email": id, "dir": dir.path().join("pages").to_string_lossy() });    assert!(answer(&handle, "chat.mail.page", ask("e-asha-1"))["coming"].is_string());    sql(&handle, "UPDATE cotton_outbox SET status = 'failed' WHERE kind = 'mail_page'", &[]);    assert_eq!(answer(&handle, "chat.mail.page", ask("e-asha-1")), json!({}));    assert_eq!(mail_rows(&handle).len(), 1, "refused once, asked no more");    let key = crate::phone::cotton_chat::read(&handle.client(), "test.key", |ctx| Ok(json!(cotton_core::media::keys::document_original_key(ctx.file.id(), "page-shop", "html")))).unwrap();    let html = b"<html><body><h1>An invented receipt</h1></body></html>".to_vec();    let media = json!([{ "key": key, "contentType": "text/html", "size": html.len(), "name": "page.html" }]);    sql(&handle, "UPDATE cotton_emails SET media = ? WHERE id = 'e-shop'", &[t(&media.to_string())]);    handle.client().set_media_fetch(Some(std::sync::Arc::new(Delivers(html.clone()))));    assert!(answer(&handle, "chat.mail.page", ask("e-shop"))["path"].is_string());    let storage = crate::methods::dispatch(&handle, "shell.settings", &json!({"commit": "abc1234"})).expect("shell.settings")["storage"].clone();    assert_eq!(storage["free_up"]["bytes"], html.len(), "the page is offered to Free up space: {storage}");}/// RULE (UNSENT HEAL walk, 26 Nov 2026): Cotton Dev can make two real changes the server refused, so the Sync page's/// Send again and Let go can be walked on a simulator's signed-in copy (the walk proves what a pass does with them);/// the real Cotton refuses it by name, and a local copy, which queues nothing to send, says so.#[test]fn a_stuck_change_is_invented_in_cotton_dev_only() {    let dir = tempfile::tempdir().unwrap();    let real = comms(&dir, cotton_core::flavor::Flavor::Real);    assert_eq!(crate::methods::dispatch(&real, "developer.stuckChange", &json!({})).unwrap_err().code, "not_dev");    drop(real);    let dir = tempfile::tempdir().unwrap();    let dev = comms(&dir, cotton_core::flavor::Flavor::Dev);    assert_eq!(crate::methods::dispatch(&dev, "developer.stuckChange", &json!({})).unwrap_err().code, "not_signed_in");    assert!(crate::methods::shell_account::sync_said(&dev.client())["stuck"].is_null(), "nothing invented is left behind");}