Cotton code
644 lines · 39.4 KB · RustRaw
//! The owner's acts on his mail from Comms (src/mail/acts.rs, drained by src/mail/trash.rs), against a fake IMAP//! server on this machine's loopback and an object inside the test that keeps the outbox. Every address, id and//! message is invented; no real account or sender is reached (the one-click POST is a recorded closure).mod support;use std::collections::BTreeMap;use std::io::{BufRead, BufReader, Write};use std::net::TcpListener;use std::sync::{Arc, Mutex};use cotton_mac::mail::acts::{Helps, Mail, GONE};use cotton_mac::mail::client::{dial, ImapClient, ImapError, Server};use cotton_mac::mail::tally::Tally;use cotton_mac::mail::trash;use cotton_mac::object::ObjectClient;use serde_json::{json, Value};/// No act here lands a page.fn no_erase(_: &[trash::GoneMail]) -> Result<usize, String> {    Ok(0)}fn no_land(_: &str, _: &[u8]) -> Result<Value, String> {    Err("unused".into())}use support::{Answer, TestServer};const SPAM: &str = "deals@shop.invented";const ACCOUNT: &str = "owner@mail.invented";#[derive(Clone, Debug)]struct Msg {    uid: u32,    from: String,    gm: u64,    mid: String,    seen: bool,    inbox: bool,    /// Said by RFC822.SIZE to be over what the Mac fetches whole.    big: bool,}#[derive(Clone)]struct Box_ {    validity: u32,    next: u32,    messages: Vec<Msg>,}#[derive(Clone)]struct Fake {    gmail: bool,    /// Gmail answering OK to taking the Inbox label off and keeping it anyway.    keeps: bool,    archive: bool,    boxes: BTreeMap<String, Box_>,}type Shared = Arc<Mutex<Fake>>;fn uids_of(set: &str) -> Vec<u32> {    set.split(',').filter_map(|u| u.parse().ok()).collect()}fn msg(uid: u32, from: &str, inbox: bool) -> Msg {    Msg { uid, from: from.to_string(), gm: 0x1000 + u64::from(uid), mid: format!("m{uid}@shop.invented"), seen: false, inbox, big: false }}/// Gmail's INBOX is a view of All Mail: the messages with the Inbox label (the fake keeps their All Mail UIDs).fn view(state: &Fake, name: &str) -> Vec<Msg> {    if state.gmail && name == "INBOX" {        return state.boxes["[Gmail]/All Mail"].messages.iter().filter(|m| m.inbox).cloned().collect();    }    state.boxes.get(name).map(|b| b.messages.clone()).unwrap_or_default()}fn imap(fake: Shared) -> (u16, Arc<Mutex<Vec<String>>>) {    let listener = TcpListener::bind("127.0.0.1:0").unwrap();    let port = listener.local_addr().unwrap().port();    let lines = Arc::new(Mutex::new(Vec::new()));    let recorded = Arc::clone(&lines);    std::thread::spawn(move || {        for stream in listener.incoming() {            let Ok(stream) = stream else { continue };            let fake = Arc::clone(&fake);            let recorded = Arc::clone(&recorded);            std::thread::spawn(move || {                let mut writer = stream.try_clone().unwrap();                let mut reader = BufReader::new(stream);                writer.write_all(b"* OK fake ready\r\n").unwrap();                let mut open: Option<(String, bool)> = None;                loop {                    let mut line = String::new();                    if reader.read_line(&mut line).unwrap_or(0) == 0 {                        return;                    }                    let line = line.trim_end().to_string();                    let (tag, rest) = line.split_once(' ').unwrap();                    let words: Vec<&str> = rest.split(' ').collect();                    if words[0] != "LOGIN" {                        recorded.lock().unwrap().push(rest.to_string());                    }                    let mut state = fake.lock().unwrap();                    let trash = if state.gmail { "[Gmail]/Trash" } else { "Deleted Items" }.to_string();                    let mut out = String::new();                    let named = |rest: &str| rest.split_once(' ').map(|(_, n)| n.trim_matches('"').to_string()).unwrap_or_default();                    let opened = open.clone().map(|o| o.0).unwrap_or_default();                    match words[0] {                        "LOGIN" => out.push_str(&format!("{tag} OK signed in\r\n")),                        "CAPABILITY" => {                            let gm = if state.gmail { " X-GM-EXT-1" } else { "" };                            out.push_str(&format!("* CAPABILITY IMAP4rev1 IDLE MOVE{gm}\r\n{tag} OK\r\n"));                        }                        "LIST" => {                            if state.gmail {                                out.push_str("* LIST (\\HasNoChildren \\All) \"/\" \"[Gmail]/All Mail\"\r\n");                            }                            if state.archive {                                out.push_str("* LIST (\\HasNoChildren \\Archive) \"/\" \"Archive\"\r\n");                            }                            out.push_str(&format!("* LIST (\\HasNoChildren) \"/\" \"INBOX\"\r\n* LIST (\\HasNoChildren \\Trash) \"/\" \"{trash}\"\r\n{tag} OK\r\n"));                        }                        "EXAMINE" | "SELECT" => {                            let name = named(rest);                            let held = state.boxes.entry(name.clone()).or_insert(Box_ { validity: 1, next: 1, messages: vec![] }).clone();                            let (validity, next) = if state.gmail && name == "INBOX" {                                let all = &state.boxes["[Gmail]/All Mail"];                                (all.validity, all.next)                            } else {                                (held.validity, held.next)                            };                            open = Some((name.clone(), words[0] == "SELECT"));                            out.push_str(&format!("* {} EXISTS\r\n* OK [UIDVALIDITY {validity}] v\r\n* OK [UIDNEXT {next}] n\r\n{tag} OK done\r\n", view(&state, &name).len()));                        }                        "UID" if words[1] == "SEARCH" => {                            let mut held = view(&state, &opened);                            let mut words = words.clone();                            if words[2] == "UID" {                                // `UID n:*`: from n on, and as a server does, the last message even below n.                                let from: u32 = words[3].trim_end_matches(":*").parse().unwrap();                                let last = held.iter().map(|m| m.uid).max().unwrap_or(0);                                held.retain(|m| m.uid >= from || m.uid == last);                                words.drain(2..4);                            }                            let found: Vec<String> = match words[2] {                                "FROM" => {                                    let wanted = words[3..].join(" ").trim_matches('"').to_lowercase();                                    held.iter().filter(|m| m.from.to_lowercase().contains(&wanted)).map(|m| m.uid.to_string()).collect()                                }                                "X-GM-MSGID" => held.iter().filter(|m| m.gm.to_string() == words[3]).map(|m| m.uid.to_string()).collect(),                                "HEADER" if words[3] == "Message-ID" => {                                    let wanted = words[4..].join(" ").trim_matches('"').to_string();                                    held.iter().filter(|m| m.mid.contains(&wanted)).map(|m| m.uid.to_string()).collect()                                }                                other => panic!("a search the fake does not know: {other}"),                            };                            out.push_str(&format!("* SEARCH {}\r\n{tag} OK\r\n", found.join(" ")));                        }                        "UID" if words[1] == "FETCH" && rest.contains("BODY.PEEK[HEADER.FIELDS (MESSAGE-ID)]") => {                            let held = view(&state, &opened);                            for (n, uid) in uids_of(words[2]).into_iter().enumerate() {                                let Some(m) = held.iter().find(|m| m.uid == uid) else { continue };                                let header = format!("Message-ID: <{}>\r\n\r\n", m.mid);                                let gm = if rest.contains("X-GM-MSGID") { format!("X-GM-MSGID {} ", m.gm) } else { String::new() };                                out.push_str(&format!("* {} FETCH (UID {uid} {gm}BODY[HEADER.FIELDS (MESSAGE-ID)] {{{}}}\r\n{header})\r\n", n + 1, header.len()));                            }                            out.push_str(&format!("{tag} OK\r\n"));                        }                        "UID" if words[1] == "FETCH" && rest.contains("BODY.PEEK[HEADER.FIELDS (FROM)]") => {                            let held = view(&state, &opened);                            for (n, uid) in uids_of(words[2]).into_iter().enumerate() {                                let Some(m) = held.iter().find(|m| m.uid == uid) else { continue };                                let header = format!("From: {}\r\n\r\n", m.from);                                out.push_str(&format!("* {} FETCH (UID {uid} BODY[HEADER.FIELDS (FROM)] {{{}}}\r\n{header})\r\n", n + 1, header.len()));                            }                            out.push_str(&format!("{tag} OK\r\n"));                        }                        "UID" if words[1] == "FETCH" && (rest.contains("RFC822.SIZE") || rest.contains("BODY.PEEK[]")) => {                            let held = view(&state, &opened);                            for (n, uid) in uids_of(words[2]).into_iter().enumerate() {                                let Some(m) = held.iter().find(|m| m.uid == uid) else { continue };                                let raw = format!("From: {}\r\nMessage-ID: <{}>\r\nSubject: invented\r\nContent-Type: text/html\r\n\r\n<p>page {uid}</p>\r\n", m.from, m.mid);                                if rest.contains("RFC822.SIZE") {                                    let size = if m.big { 70 * 1024 * 1024 } else { raw.len() };                                    out.push_str(&format!("* {} FETCH (UID {uid} RFC822.SIZE {size})\r\n", n + 1));                                } else {                                    out.push_str(&format!("* {} FETCH (UID {uid} BODY[] {{{}}}\r\n{raw})\r\n", n + 1, raw.len()));                                }                            }                            out.push_str(&format!("{tag} OK\r\n"));                        }                        "UID" if words[1] == "FETCH" && rest.contains("X-GM-LABELS") => {                            let held = view(&state, &opened);                            for (n, uid) in uids_of(words[2]).into_iter().enumerate() {                                let Some(m) = held.iter().find(|m| m.uid == uid) else { continue };                                let labels = if m.inbox { "\\Inbox \"Invented\"" } else { "\"Invented\"" };                                out.push_str(&format!("* {} FETCH (UID {uid} X-GM-LABELS ({labels}))\r\n", n + 1));                            }                            out.push_str(&format!("{tag} OK\r\n"));                        }                        "UID" if words[1] == "STORE" => {                            assert!(open.as_ref().unwrap().1, "a STORE only in a SELECTed mailbox");                            let wanted = uids_of(words[2]);                            let what = words[3..].join(" ");                            let gmail = state.gmail;                            let keeps = state.keeps;                            let real = if gmail { "[Gmail]/All Mail".to_string() } else { opened.clone() };                            let held = state.boxes.get_mut(&real).unwrap();                            for m in held.messages.iter_mut().filter(|m| wanted.contains(&m.uid)) {                                match what.as_str() {                                    "+FLAGS.SILENT (\\Seen)" => m.seen = true,                                    "-FLAGS.SILENT (\\Seen)" => m.seen = false,                                    // As Gmail does (ACTS-CHECK, 24 Nov 2026): OK, and the label of the folder open                                    // is not one it takes off there.                                    "-X-GM-LABELS.SILENT (\\Inbox)" if gmail && (opened == "INBOX" || keeps) => {}                                    "-X-GM-LABELS.SILENT (\\Inbox)" if gmail => m.inbox = false,                                    other => panic!("a STORE the Mac must never send: {other}"),                                }                            }                            out.push_str(&format!("{tag} OK\r\n"));                        }                        "UID" if words[1] == "MOVE" || words[1] == "COPY" => {                            assert!(open.as_ref().unwrap().1, "a move only from a SELECTed mailbox");                            let to = words[3..].join(" ").trim_matches('"').to_string();                            assert!(to == trash || to == "Archive", "mail moves to Trash or the Archive, nowhere else: {to}");                            let wanted = uids_of(words[2]);                            let from = if state.gmail { "[Gmail]/All Mail".to_string() } else { opened.clone() };                            let source = state.boxes.get_mut(&from).unwrap();                            let taken: Vec<Msg> = source.messages.iter().filter(|m| wanted.contains(&m.uid)).cloned().collect();                            source.messages.retain(|m| !wanted.contains(&m.uid));                            let bin = state.boxes.entry(to).or_insert(Box_ { validity: 7, next: 1, messages: vec![] });                            for mut m in taken {                                m.uid = bin.next;                                bin.next += 1;                                bin.messages.push(m);                            }                            out.push_str(&format!("{tag} OK done\r\n"));                        }                        "LOGOUT" => {                            writer.write_all(format!("* BYE bye\r\n{tag} OK\r\n").as_bytes()).unwrap();                            return;                        }                        _ => out.push_str(&format!("{tag} BAD not here\r\n")),                    }                    drop(state);                    writer.write_all(out.as_bytes()).unwrap();                }            });        }    });    (port, lines)}fn fake(gmail: bool, archive: bool, messages: Vec<Msg>) -> Shared {    let name = if gmail { "[Gmail]/All Mail" } else { "INBOX" }.to_string();    let next = messages.iter().map(|m| m.uid).max().unwrap_or(0) + 1;    Arc::new(Mutex::new(Fake { gmail, keeps: false, archive, boxes: BTreeMap::from([(name, Box_ { validity: 42, next, messages })]) }))}fn connect(port: u16) -> Result<ImapClient, ImapError> {    let mut client = ImapClient::start(dial(&Server { host: "127.0.0.1".into(), port, tls: false })?)?;    client.login(ACCOUNT, "app-pw")?;    Ok(client)}fn object(rows: Vec<Value>) -> (TestServer, Arc<Mutex<Vec<Value>>>) {    let held = Arc::new(Mutex::new(rows));    let shared = Arc::clone(&held);    let server = TestServer::start(move |request| {        let mut rows = shared.lock().unwrap();        if let Some(status) = request.path.strip_prefix("/v1/outbox?status=") {            let found: Vec<Value> = rows.iter().filter(|r| r["status"] == status).cloned().collect();            return Answer::json(200, json!({ "rows": found }));        }        let body = request.json();        assert_eq!((body["act"].as_str(), body["args"]["table"].as_str()), (Some("update"), Some("outbox")));        let id = body["args"]["id"].as_str().unwrap();        let row = rows.iter_mut().find(|r| r["id"] == id).unwrap();        for (k, v) in body["args"]["data"].as_object().unwrap() {            row[k] = v.clone();        }        Answer::json(200, json!({ "version": 1, "changed": [] }))    });    (server, held)}fn row(rows: &Arc<Mutex<Vec<Value>>>, id: &str) -> Value {    rows.lock().unwrap().iter().find(|r| r["id"] == id).cloned().unwrap()}fn status(rows: &Arc<Mutex<Vec<Value>>>, id: &str) -> (String, String) {    let r = row(rows, id);    (r["status"].as_str().unwrap_or_default().to_string(), r["error"].as_str().unwrap_or_default().to_string())}/// His Try again in Comms: the same row queued again, as `chat.sender.act { act: "retry" }` files it (the count's/// numbering stays on the row).fn try_again(rows: &Arc<Mutex<Vec<Value>>>, id: &str) {    let mut rows = rows.lock().unwrap();    let row = rows.iter_mut().find(|r| r["id"] == id).unwrap();    row["status"] = json!("queued");    row["error"] = Value::Null;}fn mail_row(id: &str, kind: &str, target: &str) -> Value {    json!({ "id": id, "channel": "mail", "kind": kind, "target": target, "to": SPAM, "account": ACCOUNT, "status": "queued" })}fn held(fake: &Shared, mailbox: &str) -> Vec<Msg> {    fake.lock().unwrap().boxes.get(mailbox).map(|b| b.messages.clone()).unwrap_or_default()}fn never_erased(lines: &[String]) {    for line in lines {        assert!(!line.contains("\\Deleted") && !line.starts_with("EXPUNGE") && !line.contains("UID EXPUNGE") && !line.starts_with("DELETE"), "never erased: {line}");    }}/// The database's mail for each `external_id` the rows name: Gmail ids for uids 1..=4, and one the mailbox lost.fn gmail_mail(external: &str) -> Option<Mail> {    let uid: u64 = external.strip_prefix("mid:")?.parse().ok()?;    Some(Mail { gmail_id: Some(format!("{:x}", 0x1000 + uid)), ..Mail::default() })}/// RULE (Senders 3, chat CONTRACT): read, unread, archive and one mail to Trash are done on that mail in Gmail, found/// by its Gmail id; a mail the mailbox no longer has answers the contract's words; nothing is ever erased.#[test]fn a_mails_read_unread_archive_and_trash_reach_gmail() {    let mut seen = msg(2, "Shop <deals@shop.invented>", true);    seen.seen = true;    let fake = fake(true, false, vec![msg(1, "Asha <asha@friend.invented>", true), seen, msg(3, "Asha <asha@friend.invented>", true), msg(4, "Shop <deals@shop.invented>", true)]);    let (port, lines) = imap(Arc::clone(&fake));    let (server, rows) = object(vec![        mail_row("read", "mark_read", "mid:1"),        mail_row("unread", "mark_unread", "mid:2"),        mail_row("archive", "archive", "mid:3"),        mail_row("trash", "trash", "mid:4"),        mail_row("lost", "mark_read", "mid:99"),        mail_row("unknown", "archive", "not-held"),        json!({ "id": "odd", "channel": "mail", "kind": "forward", "target": "mid:1", "to": SPAM, "status": "queued" }),    ]);    let object = ObjectClient::new(server.url.clone(), Some("device-token".into())).unwrap();    let no_post = |_: &str| -> Result<(), String> { panic!("no unsubscribe here") };    let helps = Helps { mail: &gmail_mail, post: &no_post, listed: None, retry_failed: false, land_page: &no_land, erase: &no_erase };    let drained = trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!((drained.done, drained.failed), (4, 3));    for id in ["read", "unread", "archive", "trash"] {        assert_eq!(status(&rows, id), ("sent".to_string(), String::new()), "{id}");    }    assert_eq!(status(&rows, "lost"), ("failed".to_string(), GONE.to_string()));    assert_eq!(status(&rows, "unknown"), ("failed".to_string(), GONE.to_string()));    assert_eq!(status(&rows, "odd").1, "Not something mail can do.");    let all = held(&fake, "[Gmail]/All Mail");    let of = |uid: u32| all.iter().find(|m| m.uid == uid).cloned();    assert!(of(1).unwrap().seen, "read in Gmail");    assert!(!of(2).unwrap().seen, "unread in Gmail");    assert!(!of(3).unwrap().inbox && of(3).is_some(), "archived: out of the Inbox, still in All Mail");    assert!(of(4).is_none() && held(&fake, "[Gmail]/Trash").len() == 1, "in Trash, where he can take it back");    never_erased(&lines.lock().unwrap());}/// RULE: a sender's Archive everything takes every message from that exact address out of the Inbox, nobody/// else's; on Gmail by its label, on another server into its Archive, refused in words where it has none.#[test]fn a_senders_archive_everything_empties_the_inbox_of_them_alone() {    let messages = vec![        msg(1, "Shop <deals@shop.invented>", true),        msg(2, "DEALS@SHOP.INVENTED", true),        msg(3, "Not Them <no-deals@shop.invented>", true),        msg(4, "Shop <deals@shop.invented>", false),        msg(5, "Asha <asha@friend.invented>", true),    ];    let gmail = fake(true, false, messages.clone());    let (port, lines) = imap(Arc::clone(&gmail));    let (server, rows) = object(vec![json!({ "id": "all", "channel": "mail", "kind": "sender_archive", "to": SPAM, "account": ACCOUNT, "status": "queued" })]);    let object = ObjectClient::new(server.url.clone(), Some("device-token".into())).unwrap();    let none = |_: &str| None;    let no_post = |_: &str| -> Result<(), String> { Err("unused".into()) };    let helps = Helps { mail: &none, post: &no_post, listed: None, retry_failed: false, land_page: &no_land, erase: &no_erase };    // ACTS-CHECK (24 Nov 2026): the Inbox counted and said first, nothing moved; his Try again archives that set.    trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!(status(&rows, "all"), ("failed".to_string(), "2 emails from them are in your Inbox. Try again to archive those 2.".to_string()));    assert_eq!(row(&rows, "all")["count"], 2);    assert_eq!(held(&gmail, "[Gmail]/All Mail").iter().filter(|m| m.inbox).count(), 4, "nothing archived before he agrees");    try_again(&rows, "all");    trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    let done = row(&rows, "all");    assert_eq!((done["status"].as_str(), done["moved"].as_u64(), done["sent_external_id"].as_str()), (Some("sent"), Some(2), Some("read_back")), "done on reading the Inbox back");    assert!(lines.lock().unwrap().iter().any(|l| l.contains("SELECT \"[Gmail]/All Mail\"")), "the label comes off in All Mail");    // The phone's own Inbox count (`target: "inbox"`): only theirs still in the Inbox, none now.    rows.lock().unwrap().push(json!({ "id": "count", "channel": "mail", "kind": "sender_count", "target": "inbox", "to": SPAM, "account": ACCOUNT, "status": "queued" }));    rows.lock().unwrap().push(json!({ "id": "count-asha", "channel": "mail", "kind": "sender_count", "target": "inbox", "to": "asha@friend.invented", "account": ACCOUNT, "status": "queued" }));    trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!((row(&rows, "count")["count"].as_u64(), row(&rows, "count-asha")["count"].as_u64()), (Some(0), Some(1)));    assert_eq!(row(&rows, "count-asha")["uid_below"], 6);    let inbox: Vec<u32> = held(&gmail, "[Gmail]/All Mail").iter().filter(|m| m.inbox).map(|m| m.uid).collect();    assert_eq!(inbox, vec![3, 5], "only theirs left the Inbox");    assert_eq!(held(&gmail, "[Gmail]/All Mail").len(), 5, "all still in All Mail");    never_erased(&lines.lock().unwrap());    let other = fake(false, true, messages.clone());    let (port, _) = imap(Arc::clone(&other));    rows.lock().unwrap().push(json!({ "id": "all-2", "channel": "mail", "kind": "sender_archive", "to": SPAM, "status": "queued" }));    rows.lock().unwrap().push(json!({ "id": "one", "channel": "mail", "kind": "archive", "target": "mid:5", "to": "asha@friend.invented", "status": "queued" }));    let by_message_id = |external: &str| (external == "mid:5").then(|| Mail { message_id: Some("<m5@shop.invented>".into()), ..Mail::default() });    let helps = Helps { mail: &by_message_id, post: &no_post, listed: None, retry_failed: false, land_page: &no_land, erase: &no_erase };    trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!(row(&rows, "all-2")["count"], 3);    try_again(&rows, "all-2");    trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!(row(&rows, "all-2")["moved"], 3, "another server: every one of theirs in INBOX");    assert_eq!(status(&rows, "one").0, "sent", "found by its Message-ID");    assert_eq!(held(&other, "Archive").len(), 4);    let left: Vec<u32> = held(&other, "INBOX").iter().map(|m| m.uid).collect();    assert_eq!(left, vec![3]);    let bare = fake(false, false, messages);    let (port, _) = imap(Arc::clone(&bare));    rows.lock().unwrap().push(json!({ "id": "all-3", "channel": "mail", "kind": "sender_archive", "to": SPAM, "status": "queued" }));    trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!(status(&rows, "all-3"), ("failed".to_string(), "This mail account has no Archive to move to.".to_string()));    assert_eq!(held(&bare, "INBOX").len(), 5, "nothing moved");}/// RULE: Unsubscribe is RFC 8058's one-click where the mail offers it and the sender takes it; otherwise the/// sender joins this Mac's own list and only what arrives from them afterwards goes to Trash.#[test]fn unsubscribe_clicks_once_or_sends_their_arrivals_to_trash() {    let fake = fake(true, false, vec![msg(1, "Shop <deals@shop.invented>", true), msg(2, "Asha <asha@friend.invented>", true)]);    let (port, lines) = imap(Arc::clone(&fake));    let (server, rows) = object(vec![mail_row("click", "unsubscribe", "mid:offers")]);    let object = ObjectClient::new(server.url.clone(), Some("device-token".into())).unwrap();    let dir = tempfile::tempdir().unwrap();    let tally = Tally::open(&dir.path().join("mail.db")).unwrap();    let mail = |external: &str| match external {        "mid:offers" => Some(Mail { list_unsubscribe: Some("<mailto:u@shop.invented>, <https://shop.invented/u/7>".into()), list_unsubscribe_post: Some("List-Unsubscribe=One-Click".into()), ..Mail::default() }),        "mid:refuses" => Some(Mail { list_unsubscribe: Some("<https://shop.invented/u/8>".into()), list_unsubscribe_post: Some("List-Unsubscribe=One-Click".into()), ..Mail::default() }),        _ => Some(Mail::default()),    };    let posted = Mutex::new(Vec::new());    let post = |link: &str| -> Result<(), String> {        posted.lock().unwrap().push(link.to_string());        if link.ends_with("/8") { Err("the sender's server answered 500".into()) } else { Ok(()) }    };    let helps = Helps { mail: &mail, post: &post, listed: Some(&tally), retry_failed: false, land_page: &no_land, erase: &no_erase };    trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!(row(&rows, "click")["sent_external_id"], "one_click");    assert_eq!(posted.lock().unwrap().clone(), vec!["https://shop.invented/u/7"]);    assert!(tally.listened(ACCOUNT).unwrap().is_empty(), "a one-click needs no list");    // No one-click offered: the list, from the mailbox's next UID. The mail already there stays.    rows.lock().unwrap().push(mail_row("list", "unsubscribe", "mid:plain"));    let drained = trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!(row(&rows, "list")["sent_external_id"], "trash_on_arrival");    assert!(row(&rows, "list")["error"].is_null(), "no click was tried, so none was refused");    assert_eq!(drained.swept, 0);    assert_eq!(tally.listened(ACCOUNT).unwrap(), vec![(SPAM.to_string(), 42, 3)]);    assert_eq!(held(&fake, "[Gmail]/All Mail").len(), 2, "what came before his word stays");    // They write again, and so does Asha: theirs goes to Trash on the next run, hers stays.    {        let mut state = fake.lock().unwrap();        let all = state.boxes.get_mut("[Gmail]/All Mail").unwrap();        all.messages.push(msg(3, "Shop <deals@shop.invented>", true));        all.messages.push(msg(4, "Asha <asha@friend.invented>", true));        all.next = 5;    }    let drained = trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!(drained.swept, 1);    let left: Vec<u32> = held(&fake, "[Gmail]/All Mail").iter().map(|m| m.uid).collect();    assert_eq!(left, vec![1, 2, 4]);    assert_eq!(held(&fake, "[Gmail]/Trash").len(), 1);    assert_eq!(tally.listened(ACCOUNT).unwrap(), vec![(SPAM.to_string(), 42, 5)], "the next look starts after them");    let drained = trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!(drained.swept, 0, "nothing moved twice");    // A one-click the sender's server refuses: his word stands, through the list.    rows.lock().unwrap().push(json!({ "id": "refused", "channel": "mail", "kind": "unsubscribe", "target": "mid:refuses", "to": "news@other.invented", "status": "queued" }));    trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!(row(&rows, "refused")["sent_external_id"], "trash_on_arrival");    assert_eq!((row(&rows, "refused")["status"].as_str(), row(&rows, "refused")["error"].as_str()), (Some("sent"), Some("the sender's server answered 500")), "the click's refusal is said, the row still sent");    assert_eq!(tally.listened(ACCOUNT).unwrap().len(), 2);    never_erased(&lines.lock().unwrap());}/// RULE (coordinator, MAIL-ACTS-NOW, 24 Nov 2026): his Delete everything and Archive everything that build 7 refused/// ("Count first, then move.", "Not something mail can do.") are taken up again by the new Mac on its first run,/// with what is still queued; a row failed for any other reason, or another channel's, is left as it is.#[test]fn what_the_old_mac_refused_is_done_on_the_first_run() {    let messages = vec![        msg(1, "Shop <deals@shop.invented>", true),        msg(2, "News <news@paper.invented>", true),        msg(3, "Club <club@team.invented>", true),        msg(4, "Asha <asha@friend.invented>", true),    ];    let fake = fake(true, false, messages);    let (port, lines) = imap(Arc::clone(&fake));    let (server, rows) = object(vec![        json!({ "id": "old-trash", "channel": "mail", "kind": "sender_trash", "to": SPAM, "account": ACCOUNT, "status": "failed", "error": "Count first, then move." }),        json!({ "id": "old-archive", "channel": "mail", "kind": "sender_archive", "to": "club@team.invented", "account": ACCOUNT, "status": "failed", "error": "Not something mail can do." }),        json!({ "id": "queued-trash", "channel": "mail", "kind": "sender_trash", "to": "news@paper.invented", "account": ACCOUNT, "status": "queued" }),        json!({ "id": "other-failure", "channel": "mail", "kind": "sender_trash", "to": "asha@friend.invented", "status": "failed", "error": "The mail server refused: no" }),        json!({ "id": "wa", "channel": "whatsapp", "kind": "text", "to": "+15550000001", "status": "failed", "error": "Not something mail can do." }),    ]);    let object = ObjectClient::new(server.url.clone(), Some("device-token".into())).unwrap();    let none = |_: &str| None;    let no_post = |_: &str| -> Result<(), String> { Err("unused".into()) };    let helps = Helps { mail: &none, post: &no_post, listed: None, retry_failed: true, land_page: &no_land, erase: &no_erase };    let drained = trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!((drained.retried, drained.failed), (2, 3), "taken up, counted and said first");    assert_eq!(status(&rows, "old-trash").1, "Your mail holds 1 email from them. Try again to move it to Trash.");    assert_eq!(held(&fake, "[Gmail]/Trash").len(), 0, "nothing moves before he is told his mail's count");    for id in ["old-trash", "old-archive", "queued-trash"] {        try_again(&rows, id);    }    let drained = trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!((drained.trashed, drained.done, drained.failed), (2, 1, 0));    for id in ["old-trash", "old-archive", "queued-trash"] {        assert_eq!(status(&rows, id), ("sent".to_string(), String::new()), "{id}");    }    assert_eq!(status(&rows, "other-failure"), ("failed".to_string(), "The mail server refused: no".to_string()));    assert_eq!(status(&rows, "wa").0, "failed", "WhatsApp's rows are not mail's");    let all: Vec<(u32, bool)> = held(&fake, "[Gmail]/All Mail").iter().map(|m| (m.uid, m.inbox)).collect();    assert_eq!(all, vec![(3, false), (4, true)], "two senders in Trash, one archived, Asha untouched");    assert_eq!(held(&fake, "[Gmail]/Trash").len(), 2);    // Taken up once: a second run with the same ask moves nothing more.    let drained = trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!(drained, trash::Drained::default());    never_erased(&lines.lock().unwrap());}/// RULE (SENDERS TRUE, ACTS-CHECK 24 Nov 2026): an archive is done only when the Inbox is read back. Where Gmail/// answers OK and keeps the label, the act fails in words saying what it kept, and one mail's archive the same.#[test]fn an_archive_gmail_kept_in_the_inbox_is_said_and_never_called_done() {    let fake = fake(true, false, vec![msg(1, "Shop <deals@shop.invented>", true), msg(2, "Shop <deals@shop.invented>", true)]);    fake.lock().unwrap().keeps = true;    let (port, lines) = imap(Arc::clone(&fake));    let (server, rows) = object(vec![        json!({ "id": "all", "channel": "mail", "kind": "sender_archive", "to": SPAM, "account": ACCOUNT, "status": "queued", "uid_validity": 42, "uid_below": 3, "count": 2 }),        mail_row("one", "archive", "mid:1"),    ]);    let object = ObjectClient::new(server.url.clone(), Some("device-token".into())).unwrap();    let no_post = |_: &str| -> Result<(), String> { Err("unused".into()) };    let helps = Helps { mail: &gmail_mail, post: &no_post, listed: None, retry_failed: false, land_page: &no_land, erase: &no_erase };    let drained = trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!((drained.done, drained.failed), (0, 2));    let all = row(&rows, "all");    assert_eq!((all["status"].as_str(), all["moved"].as_u64(), all["error"].as_str()), (Some("failed"), Some(0), Some("Gmail kept 2 of them in your Inbox.")));    assert!(all["sent_external_id"].is_null());    assert_eq!(status(&rows, "one"), ("failed".to_string(), "Gmail kept it in your Inbox.".to_string()));    // Once Gmail takes it, the same rows are done, read back.    fake.lock().unwrap().keeps = false;    try_again(&rows, "all");    try_again(&rows, "one");    trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!((row(&rows, "all")["status"].as_str(), row(&rows, "all")["sent_external_id"].as_str(), row(&rows, "all")["moved"].as_u64()), (Some("sent"), Some("read_back"), Some(2)), "both of theirs left; the one mail after it is read back too");    assert_eq!((row(&rows, "one")["sent_external_id"].as_str(), row(&rows, "one")["moved"].as_u64()), (Some("read_back"), Some(1)));    assert!(held(&fake, "[Gmail]/All Mail").iter().all(|m| !m.inbox));    never_erased(&lines.lock().unwrap());}/// RULE (DELETE FAST): a Delete everything that carries its count's numbering moves that set at once, never mail/// that came after it, and nothing when the mailbox holds more of theirs below it than it was told.#[test]fn a_counted_delete_moves_exactly_its_set_at_once() {    let fake = fake(true, false, vec![msg(1, "Shop <deals@shop.invented>", true), msg(2, "Shop <deals@shop.invented>", false), msg(3, "Shop <deals@shop.invented>", true)]);    let (port, lines) = imap(Arc::clone(&fake));    let (server, rows) = object(vec![        json!({ "id": "told-2", "channel": "mail", "kind": "sender_trash", "to": SPAM, "account": ACCOUNT, "status": "queued", "uid_validity": 42, "uid_below": 3, "count": 2 }),    ]);    let object = ObjectClient::new(server.url.clone(), Some("device-token".into())).unwrap();    let none = |_: &str| None;    let no_post = |_: &str| -> Result<(), String> { Err("unused".into()) };    let named = Mutex::new(Vec::new());    let erase = |gone: &[trash::GoneMail]| -> Result<usize, String> {        named.lock().unwrap().extend(gone.iter().cloned());        Ok(gone.len())    };    let helps = Helps { mail: &none, post: &no_post, listed: None, retry_failed: false, land_page: &no_land, erase: &erase };    let drained = trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!((row(&rows, "told-2")["status"].as_str(), row(&rows, "told-2")["moved"].as_u64()), (Some("sent"), Some(2)));    // DELETE FAST question 2: Cotton's rows of exactly the two moved go too, named by Gmail's id and the Message-ID.    let mid = |uid: u32| cotton_rules::fingerprint::email::message_id_external_id(Some(&format!("<m{uid}@shop.invented>")));    assert_eq!(        named.lock().unwrap().clone(),        vec![trash::GoneMail { gmail_id: Some("1001".into()), external: mid(1) }, trash::GoneMail { gmail_id: Some("1002".into()), external: mid(2) }]    );    assert_eq!(drained.erased, 2);    let left: Vec<u32> = held(&fake, "[Gmail]/All Mail").iter().map(|m| m.uid).collect();    assert_eq!(left, vec![3], "the mail after the count stays");    // Told 1, but 2 of theirs are below the count's UID: nothing moves.    {        let mut state = fake.lock().unwrap();        let all = state.boxes.get_mut("[Gmail]/All Mail").unwrap();        all.messages.push(msg(4, "Shop <deals@shop.invented>", true));        all.next = 5;    }    rows.lock().unwrap().push(json!({ "id": "told-1", "channel": "mail", "kind": "sender_trash", "to": SPAM, "account": ACCOUNT, "status": "queued", "uid_validity": 42, "uid_below": 5, "count": 1 }));    trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!(status(&rows, "told-1"), ("failed".to_string(), "Your mail holds more from them than was counted, so nothing was moved. Count again.".to_string()));    assert_eq!(named.lock().unwrap().len(), 2, "nothing moved, nothing erased");    assert_eq!(held(&fake, "[Gmail]/All Mail").len(), 2);    never_erased(&lines.lock().unwrap());}/// RULE (MAIL.md: the designed page and attachments are fetched when he opens a mail; Mac 10): `mail_page` fetches the/// message whole without marking it read and hands it to be landed on the mail's row; a message over the limit is/// refused in words, and one the mailbox lost says so.#[test]fn a_mail_page_is_fetched_whole_and_landed_without_marking_it_read() {    let mut big = msg(2, "Shop <deals@shop.invented>", true);    big.big = true;    let fake = fake(true, false, vec![msg(1, "Shop <deals@shop.invented>", true), big]);    let (port, lines) = imap(Arc::clone(&fake));    let (server, rows) = object(vec![mail_row("page", "mail_page", "mid:1"), mail_row("huge", "mail_page", "mid:2"), mail_row("lost", "mail_page", "mid:99")]);    let object = ObjectClient::new(server.url.clone(), Some("device-token".into())).unwrap();    let landed = Mutex::new(Vec::new());    let land = |external: &str, raw: &[u8]| -> Result<Value, String> {        landed.lock().unwrap().push((external.to_string(), String::from_utf8_lossy(raw).to_string()));        Ok(json!({ "page": true, "files": 0 }))    };    let no_post = |_: &str| -> Result<(), String> { Err("unused".into()) };    let helps = Helps { mail: &gmail_mail, post: &no_post, listed: None, retry_failed: false, land_page: &land, erase: &no_erase };    let drained = trash::drain(&object, ACCOUNT, &mut || connect(port), &helps).unwrap();    assert_eq!((drained.done, drained.failed), (1, 2));    let page = row(&rows, "page");    assert_eq!((page["status"].as_str(), page["page"].as_bool(), page["files"].as_u64()), (Some("sent"), Some(true), Some(0)));    let landed = landed.lock().unwrap().clone();    assert_eq!(landed.len(), 1);    assert_eq!(landed[0].0, "mid:1");    assert!(landed[0].1.contains("<p>page 1</p>"), "the whole message: {}", landed[0].1);    assert_eq!(status(&rows, "huge"), ("failed".to_string(), "This email is too large to bring. Open it in your mail.".to_string()));    assert_eq!(status(&rows, "lost"), ("failed".to_string(), GONE.to_string()));    assert!(held(&fake, "[Gmail]/All Mail").iter().all(|m| !m.seen), "nothing marked read");    assert!(lines.lock().unwrap().iter().all(|l| !l.contains("STORE") && !l.contains("BODY[]") || l.contains("BODY.PEEK[]")), "read with PEEK only");    never_erased(&lines.lock().unwrap());}