//! Cotton Post's reading over a phone's own copy (assets/design/mail/CONTRACT.md). Every name, address, company and//! line is invented.use rusqlite::types::ValueasSqlValue;use serde_json::{json, Value};usecrate::handle::CottonHandle;const ME: &str = "mira@invented.example";const ASHA: &str = "asha@invented.example";/// A phone running Post: the `mail` kit.pub(crate) fn post_phone() -> (tempfile::TempDir, CottonHandle) { post_phone_as(cotton_core::flavor::Flavor::Real)}pub(crate) fn post_phone_as(flavor: cotton_core::flavor::Flavor) -> (tempfile::TempDir, CottonHandle) {let dir = tempfile::tempdir().expect("a temp container");let handle = post_phone_in(dir.path(), flavor, true); (dir, handle)}/// A Post phone over the container at `path`; `fresh` starts its copy (a kept one is already started).pub(crate) fn post_phone_in(path: &std::path::Path, flavor: cotton_core::flavor::Flavor, fresh: bool) -> CottonHandle {let manifest = json!({"genesis": "personal", "flavour": "mail", "name": "Cotton Post", "databases": "single", "database": "personal","fan": {"home": false, "tools": false, "opens": "mail"}, "kit": "mail", });let handle = CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: 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");if fresh {crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started"); } handle}pub(crate) fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value {crate::methods::dispatch(handle, 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)}pub(crate) structMail<'a> {pub id: &'a str,pub thread: &'a str,pub from: (&'a str, &'a str),pub to: &'a str,pub subject: &'a str,pub body: &'a str,pub minutes_ago: i64,pub unread: bool,pub attachments: Value,pub category: Option<&'a str>,pub unsubscribe: bool,pub account: &'a str,}implDefaultforMail<'_> {fn default() -> Self {Mail { id: "", thread: "", from: ("", ""), to: ME, subject: "", body: "", minutes_ago: 10, unread: false, attachments: json!([]), category: None, unsubscribe: false, account: ME } }}pub(crate) fn mail(handle: &CottonHandle, m: Mail<'_>) {let ws = workspace(handle);let at = iso(m.minutes_ago);let (address, name) = m.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(m.thread), t(&ws), t(&format!("key-{}", m.thread)), t(m.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, gmail_category, list_unsubscribe, in_inbox, created_at, landed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", &[ t(m.id), t(&ws), t(m.thread), t(&format!("x-{}", m.id)), t(m.subject), t(address), t(name), t(&json!([{ "email": m.to, "kind": "to" }]).to_string()), t(&at), t(m.body), t(m.body), t(&m.attachments.to_string()),SqlValue::Integer(m.unread as i64), t(m.account), m.category.map_or(SqlValue::Null, t), if m.unsubscribe { t("<https://invented.example/u>") } else { SqlValue::Null },// His own sent mail is not in his Inbox, as Gmail keeps it.// Landed on the server as it was sent here (the server's own stamp, schema 157).SqlValue::Integer((address != ME) as i64), t(&at), t(&at), ], );}/// Mira's mailbox: Asha (a person she wrote to) asking a question, a stranger at a webmail, a shop's offer (Gmail's/// Promotions), a receipt, a newsletter with an unsubscribe, a bank's notice asking her to confirm, and a file.fn mailbox(handle: &CottonHandle) { mail(handle, Mail { id: "e-asha-1", thread: "et-flat", from: (ASHA, "Asha Example"), subject: "Flat papers", body: "The lease draft is attached. Can you sign by Friday?", minutes_ago: 30, unread: true, attachments: json!([{ "name": "lease.pdf", "mime": "application/pdf", "size": 48_000 }]), ..Default::default() }); mail(handle, Mail { id: "e-mira-1", thread: "et-old", from: (ME, "Mira"), to: ASHA, subject: "Dinner", body: "Thursday works.", minutes_ago: 3000, ..Default::default() }); mail(handle, Mail { id: "e-ravi", thread: "et-ravi", from: ("ravi.k@gmail.com", "Ravi K"), subject: "Hello again", body: "We met at the fair.", minutes_ago: 20, ..Default::default() }); mail(handle, Mail { id: "e-shop", thread: "et-shop", from: ("offers@kitebox.example", "Kitebox"), subject: "Your winter list is 40% off", body: "Shop now. Unsubscribe.", minutes_ago: 15, unread: true, category: Some("promotions"), unsubscribe: true, ..Default::default() }); mail(handle, Mail { id: "e-receipt", thread: "et-receipt", from: ("orders@tiffinly.example", "Tiffinly"), subject: "Your order receipt", body: "₹482 paid. Arriving by 1:20.", minutes_ago: 12, ..Default::default() }); mail(handle, Mail { id: "e-news", thread: "et-news", from: ("hello@weeklybyte.example", "Weeklybyte"), subject: "This week in tiny code", body: "Five stories. Unsubscribe any time.", minutes_ago: 8, unsubscribe: true, ..Default::default() }); mail(handle, Mail { id: "e-bank", thread: "et-bank", from: ("noreply@northbank.example", "Northbank"), subject: "Confirm your KYC details", body: "Please confirm your details within 7 days.", minutes_ago: 5, unread: true, ..Default::default() });}fn subjects(rows: &Value) -> Vec<String> { rows.as_array().unwrap().iter().map(|r| r["subject"].as_str().unwrap().to_string()).collect()}/// RULE (DECISIONS "Structure"): the home has three bands. People holds the people the rule calls people, unread on/// top; Waiting on you holds a person's question not yet answered and a machine asking him to act; From machines/// counts each group's mail by written rule (receipts by their words, Gmail's Promotions as shops, an unsubscribe as/// a newsletter, every other machine a notice). A person with a chat is still here: Post holds every mail.#[test]fn the_home_has_people_waiting_and_counted_machines() {let (_dir, handle) = post_phone(); mailbox(&handle);let home = ask(&handle, "mail.home", json!({})); assert_eq!(home["title"], "Inbox"); assert_eq!(subjects(&home["people"]["rows"]), ["Flat papers", "Hello again"], "unread first: {home}"); assert_eq!(home["people"]["line"], "1 new"); assert_eq!(home["people"]["rows"][0]["from"]["face"], "person"); assert_eq!(home["people"]["rows"][0]["attachments"], 1);let waiting = subjects(&home["waiting"]["rows"]); assert!(waiting.contains(&"Flat papers".to_string()) && waiting.contains(&"Confirm your KYC details".to_string()), "{home}"); assert_eq!(home["waiting"]["rows"].as_array().unwrap().iter().find(|r| r["subject"] == "Flat papers").unwrap()["act"], "Reply");let groups: Vec<(String, i64)> = home["machines"]["groups"].as_array().unwrap().iter().map(|g| (g["id"].as_str().unwrap().to_string(), g["inbox"].as_i64().unwrap())).collect(); assert_eq!(groups, [("group:receipts".to_string(), 1), ("group:shops".to_string(), 1), ("group:newsletters".to_string(), 1), ("group:notices".to_string(), 1)], "{home}"); assert_eq!(home["machines"]["groups"][1]["title"], "Shops and offers"); assert_eq!(home["search"]["hint"], "Search 7 mails"); assert_eq!(home["write"], "Write a mail");}/// RULE: a group lists only its senders' mail, says why it is there and offers its bulk acts with their counts.#[test]fn a_group_lists_its_mail_and_says_why() {let (_dir, handle) = post_phone(); mailbox(&handle);let shops = ask(&handle, "mail.list", json!({ "place": "group:shops" })); assert_eq!(subjects(&shops["rows"]), ["Your winter list is 40% off"]); assert_eq!(shops["title"], "Shops and offers"); assert!(shops["why"]["line"].as_str().unwrap().contains("Promotions"), "{shops}"); assert_eq!(shops["bulk"][1]["label"], "Archive 1");let receipts = ask(&handle, "mail.list", json!({ "place": "group:receipts" })); assert_eq!(subjects(&receipts["rows"]), ["Your order receipt"]);let inbox = ask(&handle, "mail.list", json!({ "place": "inbox" })); assert_eq!(inbox["rows"].as_array().unwrap().len(), 6, "every mail sent to her; her own sent mail is not in the Inbox: {inbox}"); assert!(crate::methods::dispatch(&handle, "mail.list", &json!({ "place": "nowhere" })).is_err());}/// RULE (DECISIONS "The four acts"): Archived holds what left the Inbox (here, or in the mailbox), and the Bin what/// was deleted, saying its 30 days; neither stands in the Inbox.#[test]fn archived_and_the_bin_are_places_of_their_own() {let (_dir, handle) = post_phone(); mailbox(&handle); sql(&handle, "UPDATE cotton_emails SET archived_at = ? WHERE id = 'e-news'", &[t(&iso(1))]); sql(&handle, "UPDATE cotton_emails SET in_inbox = 0 WHERE id = 'e-receipt'", &[]); sql(&handle, "UPDATE cotton_emails SET trashed_at = ? WHERE id = 'e-shop'", &[t(&iso(1))]);let archived = ask(&handle, "mail.list", json!({ "place": "archived" })); assert_eq!(subjects(&archived["rows"]), ["This week in tiny code", "Your order receipt"]);let bin = ask(&handle, "mail.list", json!({ "place": "bin" })); assert_eq!(subjects(&bin["rows"]), ["Your winter list is 40% off"]); assert_eq!(bin["bin"]["line"], "Each goes for good 30 days after it was deleted.");let inbox = subjects(&ask(&handle, "mail.list", json!({ "place": "inbox" }))["rows"]); assert!(!inbox.iter().any(|s| s == "This week in tiny code" || s == "Your order receipt" || s == "Your winter list is 40% off"), "{inbox:?}");let sent = ask(&handle, "mail.list", json!({ "place": "sent" })); assert_eq!(subjects(&sent["rows"]), ["Dinner"]);let empty = ask(&handle, "mail.list", json!({ "place": "drafts" })); assert_eq!(empty["empty"], "No drafts.");}/// RULE (CONTRACT "nothing hands the person to another app"): a conversation offers Reply, Reply all only when there/// are others, and Forward, all written in Post; no mail app's link; the designed page with pictures held back.#[test]fn a_thread_writes_in_post_and_holds_pictures_back() {let (_dir, handle) = post_phone(); mailbox(&handle);let thread = ask(&handle, "mail.thread", json!({ "thread": "et-flat" })); assert_eq!(thread["subject"], "Flat papers"); assert_eq!(thread["acts"]["reply"]["mode"], "reply"); assert_eq!(thread["acts"]["reply"]["label"], "Reply"); assert!(thread["acts"]["reply_all"].is_null(), "only Mira and Asha: {thread}"); assert_eq!(thread["acts"]["forward"]["label"], "Forward"); assert!(thread.get("reply").is_none() && !thread.to_string().contains("mailto:"), "no mail app: {thread}"); assert!(thread["page"]["pictures"]["line"].as_str().unwrap().contains("Asha Example")); assert_eq!(thread["messages"][0]["attachments"][0]["name"], "lease.pdf");let home = ask(&handle, "mail.home", json!({})); assert_eq!(home["people"]["rows"].as_array().unwrap().iter().find(|r| r["subject"] == "Flat papers").unwrap()["unread"], false, "read here on open");}/// RULE: Files lists every attachment anyone sent, newest first, by kind; search finds people, mail and files.#[test]fn files_and_search() {let (_dir, handle) = post_phone(); mailbox(&handle); mail(&handle, Mail { id: "e-photo", thread: "et-photo", from: (ASHA, "Asha Example"), subject: "Balcony", body: "Look!", minutes_ago: 2, attachments: json!([{ "name": "balcony.jpg", "mime": "image/jpeg", "size": 900_000 }]), ..Default::default() });let files = ask(&handle, "mail.files", json!({}));let names: Vec<&str> = files["rows"].as_array().unwrap().iter().map(|f| f["name"].as_str().unwrap()).collect(); assert_eq!(names, ["balcony.jpg", "lease.pdf"]); assert_eq!(files["rows"][0]["kind"], "pictures"); assert_eq!(files["rows"][0]["from"], "Asha Example");let documents = ask(&handle, "mail.files", json!({ "kind": "documents" })); assert_eq!(documents["rows"].as_array().unwrap().len(), 1);let found = ask(&handle, "mail.search", json!({ "text": "lease" })); assert_eq!(subjects(&found["mail"]["rows"]), ["Flat papers"], "{found}"); assert_eq!(found["files"]["rows"][0]["name"], "lease.pdf");let asha = ask(&handle, "mail.search", json!({ "text": "Asha" })); assert_eq!(asha["people"]["rows"][0]["from"]["name"], "Asha Example", "{asha}");let none = ask(&handle, "mail.search", json!({ "text": "zebra" })); assert_eq!(none["empty"], "Nothing found for “zebra”.");}/// RULE: the side page holds All inboxes with its unread count, each account, the places with their counts, and/// Gmail's own labels (never the system's).#[test]fn the_side_page_holds_inboxes_places_and_labels() {let (_dir, handle) = post_phone(); mailbox(&handle); sql(&handle, "UPDATE cotton_emails SET labels = '[\"INBOX\",\"CATEGORY_PROMOTIONS\",\"Travel\"]' WHERE id = 'e-receipt'", &[]); sql(&handle, "UPDATE cotton_emails SET trashed_at = ? WHERE id = 'e-shop'", &[t(&iso(1))]);let side = ask(&handle, "mail.side", json!({})); assert_eq!(side["inboxes"]["rows"][0]["title"], "All inboxes"); assert_eq!(side["inboxes"]["rows"][0]["count"], 2, "Asha's and the bank's unread: {side}");let places: Vec<&str> = side["places"]["rows"].as_array().unwrap().iter().map(|r| r["title"].as_str().unwrap()).collect(); assert_eq!(places, ["Drafts", "Sent", "Archived", "Bin"]); assert_eq!(side["places"]["rows"][3]["count"], 1); assert_eq!(side["labels"]["rows"], json!([{ "id": "label:Travel", "title": "Travel" }])); assert_eq!(side["open"], "Open the side page");}/// RULE (owner's bug on Post build 2, 86,000 mails mid-sync: the side page slid in empty for 1 to 2 seconds): asked/// with `counts: false`, the side page answers its rows from what the phone holds without counting any mail: All/// inboxes, each account, the places, no count and no labels (those come with the whole answer, after).#[test]fn the_side_page_answers_its_rows_without_counting_when_asked() {let (_dir, handle) = post_phone(); mailbox(&handle); sql(&handle, "UPDATE cotton_emails SET labels = '[\"Travel\"]' WHERE id = 'e-receipt'", &[]); sql(&handle, "UPDATE cotton_emails SET trashed_at = ? WHERE id = 'e-shop'", &[t(&iso(1))]);let quick = ask(&handle, "mail.side", json!({ "counts": false }));let whole = ask(&handle, "mail.side", json!({}));let ids = |side: &Value, band: &str| side[band]["rows"].as_array().unwrap().iter().map(|r| r["id"].clone()).collect::<Vec<_>>(); assert_eq!(ids(&quick, "inboxes"), ids(&whole, "inboxes"), "the same inboxes: {quick}"); assert_eq!(ids(&quick, "places"), ids(&whole, "places"), "the same places: {quick}");for band in ["inboxes", "places"] { assert!(quick[band]["rows"].as_array().unwrap().iter().all(|r| r["count"].is_null()), "no count yet: {quick}"); } assert!(quick["labels"].is_null(), "labels come with the whole answer: {quick}"); assert_eq!(whole["places"]["rows"][3]["count"], 1, "the whole answer counts: {whole}"); assert_eq!(quick["open"], whole["open"]);}fn archived(handle: &CottonHandle) -> Vec<String> { subjects(&ask(handle, "mail.list", json!({ "place": "archived" }))["rows"])}/// RULE (owner, 25 Nov 2026): Archive is one tap. The phone holds every mail, so the button's count is the count/// archived: every mail of the sender in the Inbox leaves it at once, kept in Archived; the after-state says the real/// number, offers Undo, and Undo puts each back. No sheet, no second tap.#[test]fn archive_is_one_tap_with_the_exact_count_and_undo() {let (_dir, handle) = post_phone(); mailbox(&handle); mail(&handle, Mail { id: "e-receipt-2", thread: "et-receipt-2", from: ("orders@tiffinly.example", "Tiffinly"), subject: "Your second order receipt", body: "₹210 paid.", minutes_ago: 3, ..Default::default() });let group = ask(&handle, "mail.list", json!({ "place": "group:receipts" })); assert_eq!(group["bulk"][1]["label"], "Archive 2", "{group}");let after = ask(&handle, "mail.archive", json!({ "scope": "sender", "key": "orders@tiffinly.example" })); assert_eq!(after["count"], 2); assert_eq!(after["line"], "Archived 2 from Tiffinly."); assert_eq!(after["undo"], "Undo"); assert_eq!(archived(&handle), ["Your second order receipt", "Your order receipt"]); assert!(subjects(&ask(&handle, "mail.list", json!({ "place": "group:receipts" }))["rows"]).is_empty());let undone = ask(&handle, "mail.undo", json!({ "after": after["after"] })); assert_eq!(undone["line"], "Undone."); assert!(undone["undo"].is_null()); assert!(archived(&handle).is_empty()); assert_eq!(subjects(&ask(&handle, "mail.list", json!({ "place": "group:receipts" }))["rows"]).len(), 2);}/// RULE (MAIL PREDICATE phase 2, rule 2): an Archive of a whole sender covers up to the newest landing among the/// mails it takes, never up to this phone's clock: mail of his landing after that, even before the tap's own moment,/// stays in the Inbox.#[test]fn archive_covers_up_to_the_newest_landing_not_the_phone_clock() {let (_dir, handle) = post_phone(); mailbox(&handle); mail(&handle, Mail { id: "e-old-1", thread: "et-old-1", from: ("hello@clockcheck.example", "Clockcheck"), subject: "First", body: "One.", minutes_ago: 60, ..Default::default() }); mail(&handle, Mail { id: "e-old-2", thread: "et-old-2", from: ("hello@clockcheck.example", "Clockcheck"), subject: "Second", body: "Two.", minutes_ago: 30, ..Default::default() });let after = ask(&handle, "mail.archive", json!({ "scope": "sender", "key": "hello@clockcheck.example" })); assert_eq!(after["count"], 2, "{after}");letmut archived_now = archived(&handle); archived_now.sort(); assert_eq!(archived_now, ["First", "Second"]);// Landed 10 minutes ago: after the newest of his mails the Archive took, before the tap. mail(&handle, Mail { id: "e-between", thread: "et-between", from: ("hello@clockcheck.example", "Clockcheck"), subject: "Between", body: "Three.", minutes_ago: 10, ..Default::default() }); assert!(!archived(&handle).contains(&"Between".to_string()), "{:?}", archived(&handle));}/// RULE: a group's Archive takes every sender in it; chosen mail archives just those.#[test]fn archive_a_group_or_the_chosen_mail() {let (_dir, handle) = post_phone(); mailbox(&handle);let after = ask(&handle, "mail.archive", json!({ "scope": "group", "key": "group:notices" })); assert_eq!(after["count"], 1, "{after}"); assert_eq!(after["line"], "Archived."); assert_eq!(archived(&handle), ["Confirm your KYC details"]);let chosen = ask(&handle, "mail.act", json!({ "emails": ["e-news", "e-shop"], "act": "archive" })); assert_eq!(chosen["line"], "Archived 2."); assert_eq!(archived(&handle).len(), 3); assert!(crate::methods::dispatch(&handle, "mail.archive", &json!({ "scope": "sender" })).is_err(), "a sender is named");}/// RULE (DECISIONS "The four acts"): Delete moves mail to the Bin (kept 30 days), Bring back returns it; read and/// unread change only the mark; each says so and Undo puts it back.#[test]fn delete_to_the_bin_bring_back_and_marks() {let (_dir, handle) = post_phone(); mailbox(&handle);let deleted = ask(&handle, "mail.act", json!({ "email": "e-shop", "act": "delete" })); assert_eq!(deleted["line"], "Moved to the Bin."); assert_eq!(subjects(&ask(&handle, "mail.list", json!({ "place": "bin" }))["rows"]), ["Your winter list is 40% off"]);let back = ask(&handle, "mail.act", json!({ "email": "e-shop", "act": "restore" })); assert_eq!(back["line"], "Brought back 1."); assert!(subjects(&ask(&handle, "mail.list", json!({ "place": "bin" }))["rows"]).is_empty());let read = ask(&handle, "mail.act", json!({ "emails": ["e-asha-1", "e-bank"], "act": "read" })); assert_eq!(read["line"], "Marked 2 read."); assert_eq!(ask(&handle, "mail.home", json!({}))["people"]["line"], Value::Null, "{}", ask(&handle, "mail.home", json!({}))); ask(&handle, "mail.undo", json!({ "after": read["after"] })); assert_eq!(ask(&handle, "mail.home", json!({}))["people"]["line"], "1 new");let again = ask(&handle, "mail.after", json!({ "after": read["after"] })); assert_eq!(again["line"], "Undone."); assert!(crate::methods::dispatch(&handle, "mail.act", &json!({ "email": "e-none", "act": "delete" })).is_err()); assert!(crate::methods::dispatch(&handle, "mail.undo", &json!({ "after": "nope" })).is_err());}/// RULE (DECISIONS "The four acts"): Delete of a whole sender asks once with its count; more mail since asks again/// with All or only the agreed; the mail goes to the Bin, not away, and Undo brings it back.#[test]fn deleting_a_sender_asks_once_by_count() {let (_dir, handle) = post_phone(); mailbox(&handle);let sheet = ask(&handle, "mail.ask", json!({ "act": "delete", "scope": "sender", "key": "offers@kitebox.example" })); assert_eq!(sheet["title"], "Delete 1 mail from Kitebox?"); assert_eq!(sheet["go"], "Delete 1"); assert_eq!(sheet["cancel"], "Not now"); mail(&handle, Mail { id: "e-shop-2", thread: "et-shop-2", from: ("offers@kitebox.example", "Kitebox"), subject: "Last call", body: "Ends tonight.", minutes_ago: 1, ..Default::default() });let more = ask(&handle, "mail.do", json!({ "plan": sheet["plan"] })); assert_eq!(more["more"]["choices"][1]["label"], "Delete only the 1", "{more}"); assert!(subjects(&ask(&handle, "mail.list", json!({ "place": "bin" }))["rows"]).is_empty(), "nothing done before he chooses");let only = ask(&handle, "mail.do", json!({ "plan": sheet["plan"], "choice": "only" })); assert_eq!(only["line"], "Moved to the Bin."); assert_eq!(subjects(&ask(&handle, "mail.list", json!({ "place": "bin" }))["rows"]), ["Your winter list is 40% off"]); ask(&handle, "mail.undo", json!({ "after": only["after"] })); assert!(subjects(&ask(&handle, "mail.list", json!({ "place": "bin" }))["rows"]).is_empty());}/// RULE: Unsubscribe with a one-tap link offers to archive the Inbox's mail too; without one it offers Bin new mail./// Block asks once and, only when chosen, deletes what is here.#[test]fn unsubscribe_and_block_sheets() {let (_dir, handle) = post_phone(); mailbox(&handle);let news = ask(&handle, "mail.ask", json!({ "act": "unsubscribe", "key": "hello@weeklybyte.example" })); assert_eq!(news["title"], "Unsubscribe from Weeklybyte?"); assert_eq!(news["also"]["label"], "Also archive the 1 in your Inbox");let bank = ask(&handle, "mail.ask", json!({ "act": "unsubscribe", "key": "noreply@northbank.example" })); assert_eq!(bank["go"], "Bin new mail from Northbank");let binned = ask(&handle, "mail.do", json!({ "plan": bank["plan"] })); assert_eq!(binned["line"], "New mail from Northbank goes to the Bin from now on.");let block = ask(&handle, "mail.ask", json!({ "act": "block", "key": "orders@tiffinly.example" })); assert_eq!(block["title"], "Block Tiffinly?"); assert_eq!(block["also"]["label"], "Also delete the 1 already here");let done = ask(&handle, "mail.do", json!({ "plan": block["plan"], "also": true })); assert_eq!(done["line"], "Blocked Tiffinly."); assert_eq!(done["deleted"]["line"], "Moved to the Bin."); assert!(crate::methods::dispatch(&handle, "mail.ask", &json!({ "act": "archive", "key": "x@y.example" })).is_err(), "Archive is one tap");}/// RULE: the Bin keeps a mail 30 days, then it goes for good; Empty the Bin asks with its count, then erases.#[test]fn the_bin_keeps_thirty_days_and_empties_by_count() {let (_dir, handle) = post_phone(); mailbox(&handle); sql(&handle, "UPDATE cotton_emails SET trashed_at = ? WHERE id = 'e-shop'", &[t(&iso(31 * 24 * 60))]); sql(&handle, "UPDATE cotton_emails SET trashed_at = ? WHERE id = 'e-news'", &[t(&iso(29 * 24 * 60))]);// Opening the Bin never writes (MAIL PREDICATE phase 2, decision 1): both are still there. assert_eq!(subjects(&ask(&handle, "mail.list", json!({ "place": "bin" }))["rows"]).len(), 2);// The background keeps its 30 days, after a pass.super::keep_the_bin(&handle.client()).unwrap();let bin = ask(&handle, "mail.list", json!({ "place": "bin" })); assert_eq!(subjects(&bin["rows"]), ["This week in tiny code"], "31 days gone, 29 kept: {bin}"); assert_eq!(bin["bin"]["empty"], "Empty the Bin now · 1");let sheet = ask(&handle, "mail.bin.empty", json!({})); assert_eq!(sheet["ask"]["go"], "Empty 1");let emptied = ask(&handle, "mail.bin.empty", json!({ "count": 1 })); assert_eq!(emptied["emptied"], 1); assert!(subjects(&ask(&handle, "mail.list", json!({ "place": "bin" }))["rows"]).is_empty());}/// RULE (CONTRACT "You"): Post's own rows, then the shared ones, with today's answers; choices change in place.#[test]fn you_answers_its_rows_and_keeps_choices() {let (_dir, handle) = post_phone(); mailbox(&handle);let you = ask(&handle, "mail.you", json!({}));let titles: Vec<&str> = you["groups"][0]["rows"].as_array().unwrap().iter().map(|r| r["title"].as_str().unwrap()).collect(); assert_eq!(titles, ["Accounts", "Signature", "Notifications", "Sorting rules", "Undo send", "Domains", "Look"]);let groups: Vec<&str> = you["groups"].as_array().unwrap().iter().map(|g| g["id"].as_str().unwrap()).collect(); assert_eq!(groups, ["post", "sync", "privacy", "storage", "help", "about"]); assert_eq!(you["groups"][0]["rows"][4]["value"], "5 seconds", "DECISIONS question 7"); assert_eq!(you["groups"][0]["rows"][2]["value"], "People only"); assert_eq!(you["groups"][3]["rows"][0]["title"], "7 mails");let changed = ask(&handle, "mail.set", json!({ "name": "undo_send", "value": 20 })); assert_eq!(changed["groups"][0]["rows"][4]["value"], "20 seconds"); assert!(crate::methods::dispatch(&handle, "mail.set", &json!({ "name": "undo_send", "value": 7 })).is_err());}/// RULE: a quoted tail folds under its label; To and Cc are Post's words; pictures-always is remembered.#[test]fn a_thread_folds_the_quote_and_remembers_pictures() {let (_dir, handle) = post_phone(); mail(&handle, Mail { id: "e-q", thread: "et-q", from: (ASHA, "Asha Example"), subject: "Re: Flat", body: "Yes, Friday is fine.\n\nOn Mon, 23 Nov 2026 at 10:02, Mira <mira@invented.example> wrote:\n> Can you sign by Friday?", minutes_ago: 5, ..Default::default() });let thread = ask(&handle, "mail.thread", json!({ "thread": "et-q" }));let m = &thread["messages"][0]; assert_eq!(m["text"], "Yes, Friday is fine."); assert_eq!(m["quoted"]["label"], "Show the quoted text"); assert!(m["quoted"]["text"].as_str().unwrap().starts_with("On Mon"), "{m}"); assert_eq!(m["to"], "To me"); assert_eq!(thread["page"]["pictures"]["on"], false);let always = ask(&handle, "mail.pictures.always", json!({ "sender": ASHA })); assert_eq!(always["always"], true); assert_eq!(ask(&handle, "mail.thread", json!({ "thread": "et-q" }))["page"]["pictures"]["on"], true);}#[test]fn quoted_tails_by_their_marks() {usesuper::split_quoted; assert_eq!(split_quoted("Thanks!\n\n> earlier\n> more"), Some(("Thanks!".into(), "> earlier\n> more".into()))); assert_eq!(split_quoted("See below.\n-----Original Message-----\nFrom: x"), Some(("See below.".into(), "-----Original Message-----\nFrom: x".into()))); assert_eq!(split_quoted("Hi\nFrom: Asha\nSent: Monday\nSubject: x"), Some(("Hi".into(), "From: Asha\nSent: Monday\nSubject: x".into()))); assert_eq!(split_quoted("Nothing quoted here."), None); assert_eq!(split_quoted("> only a quote"), None);}/// RULE (question 11): a link offers Read here or Open in Sites…, never another app; only web links open.#[test]fn links_and_the_long_press() {let (_dir, handle) = post_phone(); mailbox(&handle);let link = ask(&handle, "mail.link", json!({ "url": "https://invented.example/a b" })); assert_eq!(link["read"], "Read here"); assert_eq!(link["sites"]["label"], "Open in Sites…"); assert_eq!(link["sites"]["ios"]["live"], "cottonsites://open?url=https%3A%2F%2Finvented.example%2Fa+b&from=post"); assert_eq!(link["sites"]["android"]["dev_package"], "com.cottondb.sites.dev"); assert!(crate::methods::dispatch(&handle, "mail.link", &json!({ "url": "javascript:alert(1)" })).is_err());let hold = ask(&handle, "mail.hold", json!({ "email": "e-news" }));let ids: Vec<&str> = hold["acts"].as_array().unwrap().iter().map(|a| a["id"].as_str().unwrap()).collect(); assert_eq!(ids, ["unread", "archive", "delete", "unsubscribe", "block", "open_sender"]); assert_eq!(hold["acts"][0]["label"], "Mark unread");}/// RULE (DECISIONS "Sorting rules"): the six rules in words, and his word over them: a machine he calls a person/// moves to People, and clearing it lets the rules decide again.#[test]fn the_rules_and_his_word_over_them() {let (_dir, handle) = post_phone(); mailbox(&handle);let rules = ask(&handle, "mail.rules", json!({})); assert_eq!(rules["rules"].as_array().unwrap().len(), 6); assert_eq!(rules["rules"][0], "Someone you've written to is a person."); assert!(rules["yours"]["rows"].as_array().unwrap().is_empty());let said = ask(&handle, "mail.verdict", json!({ "address": "noreply@northbank.example", "who": "person" })); assert_eq!(said["yours"]["rows"][0]["who"], "person", "{said}");let people = subjects(&ask(&handle, "mail.home", json!({}))["people"]["rows"]); assert!(people.contains(&"Confirm your KYC details".to_string()), "{people:?}"); assert_eq!(ask(&handle, "mail.you", json!({}))["groups"][0]["rows"][3]["value"], "Six rules, 1 exception"); ask(&handle, "mail.verdict", json!({ "address": "noreply@northbank.example", "who": "clear" }));let people = subjects(&ask(&handle, "mail.home", json!({}))["people"]["rows"]); assert!(!people.contains(&"Confirm your KYC details".to_string()));}/// RULE (walk finds, 25 Nov): a row's swipe archives the whole conversation's Inbox mail; People opens People.#[test]fn a_swipe_archives_the_conversation_and_people_opens_people() {let (_dir, handle) = post_phone(); mailbox(&handle); mail(&handle, Mail { id: "e-asha-2", thread: "et-flat", from: (ASHA, "Asha Example"), subject: "Flat papers", body: "And the deposit receipt.", minutes_ago: 4, ..Default::default() });let after = ask(&handle, "mail.act", json!({ "thread": "et-flat", "act": "archive" })); assert_eq!(after["count"], 2, "{after}"); assert_eq!(after["line"], "Archived 2 from Asha Example.");let home = ask(&handle, "mail.home", json!({})); assert_eq!(home["people"]["more"]["place"], "people");let people = ask(&handle, "mail.list", json!({ "place": "people" })); assert_eq!(subjects(&people["rows"]), ["Hello again"], "{people}"); assert_eq!(people["title"], "People");let undone = ask(&handle, "mail.undo", json!({ "after": after["after"] })); assert_eq!(undone["line"], "Undone.");let pictures = ask(&handle, "mail.pictures.always", json!({ "email": "e-asha-1" })); assert_eq!(pictures["sender"], ASHA);}/// RULE (DECISIONS "Senders"): every mail sender, machines by domain, loudest first (much mail, little opened);/// people he wrote to never on top. A sender's page counts its mail and offers its four acts with their counts.#[test]fn senders_rank_loudest_first_and_a_sender_has_four_acts() {let (_dir, handle) = post_phone(); mailbox(&handle);for (i, minutes) in [40, 50, 60].iter().enumerate() {let id = format!("e-shop-{i}");let thread = format!("et-shop-{i}"); mail(&handle, Mail { id: &id, thread: &thread, from: ("deals@kitebox.example", "Kitebox"), subject: "More offers", body: "Unsubscribe.", minutes_ago: *minutes, unread: true, category: Some("promotions"), unsubscribe: true, ..Default::default() }); }let list = ask(&handle, "mail.senders", json!({})); assert_eq!(list["rows"][0]["key"], "@kitebox.example", "{list}"); assert_eq!(list["rows"][0]["count"], 4, "two addresses, one domain"); assert_eq!(list["rows"][0]["line"], "Opened 0% · never replied");let keys: Vec<&str> = list["rows"].as_array().unwrap().iter().map(|r| r["key"].as_str().unwrap()).collect(); assert_eq!(keys.last(), Some(&ASHA), "a person he wrote to is never on top: {keys:?}"); assert!(!keys.contains(&ME));let people = ask(&handle, "mail.senders", json!({ "sort": "people" }));let people: Vec<&str> = people["rows"].as_array().unwrap().iter().map(|r| r["key"].as_str().unwrap()).collect(); assert_eq!(people, ["ravi.k@gmail.com", ASHA]);let kitebox = ask(&handle, "mail.sender", json!({ "key": "@kitebox.example" })); assert_eq!(kitebox["title"], "Kitebox"); assert_eq!(kitebox["numbers"][0]["value"], "4"); assert_eq!(kitebox["addresses"]["rows"].as_array().unwrap().len(), 2);let acts: Vec<&str> = kitebox["acts"].as_array().unwrap().iter().map(|a| a["act"].as_str().unwrap()).collect(); assert_eq!(acts, ["archive", "delete", "unsubscribe", "block"]); assert_eq!(kitebox["acts"][0]["label"], "Archive 4"); assert_eq!(kitebox["acts"][0]["call"]["scope"], "domain");let archived = ask(&handle, "mail.archive", json!({ "scope": "domain", "key": "@kitebox.example" })); assert_eq!(archived["count"], 4); assert!(ask(&handle, "mail.sender", json!({ "key": "@kitebox.example" }))["acts"][0]["act"] != "archive", "nothing left in the Inbox");}/// RULE (owner, 26 Nov 2026): Mail opens on All, the whole Inbox newest first; its chips are All, People, Unread and/// the machine kinds, each a plain newest-first list, each but All carrying its unread count when above zero.#[test]fn mail_chips_carry_their_unread_counts_and_unread_lists_the_unread_inbox() {let (_dir, handle) = post_phone(); mailbox(&handle);let home = ask(&handle, "mail.home", json!({}));let chips: Vec<(String, String, Value)> = home["chips"].as_array().unwrap().iter().map(|c| (c["id"].as_str().unwrap().to_string(), c["place"].as_str().unwrap().to_string(), c["count"].clone())).collect();let ids: Vec<&str> = chips.iter().map(|(id, _, _)| id.as_str()).collect(); assert_eq!(ids, ["all", "people", "unread", "receipts", "shops", "newsletters", "notices"], "{home}"); assert_eq!(home["chips"][0]["label"], "All"); assert_eq!(chips[0].1, "inbox", "All is the Inbox"); assert_eq!(chips[0].2, Value::Null, "no count on All");let count = |id: &str| chips.iter().find(|(c, _, _)| c == id).unwrap().2.clone(); assert_eq!((count("people"), count("unread"), count("shops"), count("notices")), (json!("1"), json!("3"), json!("1"), json!("1")), "{home}"); assert_eq!((count("receipts"), count("newsletters")), (Value::Null, Value::Null), "nothing unread, no count");let unread = ask(&handle, "mail.list", json!({ "place": "unread" })); assert_eq!(subjects(&unread["rows"]), ["Confirm your KYC details", "Your winter list is 40% off", "Flat papers"], "{unread}"); assert_eq!(unread["title"], "Unread"); sql(&handle, "UPDATE cotton_emails SET unread = 0", &[]); assert_eq!(ask(&handle, "mail.list", json!({ "place": "unread" }))["empty"], "Nothing unread.");}/// RULE (owner, 26 Nov 2026): Senders searches as he types over every sender, by the name shown and by address; a/// sender's page lists every mail from it under the acts, newest first, its count the heading.#[test]fn senders_search_by_name_and_address_and_a_sender_lists_its_mail() {let (_dir, handle) = post_phone(); mailbox(&handle);for (i, minutes) in [40, 50, 60].iter().enumerate() {let id = format!("e-shop-{i}");let thread = format!("et-shop-{i}");let subject = format!("More offers {i}"); mail(&handle, Mail { id: &id, thread: &thread, from: ("deals@kitebox.example", "Kitebox"), subject: &subject, body: "Unsubscribe.", minutes_ago: *minutes, category: Some("promotions"), unsubscribe: true, ..Default::default() }); }let keys = |text: &str| -> Vec<String> { ask(&handle, "mail.senders", json!({ "text": text }))["rows"].as_array().unwrap().iter().map(|r| r["key"].as_str().unwrap().to_string()).collect() }; assert_eq!(keys("kite"), ["@kitebox.example"], "by name"); assert_eq!(keys("DEALS@"), ["@kitebox.example"], "by an address, any case"); assert_eq!(keys("ravi.k"), ["ravi.k@gmail.com"]);let none = ask(&handle, "mail.senders", json!({ "text": "nobody-here" })); assert_eq!(none["found_none"], "No sender by that name or address."); assert_eq!(ask(&handle, "mail.senders", json!({}))["search"]["hint"], "Search senders");let kitebox = ask(&handle, "mail.sender", json!({ "key": "@kitebox.example" })); assert_eq!(kitebox["mails"]["title"], "4 mails");let place = kitebox["mails"]["place"].as_str().unwrap().to_string(); assert_eq!(place, "from:@kitebox.example");let mails = ask(&handle, "mail.list", json!({ "place": place })); assert_eq!(subjects(&mails["rows"]), ["Your winter list is 40% off", "More offers 0", "More offers 1", "More offers 2"], "{mails}"); assert_eq!(mails["title"], "4 mails");// One address's page lists the mail its page counts.let address = ask(&handle, "mail.sender", json!({ "key": "deals@kitebox.example" })); assert_eq!(address["mails"]["title"], address["numbers"][0]["value"].as_str().map(|n| format!("{n} mails")).unwrap()); assert_eq!(ask(&handle, "mail.sender", json!({ "key": ASHA }))["mails"]["title"], "1 mail");}/// RULE: a block made here is in the shared list, and Unblock takes it out.#[test]fn the_blocked_list_and_unblock() {let (_dir, handle) = post_phone(); mailbox(&handle);let sheet = ask(&handle, "mail.ask", json!({ "act": "block", "key": "hello@weeklybyte.example" })); ask(&handle, "mail.do", json!({ "plan": sheet["plan"] }));let blocked = ask(&handle, "mail.blocked", json!({})); assert_eq!(blocked["rows"][0]["key"], "hello@weeklybyte.example", "{blocked}"); assert_eq!(ask(&handle, "mail.senders", json!({}))["blocked"]["label"], "Blocked · 1");let after = ask(&handle, "mail.unblock", json!({ "key": "hello@weeklybyte.example" })); assert_eq!(after["empty"], "No one is blocked.");}/// RULE: joining two senders makes one, counted and acted on together; parting puts them back.#[test]fn merge_and_part_senders() {let (_dir, handle) = post_phone(); mailbox(&handle);let joined = ask(&handle, "mail.sender.merge", json!({ "key": "@tiffinly.example", "into": "@northbank.example" })); assert_eq!(joined["numbers"][0]["value"], "2", "{joined}"); assert!(joined["part"]["label"].is_string());let list = ask(&handle, "mail.sender.part", json!({ "key": "@tiffinly.example" }));let keys: Vec<&str> = list["rows"].as_array().unwrap().iter().map(|r| r["key"].as_str().unwrap()).collect(); assert!(keys.contains(&"@tiffinly.example") && keys.contains(&"@northbank.example"), "{keys:?}");}/// RULE (walk find, POST iPhone 3): Undo of a Delete puts the mail back where Archive finds it; an Archive that/// finds nothing refuses in words, never "Archived 0".#[test]fn undo_of_delete_comes_back_archivable_and_archive_of_nothing_refuses() {let (_dir, handle) = post_phone(); mailbox(&handle);let deleted = ask(&handle, "mail.act", json!({ "thread": "et-flat", "act": "delete" })); assert_eq!(deleted["count"], 1, "{deleted}");// Meanwhile his mailbox moved it to its Trash, out of its Inbox. sql(&handle, "UPDATE cotton_emails SET in_inbox = 0 WHERE thread_id = 'et-flat'", &[]); ask(&handle, "mail.undo", json!({ "after": deleted["after"] })); assert!(subjects(&ask(&handle, "mail.list", json!({ "place": "inbox" }))["rows"]).contains(&"Flat papers".to_string()));let archived = ask(&handle, "mail.act", json!({ "thread": "et-flat", "act": "archive" })); assert_eq!(archived["count"], 1, "{archived}");let again = crate::methods::dispatch(&handle, "mail.archive", &json!({ "scope": "thread", "key": "et-flat" }));let error = again.expect_err("nothing left to archive"); assert_eq!(error.code, "nothing"); assert_eq!(error.message, "Nothing here to archive.");}/// RULE: on a Post phone his mailbox follows: an act files its outbox row (the Mac or Cotton's fetcher reads it).#[test]fn his_mailbox_follows_through_the_outbox() {let (_dir, handle) = post_phone(); mailbox(&handle);let after = ask(&handle, "mail.archive", json!({ "scope": "sender", "key": "orders@tiffinly.example" })); assert_eq!(after["mailbox"]["state"], "waiting", "{after}"); assert_eq!(after["mailbox"]["line"], "Your mailbox will follow in a moment.");let deleted = ask(&handle, "mail.act", json!({ "email": "e-bank", "act": "delete" })); assert_eq!(deleted["mailbox"]["state"], "waiting", "{deleted}");}/// RULE (CONTRACT "Write"): Reply goes to the sender, Reply all adds everyone else but him, Forward goes to no one/// yet with the mail below; every one is written here, from the address the mail came to.#[test]fn compose_reply_reply_all_and_forward() {let (_dir, handle) = post_phone(); mail(&handle, Mail { id: "e-group", thread: "et-group", from: (ASHA, "Asha Example"), to: ME, subject: "Trip", body: "Who's in?", minutes_ago: 9, ..Default::default() }); sql(&handle, "UPDATE cotton_emails SET recipients = ? WHERE id = 'e-group'", &[t(&json!([{ "email": ME, "kind": "to" }, { "email": "jon@invented.example", "kind": "cc" }]).to_string())]);let reply = ask(&handle, "mail.compose", json!({ "mode": "reply", "thread": "et-group" })); assert_eq!(reply["to"], json!([ASHA])); assert_eq!(reply["cc"], json!([])); assert_eq!(reply["subject"], "Re: Trip"); assert!(reply["quoted"].as_str().unwrap().ends_with("> Who's in?"), "{reply}"); assert_eq!(reply["from"]["address"], ME); assert_eq!(reply["title"], "Reply");let all = ask(&handle, "mail.compose", json!({ "mode": "all", "thread": "et-group" })); assert_eq!(all["cc"], json!(["jon@invented.example"]));let forward = ask(&handle, "mail.compose", json!({ "mode": "forward", "thread": "et-group" })); assert_eq!(forward["to"], json!([])); assert_eq!(forward["subject"], "Fwd: Trip"); assert!(forward["quoted"].as_str().unwrap().starts_with("Forwarded mail")); assert!(forward["thread"].is_null()); assert!(!ask(&handle, "mail.compose", json!({})).to_string().contains("mailto:"));}/// The draft's own status, as its row holds it.fn draft_status(handle: &CottonHandle, draft: &str) -> Option<String> {let found = crate::phone::cotton_chat::read(&handle.client(), "test.draft", |ctx| Ok(json!(super::super::writing::draft_of(ctx, draft)?.and_then(|d| d.get("status").and_then(Value::as_str).map(str::to_string))))).unwrap(); found.as_str().map(str::to_string)}/// RULE (UNDO SEND FIX; the Android walk of 27 Nov, where a mail he took back went out 2 of 2): Undo send stops the/// mail for good. The screen polls `mail.sending` beside Undo, as the app does: no poll that lands after Undo, and no/// sweep from the home, sends or queues what he took back.#[test]fn undo_send_holds_against_the_screens_poll_running_beside_it() {let (_dir, handle) = post_phone(); mailbox(&handle);let draft = ask(&handle, "mail.save", json!({ "to": [ASHA], "subject": "Taken back", "body": "Not this one." }))["draft"].as_str().unwrap().to_string(); assert_eq!(ask(&handle, "mail.send", json!({ "draft": draft }))["state"], "holding");let stop = std::sync::atomic::AtomicBool::new(false);let (undone, seen) = std::thread::scope(|scope| {let poll = scope.spawn(|| {letmut seen = Vec::new();while !stop.load(std::sync::atomic::Ordering::SeqCst) {ifletOk(answer) = crate::methods::dispatch(&handle, "mail.sending", &json!({ "draft": draft })) { seen.push(answer["state"].as_str().unwrap_or_default().to_string()); } } seen }); std::thread::sleep(std::time::Duration::from_millis(30));let undone = crate::methods::dispatch(&handle, "mail.unsend", &json!({ "draft": draft })); std::thread::sleep(std::time::Duration::from_millis(30)); stop.store(true, std::sync::atomic::Ordering::SeqCst); (undone, poll.join().unwrap()) });let undone = undone.unwrap_or_else(|e| panic!("Undo refused: {} {}", e.code, e.message)); assert_eq!(undone["line"], "Back in Drafts. Nothing was sent."); assert!(seen.iter().all(|s| s == "holding" || s == "draft"), "a poll beside Undo sent or queued it: {seen:?}");// The poll that lands after Undo, and the home's sweep.let after = ask(&handle, "mail.sending", json!({ "draft": draft })); assert_eq!(after["state"], "draft", "{after}"); ask(&handle, "mail.home", json!({})); assert_eq!(draft_status(&handle, &draft).as_deref(), Some("draft")); assert_eq!(subjects(&ask(&handle, "mail.list", json!({ "place": "drafts" }))["rows"]), ["Taken back"]);}/// RULE (the Android walk, 27 Nov 2026): with no account (signed out on a fresh phone) the home has no foot, never/// "Fetched by your Mac".#[test]fn no_account_no_fetched_by_foot() {let (_dir, handle) = post_phone();let home = ask(&handle, "mail.home", json!({})); assert!(home["status"].is_null(), "{}", home["status"]); assert!(!home.to_string().contains("Fetched by your Mac"));}/// A held send's time moved, as if that much of it had passed (the hold's record on this phone).fn hold_moves(handle: &CottonHandle, draft: &str, until_ms: i64) {let path = handle.client().layout().client_dir().join("post-holds.json");letmut all: serde_json::Map<String, Value> = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); all[draft]["until"] = json!(until_ms); std::fs::write(&path, serde_json::to_vec(&all).unwrap()).unwrap();super::writer::forget_steady(draft);}/// RULE (UNDO SEND FIX): the countdown reads the hold's real time; once the send has taken the mail, Undo says it/// is too late and the draft is not put back; a second Send of a mail on its way sends nothing more; and a mail/// never sent never goes from `mail.sending`.#[test]fn the_countdown_is_the_holds_own_time_and_undo_after_it_goes_says_so() {let (_dir, handle) = post_phone(); mailbox(&handle);let draft = ask(&handle, "mail.save", json!({ "to": [ASHA], "subject": "Counted", "body": "Down." }))["draft"].as_str().unwrap().to_string();let never = ask(&handle, "mail.sending", json!({ "draft": draft })); assert_eq!(never["state"], "draft", "a draft never sent does not go from here: {never}"); assert_eq!(draft_status(&handle, &draft).as_deref(), Some("draft"));let held = ask(&handle, "mail.send", json!({ "draft": draft })); assert_eq!((held["line"].as_str(), held["seconds"].as_i64()), (Some("Sending in 5 seconds"), Some(5)));let now = chrono::Utc::now().timestamp_millis();// Moved to 40 seconds out (wide, so a slow box cannot blur it): the line counts from the hold, not from Send. hold_moves(&handle, &draft, now + 40_000);let later = ask(&handle, "mail.sending", json!({ "draft": draft }));let left = later["seconds"].as_i64().unwrap(); assert!((30..=40).contains(&left), "{later}"); assert_eq!(later["line"], format!("Sending in {left} seconds")); hold_moves(&handle, &draft, now - 1);let went = ask(&handle, "mail.sending", json!({ "draft": draft })); assert_eq!(went["state"], "waiting", "a local phone keeps it to send: {went}");let again = ask(&handle, "mail.send", json!({ "draft": draft })); assert_eq!(again["state"], "waiting", "a second Send is the same send: {again}");// Waiting for a connection, never posted: Undo still takes it back, for good. assert_eq!(ask(&handle, "mail.unsend", json!({ "draft": draft }))["line"], "Back in Drafts. Nothing was sent."); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": draft }))["state"], "draft"); assert_eq!(draft_status(&handle, &draft).as_deref(), Some("draft"));// Posted once (the object may have it): Undo says so and the draft is not put back under the send. ask(&handle, "mail.send", json!({ "draft": draft })); hold_moves(&handle, &draft, now - 1); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": draft }))["state"], "waiting");crate::phone::cotton_chat::write(&handle.client(), "test.posted", |ctx| { cotton_tools::mcp::handlers::tables::update_produced_record(ctx, json!({ "table": "email_draft", "id": draft, "patch": { "status": "failed" } }).as_object().unwrap()).map_err(|f| f.to_string())?;Ok(json!(null)) }) .unwrap();let late = crate::methods::dispatch(&handle, "mail.unsend", &json!({ "draft": draft })).expect_err("taken"); assert_eq!((late.code.as_str(), late.message.as_str()), ("too_late", "It has already gone.")); assert_eq!(draft_status(&handle, &draft).as_deref(), Some("failed"), "not put back in Drafts under the send"); assert_eq!(ask(&handle, "mail.discard", json!({ "draft": draft }))["said"], "Draft discarded");}/// A scripted object for Post's sends: each POST to `/v1/mail/send` takes the next answer.fn send_door(handle: &CottonHandle, answers: &[&str]) -> std::sync::Arc<cotton_client::transport::scripted::ScriptedExchange> {let (door, exchange) = crate::phone::unlock::tests::door(answers.iter().map(|a| cotton_client::transport::scripted::Reply::ok(a))); handle.client().set_object_door(Some(std::sync::Arc::new(door))); exchange}fn posts(exchange: &cotton_client::transport::scripted::ScriptedExchange) -> usize { exchange.seen().iter().filter(|s| s.path.ends_with("/v1/mail/send")).count()}fn held_draft(handle: &CottonHandle, subject: &str) -> String {let draft = ask(handle, "mail.save", json!({ "to": [ASHA], "subject": subject, "body": "Invented words." }))["draft"].as_str().unwrap().to_string(); assert_eq!(ask(handle, "mail.send", json!({ "draft": draft }))["state"], "holding");// Ten minutes out, so a slow box never runs the hold out before the test means it to. hold_moves(handle, &draft, chrono::Utc::now().timestamp_millis() + 600_000); draft}/// RULE (UNDO SEND 2 M1, UNDO SEND 3 HIGH 1): a held mail lists as Sending with Undo and opens still on its way; a/// save that changes nothing Send was tapped on (an autosave landing after Send) leaves it going and it goes once; a/// real change takes it back, says so, and nothing goes; a draft changed under its hold by another phone is not sent/// by it either.#[test]fn a_held_mail_edited_is_a_draft_again_and_never_sent_by_its_hold() {let (_dir, handle) = post_phone(); mailbox(&handle);let exchange = send_door(&handle, &[r#"{"state":"sent","email":"e-sent-same"}"#]);// Listed and opened while held: on its way, with its time and Undo.let draft = held_draft(&handle, "Saved the same");let row = ask(&handle, "mail.list", json!({ "place": "drafts" }))["rows"][0].clone(); assert_eq!((row["mark"].as_str(), row["sending"]["undo"].as_str()), (Some("Sending"), Some("Undo")), "{row}"); assert!(row["note"].as_str().unwrap().starts_with("Sending in "), "{row}");// Opened while held: taken back, an ordinary draft again, said so (round 2's rule).let opened = ask(&handle, "mail.compose", json!({ "draft": draft })); assert_eq!(opened["said"], "Back in Drafts. Nothing was sent.", "{opened}"); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": draft }))["state"], "draft"); assert_eq!(ask(&handle, "mail.send", json!({ "draft": draft }))["state"], "holding"); hold_moves(&handle, &draft, chrono::Utc::now().timestamp_millis() + 600_000);// The autosave lands after Send with the same words: still going, and it goes once.let same = ask(&handle, "mail.save", json!({ "draft": draft, "to": [ASHA], "subject": "Saved the same", "body": "Invented words." })); assert_eq!(same["said"], "Draft saved"); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": draft }))["state"], "holding"); hold_moves(&handle, &draft, chrono::Utc::now().timestamp_millis() - 1); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": draft }))["state"], "sent"); ask(&handle, "mail.home", json!({})); assert_eq!(posts(&exchange), 1, "sent once");// A real change during the hold: taken back, said, and nothing goes.let changed = held_draft(&handle, "Saved changed");let said = ask(&handle, "mail.save", json!({ "draft": changed, "to": [ASHA], "subject": "Saved changed", "body": "Half writ" })); assert_eq!(said["said"], "Not sent: it changed after Send. Send it again."); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": changed }))["state"], "draft"); hold_moves_if_held(&handle, &changed, chrono::Utc::now().timestamp_millis() - 1); ask(&handle, "mail.home", json!({})); assert_eq!(posts(&exchange), 1, "nothing more went"); assert_eq!(draft_status(&handle, &changed).as_deref(), Some("draft"));let row = ask(&handle, "mail.list", json!({ "place": "drafts" }))["rows"].as_array().unwrap().iter().find(|r| r["draft"] == json!(changed)).unwrap().clone(); assert_eq!((row["mark"].as_str(), row["note"].as_str()), (Some("Draft"), Some("Not sent: it changed after Send. Send it again.")), "{row}");// Changed under its hold by another phone (the synced row, not this phone's save): not sent by that hold. assert_eq!(ask(&handle, "mail.send", json!({ "draft": changed }))["state"], "holding");crate::phone::cotton_chat::write(&handle.client(), "test.other_phone", |ctx| { cotton_tools::mcp::handlers::tables::update_produced_record(ctx, json!({ "table": "email_draft", "id": changed, "patch": { "body": "Other phone's words" } }).as_object().unwrap()).map_err(|f| f.to_string())?;Ok(json!(null)) }) .unwrap(); hold_moves(&handle, &changed, chrono::Utc::now().timestamp_millis() - 1);let other = ask(&handle, "mail.sending", json!({ "draft": changed })); assert_eq!((other["state"].as_str(), other["line"].as_str()), (Some("draft"), Some("Not sent: it changed after Send. Send it again.")), "{other}"); assert_eq!(posts(&exchange), 1);}/// RULE (UNDO SEND 3, MEDIUM 2): a send killed while going is resumed by the next look through the object's ledger,/// never left as a plain Draft: one the object already sent is Sent with no second post; one it never saw is posted;/// one waiting for a connection lists as Sending and goes once the connection is back.#[test]fn a_send_killed_while_going_is_resumed_through_the_ledger() {let (_dir, handle) = post_phone(); mailbox(&handle);let killed = |draft: &str| {let path = handle.client().layout().client_dir().join("post-holds.json");letmut all: serde_json::Map<String, Value> = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); all[draft]["stage"] = json!("going"); std::fs::write(&path, serde_json::to_vec(&all).unwrap()).unwrap();crate::phone::cotton_chat::write(&handle.client(), "test.killed", |ctx| { cotton_tools::mcp::handlers::tables::update_produced_record(ctx, json!({ "table": "email_draft", "id": draft, "patch": { "status": "sending" } }).as_object().unwrap()).map_err(|f| f.to_string())?;Ok(json!(null)) }) .unwrap(); };let went = held_draft(&handle, "Went before the kill");let never = held_draft(&handle, "Never reached the object"); killed(&went); killed(&never);let row = ask(&handle, "mail.list", json!({ "place": "drafts" }))["rows"].clone(); assert!(row.as_array().unwrap().iter().all(|r| r["mark"] == "Sending"), "never a plain Draft: {row}");let (door, exchange) = crate::phone::unlock::tests::door([ cotton_client::transport::scripted::Reply::ok(&format!(r#"{{"sends":[{{"draft":"{went}","state":"sent"}}]}}"#)), cotton_client::transport::scripted::Reply::ok(&format!(r#"{{"sends":[{{"draft":"{never}","state":null}}]}}"#)), cotton_client::transport::scripted::Reply::ok(r#"{"state":"sent","email":"e-after-kill"}"#), ]); handle.client().set_object_door(Some(std::sync::Arc::new(door))); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": went }))["state"], "sent"); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": never }))["state"], "sent"); assert_eq!(posts(&exchange), 1, "only the one the object never saw was posted");// Waiting for a connection: listed as Sending, and the next look once online sends it. handle.client().set_object_door(None);let waiting = held_draft(&handle, "Waiting for a connection"); hold_moves(&handle, &waiting, chrono::Utc::now().timestamp_millis() - 1); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": waiting }))["state"], "waiting");let row = ask(&handle, "mail.list", json!({ "place": "drafts" }))["rows"].as_array().unwrap().iter().find(|r| r["draft"] == json!(waiting)).unwrap().clone(); assert_eq!((row["mark"].as_str(), row["note"].as_str()), (Some("Sending"), Some("Waiting to send · goes when you're online")), "{row}");let online = send_door(&handle, &[r#"{"state":"sent","email":"e-online"}"#]);super::send_after_pass(&handle.client()); assert_eq!(posts(&online), 1); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": waiting }))["state"], "sent");}/// RULE (UNDO SEND 3, MEDIUM 3): the account is settled at Send and kept in the hold: a draft naming an address/// that is not his is refused in words, never sent from his first; one naming none goes from his first, and that/// resumed send is not "changed after Send".#[test]fn the_account_is_settled_at_send() {let (_dir, handle) = post_phone(); mailbox(&handle);let exchange = send_door(&handle, &[r#"{"state":"sent","email":"e-first"}"#]);let first = ask(&handle, "mail.compose", json!({}))["from"]["address"].as_str().unwrap().to_string();let stranger = ask(&handle, "mail.save", json!({ "to": [ASHA], "subject": "Not his", "body": "Words.", "from": "someone@elsewhere.example" }))["draft"].as_str().unwrap().to_string();let refused = crate::methods::dispatch(&handle, "mail.send", &json!({ "draft": stranger })).expect_err("not his"); assert_eq!((refused.code.as_str(), refused.message.as_str()), ("not_yours", "someone@elsewhere.example isn't one of your accounts. Choose who it's from."));let plain = ask(&handle, "mail.save", json!({ "to": [ASHA], "subject": "No account named", "body": "Words." }))["draft"].as_str().unwrap().to_string(); assert_eq!(ask(&handle, "mail.send", json!({ "draft": plain }))["state"], "holding"); hold_moves(&handle, &plain, chrono::Utc::now().timestamp_millis() - 1); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": plain }))["state"], "sent");let posted: Value = serde_json::from_slice(&exchange.seen().iter().find(|s| s.path.ends_with("/v1/mail/send")).unwrap().body).unwrap(); assert_eq!(posted["from"], json!(first));}/// RULE (UNDO SEND 5): a list does no network work and tells the screens nothing (so no refresh can loop): the send/// it finds due goes from the screen's poll or the sync pass.#[test]fn a_list_does_no_network_work_and_emits_nothing() {let (_dir, handle) = post_phone(); mailbox(&handle);let exchange = send_door(&handle, &[r#"{"state":"sent","email":"e-after-pass"}"#]);let draft = held_draft(&handle, "Due when the list opens"); hold_moves(&handle, &draft, chrono::Utc::now().timestamp_millis() - 1);let before = handle.events().buffered_of(crate::events::EventKind::Data); ask(&handle, "mail.list", json!({ "place": "inbox" })); ask(&handle, "mail.home", json!({})); assert_eq!(handle.events().buffered_of(crate::events::EventKind::Data), before, "no event from a list"); assert_eq!(posts(&exchange), 0, "no network work from a list");super::send_after_pass(&handle.client()); assert_eq!(posts(&exchange), 1); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": draft }))["state"], "sent");}/// RULE (UNDO SEND 5): within one run of Post the steady clock decides whether a hold is stale: a wall clock moved/// during an open hold changes nothing; one the steady clock says is long overdue goes back to Drafts.#[test]fn the_steady_clock_decides_within_a_run() {let (_dir, handle) = post_phone(); mailbox(&handle);let exchange = send_door(&handle, &[r#"{"state":"sent","email":"e-jumped"}"#]);// The wall clock jumped an hour; the steady clock says it is just due: it goes.let jumped = held_draft(&handle, "Wall clock jumped"); hold_moves(&handle, &jumped, chrono::Utc::now().timestamp_millis() - 60 * 60 * 1000);super::writer::steady_moves(&jumped, std::time::Instant::now()); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": jumped }))["state"], "sent");// The steady clock says five minutes overdue: back in Drafts, not sent late.let overdue = held_draft(&handle, "Steady overdue"); hold_moves(&handle, &overdue, chrono::Utc::now().timestamp_millis() - 1);super::writer::steady_moves(&overdue, std::time::Instant::now() - std::time::Duration::from_secs(5 * 60)); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": overdue }))["line"], "Not sent: Post was closed"); assert_eq!(posts(&exchange), 1);}/// RULE (UNDO SEND 5): an edit landing after the mail went to the object is saved in the same row, never sent; when the/// send lands the row stays a draft holding it and saying so; once the row has gone as sent, the save is refused in/// words (the shell keeps the text on screen). Never a second draft.#[test]fn an_edit_after_the_mail_has_gone_is_kept_in_its_row_and_said() {let (_dir, handle) = post_phone(); mailbox(&handle);let draft = held_draft(&handle, "Raced");// Posted, the answer not back yet (going, status sending).let path = handle.client().layout().client_dir().join("post-holds.json");letmut all: serde_json::Map<String, Value> = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); all[&draft]["stage"] = json!("going"); std::fs::write(&path, serde_json::to_vec(&all).unwrap()).unwrap();crate::phone::cotton_chat::write(&handle.client(), "test.posting", |ctx| { cotton_tools::mcp::handlers::tables::update_produced_record(ctx, json!({ "table": "email_draft", "id": draft, "patch": { "status": "sending" } }).as_object().unwrap()).map_err(|f| f.to_string())?;Ok(json!(null)) }) .unwrap();let edited = ask(&handle, "mail.save", json!({ "draft": draft, "to": [ASHA], "subject": "Raced", "body": "Words typed as it went." })); assert_eq!((edited["draft"].as_str(), edited["said"].as_str()), (Some(draft.as_str()), Some("This went as it was when you tapped Send. Your change is saved here and was not sent.")));// The object's answer lands: sent as tapped; the row stays a draft with his words.let (door, _exchange) = crate::phone::unlock::tests::door([cotton_client::transport::scripted::Reply::ok(&format!(r#"{{"sends":[{{"draft":"{draft}","state":"sent"}}]}}"#))]); handle.client().set_object_door(Some(std::sync::Arc::new(door)));super::send_after_pass(&handle.client());let rows = ask(&handle, "mail.list", json!({ "place": "drafts" }))["rows"].clone();let row = rows.as_array().unwrap().iter().find(|r| r["draft"] == json!(draft)).expect("still in Drafts").clone(); assert_eq!((row["line"].as_str(), row["note"].as_str()), (Some("Words typed as it went."), Some("This went as it was when you tapped Send. Your change is saved here and was not sent.")), "{row}"); assert_eq!(rows.as_array().unwrap().len(), 1, "never a second draft");// Gone as sent: a save is refused in words.let gone = held_draft(&handle, "Gone already");let (door, _exchange) = crate::phone::unlock::tests::door([cotton_client::transport::scripted::Reply::ok(r#"{"state":"sent","email":"e-gone"}"#)]); handle.client().set_object_door(Some(std::sync::Arc::new(door))); hold_moves(&handle, &gone, chrono::Utc::now().timestamp_millis() - 1); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": gone }))["state"], "sent");let refused = crate::methods::dispatch(&handle, "mail.save", &json!({ "draft": gone, "to": [ASHA], "subject": "Gone already", "body": "Too late." })).expect_err("gone"); assert_eq!((refused.code.as_str(), refused.message.as_str()), ("gone", "This has already gone, so your change wasn't saved. Copy it before you leave."));}/// RULE (UNDO SEND 5): a hold belongs to its account's database: another account's hold is never touched by this/// one's sweep, even though its draft is not here.#[test]fn another_accounts_hold_is_never_touched() {let (_dir, handle) = post_phone(); mailbox(&handle);let exchange = send_door(&handle, &[]);let path = handle.client().layout().client_dir().join("post-holds.json");let theirs = json!({ "stage": "held", "until": 1, "hash": "h", "db": "another-database" }); std::fs::write(&path, serde_json::to_vec(&json!({ "draft-of-another": theirs })).unwrap()).unwrap(); ask(&handle, "mail.home", json!({})); ask(&handle, "mail.list", json!({ "place": "drafts" }));super::send_after_pass(&handle.client());let mine = held_draft(&handle, "Mine"); hold_moves(&handle, &mine, chrono::Utc::now().timestamp_millis() + 600_000);let all: serde_json::Map<String, Value> = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();let kept = &all["draft-of-another"]; assert_eq!((&kept["stage"], &kept["until"], &kept["hash"], &kept["db"]), (&theirs["stage"], &theirs["until"], &theirs["hash"], &theirs["db"]), "untouched: {kept}"); assert!(crate::methods::dispatch(&handle, "mail.sending", &json!({ "draft": "draft-of-another" })).is_err()); assert_eq!(posts(&exchange), 0);}/// RULE (UNDO SEND 5): Undo is never refused because the lock is busy: it waits and answers from the record. Only/// Send may be refused as busy.#[test]fn undo_waits_for_a_busy_lock_and_send_may_be_refused() {let (_dir, handle) = post_phone(); mailbox(&handle);let draft = held_draft(&handle, "Busy");let lock_path = handle.client().layout().client_dir().join("post-holds.lock");let held = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(&lock_path).unwrap(); held.lock().unwrap();let releaser = std::thread::spawn(move || { std::thread::sleep(std::time::Duration::from_secs(4)); drop(held); });let began = std::time::Instant::now(); assert_eq!(ask(&handle, "mail.unsend", json!({ "draft": draft }))["line"], "Back in Drafts. Nothing was sent."); assert!(began.elapsed() >= std::time::Duration::from_secs(3), "it waited for the lock"); releaser.join().unwrap();let held = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(&lock_path).unwrap(); held.lock().unwrap();let busy = crate::methods::dispatch(&handle, "mail.send", &json!({ "draft": draft })).expect_err("busy"); assert_eq!((busy.code.as_str(), busy.message.as_str()), ("busy", "Post is busy with this mail. Try again in a moment.")); drop(held);}/// RULE (UNDO SEND 3, LOW): no hold changes unlocked: a lock that cannot be taken refuses the act.#[test]fn a_send_whose_lock_cannot_be_taken_is_refused() {let (_dir, handle) = post_phone(); mailbox(&handle); std::fs::create_dir_all(handle.client().layout().client_dir().join("post-holds.lock")).unwrap();let draft = ask(&handle, "mail.save", json!({ "to": [ASHA], "subject": "Unlocked", "body": "Words." }))["draft"].as_str().unwrap().to_string();let refused = crate::methods::dispatch(&handle, "mail.send", &json!({ "draft": draft })).expect_err("no lock"); assert_eq!(refused.code, "unwritable"); assert_eq!(draft_status(&handle, &draft).as_deref(), Some("draft"));}/// A held send's time moved, when it is still held.fn hold_moves_if_held(handle: &CottonHandle, draft: &str, until_ms: i64) {let path = handle.client().layout().client_dir().join("post-holds.json");let all: serde_json::Map<String, Value> = serde_json::from_slice(&std::fs::read(&path).unwrap_or_else(|_| b"{}".to_vec())).unwrap();if all.contains_key(draft) { hold_moves(handle, draft, until_ms); }}/// RULE (UNDO SEND 2, M2): a failed send ends failed; Undo after a refusal says nothing went and puts it back; Send/// again is a fresh hold with its Undo and goes through the real post; "could not tell" is said as such, never/// "already gone".#[test]fn a_failed_send_ends_failed_and_send_again_is_a_fresh_hold() {let (_dir, handle) = post_phone(); mailbox(&handle);let exchange = send_door(&handle, &[r#"{"state":"failed","said":"Your mail server refused the password. Give it again in Post."}"#, r#"{"state":"sent","email":"e-sent-1"}"#, r#"{"state":"unknown"}"#]);let draft = held_draft(&handle, "Refused first"); hold_moves(&handle, &draft, chrono::Utc::now().timestamp_millis() - 1);let refused = ask(&handle, "mail.sending", json!({ "draft": draft })); assert_eq!((refused["state"].as_str(), refused["retry"].as_str()), (Some("failed"), Some("Retry")), "{refused}"); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": draft }))["state"], "failed", "failed stays failed: no post by itself"); assert_eq!(posts(&exchange), 1);// Undo after a refusal: it never went. assert_eq!(ask(&handle, "mail.unsend", json!({ "draft": draft }))["line"], "Back in Drafts. Nothing was sent."); assert_eq!(draft_status(&handle, &draft).as_deref(), Some("draft"));// Fixed and sent again: a fresh hold, then the real post, then Sent. ask(&handle, "mail.save", json!({ "draft": draft, "to": [ASHA], "subject": "Refused first", "body": "Fixed." }));let again = ask(&handle, "mail.send", json!({ "draft": draft })); assert_eq!((again["state"].as_str(), again["undo"].as_str()), (Some("holding"), Some("Undo")), "{again}"); hold_moves(&handle, &draft, chrono::Utc::now().timestamp_millis() - 1);let sent = ask(&handle, "mail.sending", json!({ "draft": draft })); assert_eq!(sent["state"], "sent", "{sent}"); assert_eq!(posts(&exchange), 2);let late = crate::methods::dispatch(&handle, "mail.unsend", &json!({ "draft": draft })).expect_err("sent"); assert_eq!(late.code, "too_late");// Could not tell: said so, Undo says so too, and Send again is offered.let other = held_draft(&handle, "Could not tell"); hold_moves(&handle, &other, chrono::Utc::now().timestamp_millis() - 1);let unknown = ask(&handle, "mail.sending", json!({ "draft": other })); assert_eq!((unknown["state"].as_str(), unknown["retry"].as_str()), (Some("unknown"), Some("Retry")), "{unknown}");let maybe = crate::methods::dispatch(&handle, "mail.unsend", &json!({ "draft": other })).expect_err("may have gone"); assert_eq!((maybe.code.as_str(), maybe.message.as_str()), ("unknown", "Post couldn't tell whether this went. Check Sent: sent again, it may arrive twice.")); assert_eq!(ask(&handle, "mail.send", json!({ "draft": other }))["state"], "holding", "Send again, knowingly");}/// RULE (UNDO SEND 2): a hold whose time passed while Post was closed (more than two minutes) is not sent late: it/// goes back to Drafts saying so.#[test]fn a_hold_due_while_post_was_closed_is_not_sent_late() {let (_dir, handle) = post_phone(); mailbox(&handle);let exchange = send_door(&handle, &[]);let draft = held_draft(&handle, "Closed"); hold_moves(&handle, &draft, chrono::Utc::now().timestamp_millis() - 3 * 60 * 1000); ask(&handle, "mail.list", json!({ "place": "inbox" })); assert_eq!(posts(&exchange), 0);let said = ask(&handle, "mail.sending", json!({ "draft": draft })); assert_eq!(said["state"], "draft", "{said}");let row = ask(&handle, "mail.list", json!({ "place": "drafts" }))["rows"][0].clone(); assert_eq!(row["note"], "Not sent: Post was closed", "{row}"); assert_eq!(draft_status(&handle, &draft).as_deref(), Some("draft"));// Undo now answers from what happened, not "already gone". assert_eq!(ask(&handle, "mail.unsend", json!({ "draft": draft }))["line"], "Not sent: Post was closed");}/// RULE (UNDO SEND 2): Undo, the screen's poll and the home's sweep at the moment the hold runs out agree with/// what went: the mail went once and Undo says too late, or it did not go and Undo says so.#[test]fn undo_the_poll_and_the_sweep_at_the_moment_the_hold_runs_out_agree() {for round in0..6 {let (_dir, handle) = post_phone(); mailbox(&handle);let exchange = send_door(&handle, &[r#"{"state":"sent","email":"e-sent"}"#]);let draft = held_draft(&handle, "At the edge"); hold_moves(&handle, &draft, chrono::Utc::now().timestamp_millis() + 40 + round * 15);let stop = std::sync::atomic::AtomicBool::new(false);let undone = std::thread::scope(|scope| { scope.spawn(|| {while !stop.load(std::sync::atomic::Ordering::SeqCst) {let _ = crate::methods::dispatch(&handle, "mail.sending", &json!({ "draft": draft })); } }); scope.spawn(|| {while !stop.load(std::sync::atomic::Ordering::SeqCst) {super::send_after_pass(&handle.client()); } }); std::thread::sleep(std::time::Duration::from_millis(60));let undone = crate::methods::dispatch(&handle, "mail.unsend", &json!({ "draft": draft })); std::thread::sleep(std::time::Duration::from_millis(100)); stop.store(true, std::sync::atomic::Ordering::SeqCst); undone });let went = posts(&exchange);match undone {Ok(answer) => { assert_eq!(answer["line"], "Back in Drafts. Nothing was sent."); assert_eq!(went, 0, "round {round}: Undone, yet it went"); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": draft }))["state"], "draft"); }Err(late) => { assert_eq!(late.code, "too_late", "round {round}"); assert_eq!(went, 1, "round {round}: too late, yet it did not go once"); } } }}/// RULE (UNDO SEND 2, the upgrade): a draft an older build left queued, with its old hold file, is never sent by this/// build: it is back in Drafts saying it was not sent; an old failed draft says so and Send again works.#[test]fn an_older_builds_queued_and_failed_drafts_after_the_upgrade() {let (_dir, handle) = post_phone(); mailbox(&handle);let exchange = send_door(&handle, &[r#"{"state":"sent","email":"e-sent-old"}"#]);let queued = ask(&handle, "mail.save", json!({ "to": [ASHA], "subject": "Old queued", "body": "From before." }))["draft"].as_str().unwrap().to_string();let failed = ask(&handle, "mail.save", json!({ "to": [ASHA], "subject": "Old failed", "body": "From before." }))["draft"].as_str().unwrap().to_string();crate::phone::cotton_chat::write(&handle.client(), "test.old_build", |ctx| {for (id, patch) in [(&queued, json!({ "status": "queued" })), (&failed, json!({ "status": "failed", "error": "Your mail server did not send it. Try again." }))] { cotton_tools::mcp::handlers::tables::update_produced_record(ctx, json!({ "table": "email_draft", "id": id, "patch": patch }).as_object().unwrap()).map_err(|f| f.to_string())?; }Ok(json!(null)) }) .unwrap();let old = handle.client().layout().client_dir().join("post-held.json"); std::fs::write(&old, serde_json::to_vec(&json!({ queued.clone(): 1_700_000_000_000i64 })).unwrap()).unwrap(); ask(&handle, "mail.home", json!({})); assert!(!old.exists(), "the old hold file goes"); assert_eq!(draft_status(&handle, &queued).as_deref(), Some("draft")); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": queued }))["state"], "draft");let rows = ask(&handle, "mail.list", json!({ "place": "drafts" }))["rows"].clone();let note = rows.as_array().unwrap().iter().find(|r| r["draft"] == json!(queued)).unwrap()["note"].clone(); assert_eq!(note, "Not sent: Post was closed");let said = ask(&handle, "mail.sending", json!({ "draft": failed })); assert_eq!((said["state"].as_str(), said["retry"].as_str()), (Some("failed"), Some("Retry")), "{said}"); assert_eq!(posts(&exchange), 0); assert_eq!(ask(&handle, "mail.send", json!({ "draft": failed }))["state"], "holding"); hold_moves(&handle, &failed, chrono::Utc::now().timestamp_millis() - 1); assert_eq!(ask(&handle, "mail.sending", json!({ "draft": failed }))["state"], "sent"); assert_eq!(posts(&exchange), 1);// A hold the UNDO SEND FIX build made (no hash): the ledger is asked; "could not tell" is said as such, never// "changed after Send".let (door, _exchange) = crate::phone::unlock::tests::door([cotton_client::transport::scripted::Reply::ok(&format!(r#"{{"sends":[{{"draft":"{queued}","state":"unknown","words":"Cotton could not tell whether this went."}}]}}"#))]); handle.client().set_object_door(Some(std::sync::Arc::new(door)));let path = handle.client().layout().client_dir().join("post-holds.json");letmut all: serde_json::Map<String, Value> = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); all.insert(queued.clone(), json!({ "stage": "going", "until": 1 })); std::fs::write(&path, serde_json::to_vec(&all).unwrap()).unwrap();let said = ask(&handle, "mail.sending", json!({ "draft": queued })); assert_eq!((said["state"].as_str(), said["line"].as_str()), (Some("unknown"), Some("Post couldn't tell whether this went. Check Sent: sent again, it may arrive twice.")), "{said}");// One the object never saw: what is in the draft now may not be what Send was tapped on, so it is not sent.let unseen = ask(&handle, "mail.save", json!({ "to": [ASHA], "subject": "Old, never seen", "body": "Edited after the upgrade." }))["draft"].as_str().unwrap().to_string();let (door, unseen_exchange) = crate::phone::unlock::tests::door([cotton_client::transport::scripted::Reply::ok(&format!(r#"{{"sends":[{{"draft":"{unseen}","state":null}}]}}"#))]); handle.client().set_object_door(Some(std::sync::Arc::new(door)));letmut all: serde_json::Map<String, Value> = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); all.insert(unseen.clone(), json!({ "stage": "going", "until": 1 })); std::fs::write(&path, serde_json::to_vec(&all).unwrap()).unwrap();let back = ask(&handle, "mail.sending", json!({ "draft": unseen })); assert_eq!((back["state"].as_str(), back["line"].as_str()), (Some("draft"), Some("Not sent: Post was updated while it waited. Send it again.")), "{back}"); assert_eq!(posts(&unseen_exchange), 0);}/// RULE: a draft is kept without anyone to send to; Send asks for one, holds the mail for Undo send, and Undo puts/// it back in Drafts. With nowhere to send from yet, it says so in words.#[test]fn save_send_hold_and_undo() {let (_dir, handle) = post_phone(); mailbox(&handle);let saved = ask(&handle, "mail.save", json!({ "subject": "Notes", "body": "Half done" })); assert_eq!(saved["said"], "Draft saved");let draft = saved["draft"].as_str().unwrap().to_string(); assert_eq!(subjects(&ask(&handle, "mail.list", json!({ "place": "drafts" }))["rows"]), ["Notes"]);let none = crate::methods::dispatch(&handle, "mail.send", &json!({ "draft": draft })).expect_err("no one to send to"); assert_eq!(none.message, "Add someone to send it to.");let bad = crate::methods::dispatch(&handle, "mail.save", &json!({ "draft": draft, "to": ["not an address"] })).expect_err("bad"); assert_eq!(bad.code, "bad_address"); ask(&handle, "mail.save", json!({ "draft": draft, "to": [ASHA], "subject": "Notes", "body": "Half done" }));let held = ask(&handle, "mail.send", json!({ "draft": draft })); assert_eq!(held["state"], "holding"); assert_eq!(held["line"], "Sending in 5 seconds", "DECISIONS question 7: 5 seconds by default"); assert_eq!(held["undo"], "Undo");let still = ask(&handle, "mail.sending", json!({ "draft": draft })); assert_eq!(still["state"], "holding");let undone = ask(&handle, "mail.unsend", json!({ "draft": draft })); assert_eq!(undone["line"], "Back in Drafts. Nothing was sent."); ask(&handle, "mail.set", json!({ "name": "undo_send", "value": 0 }));let now = ask(&handle, "mail.send", json!({ "draft": draft })); assert!(matches!(now["state"].as_str(), Some("waiting") | Some("failed")), "{now}"); assert_eq!(now["retry"], "Retry");let gone = ask(&handle, "mail.discard", json!({ "draft": draft })); assert_eq!(gone["said"], "Draft discarded"); assert!(subjects(&ask(&handle, "mail.list", json!({ "place": "drafts" }))["rows"]).is_empty());}/// RULE (DECISIONS "How mail arrives"): adding an account says the three ways honestly before he picks, This phone/// first; the account keeps no password; its page says who fetches and how the password is kept.#[test]fn accounts_and_how_mail_arrives() {let (_dir, handle) = post_phone();let plan = ask(&handle, "mail.account.plan", json!({ "kind": "gmail" })); assert_eq!(plan["chosen"], "phone");let ways: Vec<&str> = plan["ways"].as_array().unwrap().iter().map(|w| w["id"].as_str().unwrap()).collect(); assert_eq!(ways, ["phone", "mac", "cotton"]); assert!(plan["ways"][2]["could"].as_str().unwrap().contains("could open your whole Gmail"), "{plan}"); assert_eq!(plan["steps"].as_array().unwrap().len(), 3);let added = ask(&handle, "mail.account.add", json!({ "kind": "gmail", "address": "Mira.Test@gmail.com", "way": "phone", "password": "abcd efgh ijkl mnop" })); assert_eq!(added["address"], "mira.test@gmail.com"); assert_eq!(added["status"]["line"], "Fetched by this phone"); assert!(!added.to_string().contains("abcd"), "no password kept or answered");let id = added["id"].as_str().unwrap().to_string();let twice = crate::methods::dispatch(&handle, "mail.account.add", &json!({ "kind": "gmail", "address": "mira.test@gmail.com" })).expect_err("held"); assert_eq!(twice.code, "held");let cotton = crate::methods::dispatch(&handle, "mail.account.way", &json!({ "id": id, "way": "cotton", "password": "abcd efgh ijkl mnop" })).expect_err("no object on a local phone"); assert!(matches!(cotton.code.as_str(), "offline" | "not_ready"), "{}", cotton.code);let mac = ask(&handle, "mail.account.way", json!({ "id": id, "way": "mac" })); assert_eq!(mac["status"]["line"], "Fetched by your Mac");let signed = ask(&handle, "mail.account.set", json!({ "id": id, "signature": "Mira\nInvented Studio" })); assert_eq!(signed["signature"]["value"], "Mira\nInvented Studio"); assert_eq!(ask(&handle, "mail.you", json!({}))["groups"][0]["rows"][1]["value"], "Mira");let new = ask(&handle, "mail.compose", json!({})); assert!(new["body"].as_str().unwrap().ends_with("-- \nMira\nInvented Studio"), "{new}");let list = ask(&handle, "mail.accounts", json!({})); assert_eq!(list["rows"][0]["address"], "mira.test@gmail.com");let sheet = ask(&handle, "mail.account.remove", json!({ "id": id }));let gone = ask(&handle, "mail.account.remove", json!({ "id": id, "count": sheet["ask"]["count"] })); assert!(gone["line"].as_str().unwrap().starts_with("mira.test@gmail.com is gone")); assert_eq!(ask(&handle, "mail.accounts", json!({}))["empty"], "No accounts yet.");}/// RULE (DECISIONS question 12): a domain's page says each record in words and what still needs doing, its/// addresses with the ones that land in another, plus addresses, and Anything else; it lives on his Cotton, so a/// phone without a connection says so.#[test]fn a_domain_page_in_words() {let held = json!({"domains": [{ "domain": "inventedmail.example", "proved": true, "catchAll": false, "proof": { "name": "_cotton.inventedmail.example", "value": "cotton-verify=abc" } }],"addresses": [ { "address": "hello@inventedmail.example", "forwardTo": null, "isDefault": true, "lands": null }, { "address": "shop@inventedmail.example", "forwardTo": null, "isDefault": false, "lands": "hello@inventedmail.example" }, ], });let check = json!({ "domain": "inventedmail.example", "proved": true, "lines": [ { "id": "proof", "ok": true, "said": "inventedmail.example is yours." }, { "id": "mx", "ok": true, "said": "Mail can reach Cotton." }, { "id": "spf", "ok": false, "said": "The SPF record should include include:_spf.mx.cloudflare.net." }, ]});let page = super::domains::shape("inventedmail.example", &held, Some(&check)).unwrap();let states: Vec<(&str, &str)> = page["records"].as_array().unwrap().iter().map(|r| (r["id"].as_str().unwrap(), r["state"].as_str().unwrap())).collect(); assert_eq!(states, [("proof", "done"), ("mx", "done"), ("spf", "wrong")]); assert_eq!(page["line"], "1 record still to check"); assert_eq!(page["addresses"]["title"], "2 addresses"); assert_eq!(page["addresses"]["rows"][1]["line"], "Lands in hello@inventedmail.example"); assert_eq!(page["plus"]["line"], "hello+shops@inventedmail.example lands in hello@inventedmail.example"); assert_eq!(page["catch_all"]["line"], "Bounces back as not found"); assert!(super::domains::shape("other.example", &held, None).is_err());// Remove asks once, saying what goes and that mail here stays (CONTRACT row 15, launch-ios walk POST IPHONE 5). assert_eq!(page["remove"]["call"]["method"], "mail.domain.remove");let asked = super::domains::removal("inventedmail.example", &held).unwrap(); assert_eq!(asked["ask"]["title"], "Remove inventedmail.example?"); assert!(asked["ask"]["line"].as_str().unwrap().starts_with("Its 2 addresses go") && asked["ask"]["line"].as_str().unwrap().ends_with("Mail already here stays."), "{asked}");let bare = json!({ "domains": [{ "domain": "spare.example", "proved": false, "proof": { "name": "_cotton.spare.example", "value": "cotton-verify=x" } }], "addresses": [] }); assert!(!super::domains::removal("spare.example", &bare).unwrap()["ask"]["line"].as_str().unwrap().contains('0'), "no zero said: {}", super::domains::removal("spare.example", &bare).unwrap()); assert_eq!(super::domains::shape("spare.example", &bare, None).unwrap()["addresses"]["title"], "No addresses yet"); assert!(super::domains::removal("other.example", &held).is_err());let (_dir, handle) = post_phone();let offline = crate::methods::dispatch(&handle, "mail.domains", &json!({})).expect_err("no object here"); assert_eq!(offline.code, "offline");let ask_first = ask(&handle, "mail.address.remove", json!({ "address": "shop@inventedmail.example" })); assert_eq!(ask_first["ask"]["go"], "Remove address");}/// RULE (CONTRACT "Write"): a draft carries Bcc and files; a file is listed with its size, can be taken off, and a/// mail's files may not pass what a mailbox takes.#[test]fn attach_files_and_bcc() {let (dir, handle) = post_phone();let saved = ask(&handle, "mail.save", json!({ "to": [ASHA], "bcc": ["jon@invented.example"], "subject": "Plans" }));let draft = saved["draft"].as_str().unwrap().to_string();let file = dir.path().join("floor-plan.pdf"); std::fs::write(&file, vec![7u8; 2048]).unwrap();let attached = ask(&handle, "mail.attach", json!({ "draft": draft, "path": file.to_string_lossy(), "mime": "application/pdf" })); assert_eq!(attached["attachments"][0]["name"], "floor-plan.pdf");let form = ask(&handle, "mail.compose", json!({ "draft": draft })); assert_eq!(form["bcc"], json!(["jon@invented.example"])); assert_eq!(form["attachments"].as_array().unwrap().len(), 1);let big = dir.path().join("huge.mov"); std::fs::File::create(&big).unwrap().set_len(26 * 1024 * 1024).unwrap();let refused = crate::methods::dispatch(&handle, "mail.attach", &json!({ "draft": draft, "path": big.to_string_lossy() })).expect_err("too large"); assert_eq!(refused.code, "too_large"); assert!(refused.message.starts_with("A mailbox takes up to"), "{}", refused.message);let off = ask(&handle, "mail.unattach", json!({ "draft": draft, "index": 0 })); assert_eq!(off["attachments"], json!([]));}/// RULE (meetings-comms, row 13): a Cotton-fetched account's acts go to the object itself (`/v1/mail/fetch/act`),/// never into the sealed outbox it can't read; a phone that can't reach it says so in the mailbox line.#[test]fn a_cotton_fetched_accounts_acts_go_to_the_object() {let (_dir, handle) = post_phone(); mailbox(&handle);let added = ask(&handle, "mail.account.add", json!({ "kind": "gmail", "address": ME, "way": "phone" }));let id = added["id"].as_str().unwrap().to_string();crate::phone::cotton_chat::write(&handle.client(), "test.way", |ctx| { cotton_tools::mcp::handlers::tables::update_produced_record(ctx, json!({ "table": "email_account", "id": id, "patch": { "way": "cotton" } }).as_object().unwrap()).map(|_| Value::Null).map_err(|f| f.to_string()) }) .unwrap();let after = ask(&handle, "mail.archive", json!({ "scope": "sender", "key": "orders@tiffinly.example" })); assert_eq!(after["mailbox"]["state"], "failed", "{after}"); assert!(after["mailbox"]["line"].as_str().unwrap().contains("you're offline"), "{after}");let read = ask(&handle, "mail.act", json!({ "email": "e-bank", "act": "read" })); assert_eq!(read["mailbox"]["state"], "failed");}/// An IMAP server on this machine with two invented messages, answering every connection from `script`.fn scripted_imap() -> u16 {use std::io::{BufRead, BufReader, Write};let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();let port = listener.local_addr().unwrap().port(); std::thread::spawn(move || {for stream in listener.incoming() {letOk(stream) = stream else { return }; std::thread::spawn(move || {letmut writer = stream.try_clone().unwrap();letmut reader = BufReader::new(stream); writer.write_all(b"* OK invented server ready\r\n").unwrap();let message = |uid: u32, from: &str, subject: &str, id: &str| {let raw = format!("From: {from}\r\nTo: mira.test@invented.example\r\nSubject: {subject}\r\nDate: Mon, 23 Nov 2026 10:0{uid}:00 +0530\r\nMessage-ID: <{id}@invented.example>\r\n\r\nHello from the invented server.\r\n"); format!("* {uid} FETCH (UID {uid} FLAGS () INTERNALDATE \"23-Nov-2026 10:0{uid}:00 +0530\" BODY[] {{{}}}\r\n{raw})\r\n", raw.len()) };loop {letmut line = String::new();if reader.read_line(&mut line).unwrap_or(0) == 0 {return; }let line = line.trim_end();let (tag, rest) = line.split_once(' ').unwrap_or((line, ""));let out: Vec<String> = if rest.starts_with("LOGIN") {if rest.contains("wrong") { vec![format!("{tag} NO [AUTHENTICATIONFAILED] Invalid credentials\r\n")] } else { vec![format!("{tag} OK in\r\n")] } } elseif rest.starts_with("CAPABILITY") { vec!["* CAPABILITY IMAP4rev1\r\n".into(), format!("{tag} OK\r\n")] } elseif rest.starts_with("EXAMINE") { vec!["* 2 EXISTS\r\n".into(), "* OK [UIDVALIDITY 7] ok\r\n".into(), "* OK [UIDNEXT 3] ok\r\n".into(), format!("{tag} OK [READ-ONLY] done\r\n")] } elseif rest.starts_with("UID SEARCH ALL") { vec!["* SEARCH 1 2\r\n".into(), format!("{tag} OK\r\n")] } elseif rest.starts_with("UID SEARCH UID 1:1") { vec!["* SEARCH 1\r\n".into(), format!("{tag} OK\r\n")] } elseif rest.starts_with("UID SEARCH") {// `n:*` answers the last message even below n. vec!["* SEARCH 2\r\n".into(), format!("{tag} OK\r\n")] } elseif rest.starts_with("UID FETCH") {letmut out = Vec::new();if rest.contains('1') { out.push(message(1, "Asha Example <asha@invented.example>", "Flat keys", "m1")); }if rest.contains('2') { out.push(message(2, "Tiffinly <orders@tiffinly.example>", "Your order receipt", "m2")); } out.push(format!("{tag} OK\r\n")); out } elseif rest.starts_with("LOGOUT") { vec!["* BYE\r\n".into(), format!("{tag} OK\r\n")] } else { vec![format!("{tag} BAD what\r\n")] };for o in out {if writer.write_all(o.as_bytes()).is_err() {return; } } } }); } }); port}/// RULE (CONTRACT row 12): This phone fetches reads the account's new mail over IMAP, read-only, into the very rows/// the Mac writes; a second round brings only what is new; a refused password says so, and nothing is kept of it.#[test]fn this_phone_fetches_over_imap() {let (_dir, handle) = post_phone();let port = scripted_imap();let added = ask(&handle, "mail.account.add", json!({ "kind": "imap", "address": "mira.test@invented.example", "way": "phone", "host": "imap.invented.example" }));let id = added["id"].as_str().unwrap().to_string();let server = json!({ "host": "127.0.0.1", "port": port, "tls": false });let round = ask(&handle, "mail.fetch", json!({ "account": id, "password": "invented-app-password", "server": server }));// The first round takes the newest (one, under test). assert_eq!(round["fetched"], 1, "{round}"); assert_eq!(round["line"], "Fetched by this phone · 1 new"); assert_eq!(round["notify"], json!([]), "an account's first round rings nothing: {round}"); assert_eq!(subjects(&ask(&handle, "mail.list", json!({ "place": "inbox" }))["rows"]), ["Your order receipt"]);// The next brings nothing new, and the older mail below it (all mail on the phone).let older = ask(&handle, "mail.fetch", json!({ "account": id, "password": "invented-app-password", "server": server })); assert_eq!(older["fetched"], 1, "{older}");let inbox = subjects(&ask(&handle, "mail.list", json!({ "place": "inbox" }))["rows"]); assert!(inbox.contains(&"Flat keys".to_string()) && inbox.contains(&"Your order receipt".to_string()), "{inbox:?}");let again = ask(&handle, "mail.fetch", json!({ "account": id, "password": "invented-app-password", "server": server })); assert_eq!(again["fetched"], 0, "the mailbox is whole: {again}");let refused = ask(&handle, "mail.fetch", json!({ "account": id, "password": "wrong", "server": server })); assert_eq!(refused["state"], "refused");let far = ask(&handle, "mail.fetch", json!({ "account": id, "password": "x", "server": { "host": "192.0.2.1", "port": 143, "tls": false } })); assert_eq!(far["state"], "stopped", "a password never goes in the clear to another machine: {far}");}/// RULE (Post's Notifications): a round's new mail rings for people by default, for anyone with `everyone`, never/// with `none`; mail already read, out of the Inbox, or his own never rings. Each says who and the subject.#[test]fn new_mail_rings_by_the_notifications_setting() {let (_dir, handle) = post_phone();let mail = |id: &str, name: &str, from: &str, subject: &str, unread: bool, in_inbox: bool| { json!({ "email": { "id": id, "data": { "from_email": from, "from_name": name, "subject": subject, "unread": unread, "in_inbox": in_inbox, "direction": "in" } }, "thread": { "id": format!("t-{id}") } }) };let fresh = vec![ mail("e1", "Asha Example", "asha@invented.example", "Flat keys", true, true), mail("e2", "Tiffinly", "orders@tiffinly.example", "Your order receipt #4471", true, true), mail("e3", "Asha Example", "asha@invented.example", "Already read", false, true), mail("e4", "Asha Example", "asha@invented.example", "", true, true), mail("e5", "Asha Example", "asha@invented.example", "Archived elsewhere", true, false), ];let ids = |said: &[Value]| said.iter().map(|n| n["id"].as_str().unwrap_or_default().to_string()).collect::<Vec<_>>();let people = super::fetcher::notify_of(&handle.client(), &fresh).expect("notify"); assert_eq!(ids(&people), ["e1", "e4"], "{people:?}"); assert_eq!(people[0]["title"], "Asha Example"); assert_eq!(people[0]["body"], "Flat keys"); assert_eq!(people[0]["thread"], "t-e1"); assert_eq!(people[1]["body"], "(no subject)"); ask(&handle, "mail.set", json!({ "name": "notifications", "value": "everyone" })); assert_eq!(ids(&super::fetcher::notify_of(&handle.client(), &fresh).expect("notify")), ["e1", "e2", "e4"]); ask(&handle, "mail.set", json!({ "name": "notifications", "value": "none" })); assert!(super::fetcher::notify_of(&handle.client(), &fresh).expect("notify").is_empty());}/// RULE: a forward lists the mail's files and carries them on the draft; one not on this phone yet is said at Send.#[test]fn a_forward_carries_its_files() {let (_dir, handle) = post_phone(); mailbox(&handle);let forward = ask(&handle, "mail.compose", json!({ "mode": "forward", "thread": "et-flat" })); assert_eq!(forward["attachments"][0]["name"], "lease.pdf", "{forward}");let carry = json!([forward["attachments"][0]["carry"]]);let saved = ask(&handle, "mail.save", json!({ "to": ["jon@invented.example"], "subject": forward["subject"], "carry": carry }));let draft = saved["draft"].as_str().unwrap();let form = ask(&handle, "mail.compose", json!({ "draft": draft })); assert_eq!(form["attachments"][0]["name"], "lease.pdf"); ask(&handle, "mail.set", json!({ "name": "undo_send", "value": 0 }));let refused = crate::methods::dispatch(&handle, "mail.send", &json!({ "draft": draft })).expect_err("the file is not here"); assert_eq!(refused.code, "attachment_coming"); assert_eq!(refused.message, "lease.pdf isn't on this phone yet. Open it in the mail once, then send.");}/// RULE: Rename gives a sender his own name for them, over what their mail calls them; empty gives it back.#[test]fn rename_a_sender() {let (_dir, handle) = post_phone(); mailbox(&handle);let renamed = ask(&handle, "mail.sender.name", json!({ "key": "@tiffinly.example", "name": "Lunch orders" })); assert_eq!(renamed["title"], "Lunch orders", "{renamed}"); assert_eq!(renamed["addresses"]["rows"][0]["line"], "Tiffinly", "each address keeps its own name: {}", renamed["addresses"]);let list = ask(&handle, "mail.senders", json!({ "sort": "az" })); assert!(list["rows"].as_array().unwrap().iter().any(|r| r["title"] == "Lunch orders"));let back = ask(&handle, "mail.sender.name", json!({ "key": "@tiffinly.example", "name": "" })); assert_eq!(back["title"], "Tiffinly");}/// AT HIS SIZE (CONTRACT row 19): a Post phone holding an invented mailbox as large as his (about 110,000 mails in/// 80,000 conversations, `developer.inventMail`'s own measure; COTTON_POST_SIZE and COTTON_POST_THREADS change it), and/// how long each screen's call takes on it. Run by name: it writes a large copy.////// `pnpm -s box:cargo test -p cotton-ffi --lib -- --ignored post::tests::post_at_his_size --nocapture`#[test]#[ignore]fn post_at_his_size() {let size = std::env::var("COTTON_POST_SIZE").ok().and_then(|v| v.parse().ok()).unwrap_or(110_000usize);let threads = std::env::var("COTTON_POST_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(80_000usize);// COTTON_POST_KEEP names a folder to keep the invented phone in, so a second run measures without writing it again.let kept = std::env::var("COTTON_POST_KEEP").ok().map(std::path::PathBuf::from);let temp = tempfile::tempdir().expect("a temp container");let path = kept.clone().unwrap_or_else(|| temp.path().to_path_buf());let marker = path.join(format!("post-at-size-{size}-{threads}.done"));let fresh = !marker.exists();if fresh && kept.is_some() {let _ = std::fs::remove_dir_all(&path); std::fs::create_dir_all(&path).unwrap(); }let opening = std::time::Instant::now();let handle = post_phone_in(&path, cotton_core::flavor::Flavor::Dev, fresh); println!("POST AT SIZE opened in {:.0} ms (a copy made by an older build moves to this build's shape here)", opening.elapsed().as_secs_f64() * 1000.0);// What the phone's pass after a sync does (it never syncs here): the indexes a move left to the background.let building = std::time::Instant::now();// And the worst case the quiet keeps away: a write that comes while the widest index is being made waits for it.let missing = handle.client().with_writer(|r| cotton_store::index_later::missing(r.driver).map_err(|e| e.to_string())).unwrap();// The app comes to the front while the widest is being made: it is taken back, and the person's write that// follows waits only for that.let forward = std::sync::atomic::AtomicBool::new(false);let taken_back = std::thread::scope(|scope| {let builder = scope.spawn(|| crate::phone::mail_index::build_later_after(&handle.client(), std::time::Duration::ZERO, &|| !forward.load(std::sync::atomic::Ordering::SeqCst)).unwrap());if !missing.is_empty() { std::thread::sleep(std::time::Duration::from_millis(500));let t = std::time::Instant::now(); forward.store(true, std::sync::atomic::Ordering::SeqCst);crate::phone::mail_index::came_forward(); ask(&handle, "mail.save", json!({ "to": ["ada@invented.example"], "subject": "Invented draft", "body": "Written as the app came forward." })); println!("POST AT SIZE the app came forward while {} was made: a write then waited {:.0} ms", missing[0], t.elapsed().as_secs_f64() * 1000.0); } builder.join().unwrap() }); println!("POST AT SIZE made before it came forward: {taken_back:?}");let building = std::time::Instant::now();let built = crate::phone::mail_index::build_later_after(&handle.client(), std::time::Duration::ZERO, &|| true).unwrap();if !built.is_empty() { println!("POST AT SIZE built after the move, in the background: {built:?} in {:.0} ms", building.elapsed().as_secs_f64() * 1000.0); }let started = std::time::Instant::now();letmut at = if fresh { 0 } else { size };while at < size {let n = 5000.min(size - at); ask(&handle, "developer.inventMail", json!({ "me": { "address": ME }, "generate": { "emails": n, "threads": threads, "from": at, "total": size, "step": 7, "end": "2026-11-21T09:00:00Z" } })); at += n; }if fresh { std::fs::write(&marker, b"").unwrap(); println!("POST AT SIZE {size} mails in {threads} conversations written in {:.0} s", started.elapsed().as_secs_f64()); }letmut slowest = (String::new(), 0f64);letmut warm: Vec<(String, f64)> = Vec::new();// Each read twice: the first warms the copy's pages, the second is what a screen opened again waits (warm).letmut timed = |name: &str, method: &str, request: Value| -> Value {let reads = !matches!(method, "mail.archive" | "mail.undo" | "mail.do" | "mail.act");let t = std::time::Instant::now();letmut answer = ask(&handle, method, request.clone());let cold = t.elapsed().as_secs_f64();letmut took = cold;if reads {let t = std::time::Instant::now(); answer = ask(&handle, method, request); took = t.elapsed().as_secs_f64(); } println!("POST AT SIZE {name}: {:.0} ms warm ({:.0} ms first)", took * 1000.0, cold * 1000.0); warm.push((name.to_string(), took));if took > slowest.1 { slowest = (name.to_string(), took); } answer };let home = timed("home", "mail.home", json!({}));let inbox = timed("inbox", "mail.list", json!({ "place": "inbox" })); timed("inbox, next page", "mail.list", json!({ "place": "inbox", "after": inbox["next"] })); timed("archived", "mail.list", json!({ "place": "archived" }));let senders = timed("senders, most", "mail.senders", json!({ "sort": "most" })); timed("senders, never read", "mail.senders", json!({ "sort": "never_read" }));let top = senders["rows"][0]["key"].clone(); println!("POST AT SIZE {} senders, the first {} · inbox rows {}", senders["rows"].as_array().map_or(0, Vec::len), top, inbox["rows"].as_array().map_or(0, Vec::len)); timed("one sender", "mail.sender", json!({ "key": top }));let thread = inbox["rows"][0]["thread"].clone(); timed("a conversation", "mail.thread", json!({ "thread": thread })); timed("search", "mail.search", json!({ "text": "receipt" }));let _ = cotton_store::spans::take();let archived = timed("archive a whole sender", "mail.archive", json!({ "scope": if top.as_str().is_some_and(|k| k.starts_with('@')) { "domain" } else { "sender" }, "key": top })); println!("POST AT SIZE archived: {}", archived["line"]);for (name, took, n) in cotton_store::spans::take().into_iter().take(14) { println!("POST AT SIZE span {name}: {:.0} ms over {n}", took.as_secs_f64() * 1000.0); } timed("undo it", "mail.undo", json!({ "after": archived["after"] }));// The acts that fan out per mail (CONTRACT row 19's list): Delete a whole sender, Block with "also delete", and a// group marked read, each timed at his size.let scope_of = |key: &Value| if key.as_str().is_some_and(|k| k.starts_with('@')) { "domain" } else { "sender" };let second = senders["rows"][1]["key"].clone();let sheet = ask(&handle, "mail.ask", json!({ "act": "delete", "scope": scope_of(&second), "key": second }));let _ = cotton_store::spans::take();let deleted = timed("delete a whole sender", "mail.do", json!({ "plan": sheet["plan"] })); println!("POST AT SIZE deleted: {}", deleted["line"]);for (name, took, n) in cotton_store::spans::take().into_iter().take(8) { println!("POST AT SIZE span {name}: {:.0} ms over {n}", took.as_secs_f64() * 1000.0); } timed("bring it back", "mail.undo", json!({ "after": deleted["after"] }));let third = senders["rows"][2]["key"].clone();let sheet = ask(&handle, "mail.ask", json!({ "act": "block", "scope": scope_of(&third), "key": third }));let blocked = timed("block with also delete", "mail.do", json!({ "plan": sheet["plan"], "also": true })); println!("POST AT SIZE blocked: {} / {}", blocked["line"], blocked["deleted"]["line"]);// A group's unread, at most 5,000 (a group's Mark read takes every unread mail in it).let unread: Vec<String> = handle .client() .with_file(|f| { f.driver.all("SELECT id FROM cotton_emails WHERE unread = 1 AND trashed_at IS NULL AND archived_at IS NULL LIMIT 5000", &[]).map_err(|e| e.to_string()) }) .unwrap() .iter() .filter_map(|r| r.text("id").map(str::to_string)) .collect();let read = timed(&format!("mark {} unread Inbox mails read", unread.len()), "mail.act", json!({ "act": "read", "emails": unread })); println!("POST AT SIZE marked read: {}", read["line"]); timed("home again", "mail.home", json!({}));let _ = home; println!("POST AT SIZE slowest: {} ({:.0} ms)", slowest.0, slowest.1 * 1000.0);// The coordinator's bar (25 Nov 2026): home, a sender, a conversation, search and Archived each within 300 ms warm// at his size. Said for each; the test fails when one goes past a second, a bad regression on any machine.let bar = ["home", "one sender", "a conversation", "search", "archived"];letmut over = Vec::new();for (name, took) in warm.iter().filter(|(n, _)| bar.contains(&n.as_str())) { println!("POST AT SIZE bar {name}: {:.0} ms warm, {}", took * 1000.0, if *took <= 0.3 { "within 300 ms" } else { "OVER 300 ms" });if *took > 1.0 { over.push(format!("{name} {:.2} s", took)); } } assert!(over.is_empty(), "past a second warm at his size: {over:?}");// Cold: the first open after a new mail lands, and after the app starts (the coordinator's bar: under 500 ms).letmut cold: Vec<(String, f64)> = Vec::new();letmut once = |phase: &str, handle: &CottonHandle, name: &str, method: &str, request: Value| {let t = std::time::Instant::now(); ask(handle, method, request);let took = t.elapsed().as_secs_f64(); println!("POST AT SIZE cold {phase} {name}: {:.0} ms", took * 1000.0); cold.push((format!("{phase} {name}"), took)); };let five = |sender: &Value, thread: &Value| vec![ ("home", "mail.home", json!({})), ("one sender", "mail.sender", json!({ "key": sender })), ("a conversation", "mail.thread", json!({ "thread": thread })), ("search", "mail.search", json!({ "text": "receipt" })), ("archived", "mail.list", json!({ "place": "archived" })), ];for (k, (name, method, request)) in five(&top, &thread).into_iter().enumerate() { ask(&handle, "developer.inventMail", json!({ "me": { "address": ME }, "generate": { "emails": 1, "threads": threads, "from": size + k, "total": size + 100, "step": 7, "end": "2026-11-21T09:00:00Z" } })); once("after new mail", &handle, name, method, request); } drop(handle);let handle = post_phone_in(&path, cotton_core::flavor::Flavor::Dev, false);for (name, method, request) in five(&top, &thread) { once("after start", &handle, name, method, request); }let slow: Vec<String> = cold.iter().filter(|(_, t)| *t > 0.5).map(|(n, t)| format!("{n} {:.0} ms", t * 1000.0)).collect(); println!("POST AT SIZE cold over 500 ms: {slow:?}");// The coordinator's bar for cold opens (26 Nov 2026): under 500 ms. The test fails past 1.5 s, a bad regression.let bad: Vec<String> = cold.iter().filter(|(_, t)| *t > 1.5).map(|(n, t)| format!("{n} {:.2} s", t)).collect(); assert!(bad.is_empty(), "past 1.5 s cold at his size: {bad:?}");}/// RULE (DECISIONS "Archive in one tap", the coordinator's conditions, 25 Nov 2026): a whole sender's Archive is one/// row however many mails, and stays exact. Mail landing after it is not archived, even with an older date; a mail/// moved back to the Inbox stays there; Undo is deleting the row.#[test]fn archiving_a_whole_sender_is_one_row_and_stays_exact() {let (_dir, handle) = post_phone(); mailbox(&handle); mail(&handle, Mail { id: "e-shop-2", thread: "et-shop-2", from: ("offers@kitebox.example", "Kitebox"), subject: "Socks for winter", body: "Shop now.", minutes_ago: 40, ..Default::default() });let done = ask(&handle, "mail.archive", json!({ "scope": "sender", "key": "offers@kitebox.example" })); assert_eq!(done["count"], 2, "{done}");let written = crate::phone::cotton_chat::read(&handle.client(), "test", |ctx| Ok(json!(super::cuts::read_cuts(ctx).len()))).unwrap(); assert_eq!(written, 1, "one row for the whole sender");let held = crate::phone::cotton_chat::read(&handle.client(), "test", |ctx| Ok(json!(crate::phone::cotton_chat::rows(ctx, "SELECT id FROM cotton_emails WHERE archived_at IS NOT NULL", &[])?.len()))).unwrap(); assert_eq!(held, 0, "no mail row written");let inbox = |h: &CottonHandle| subjects(&ask(h, "mail.list", json!({ "place": "inbox" }))["rows"]); assert!(!inbox(&handle).iter().any(|s| s.contains("40% off") || s.contains("Socks")), "{:?}", inbox(&handle)); assert!(subjects(&ask(&handle, "mail.list", json!({ "place": "archived" }))["rows"]).contains(&"Socks for winter".to_string()));// New mail after the Archive: in the Inbox. A late one dated before it, landed after: in the Inbox too. mail(&handle, Mail { id: "e-shop-3", thread: "et-shop-3", from: ("offers@kitebox.example", "Kitebox"), subject: "New arrivals", body: "Shop now.", minutes_ago: -1, ..Default::default() }); mail(&handle, Mail { id: "e-shop-late", thread: "et-shop-late", from: ("offers@kitebox.example", "Kitebox"), subject: "Delayed offer", body: "Shop now.", minutes_ago: 50, ..Default::default() }); sql(&handle, "UPDATE cotton_emails SET created_at = ?, landed_at = ? WHERE id = 'e-shop-late'", &[t(&iso(-2)), t(&iso(-2))]);let now = inbox(&handle); assert!(now.contains(&"New arrivals".to_string()) && now.contains(&"Delayed offer".to_string()), "{now:?}");// One moved back to the Inbox stays there, over the row. ask(&handle, "mail.act", json!({ "act": "restore", "email": "e-shop-2" })); assert!(inbox(&handle).contains(&"Socks for winter".to_string()), "kept in the Inbox"); assert!(!inbox(&handle).iter().any(|s| s.contains("40% off")), "the rest stays archived");// Undo: the row goes, and everything is back. ask(&handle, "mail.undo", json!({ "after": done["after"] })); assert!(inbox(&handle).iter().any(|s| s.contains("40% off")), "{:?}", inbox(&handle));let left = crate::phone::cotton_chat::read(&handle.client(), "test", |ctx| Ok(json!(super::cuts::read_cuts(ctx).len()))).unwrap(); assert_eq!(left, 0);}/// RULE (launch-ios walk, POST IPHONE 5): Send with no account to send from is refused before anything is held or/// sent, in words, with the act that adds one.#[test]fn send_with_no_account_is_refused_first() {let (_dir, handle) = post_phone();let saved = ask(&handle, "mail.save", json!({ "to": ["jon@invented.example"], "subject": "Hello", "body": "An invented line." }));let refused = crate::methods::dispatch(&handle, "mail.send", &json!({ "draft": saved["draft"] })).expect_err("no account"); assert_eq!(refused.code, "no_sender"); assert_eq!(refused.message, "Add an account to send from"); assert_eq!(refused.details["act"]["method"], "mail.account.plan"); assert_eq!(ask(&handle, "mail.compose", json!({ "draft": saved["draft"] }))["subject"], "Hello", "still a draft, nothing held");}/// RULE (sync seen, owner 25 Nov 2026): `sync.status` carries the one quiet line every home draws, `seen`, with its state, its words, what VoiceOver says and how long a pass must run before catching up shows, the same line `shell.home` gives Android.#[test]fn sync_status_carries_the_seen_line() {let (_dir, handle) = post_phone();let status = crate::methods::dispatch(&handle, "sync.status", &json!({})).expect("sync.status");let seen = &status["seen"]; assert!(seen.is_object(), "{status}"); assert_eq!(seen["showAfterMs"], 1_000); assert!(seen["line"].as_str().is_some_and(|l| !l.is_empty()), "{seen}"); assert!(seen["spoken"].is_string(), "{seen}");// One line for both phones: `sync.status` and `shell.home` say the same.let home = crate::methods::shell_account::seen(&handle.client()); assert_eq!(home["state"], seen["state"], "{home}"); assert_eq!(home["line"], seen["line"], "{home}");// A phone that never signed in says so. assert_eq!(seen["state"], "signed_out", "{seen}");}/// RULE (SYNC SEEN, owner 25 Nov 2026: a row being edited while a newer copy is on its way says so before he types):/// `sync.row { table }` answers `coming` and the line only while a pass still brings rows of that table; with no pass/// running nothing is on its way, and the words are the shell's.#[test]fn sync_row_says_a_newer_copy_is_coming_only_while_its_table_arrives() {let (_dir, handle) = post_phone();let quiet = ask(&handle, "sync.row", json!({ "table": "cotton_notes" })); assert_eq!(quiet, json!({ "coming": false, "line": null }));let refused = crate::methods::dispatch(&handle, "sync.row", &json!({})).expect_err("no table"); assert_eq!(refused.code, "bad_request");let words = cotton_core::rules::sync_status::SyncWords::shipped(); assert_eq!(words.row["coming"], "A newer copy may be on its way. Wait a moment before you change this.");}/// RULE: `developer.cutNetwork` (a simulator's airplane mode for walks) answers only in Cotton Dev; a live build refuses it.#[test]fn the_network_cut_is_cotton_devs_alone() {let (_dir, live) = post_phone();let refused = crate::methods::dispatch(&live, "developer.cutNetwork", &json!({ "on": true })).expect_err("live refuses"); assert_eq!(refused.code, "not_dev"); assert!(!cotton_client::transport::wire::CUT.load(std::sync::atomic::Ordering::SeqCst));let (_dev_dir, dev) = post_phone_as(cotton_core::flavor::Flavor::Dev);// Lifting only: setting it here would cut every other test's dials in this process. assert_eq!(ask(&dev, "developer.cutNetwork", json!({ "on": false }))["cut"], false);}/// RULE (SCHEMA 155, POST AT SIZE cold, 26 Nov 2026): Home's tallies, Archived and Files read schema 155's partial/// indexes, with an Archive row standing: never a pass over every mail, which is mostly bodies (110,000 at his size).#[test]fn home_archived_and_files_read_their_indexes() {let (_dir, handle) = post_phone(); mailbox(&handle);let senders = ask(&handle, "mail.senders", json!({ "sort": "most" }));let key = senders["rows"][0]["key"].clone(); ask(&handle, "mail.archive", json!({ "scope": if key.as_str().is_some_and(|k| k.starts_with('@')) { "domain" } else { "sender" }, "key": key }));let plans = crate::phone::cotton_chat::read(&handle.client(), "test.plans", |ctx| {let know = super::cuts::know(ctx)?; assert!(!know.cuts.is_empty(), "an Archive row stands");let plan = |ctx: &mut cotton_tools::mcp::dispatch::Ctx<'_>, sql: &str, params: &[SqlValue]| -> Result<Vec<String>, String> {Ok(crate::phone::cotton_chat::rows(ctx, &format!("EXPLAIN QUERY PLAN {sql}"), params)?.iter().filter_map(|r| r["detail"].as_str().map(str::to_string)).collect()) };let ws = crate::phone::cotton_chat::ws(ctx);let tallies = plan(ctx, &super::tallies_sql(&super::cuts::inbox(&know, ""), ""), &[SqlValue::Text("2026-11-26".into()), ws.clone()])?;let archived = plan(ctx, &format!("SELECT t.id FROM cotton_email_threads t WHERE t.workspace_id = ?{} ORDER BY t.last_at DESC, t.id DESC LIMIT 120", super::archived_sets(&know, ctx.workspace_id)), &[ws.clone()])?;let files = plan(ctx, &super::files_sql(""), &[ws])?;Ok(json!({ "tallies": tallies, "archived": archived, "files": files })) }) .unwrap();let has = |part: &str, index: &str| plans[part].as_array().unwrap().iter().any(|d| d.as_str().is_some_and(|d| d.contains(index)));let scans = |part: &str| plans[part].as_array().unwrap().iter().any(|d| d.as_str().is_some_and(|d| d.starts_with("SCAN") && d.contains("cotton_emails") && !d.contains("INDEX"))); assert!(has("tallies", "COVERING INDEX idx_cotton_emails_inbox"), "{plans}"); assert!(has("archived", "idx_cotton_emails_archived") && has("archived", "COVERING INDEX idx_cotton_emails_inbox"), "{plans}"); assert!(has("files", "idx_cotton_emails_files"), "{plans}");for part in ["tallies", "archived", "files"] { assert!(!scans(part), "{part} reads every mail: {plans}"); }}/// RULE (DECISIONS: attachments; POST Android walk, 26 Nov 2026): a kind that runs code is offered only to Save,/// whether it is reached from its thread or from Files.#[test]fn a_file_that_runs_code_is_known_by_its_kind() {usesuper::runs_code; assert!(runs_code("plotter-setup.EXE")); assert!(runs_code("macros.docm")); assert!(!runs_code("lease-draft.pdf")); assert!(!runs_code("notes.txt"));}/// A phone whose copy lacks the indexes a move leaves to the background (SCHEMA 155), as a moved copy does.fn moved_phone() -> (tempfile::TempDir, CottonHandle) {let (dir, handle) = post_phone(); mailbox(&handle); handle.client().with_writer(|replica| {for name in cotton_store::index_later::LATER { replica.driver.exec(&format!("DROP INDEX {name}")).map_err(|e| e.to_string())?; }Ok(()) }).unwrap(); (dir, handle)}/// RULE (SCHEMA 155 REVIEW): an index a move left is made only once the copy has had no write for the quiet time:/// a write in that time puts it off, so a send or an Archive never waits behind one.#[test]fn the_indexes_wait_for_a_quiet_copy() {let (_dir, handle) = moved_phone();let client = handle.client();let quiet = std::time::Duration::from_millis(800); assert!(crate::phone::mail_index::build_later_after(&client, quiet, &|| true).unwrap().is_empty(), "the first pass only starts the quiet"); std::thread::sleep(std::time::Duration::from_millis(400));let key = ask(&handle, "mail.senders", json!({ "sort": "most" }))["rows"][0]["key"].clone();let before = client.moved(); ask(&handle, "mail.archive", json!({ "scope": if key.as_str().is_some_and(|k| k.starts_with('@')) { "domain" } else { "sender" }, "key": key })); assert_ne!(client.moved(), before, "an Archive is a write the quiet sees"); std::thread::sleep(std::time::Duration::from_millis(500)); assert!(crate::phone::mail_index::build_later_after(&client, quiet, &|| true).unwrap().is_empty(), "a write began the quiet again");// Work the Archive set going on its own (the search index's fill) may write again a moment later and start the// quiet over: so passes go on, a quiet apart, until one finds the copy quiet for long enough.letmut made = Vec::new();for _ in0..10 { std::thread::sleep(std::time::Duration::from_millis(900)); made = crate::phone::mail_index::build_later_after(&client, quiet, &|| true).unwrap();if !made.is_empty() {break; } } assert_eq!(made, cotton_store::index_later::LATER, "quiet for long enough");}/// RULE (SCHEMA 155 REVIEW): a phone short of room is not asked to make an index, and once one is refused this/// launch never asks again, room or not (SQLITE_FULL half way is a 7 s stall each pass).#[test]fn a_phone_short_of_room_is_not_asked_again_this_launch() { #[derive(Debug)]structFree(u64);implcrate::phone::disk::DiskforFree {fn size_of(&self, _: &std::path::Path) -> u64 {0 }fn free_bytes(&self, _: &std::path::Path) -> Option<u64> {Some(self.0) } }let (_dir, handle) = moved_phone();let client = handle.client(); client.set_disk(std::sync::Arc::new(Free(10 * 1024 * 1024))); assert!(crate::phone::mail_index::build_later_after(&client, std::time::Duration::ZERO, &|| true).unwrap().is_empty());let path = client.layout().replica(&client.attached_database().unwrap()); assert!(crate::phone::mail_index::later_refused(&path).is_some_and(|why| why.contains("MB free")), "{:?}", crate::phone::mail_index::later_refused(&path)); client.set_disk(std::sync::Arc::new(Free(100 * 1024 * 1024 * 1024))); assert!(crate::phone::mail_index::build_later_after(&client, std::time::Duration::ZERO, &|| true).unwrap().is_empty(), "not asked again this launch"); assert_eq!(client.with_writer(|r| cotton_store::index_later::missing(r.driver).map_err(|e| e.to_string())).unwrap(), cotton_store::index_later::LATER);}/// A moved phone holding `n` more invented mails, cloned from its first (an index over them takes long enough to/// be caught half way).fn moved_phone_of(n: u32) -> (tempfile::TempDir, CottonHandle, std::path::PathBuf) {let (dir, handle) = moved_phone();let client = handle.client(); client .with_writer(|replica| {let columns: Vec<String> = replica.driver.all("SELECT name FROM pragma_table_info('cotton_emails')", &[]).map_err(|e| e.to_string())?.iter().filter_map(|r| r.text("name").map(str::to_string)).collect();let chosen: Vec<String> = columns .iter() .map(|c| match c.as_str() {"id" => "'bulk-' || n".to_string(),"external_id" => "'x-bulk-' || n".to_string(),"from_email" => "'p' || (n % 997) || '@invented.example'".to_string(),"body" => "''".to_string(), other => format!("\"{other}\""), }) .collect();let named = columns.iter().map(|c| format!("\"{c}\"")).collect::<Vec<_>>().join(","); replica .driver .exec(&format!("WITH RECURSIVE seq(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM seq WHERE n < {n}) INSERT INTO cotton_emails ({named}) SELECT {} FROM seq, (SELECT * FROM cotton_emails ORDER BY rowid LIMIT 1)", chosen.join(",") )) .map_err(|e| e.to_string()) }) .unwrap();let path = client.layout().replica(&client.attached_database().unwrap()); (dir, handle, path)}fn missing_indexes(client: &crate::shell::client::ClientController) -> Vec<&'static str> { client.with_writer(|r| cotton_store::index_later::missing(r.driver).map_err(|e| e.to_string())).unwrap()}fn whole(client: &crate::shell::client::ClientController) -> String { client.with_writer(|r| r.driver.get("PRAGMA quick_check", &[]).map_err(|e| e.to_string())).unwrap().and_then(|r| r.text("quick_check").map(str::to_string)).unwrap_or_default()}/// RULE (SCHEMA 155 REVIEW, INDEX LATER 2): the indexes a move left are made only while nobody waits on the copy./// One being made when someone comes is taken back half way: the file whole, the index absent, no refusal, and the/// next time makes it.#[test]fn an_index_is_taken_back_half_way_and_made_the_next_time() {let (_dir, handle, path) = moved_phone_of(150_000);let client = handle.client();let quiet = std::time::Duration::ZERO; assert!(crate::phone::mail_index::build_later_after(&client, quiet, &|| false).unwrap().is_empty(), "in front: nothing");let made = std::thread::scope(|scope| {let builder = scope.spawn(|| crate::phone::mail_index::build_later_after(&client, quiet, &|| true).unwrap());// Under way: its progress handler has looked at its flag.let began = std::time::Instant::now();whilecrate::phone::mail_index::watched_at(&path) < 3 { assert!(!builder.is_finished(), "the index was made before it could be caught"); assert!(began.elapsed() < std::time::Duration::from_secs(60)); std::thread::yield_now(); } assert!(crate::phone::mail_index::came_forward_at(&path)); builder.join().unwrap() }); assert!(made.is_empty(), "taken back half way: {made:?}"); assert_eq!(crate::phone::mail_index::later_taken_back(&path), 1); assert!(crate::phone::mail_index::later_refused(&path).is_none(), "coming forward is no refusal"); assert_eq!(missing_indexes(&client), cotton_store::index_later::LATER, "the index is absent"); assert_eq!(whole(&client), "ok", "the file as it was");let rest = crate::phone::mail_index::build_later_after(&client, quiet, &|| true).unwrap(); assert_eq!(rest, cotton_store::index_later::LATER, "the next time makes them all"); assert_eq!(whole(&client), "ok");}/// RULE (INDEX LATER 2 REVIEW): the away is asked again once the writer is held. A pass holding the writer, the app/// coming forward meanwhile, then the pass ending: the build that waited makes nothing.#[test]fn the_app_coming_forward_while_the_build_waits_for_the_writer_stops_it() {let (_dir, handle) = moved_phone();let client = handle.client();let path = client.layout().replica(&client.attached_database().unwrap());let away = std::sync::atomic::AtomicBool::new(true);let (held_tx, held_rx) = std::sync::mpsc::channel();let (go_tx, go_rx) = std::sync::mpsc::channel::<()>();let made = std::thread::scope(|scope| {let client = &client;let pass = scope.spawn(move || { client .with_writer(|_| { held_tx.send(()).unwrap(); go_rx.recv().unwrap();Ok(()) }) .unwrap() }); held_rx.recv().unwrap();let away = &away;let builder = scope.spawn(move || crate::phone::mail_index::build_later_after(client, std::time::Duration::ZERO, &|| away.load(std::sync::atomic::Ordering::SeqCst)).unwrap()); std::thread::sleep(std::time::Duration::from_millis(300));// The person opens the app while the pass still holds the writer; then the pass ends. away.store(false, std::sync::atomic::Ordering::SeqCst); assert!(crate::phone::mail_index::came_forward_at(&path), "registered before it waited for the writer"); go_tx.send(()).unwrap(); pass.join().unwrap(); builder.join().unwrap() }); assert!(made.is_empty(), "made in front: {made:?}"); assert_eq!(missing_indexes(&client), cotton_store::index_later::LATER);}/// RULE (SCHEMA 155 REVIEW): a real SQLITE_FULL half way refuses the index for this launch: the file whole, the/// index absent, and nothing tried on the passes after.#[test]fn a_disk_that_fills_half_way_is_not_asked_again_this_launch() {let (_dir, handle, path) = moved_phone_of(20_000);let client = handle.client(); client .with_writer(|r| {let pages = r.driver.get("PRAGMA page_count", &[]).map_err(|e| e.to_string())?.and_then(|row| row.int("page_count")).unwrap(); r.driver.exec(&format!("PRAGMA max_page_count = {}", pages + 4)).map_err(|e| e.to_string()) }) .unwrap();let made = crate::phone::mail_index::build_later_after(&client, std::time::Duration::ZERO, &|| true).unwrap(); assert!(made.is_empty(), "{made:?}");let why = crate::phone::mail_index::later_refused(&path).expect("refused"); assert!(why.to_lowercase().contains("full"), "{why}"); assert_eq!(whole(&client), "ok"); assert_eq!(missing_indexes(&client), cotton_store::index_later::LATER); client.with_writer(|r| r.driver.exec("PRAGMA max_page_count = 1073741823").map_err(|e| e.to_string())).unwrap(); assert!(crate::phone::mail_index::build_later_after(&client, std::time::Duration::ZERO, &|| true).unwrap().is_empty(), "not again this launch, even with room now"); assert!(!crate::phone::mail_index::later_owed(&client), "and the job is not asked for it");}/// RULE (INDEX LATER 2 REVIEW): the phone's processing job, minutes on the charger, is where the indexes are made:/// `sync.compact {}` says they are owed (so the phone asks for the job), and `{budgetMs}` makes them.#[test]fn the_processing_job_makes_the_indexes() {let (_dir, handle) = moved_phone();let asked = crate::methods::dispatch(&handle, "sync.compact", &json!({})).unwrap(); assert_eq!(asked["owed"], true, "{asked}"); assert_eq!(asked["indexes"], json!(cotton_store::index_later::LATER));let ran = crate::methods::dispatch(&handle, "sync.compact", &json!({ "budgetMs": 600_000 })).unwrap(); assert_eq!((ran["owed"].clone(), ran["ran"].clone()), (json!(false), json!(true)), "{ran}"); assert_eq!(ran["made"], json!(cotton_store::index_later::LATER)); assert!(ran["tookMs"].is_u64()); assert!(missing_indexes(&handle.client()).is_empty()); assert_eq!(crate::methods::dispatch(&handle, "sync.compact", &json!({})).unwrap()["owed"], false);}/// RULE (INDEX LATER 3 REVIEW): the job's `{stop}` sticks. One that came before an index began (during the/// compaction) means none begins; one that comes half way takes the index back, the file whole, still owed.#[test]fn the_jobs_stop_sticks_before_and_during_a_build() {let (_dir, handle, path) = moved_phone_of(150_000);let client = handle.client();let (made, owed) = crate::phone::mail_index::build_in_task(&client, std::time::Duration::from_secs(600), &|| true).unwrap(); assert!(made.is_empty() && owed, "stopped before it began: nothing begun, still owed"); assert_eq!(missing_indexes(&client), cotton_store::index_later::LATER);let answer = std::thread::scope(|scope| {let job = scope.spawn(|| crate::methods::dispatch(&handle, "sync.compact", &json!({ "budgetMs": 600_000 })).unwrap());let began = std::time::Instant::now();whilecrate::phone::mail_index::watched_at(&path) < 3 { assert!(!job.is_finished(), "made before it could be stopped"); assert!(began.elapsed() < std::time::Duration::from_secs(60)); std::thread::yield_now(); }let stopped = crate::methods::dispatch(&handle, "sync.compact", &json!({ "stop": true })).unwrap(); assert_eq!(stopped["stopped"], true, "{stopped}"); job.join().unwrap() }); assert_eq!((answer["owed"].clone(), answer["made"].clone()), (json!(true), json!([])), "{answer}"); assert_eq!(missing_indexes(&client), cotton_store::index_later::LATER, "taken back, and none after it"); assert_eq!(whole(&client), "ok"); assert_eq!(crate::phone::mail_index::later_taken_back(&path), 0, "the job's stop is no trip to the back taken back");}/// RULE (INDEX LATER 3 REVIEW): `sync.compact {}` answers while a build runs; it never waits for one.#[test]fn asking_what_is_owed_never_waits_for_a_build() {let (_dir, handle, path) = moved_phone_of(150_000);let client = handle.client(); std::thread::scope(|scope| {let builder = scope.spawn(|| crate::phone::mail_index::build_later_after(&client, std::time::Duration::ZERO, &|| true).unwrap());whilecrate::phone::mail_index::watched_at(&path) < 3 { assert!(!builder.is_finished(), "made before it could be asked"); std::thread::yield_now(); }let t = std::time::Instant::now();let asked = crate::methods::dispatch(&handle, "sync.compact", &json!({})).unwrap();let took = t.elapsed(); assert!(crate::phone::mail_index::watched_at(&path) > 0, "still building as it answered"); assert_eq!(asked["owed"], true, "{asked}"); assert!(took < std::time::Duration::from_secs(2), "answered in {took:?}");crate::phone::mail_index::came_forward_at(&path); builder.join().unwrap(); });}/// RULE (INDEX LATER 3 REVIEW): an index is never made inside a transaction left open on the writer.#[test]fn no_index_is_made_inside_an_open_transaction() {let (_dir, handle) = moved_phone();let client = handle.client(); client.with_writer(|r| r.driver.exec("BEGIN").map_err(|e| e.to_string())).unwrap();let made = crate::phone::mail_index::build_later_after(&client, std::time::Duration::ZERO, &|| true).unwrap(); client.with_writer(|r| r.driver.exec("ROLLBACK").map_err(|e| e.to_string())).unwrap(); assert!(made.is_empty(), "{made:?}"); assert_eq!(missing_indexes(&client), cotton_store::index_later::LATER);let path = client.layout().replica(&client.attached_database().unwrap()); assert!(crate::phone::mail_index::later_refused(&path).is_none(), "not a refusal: the next time"); assert_eq!(crate::phone::mail_index::build_later_after(&client, std::time::Duration::ZERO, &|| true).unwrap(), cotton_store::index_later::LATER);}/// RULE (FIRST SYNC 4 REVIEW): two processing jobs on one copy at once each keep their own stop: the second ending/// leaves the first's, and a stop then still reaches the first.#[test]fn two_jobs_at_once_each_keep_their_own_stop() {let (_dir, handle, path) = moved_phone_of(150_000);let client = handle.client();let first = std::thread::scope(|scope| {let first = scope.spawn(|| crate::methods::dispatch(&handle, "sync.compact", &json!({ "budgetMs": 600_000 })).unwrap());whilecrate::phone::mail_index::watched_at(&path) < 3 { assert!(!first.is_finished(), "made before the second job came"); std::thread::yield_now(); }// The second finds the build under way (one a copy at a time) and ends at once.let second = crate::methods::dispatch(&handle, "sync.compact", &json!({ "budgetMs": 600_000 })).unwrap(); assert_eq!(second["made"], json!([]), "{second}"); assert_eq!(crate::phone::trim::jobs_at(&path), 1, "the second's end left the first's stop");let stopped = crate::methods::dispatch(&handle, "sync.compact", &json!({ "stop": true })).unwrap(); assert_eq!(stopped["stopped"], true); first.join().unwrap() }); assert_eq!((first["owed"].clone(), first["made"].clone()), (json!(true), json!([])), "{first}"); assert_eq!(crate::phone::trim::jobs_at(&path), 0); assert_eq!(whole(&client), "ok");}/// RULE (FIRST SYNC 9): an old index over the wide park table goes in the background step, once the parks' keys are/// full, never on a pass: it waits while someone is at the phone, and once dropped is owed no more.#[test]fn an_old_park_index_is_dropped_in_the_background_only() {let (_dir, handle) = post_phone();let client = handle.client(); client.with_writer(|replica| {let connection = replica.driver.connection(); cotton_client::seal::write_notes(connection, &[])?; connection.execute_batch("CREATE INDEX _seal_parked_at ON _seal_parked (at)").map_err(|e| e.to_string()) }).unwrap();let held = |client: &crate::shell::client::ClientController| { client.with_file(|replica| replica.driver.get("SELECT 1 AS held FROM sqlite_master WHERE name = '_seal_parked_at'", &[]).map_err(|e| e.to_string())).unwrap().is_some() }; assert!(crate::phone::mail_index::later_owed(&client), "owed: the processing job is asked"); assert!(crate::phone::mail_index::build_later_after(&client, std::time::Duration::ZERO, &|| false).unwrap().is_empty()); assert!(held(&client), "someone at the phone: kept");crate::phone::mail_index::build_later_after(&client, std::time::Duration::ZERO, &|| true).unwrap(); assert!(!held(&client), "away: dropped"); assert!(!crate::phone::mail_index::later_owed(&client), "owed no more");}/// RULE (9c, the page-by-number guard): search pages by its (newest mail, conversation) cursor, by the index and/// before it is filled: every conversation found is reachable, each once, and the last page says there is no more.#[test]fn search_pages_every_hit_once() {let (_dir, handle) = post_phone(); mailbox(&handle);let ids: Vec<(String, String)> = (0..95).map(|n| (format!("e-rent-{n:03}"), format!("et-rent-{n:03}"))).collect();for (n, (id, thread)) in ids.iter().enumerate() { mail(&handle, Mail { id, thread, from: (ASHA, "Asha Example"), subject: "Rent receipt", body: "Paid.", minutes_ago: 10 + n as i64, ..Default::default() }); }let walk = |handle: &CottonHandle| -> Vec<String> {letmut seen = Vec::new();letmut after = Value::Null;for _ in0..10 {let page = ask(handle, "mail.search", json!({ "text": "rent", "after": after })); seen.extend(page["mail"]["rows"].as_array().unwrap().iter().map(|r| r["thread"].as_str().unwrap_or_default().to_string())); after = page["mail"]["after"].clone();if after.is_null() {return seen; } } panic!("search never ended"); };let before_index = walk(&handle); assert_eq!(before_index.len(), 95, "every conversation, the LIKE search"); assert_eq!(before_index.iter().collect::<std::collections::HashSet<_>>().len(), 95, "each once");crate::phone::mail_index::fill(&handle.client(), std::time::Duration::from_secs(30)).expect("fills");let by_index = walk(&handle); assert_eq!(by_index.len(), 95, "every conversation, the index"); assert_eq!(by_index.iter().collect::<std::collections::HashSet<_>>().len(), 95, "each once");}/// RULE (review of FIRST SYNC 9c, lows 1 and 2): a search groups mail into conversations before it cuts a page, so a/// conversation with hits on both sides of a cursor is on one page only; hits from a blocked sender never end the/// walk early (the next cursor is None only when the hits run out); and a page whose batches are all blocked senders/// ends short with a next cursor rather than reading on without bound, but never empty while time allows (review of 9d). Both before and after the wide index fills.#[test]fn search_groups_before_it_cuts_and_skips_blocked_senders_to_the_end() {let (_dir, handle) = post_phone(); mailbox(&handle);let blocked = "rent@blocked.example";let blocked_count = super::super::SEARCH_BATCH * super::super::SEARCH_BATCHES + 10;// The blocked sender's conversations are the newest, more than one page's batches.let blocked_ids: Vec<(String, String)> = (0..blocked_count).map(|n| (format!("e-bl-{n:03}"), format!("et-bl-{n:03}"))).collect();for (n, (id, thread)) in blocked_ids.iter().enumerate() { mail(&handle, Mail { id, thread, from: (blocked, "Blocked Example"), subject: "Rent due", body: "Pay.", minutes_ago: 10 + n as i64, ..Default::default() }); }// Then 50 conversations of two mails each: a new one and one 500 minutes older, so each conversation's older hit// falls among the others' newer hits.let ids: Vec<(String, String, String)> = (0..50).map(|n| (format!("e-two-{n:02}-a"), format!("e-two-{n:02}-b"), format!("et-two-{n:02}"))).collect();let base = 10 + blocked_count as i64;for (n, (a, b, thread)) in ids.iter().enumerate() { mail(&handle, Mail { id: a, thread, from: (ASHA, "Asha Example"), subject: "Rent receipt", body: "Paid.", minutes_ago: base + 3 * n as i64, ..Default::default() }); mail(&handle, Mail { id: b, thread, from: (ASHA, "Asha Example"), subject: "Rent reminder", body: "Due.", minutes_ago: base + 500 + 3 * n as i64, ..Default::default() }); }let sheet = ask(&handle, "mail.ask", json!({ "act": "block", "key": blocked })); ask(&handle, "mail.do", json!({ "plan": sheet["plan"], "also": false }));let walk = |handle: &CottonHandle| -> (Vec<String>, usize) {letmut seen = Vec::new();letmut after = Value::Null;for pages in1..20 {let page = ask(handle, "mail.search", json!({ "text": "rent", "after": after })); seen.extend(page["mail"]["rows"].as_array().unwrap().iter().map(|r| r["thread"].as_str().unwrap_or_default().to_string())); after = page["mail"]["after"].clone();if after.is_null() {return (seen, pages); } } panic!("search never ended"); };for (when, fill) in [("the search before the index", false), ("the index", true)] {if fill {crate::phone::mail_index::fill(&handle.client(), std::time::Duration::from_secs(60)).expect("fills"); }let (seen, pages) = walk(&handle); assert!(seen.iter().all(|t| t.starts_with("et-two-")), "{when}: no blocked sender's conversation"); assert_eq!(seen.len(), 50, "{when}: every conversation"); assert_eq!(seen.iter().collect::<std::collections::HashSet<_>>().len(), 50, "{when}: each once"); assert!(pages >= 2, "{when}: the first page ends short at its bound, then reads on ({pages} pages)");let first = ask(&handle, "mail.search", json!({ "text": "rent" })); assert!(!first["mail"]["rows"].as_array().unwrap().is_empty(), "{when}: the first page is never empty while matches exist"); }}fn kit_rows(handle: &CottonHandle, statement: &str) -> Vec<Value> {let rows = handle.client().with_writer(|replica| replica.driver.all_values(statement, &[]).map_err(|e| e.to_string())).expect(statement); rows.into_iter() .map(|cells| Value::Array(cells.into_iter().map(|v| match v { SqlValue::Text(t) => json!(t), SqlValue::Integer(n) => json!(n), _ => Value::Null }).collect())) .collect()}/// RULE (MAIL PREDICATE phase 2, decisions 1 to 3 and rules 1, 2, 7): a whole sender's Delete writes ONE row, not a/// write per mail; their mail landed up to its newest is in the Bin, mail landing after stays; mail with no landing/// time yet waits and is said; bringing one back keeps it out of the row; Undo takes the row away until this device/// began erasing it 30 days on, and an erase stops when another device undid it.#[test]fn a_whole_senders_delete_is_one_row_that_the_bin_honours() {let (_dir, handle) = post_phone(); mailbox(&handle);for (id, minutes) in [("e-kb-1", 50), ("e-kb-2", 40), ("e-kb-3", 30)] { mail(&handle, Mail { id, thread: &format!("t-{id}"), from: ("deals@kitebox.example", "Kitebox"), subject: id, body: "Sale.", minutes_ago: minutes, ..Default::default() }); }// One of theirs held before schema 157's backfill reached it. sql(&handle, "UPDATE cotton_emails SET landed_at = NULL WHERE id = 'e-kb-1'", &[]); sql(&handle, "DELETE FROM _mail_landed WHERE id = 'e-kb-1'", &[]);let sheet = ask(&handle, "mail.ask", json!({ "act": "delete", "scope": "sender", "key": "deals@kitebox.example" }));let done = ask(&handle, "mail.do", json!({ "plan": sheet["plan"], "choice": "all" })); assert_eq!(done["line"], "Moved 2 to the Bin. 1 more from them goes once this phone has caught up.", "{done}");let cuts = kit_rows(&handle, "SELECT \"key\" FROM cotton_email_bin_cut WHERE deleted_at IS NULL"); assert_eq!(cuts, [json!(["deals@kitebox.example"])], "one row");let trashed = kit_rows(&handle, "SELECT count(*) FROM cotton_emails WHERE trashed_at IS NOT NULL"); assert_eq!(trashed, [json!([0])], "no write per mail");letmut bin = subjects(&ask(&handle, "mail.list", json!({ "place": "bin" }))["rows"]); bin.sort(); assert_eq!(bin, ["e-kb-2", "e-kb-3"]);// Landing after the row: theirs, but not covered. mail(&handle, Mail { id: "e-kb-4", thread: "t-e-kb-4", from: ("deals@kitebox.example", "Kitebox"), subject: "e-kb-4", body: "New.", minutes_ago: 0, ..Default::default() }); assert!(!subjects(&ask(&handle, "mail.list", json!({ "place": "bin" }))["rows"]).contains(&"e-kb-4".to_string()));// His act on one mail wins over the row. ask(&handle, "mail.act", json!({ "email": "e-kb-2", "act": "restore" })); assert_eq!(subjects(&ask(&handle, "mail.list", json!({ "place": "bin" }))["rows"]), ["e-kb-3"]);// Undo, then the act again. ask(&handle, "mail.undo", json!({ "after": done["after"] })); assert!(subjects(&ask(&handle, "mail.list", json!({ "place": "bin" }))["rows"]).is_empty());let sheet = ask(&handle, "mail.ask", json!({ "act": "delete", "scope": "sender", "key": "deals@kitebox.example" }));let again = ask(&handle, "mail.do", json!({ "plan": sheet["plan"], "choice": "all" }));// The first Delete's row stays, undone (item 3: a phone never removes one); the new one is live.let states = kit_rows(&handle, "SELECT coalesce(state, 'live') FROM cotton_email_bin_cut WHERE deleted_at IS NULL ORDER BY made_at"); assert_eq!(states, [json!(["undone"]), json!(["live"])]);let id = kit_rows(&handle, "SELECT id FROM cotton_email_bin_cut WHERE deleted_at IS NULL AND state = 'live'")[0][0].as_str().unwrap().to_string();let state = |handle: &CottonHandle| kit_rows(handle, &format!("SELECT state FROM cotton_email_bin_cut WHERE id = '{id}'"))[0][0].clone();// 30 days after he made it: `made_at` moved back by hand; the mail and its arrival stay as they were. sql(&handle, "UPDATE cotton_email_bin_cut SET made_at = ? WHERE id = ?", &[t(&iso(31 * 24 * 60)), t(&id)]);// Another device undid it first: no erase begins. sql(&handle, "UPDATE cotton_email_bin_cut SET state = 'undone' WHERE id = ?", &[t(&id)]); assert_eq!(super::keep_the_bin(&handle.client()).unwrap(), 0, "undone: nothing erased"); assert_eq!(state(&handle), json!("undone")); sql(&handle, "UPDATE cotton_email_bin_cut SET state = 'live' WHERE id = ?", &[t(&id)]);// The erase begins by writing the row erasing; nothing is erased until the object has taken that write.let pending = |handle: &CottonHandle| kit_rows(handle, &format!("SELECT count(*) FROM _outbox o JOIN _writes w ON w.op_id = o.op_id WHERE w.tbl = 'cotton_email_bin_cut' AND w.row_id = '{id}'"))[0][0].as_i64().unwrap();let first = super::keep_the_bin(&handle.client()).unwrap(); assert!(matches!(state(&handle).as_str(), Some("erasing") | Some("erased")), "{}", state(&handle));if pending(&handle) > 0 { assert_eq!(first, 0, "the object has not taken the erasing write yet"); taken(&handle, &id); }// From here its Undo is refused, in words.let refused = crate::methods::dispatch(&handle, "mail.undo", &json!({ "after": again["after"] })).unwrap_err(); assert_eq!(refused.message, "Too late to undo: these mails are already being erased.");let erased = if first > 0 { first } else { super::keep_the_bin(&handle.client()).unwrap() }; assert_eq!(erased, 3, "e-kb-2, e-kb-3 and e-kb-4 erased (all landed by the second Delete); e-kb-1 has no arrival time");// Nothing left and every erase taken: erased, kept as the rule for what it covered. taken(&handle, &id); sql(&handle, "DELETE FROM _outbox WHERE tbl IN ('email', 'cotton_emails')", &[]);super::keep_the_bin(&handle.client()).unwrap(); assert_eq!(state(&handle), json!("erased"));// Mail it covers that turns up later (its arrival time learned late) is erased where it is seen. taken(&handle, &id); sql(&handle, "INSERT INTO _mail_landed (id, landed_at, \"key\", domain) VALUES ('e-kb-1', ?, 'deals@kitebox.example', '@kitebox.example')", &[t(&iso(50))]); assert_eq!(super::keep_the_bin(&handle.client()).unwrap(), 1, "e-kb-1, covered once its time came"); assert!(kit_rows(&handle, "SELECT count(*) FROM cotton_emails WHERE id = 'e-kb-1'")[0][0] == json!(0));}/// The object took every write of a Delete row this copy made (a pass would): its outbox ops for the row gone.fn taken(handle: &CottonHandle, id: &str) { sql(handle, "DELETE FROM _outbox WHERE op_id IN (SELECT op_id FROM _writes WHERE tbl = 'cotton_email_bin_cut' AND row_id = ?)", &[t(id)]);}/// RULE (PHASE 2 PHONE 2, item 1): a Delete's 30 days run from when he tapped, never from the newest mail it covers./// A sender quiet for 40 days is deleted: the next pass erases nothing, the mail is in the Bin dated today, and Undo/// brings it back.#[test]fn a_sender_quiet_for_forty_days_is_not_erased_the_pass_after_its_delete() {let (_dir, handle) = post_phone(); mailbox(&handle);for (id, days) in [("e-q-1", 41), ("e-q-2", 40)] { mail(&handle, Mail { id, thread: &format!("t-{id}"), from: ("letters@quietco.example", "Quietco"), subject: id, body: "Old news.", minutes_ago: days * 24 * 60, ..Default::default() }); }let sheet = ask(&handle, "mail.ask", json!({ "act": "delete", "scope": "sender", "key": "letters@quietco.example" }));let done = ask(&handle, "mail.do", json!({ "plan": sheet["plan"], "choice": "all" }));let id = kit_rows(&handle, "SELECT id FROM cotton_email_bin_cut WHERE deleted_at IS NULL")[0][0].as_str().unwrap().to_string();let times = kit_rows(&handle, &format!("SELECT \"at\", made_at FROM cotton_email_bin_cut WHERE id = '{id}'"));let (at, made) = (times[0][0].as_str().unwrap().to_string(), times[0][1].as_str().unwrap().to_string()); assert!(at < iso(39 * 24 * 60), "covers what landed 40 days ago: {at}"); assert!(made > iso(1), "made when he tapped: {made}"); taken(&handle, &id); assert_eq!(super::keep_the_bin(&handle.client()).unwrap(), 0, "nothing erased"); assert_eq!(kit_rows(&handle, &format!("SELECT coalesce(state, 'live') FROM cotton_email_bin_cut WHERE id = '{id}'"))[0][0], json!("live"));let binned_at = kit_rows(&handle, &format!("SELECT {} FROM cotton_emails WHERE id = 'e-q-1'", cotton_core::rules::mail_predicate::binned_at("")))[0][0].as_str().unwrap().to_string(); assert_eq!(binned_at, made, "in the Bin from when he tapped"); ask(&handle, "mail.undo", json!({ "after": done["after"] })); assert!(subjects(&ask(&handle, "mail.list", json!({ "place": "bin" }))["rows"]).is_empty(), "Undo brings them back");}/// RULE (PHASE 2 PHONE 2, low): his own addresses are never covered by any cut. A Delete of his own domain takes the/// others' mail there and leaves his own, in its sheet and in the predicate (a domain row written by hand covers his/// colleague's mail, never his).#[test]fn his_own_mail_is_never_covered_by_a_cut_of_his_domain() {let (_dir, handle) = post_phone(); mailbox(&handle); mail(&handle, Mail { id: "e-col", thread: "et-col", from: ("colleague@invented.example", "Colleague"), subject: "Standup", body: "At ten.", minutes_ago: 9, ..Default::default() });let sheet = ask(&handle, "mail.ask", json!({ "act": "delete", "scope": "domain", "key": "invented.example" }));// Asha and his colleague: never Mira herself. assert_eq!(sheet["title"], "Delete 2 mails from 2 senders at invented.example?", "{sheet}");super::keep_the_bin(&handle.client()).unwrap(); assert_eq!(kit_rows(&handle, "SELECT \"key\" FROM _mail_own"), [json!([ME])], "his own address kept for the predicate");let now = iso(0);crate::phone::cotton_chat::write(&handle.client(), "test.cut", |ctx| {let at = super::cuts::newest_landed(ctx)?.unwrap();Ok(json!(super::cuts::cut_in(ctx, super::cuts::BIN, "@invented.example", &now, &at, &now)?)) }) .unwrap();let binned = |id: &str| kit_rows(&handle, &format!("SELECT count(*) FROM cotton_emails WHERE id = '{id}' AND {}", cotton_core::rules::mail_predicate::binned("")))[0][0] == json!(1); assert!(binned("e-col"), "his colleague's mail is covered"); assert!(!binned("e-mira-1"), "his own is not");}/// RULE (PHASE 2 PHONE 2, low): a domain with more than 25 different senders here is taken in one act only after a/// second sheet names the count.#[test]fn a_domain_of_many_senders_asks_again_naming_the_count() {let (_dir, handle) = post_phone(); mailbox(&handle);for n in0..26 {let from = format!("member{n}@bigforum.example"); mail(&handle, Mail { id: &format!("e-bf-{n}"), thread: &format!("et-bf-{n}"), from: (&from, "Member"), subject: "Thread", body: "Reply.", minutes_ago: 60 + n, ..Default::default() }); }let first = ask(&handle, "mail.ask", json!({ "act": "delete", "scope": "domain", "key": "bigforum.example" })); assert_eq!(first["confirm"]["line"], "bigforum.example has 26 different senders here. Take mail from all 26?", "{first}"); assert!(first.get("plan").is_none(), "nothing to do yet");let sheet = ask(&handle, "mail.ask", json!({ "act": "delete", "scope": "domain", "key": "bigforum.example", "senders": 26 })); assert_eq!(sheet["title"], "Delete 26 mails from 26 senders at bigforum.example?", "{sheet}");let archive = ask(&handle, "mail.archive", json!({ "scope": "domain", "key": "bigforum.example" })); assert!(archive.get("confirm").is_some(), "{archive}");}/// RULE (MAIL PREDICATE phase 2, decision 4): a Mark read of a group's mail is one row per sender; it carries the/// count the list showed and the newest landing the list knew; mail landing after stays unread; a count that no longer/// matches is refused "changed"; Undo takes the rows away.#[test]fn a_groups_mark_read_is_one_row_per_sender_bounded_by_what_the_list_knew() {let (_dir, handle) = post_phone(); mailbox(&handle); mail(&handle, Mail { id: "e-r-1", thread: "et-r-1", from: ("orders@tiffinly.example", "Tiffinly"), subject: "Receipt one", body: "Paid.", minutes_ago: 20, unread: true, ..Default::default() });let group = ask(&handle, "mail.list", json!({ "place": "group:receipts" }));let offer = group["bulk"][0].clone(); assert_eq!(offer["act"], "read", "{group}");let shown = offer["count"].as_u64().unwrap(); assert!(shown >= 1, "{offer}");// A changed list: the count he saw is no longer what it would cover.let wrong = crate::methods::dispatch(&handle, "mail.act", &json!({ "act": "read", "scope": "group", "key": "group:receipts", "count": shown + 1, "upto": offer["upto"] })).unwrap_err(); assert_eq!(wrong.message, "This list changed since you saw it. Look again, then mark them read.");// Arriving after the list: not his to mark read unseen. mail(&handle, Mail { id: "e-r-2", thread: "et-r-2", from: ("orders@tiffinly.example", "Tiffinly"), subject: "Receipt two", body: "Paid.", minutes_ago: 0, unread: true, ..Default::default() }); sql(&handle, "UPDATE cotton_emails SET landed_at = ? WHERE id = 'e-r-2'", &[t(&(chrono::Utc::now() + chrono::Duration::seconds(5)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true))]);let done = ask(&handle, "mail.act", json!({ "act": "read", "scope": "group", "key": "group:receipts", "count": shown, "upto": offer["upto"] })); assert!(done["after"].is_string(), "{done}"); assert!(kit_rows(&handle, "SELECT count(*) FROM cotton_email_read_cut WHERE deleted_at IS NULL")[0][0].as_i64().unwrap() >= 1);let unread = |id: &str| kit_rows(&handle, &format!("SELECT count(*) FROM cotton_emails WHERE id = '{id}' AND {}", cotton_core::rules::mail_predicate::unread("")))[0][0].as_i64().unwrap() == 1; assert!(!unread("e-r-1"), "marked read by the row"); assert!(unread("e-r-2"), "landed after the list: still unread");// Marked unread again by hand: his act wins over the row. ask(&handle, "mail.act", json!({ "email": "e-r-1", "act": "unread" })); assert!(unread("e-r-1")); ask(&handle, "mail.undo", json!({ "after": done["after"] })); assert_eq!(kit_rows(&handle, "SELECT count(*) FROM cotton_email_read_cut WHERE deleted_at IS NULL")[0][0], json!(0));}/// RULE (review of the rules, 3): Archive compares times in the one shape. The newest mail it meant to take, stored as/// `…:00Z` (sorting after `…:00.000Z` as text), is taken all the same, and so is one landed in another offset.#[test]fn archive_takes_mail_whatever_shape_its_times_are_stored_in() {let (_dir, handle) = post_phone(); mailbox(&handle); mail(&handle, Mail { id: "e-sh-1", thread: "et-sh-1", from: ("hello@shapes.example", "Shapes"), subject: "Older", body: "One.", minutes_ago: 60, ..Default::default() }); mail(&handle, Mail { id: "e-sh-2", thread: "et-sh-2", from: ("hello@shapes.example", "Shapes"), subject: "Newest", body: "Two.", minutes_ago: 30, ..Default::default() }); sql(&handle, "UPDATE cotton_emails SET sent_at = '2026-11-20T10:00:00Z', landed_at = '2026-11-20T10:00:01Z' WHERE id = 'e-sh-2'", &[]); sql(&handle, "UPDATE cotton_emails SET sent_at = '2026-11-20T15:29:00+05:30', landed_at = '2026-11-20T15:29:30.5+05:30' WHERE id = 'e-sh-1'", &[]);let after = ask(&handle, "mail.archive", json!({ "scope": "sender", "key": "Hello@Shapes.example " })); assert_eq!(after["count"], 2, "{after}");letmut now = archived(&handle); now.sort(); assert_eq!(now, ["Newest", "Older"]);}/// RULE (MAIL PREDICATE phase 2, rule 5; review of the rules, 4): a public mail service's whole domain is never one/// act's, said in words before anything is counted; any other domain's sheet says how many senders it takes as well/// as how many mails.#[test]fn a_public_mail_domain_is_refused_and_a_domains_sheet_counts_its_senders() {let (_dir, handle) = post_phone(); mailbox(&handle);for (method, request) in [ ("mail.archive", json!({ "scope": "domain", "key": "@GMail.com" })), ("mail.ask", json!({ "act": "delete", "scope": "domain", "key": "gmail.com" })), ("mail.ask", json!({ "act": "block", "scope": "domain", "key": "yahoo.co.jp" })), ] {let refused = crate::methods::dispatch(&handle, method, &request).unwrap_err(); assert_eq!(refused.code, "refused", "{method} {request}"); assert!(refused.message.starts_with("Not offered for "), "{}", refused.message); } mail(&handle, Mail { id: "e-d-1", thread: "et-d-1", from: ("deals@kitebox.example", "Kitebox"), subject: "Sale", body: "One.", minutes_ago: 50, ..Default::default() }); mail(&handle, Mail { id: "e-d-2", thread: "et-d-2", from: ("help@kitebox.example", "Kitebox help"), subject: "Help", body: "Two.", minutes_ago: 40, ..Default::default() }); mail(&handle, Mail { id: "e-d-3", thread: "et-d-3", from: ("x@notkitebox.example", "Other"), subject: "Other", body: "Three.", minutes_ago: 30, ..Default::default() });let sheet = ask(&handle, "mail.ask", json!({ "act": "delete", "scope": "domain", "key": "@kitebox.example" }));// Mira's mailbox holds one from offers@kitebox.example already. assert_eq!(sheet["title"], "Delete 3 mails from 3 senders at kitebox.example?", "{sheet}");}/// RULE (PHASE 2 PHONE 2, item 2): at 300,000 mails no act reads every mail. Choosing a sender's mail, a domain's, a/// Delete's held mail, a domain's senders, the newest landing and what a Delete covers each seek an index, on this/// build's own schema: after `index_later` has made the sender index with `id`, and before (a moved copy still on/// the 153 sender index).#[test]fn every_selection_seeks_an_index_before_and_after_the_new_sender_index() {let (_dir, handle) = post_phone(); mailbox(&handle);let sheet = ask(&handle, "mail.ask", json!({ "act": "delete", "scope": "sender", "key": "offers@kitebox.example" })); ask(&handle, "mail.do", json!({ "plan": sheet["plan"], "choice": "all" }));let id = kit_rows(&handle, "SELECT id FROM cotton_email_bin_cut")[0][0].as_str().unwrap().to_string();let plans = |handle: &CottonHandle| -> Value {crate::phone::cotton_chat::read(&handle.client(), "test.plans", |ctx| {let know = super::cuts::know(ctx)?;let base = super::acts::inbox_base(&know);let ws = crate::phone::cotton_chat::ws(ctx);let explain = |ctx: &mut cotton_tools::mcp::dispatch::Ctx<'_>, sql: &str, params: &[SqlValue]| -> Result<Value, String> {Ok(json!(crate::phone::cotton_chat::rows(ctx, &format!("EXPLAIN QUERY PLAN {sql}"), params)?.iter().filter_map(|r| r["detail"].as_str().map(str::to_string)).collect::<Vec<_>>())) };Ok(json!({"sender": explain(ctx, &super::acts::sender_sql(&base), &[ws.clone(), t("offers@kitebox.example")])?,"domain": explain(ctx, &super::acts::domain_sql(&base), &[ws.clone(), t("@kitebox.example")])?,"held": explain(ctx, &format!("{} AND lower(trim(from_email)) IN (?)", super::acts::held_select()), &[ws.clone(), t("offers@kitebox.example")])?,"domain_senders": explain(ctx, &super::acts::domain_senders_sql(), &[t("@kitebox.example")])?,"newest": explain(ctx, &format!("SELECT max(landed_at) AS n FROM {}", cotton_core::rules::mail_predicate::cuts::LANDED), &[])?,"bin_covered": explain(ctx, &super::cuts::bin_covered_sql(false, 100), &[t("offers@kitebox.example"), t(&id), ws.clone()])?, })) }) .unwrap() };let check = |plans: &Value, sender_index: &str| {for (name, lines) in plans.as_object().unwrap() {let lines: Vec<&str> = lines.as_array().unwrap().iter().filter_map(Value::as_str).collect();// A whole-table read of the mail or of the landings is what at his size reads everything.// So is a range over the whole workspace's mail by any index (`(workspace_id=?)` and nothing more).let scans = lines .iter() .filter(|d| (d.starts_with("SCAN") && ["cotton_emails", " e", " l", "_mail_landed"].iter().any(|t| d.contains(t)) && !d.contains("INDEX")) || d.ends_with("(workspace_id=?)")) .count(); assert_eq!(scans, 0, "{name}: {lines:?}");let wants = match name.as_str() {"sender" | "held" => sender_index,"domain" | "domain_senders" => "_mail_landed_domain","newest" => "_mail_landed_at","bin_covered" => "_mail_landed_key", _ => unreachable!(), }; assert!(lines.iter().any(|d| d.contains(wants)), "{name} seeks {wants}: {lines:?}"); } }; check(&plans(&handle), "idx_cotton_emails_sender_id");// A copy moved from 156 before `index_later` made the new index: the 153 one, still a seek. sql(&handle, "DROP INDEX idx_cotton_emails_sender_id", &[]); sql(&handle, "CREATE INDEX idx_cotton_emails_sender ON cotton_emails (workspace_id, lower(trim(from_email)), sent_at, from_name, trashed_at, from_email)", &[]); check(&plans(&handle), "idx_cotton_emails_sender");}