//! Cotton Chat's answers over a phone's own copy. Every name, number and //! line is invented. use rusqlite::types::Value as SqlValue; use serde_json::{json, Value}; use crate::handle::CottonHandle; use crate::phone::cotton_chat::over; use crate::phone::passwords::tests::phone; /// Kabir's chat (Comms 28 fixes 2): a document and a link to open. const KABIR: &str = "11111111-1111-4111-8111-0000000000h1"; const ASHA: &str = "11111111-1111-4111-8111-0000000000a1"; const WEEKEND: &str = "11111111-1111-4111-8111-0000000000b1"; const OLD_SMS: &str = "11111111-1111-4111-8111-0000000000c1"; fn answer(handle: &CottonHandle, method: &str, request: Value) -> Value { over(&handle.client(), method, &request).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message)) } fn refused(handle: &CottonHandle, method: &str, request: Value) -> String { over(&handle.client(), method, &request).err().unwrap_or_else(|| panic!("{method} answered")).code } 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) } fn thread(handle: &CottonHandle, id: &str, kind: &str, key: Option<&str>, title: Option<&str>, contact: Option<&str>, last: &str) { let ws = workspace(handle); sql( handle, "INSERT INTO cotton_msg_threads (id, workspace_id, kind, external_key, title, contact_id, last_message_at, read_seq, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?)", &[t(id), t(&ws), t(kind), key.map_or(SqlValue::Null, t), title.map_or(SqlValue::Null, t), contact.map_or(SqlValue::Null, t), t(last), t(last), t(last)], ); } fn contact(handle: &CottonHandle, id: &str, name: &str, phone: &str) { let ws = workspace(handle); sql(handle, "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, created_at, updated_at) VALUES (?, ?, ?, ?, '2026-01-01', '2026-01-01')", &[t(id), t(&ws), t(phone), t(name)]); } fn seat(handle: &CottonHandle, id: &str, thread: &str, name: &str, is_self: bool) { let ws = workspace(handle); sql(handle, "INSERT INTO cotton_msg_thread_participants (id, thread_id, workspace_id, display_name, is_self, created_at) VALUES (?, ?, ?, ?, ?, '2026-01-01')", &[t(id), t(thread), t(&ws), t(name), SqlValue::Integer(is_self as i64)]); } #[allow(clippy::too_many_arguments)] fn message(handle: &CottonHandle, id: &str, thread: &str, out: bool, channel: &str, origin: &str, body: &str, at: &str, seq: i64, seat: Option<&str>) { let ws = workspace(handle); sql( handle, "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, seq, sender_participant_id, send_state, created_at, external_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", &[t(id), t(thread), t(&ws), t(if out { "out" } else { "in" }), t(channel), t(origin), t(body), t(at), SqlValue::Integer(seq), seat.map_or(SqlValue::Null, t), if out && channel == "cotton" { t("read") } else { SqlValue::Null }, t(at), t(&format!("x-{id}"))], ); } /// Asha on Cotton (two unread), a WhatsApp group, an archived SMS thread. fn three_chats(handle: &CottonHandle) { contact(handle, "c-asha", "Asha Example", "15550100001"); thread(handle, ASHA, "dm", Some("cotton:+15550100001"), None, Some("c-asha"), &iso(5)); message(handle, "m-a1", ASHA, true, "cotton", "live", "Are we still on?", &iso(10), 1, None); message(handle, "m-a2", ASHA, false, "cotton", "live", "Yes, at the lake", &iso(6), 2, None); message(handle, "m-a3", ASHA, false, "cotton", "live", "Bring the kite", &iso(5), 3, None); thread(handle, WEEKEND, "group", Some("group:weekend"), Some("Weekend plans"), None, &iso(60)); seat(handle, "s-me", WEEKEND, "Me", true); seat(handle, "s-bimal", WEEKEND, "Bimal Example", false); seat(handle, "s-chitra", WEEKEND, "Chitra Example", false); message(handle, "m-w1", WEEKEND, false, "whatsapp", "imported", "Who has the tent?", &iso(62), 0, Some("s-bimal")); message(handle, "m-w2", WEEKEND, false, "whatsapp", "imported", "I do", &iso(60), 0, Some("s-chitra")); thread(handle, OLD_SMS, "dm", Some("+15550100009"), Some("Old number"), None, &iso(9000)); message(handle, "m-s1", OLD_SMS, false, "sms", "imported", "Your parcel is here", &iso(9000), 0, None); sql(handle, "UPDATE cotton_msg_threads SET archived = 1 WHERE id = ?", &[t(OLD_SMS)]); } // RULE: the list is pinned first then newest, says each last line (a group's with its sender's first name), // counts what is unread, and its fan names each source the person has. #[test] fn the_list_orders_says_and_counts() { let (_dir, handle) = phone(); three_chats(&handle); let list = answer(&handle, "chat.list", json!({})); let rows = list["rows"].as_array().unwrap(); assert_eq!(rows.len(), 2, "archived stands only under Archived: {list}"); assert_eq!(rows[0]["name"], "Asha Example"); assert_eq!(rows[0]["unread"], 2); assert_eq!(rows[0]["source"], "cotton"); assert_eq!(rows[0]["picture"]["initials"], "AE"); assert_eq!(rows[0]["lastLine"]["text"], "Bring the kite"); assert_eq!(rows[1]["name"], "Weekend plans"); assert_eq!(rows[1]["group"], true); assert_eq!(rows[1]["lastLine"]["sender"], "Chitra"); assert_eq!(list["counts"]["unread"], 1); assert_eq!(list["counts"]["archived"], 1); let fan: Vec<&str> = list["fan"].as_array().unwrap().iter().map(|t| t["id"].as_str().unwrap()).collect(); assert_eq!(fan, ["all", "people", "groups", "unread", "archived", "cotton", "whatsapp", "calls", "account"]); // Pinning the group puts it first; the act answers the row as it now stands. let pinned = answer(&handle, "chat.act", json!({ "act": "pinChat", "thread": WEEKEND })); assert_eq!(pinned["row"]["pinned"], true); let list = answer(&handle, "chat.list", json!({})); assert_eq!(list["rows"][0]["thread"], WEEKEND); // Filters and search. let archived = answer(&handle, "chat.list", json!({ "filter": "archived" })); assert_eq!(archived["rows"][0]["thread"], OLD_SMS); let unread = answer(&handle, "chat.list", json!({ "filter": "unread" })); assert_eq!(unread["rows"].as_array().unwrap().len(), 1); let found = answer(&handle, "chat.list", json!({ "search": "weekend" })); assert_eq!(found["rows"][0]["thread"], WEEKEND); let by_line = answer(&handle, "chat.list", json!({ "search": "parcel" })); assert_eq!(by_line["rows"][0]["thread"], OLD_SMS, "search reaches archived chats and message text: {by_line}"); // Read clears the badge; Unread marks it with no number. let read = answer(&handle, "chat.act", json!({ "act": "read", "thread": ASHA })); assert_eq!(read["row"]["unread"], 0); let marked = answer(&handle, "chat.act", json!({ "act": "unread", "thread": ASHA })); assert_eq!(marked["row"]["markedUnread"], true); let muted = answer(&handle, "chat.act", json!({ "act": "mute", "thread": ASHA })); assert_eq!(muted["row"]["muted"], true); } // RULE: an imported thread is read as it is: no composer, a line saying why, and only copy, forward, pin, select. // RULE: a message that just landed (no sequence until the copy syncs) is unread at once, and reading the chat // clears it: the list's dot never waits for a sync (chat-warm-android on an emulator, 21 Nov 2026). #[test] fn a_message_just_landed_is_unread_before_it_syncs() { let (_dir, handle) = phone(); three_chats(&handle); let id = "11111111-1111-4111-8111-0000000000e1"; thread(&handle, id, "dm", Some("cotton:+15550100999"), Some("Ravi Example"), None, &iso(0)); let ws = workspace(&handle); sql( &handle, "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, seq, created_at) VALUES (?, ?, ?, 'in', 'cotton', 'live', 'Dinner at seven?', ?, NULL, ?)", &[t("landed-1"), t(id), t(&ws), t(&iso(0)), t(&iso(0))], ); let row = |list: &Value| list["rows"].as_array().unwrap().iter().find(|r| r["thread"] == id).cloned().unwrap(); assert_eq!(row(&answer(&handle, "chat.list", json!({})))["unread"], 1); answer(&handle, "chat.act", json!({ "act": "read", "thread": id })); assert_eq!(row(&answer(&handle, "chat.list", json!({})))["unread"], 0); } #[test] fn an_imported_thread_offers_only_what_it_can() { let (_dir, handle) = phone(); three_chats(&handle); let page = answer(&handle, "chat.thread", json!({ "thread": WEEKEND })); assert!(page.get("composer").is_none()); assert_eq!(page["readOnly"], "Read only: imported from WhatsApp."); // You, Bimal and Chitra: counted as the group page counts them. assert_eq!(page["header"]["status"], "3 members"); let bubbles: Vec<&Value> = page["items"].as_array().unwrap().iter().filter(|i| i["item"] == "bubble").collect(); assert_eq!(bubbles[0]["actions"], json!(["copy", "forward", "pin", "star", "select"])); assert_eq!(bubbles[0]["sender"]["name"], "Bimal Example"); assert_eq!(refused(&handle, "chat.act", json!({ "act": "send", "thread": WEEKEND, "text": "hi" })), "cannot"); assert_eq!(refused(&handle, "chat.act", json!({ "act": "react", "thread": WEEKEND, "message": "m-w1", "emoji": "👍" })), "cannot"); } // RULE: a Cotton thread opens on its newest page with the unread divider over the first unread message, // one sender's run grouped with one head and one tail. #[test] fn a_thread_lays_runs_dividers_and_the_composer() { let (_dir, handle) = phone(); three_chats(&handle); let page = answer(&handle, "chat.thread", json!({ "thread": ASHA })); let kinds: Vec<&str> = page["items"].as_array().unwrap().iter().map(|i| i["item"].as_str().unwrap()).collect(); assert_eq!(kinds, ["day", "bubble", "unread", "bubble", "bubble"]); let items = page["items"].as_array().unwrap(); assert_eq!(items[2]["label"], "2 unread messages"); assert_eq!((items[3]["head"].as_bool(), items[3]["tail"].as_bool()), (Some(true), Some(false))); assert_eq!((items[4]["head"].as_bool(), items[4]["tail"].as_bool()), (Some(false), Some(true))); assert_eq!(items[1]["tick"], "read"); assert_eq!(page["composer"]["button"], "mic"); assert_eq!(page["composer"]["placeholder"], "Message"); assert!(page.get("older").is_none() && page.get("newer").is_none()); assert_eq!(items[1]["actions"], json!(["reply", "react", "copy", "forward", "edit", "pin", "star", "delete", "select"])); } // RULE: a send stands in the thread at once, before any network, ticking as sending; the list row follows. #[test] fn a_send_answers_its_bubble_at_once() { let (_dir, handle) = phone(); three_chats(&handle); let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": ASHA, "text": " On my way ", "replyTo": "m-a3" })); assert_eq!(sent["flush"], true); assert_eq!(sent["bubble"]["text"], "On my way"); assert_eq!(sent["bubble"]["tick"], "sending"); assert_eq!(sent["bubble"]["mine"], true); assert_eq!(sent["bubble"]["reply"]["line"], "Bring the kite"); assert_eq!(sent["bubble"]["reply"]["sender"], "Asha Example"); assert_eq!(sent["row"]["lastLine"]["text"], "On my way"); let page = answer(&handle, "chat.thread", json!({ "thread": ASHA })); let last = page["items"].as_array().unwrap().last().unwrap().clone(); assert_eq!(last["message"], sent["message"]); assert_eq!(refused(&handle, "chat.act", json!({ "act": "send", "thread": ASHA, "text": " " })), "empty"); } // RULE (owner, 23 Nov 2026: a reply he sent did not show the message it answered): the reply strip the composer // stands (`chat.compose replyTo`) is what a send answers, whether or not the send names it again; a cancelled strip // answers nothing. #[test] fn a_send_answers_the_strip_it_was_written_under() { let (_dir, handle) = phone(); three_chats(&handle); answer(&handle, "chat.compose", json!({ "thread": ASHA, "text": "", "replyTo": "m-a3" })); let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": ASHA, "text": "On my way" })); assert_eq!(sent["bubble"]["reply"]["line"], "Bring the kite"); assert_eq!(sent["bubble"]["reply"]["message"], "m-a3"); let page = answer(&handle, "chat.thread", json!({ "thread": ASHA })); let last = page["items"].as_array().unwrap().last().unwrap().clone(); assert_eq!(last["reply"]["line"], "Bring the kite"); // The strip is spent by the send: the next words answer nothing. assert!(page["composer"].get("strip").is_none()); let next = answer(&handle, "chat.act", json!({ "act": "send", "thread": ASHA, "text": "Five minutes" })); assert!(next["bubble"].get("reply").is_none()); // A strip cancelled before the send answers nothing. answer(&handle, "chat.compose", json!({ "thread": ASHA, "text": "", "replyTo": "m-a2" })); answer(&handle, "chat.compose", json!({ "thread": ASHA, "text": "", "cancel": true })); let plain = answer(&handle, "chat.act", json!({ "act": "send", "thread": ASHA, "text": "Never mind" })); assert!(plain["bubble"].get("reply").is_none()); } // RULE: the composer's button is Send with text; a reply strip names whom it answers; the draft is kept when the thread is left. #[test] fn the_composer_keeps_its_draft_and_strip() { let (_dir, handle) = phone(); three_chats(&handle); let typing = answer(&handle, "chat.compose", json!({ "thread": ASHA, "text": "see" })); assert_eq!(typing["button"], "send"); let replying = answer(&handle, "chat.compose", json!({ "thread": ASHA, "text": "see", "replyTo": "m-a2" })); assert_eq!(replying["strip"]["title"], "Reply to Asha Example"); assert_eq!(replying["strip"]["line"], "Yes, at the lake"); answer(&handle, "chat.compose", json!({ "thread": ASHA, "text": "see you there", "keep": true })); let page = answer(&handle, "chat.thread", json!({ "thread": ASHA })); assert_eq!(page["composer"]["text"], "see you there"); assert_eq!(page["composer"]["strip"]["kind"], "reply"); let list = answer(&handle, "chat.list", json!({})); assert_eq!(list["rows"][0]["draft"], "Draft: see you there"); let cancelled = answer(&handle, "chat.compose", json!({ "thread": ASHA, "text": "see you there", "cancel": true })); assert!(cancelled.get("strip").is_none()); // An edit fills the field with your own words and saves rather than sends. let editing = answer(&handle, "chat.compose", json!({ "thread": ASHA, "edit": "m-a1" })); assert_eq!((editing["text"].as_str(), editing["buttonLabel"].as_str(), editing["strip"]["kind"].as_str()), (Some("Are we still on?"), Some("Save"), Some("edit"))); assert_eq!(refused(&handle, "chat.compose", json!({ "thread": ASHA, "edit": "m-a2" })), "not_yours"); } // RULE (owner, Comms build 19: no way to write words with the pictures he attaches): pictures waiting in the writing // box (`attached`) make Send live with nothing written, and go with what is written as their caption, which the // bubble draws as its words under the picture. #[test] fn pictures_waiting_in_the_box_send_with_their_caption() { let (dir, handle) = phone(); three_chats(&handle); let empty = answer(&handle, "chat.compose", json!({ "thread": ASHA, "text": "" })); assert_eq!((empty["button"].as_str(), empty["sendEnabled"].as_bool()), (Some("mic"), Some(false))); let waiting = answer(&handle, "chat.compose", json!({ "thread": ASHA, "text": "", "attached": 2 })); assert_eq!((waiting["button"].as_str(), waiting["sendEnabled"].as_bool(), waiting["buttonLabel"].as_str()), (Some("send"), Some(true), Some("Send"))); let gone = answer(&handle, "chat.compose", json!({ "thread": ASHA, "text": "", "attached": 0 })); assert_eq!(gone["button"], "mic", "the pictures taken out of the box"); let photo = dir.path().join("invented.jpg"); std::fs::write(&photo, [0xFF, 0xD8, 0xFF, 0xD9]).unwrap(); let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": ASHA, "text": "The invented lake", "attachments": [{ "path": photo.to_string_lossy(), "mime": "image/jpeg", "kind": "photo", "width": 4, "height": 3 }] })); assert_eq!((sent["bubble"]["kind"].as_str(), sent["bubble"]["text"].as_str()), (Some("photo"), Some("The invented lake"))); let page = answer(&handle, "chat.thread", json!({ "thread": ASHA })); let last = page["items"].as_array().unwrap().last().unwrap().clone(); assert_eq!((last["kind"].as_str(), last["text"].as_str()), (Some("photo"), Some("The invented lake"))); } // RULE: react, pin, edit and delete change the bubble they name; the pinned bar shows the newest pin. #[test] fn acts_on_a_message_change_its_bubble() { let (_dir, handle) = phone(); three_chats(&handle); let reacted = answer(&handle, "chat.act", json!({ "act": "react", "thread": ASHA, "message": "m-a3", "emoji": "❤️" })); assert_eq!(reacted["bubble"]["reactions"], json!([{ "emoji": "❤️", "count": 1, "mine": true }])); assert_eq!(reacted["flush"], true, "a Cotton reaction waits to be told"); let waiting = crate::phone::cotton_chat::read(&handle.client(), "test", |ctx| { Ok(crate::phone::cotton_chat::one(ctx, "SELECT changes_waiting FROM cotton_msg_threads WHERE id = ?", &[t(ASHA)])?.map(serde_json::Value::Object).unwrap_or_default()) }) .unwrap(); let waiting: Value = serde_json::from_str(waiting["changes_waiting"].as_str().unwrap()).unwrap(); assert_eq!((waiting[0]["what"].as_str(), waiting[0]["emoji"].as_str()), (Some("react"), Some("❤️"))); let changed = answer(&handle, "chat.act", json!({ "act": "react", "thread": ASHA, "message": "m-a3", "emoji": "👍" })); assert_eq!(changed["bubble"]["reactions"][0]["emoji"], "👍"); let gone = answer(&handle, "chat.act", json!({ "act": "unreact", "thread": ASHA, "message": "m-a3" })); assert!(gone["bubble"].get("reactions").is_none()); let pinned = answer(&handle, "chat.act", json!({ "act": "pin", "thread": ASHA, "message": "m-a2" })); assert_eq!(pinned["bubble"]["pinned"], true); let page = answer(&handle, "chat.thread", json!({ "thread": ASHA })); assert_eq!(page["pinned"]["message"], "m-a2"); assert_eq!(page["pinned"]["line"], "Yes, at the lake"); answer(&handle, "chat.act", json!({ "act": "unpin", "thread": ASHA, "message": "m-a2" })); assert!(answer(&handle, "chat.thread", json!({ "thread": ASHA })).get("pinned").is_none()); let edited = answer(&handle, "chat.act", json!({ "act": "edit", "thread": ASHA, "message": "m-a1", "text": "Still on?" })); assert_eq!((edited["bubble"]["text"].as_str(), edited["bubble"]["edited"].as_str()), (Some("Still on?"), Some("edited"))); assert_eq!(refused(&handle, "chat.act", json!({ "act": "edit", "thread": ASHA, "message": "m-a2", "text": "x" })), "not_yours"); let deleted = answer(&handle, "chat.act", json!({ "act": "delete", "thread": ASHA, "message": "m-a1" })); assert_eq!(deleted["bubble"]["kind"], "deleted"); assert_eq!(deleted["bubble"]["actions"], json!(["select"])); let forwarded = answer(&handle, "chat.act", json!({ "act": "forward", "thread": ASHA, "message": "m-a2", "to": [ASHA] })); assert_eq!(forwarded["sentTo"], json!([ASHA])); let page = answer(&handle, "chat.thread", json!({ "thread": ASHA })); let last = page["items"].as_array().unwrap().last().unwrap().clone(); assert_eq!((last["text"].as_str(), last["forwarded"].as_str()), (Some("Yes, at the lake"), Some("Forwarded"))); } // RULE: the looks are the kit's; the plain pair stands until a phone picks another, and the pick is kept. #[test] fn the_looks_are_the_kits_and_a_pick_is_kept() { let (_dir, handle) = phone(); let looks = answer(&handle, "chat.themes", json!({})); assert_eq!((looks["light"].as_str(), looks["dark"].as_str()), (Some("plain"), Some("plain"))); let ids: Vec<&str> = looks["themes"].as_array().unwrap().iter().map(|t| t["id"].as_str().unwrap()).collect(); assert_eq!(ids, ["plain", "cotton", "contrast"]); assert_eq!(looks["themes"][1]["name"], "Cotton"); assert_eq!(looks["themes"][1]["ground"], "weave"); assert!(looks["themes"][0]["light"]["bubble_out"].as_str().unwrap().starts_with('#')); assert!(looks["themes"][0]["dark"]["tint.0"].is_string()); let picked = answer(&handle, "chat.theme.set", json!({ "appearance": "dark", "id": "cotton" })); assert_eq!((picked["light"].as_str(), picked["dark"].as_str()), (Some("plain"), Some("cotton"))); assert_eq!(answer(&handle, "chat.themes", json!({}))["dark"], "cotton"); assert_eq!(refused(&handle, "chat.theme.set", json!({ "appearance": "dark", "id": "neon" })), "not_found"); assert_eq!(refused(&handle, "chat.theme.set", json!({ "appearance": "dusk", "id": "plain" })), "invalid_request"); // Settings: the theme by appearance, the text size and the thread's ground, each kept and answered whole. let set = answer(&handle, "chat.theme", json!({ "theme": "contrast", "dark": false })); assert_eq!(set["light"], "contrast"); assert_eq!((set["text"]["chosen"].as_str(), set["ground"]["chosen"].as_str()), (Some("standard"), Some("theme"))); assert_eq!(set["text"]["options"][2], json!({ "id": "large", "label": "Large", "scale": 1.15 })); let larger = answer(&handle, "chat.text", json!({ "value": "larger" })); assert_eq!(larger["text"]["chosen"], "larger"); let woven = answer(&handle, "chat.ground", json!({ "ground": "weave" })); assert!(woven["themes"].as_array().unwrap().iter().all(|t| t["ground"] == "weave"), "a chosen ground stands over each theme's own"); assert_eq!(woven["words"]["settings"], "Settings"); assert_eq!(woven["ground"]["options"][0]["label"], "As the look"); assert_eq!(refused(&handle, "chat.text", json!({ "value": "huge" })), "not_found"); } // RULE: a photo, a file and a voice message go through chat.act send and stand as their bubbles at once; // Forward's picker is only the conversations a message can go to. #[test] fn attachments_send_and_the_forward_picker() { let (dir, handle) = phone(); three_chats(&handle); let photo = dir.path().join("invented.jpg"); std::fs::write(&photo, [0xFF, 0xD8, 0xFF, 0xD9]).unwrap(); let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": ASHA, "attachments": [{ "path": photo.to_string_lossy(), "mime": "image/jpeg", "width": 4, "height": 3 }] })); assert_eq!(sent["bubble"]["kind"], "photo"); assert_eq!(sent["bubble"]["media"][0]["width"], 4.0); assert_eq!(sent["row"]["lastLine"]["mark"], "photo"); let voice = dir.path().join("invented.m4a"); std::fs::write(&voice, [0u8; 64]).unwrap(); let said = answer(&handle, "chat.act", json!({ "act": "send", "thread": ASHA, "attachments": [{ "path": voice.to_string_lossy(), "mime": "audio/mp4", "kind": "voice", "durationMs": 12_000, "waveform": [0.1, 0.5, 1.0] }] })); assert_eq!(said["bubble"]["kind"], "voice"); assert_eq!(said["bubble"]["media"][0]["length"], "0:12"); assert_eq!(said["bubble"]["media"][0]["waveform"], json!([0.1, 0.5, 1.0])); let file = dir.path().join("invented.pdf"); std::fs::write(&file, [1u8; 2048]).unwrap(); let filed = answer(&handle, "chat.act", json!({ "act": "send", "thread": ASHA, "attachments": [{ "path": file.to_string_lossy(), "mime": "application/pdf", "name": "Invented plan.pdf", "kind": "file" }] })); assert_eq!((filed["bubble"]["kind"].as_str(), filed["bubble"]["media"][0]["name"].as_str()), (Some("file"), Some("Invented plan.pdf"))); assert_eq!(refused(&handle, "chat.act", json!({ "act": "send", "thread": WEEKEND, "attachments": [{ "path": photo.to_string_lossy(), "mime": "image/jpeg" }] })), "cannot"); let picker = answer(&handle, "chat.list", json!({ "sendable": true })); let ids: Vec<&str> = picker["rows"].as_array().unwrap().iter().map(|r| r["thread"].as_str().unwrap()).collect(); assert_eq!(ids, [ASHA]); assert_eq!(picker["rows"][0]["sendable"], true); } /// One Cotton thread of `count` messages, two minutes apart, alternating in runs of three. fn long_thread(handle: &CottonHandle, id: &str, count: usize) { contact(handle, "c-long", "Long Example", "15550100077"); thread(handle, id, "dm", Some("cotton:+15550100077"), None, Some("c-long"), &iso(0)); let ws = workspace(handle); // A fixed morning (UTC and IST alike), so a run never crosses a day's // separator: from now, a thread read near midnight split its runs of three. let start = chrono::DateTime::parse_from_rfc3339("2026-11-18T03:00:00Z").unwrap().with_timezone(&chrono::Utc); handle .client() .with_writer(|replica| { let db = &replica.driver; db.run("BEGIN", &[]).map_err(|e| e.to_string())?; for n in 0..count { let at = (start + chrono::Duration::minutes(2 * n as i64)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true); let out = (n / 3) % 2 == 0; db.run( "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, seq, created_at) VALUES (?, ?, ?, ?, 'cotton', 'live', ?, ?, ?, ?)", &[t(&format!("{id}-{n:07}")), t(id), t(&ws), t(if out { "out" } else { "in" }), t(&format!("Invented line {n}")), t(&at), SqlValue::Integer(n as i64 + 1), t(&at)], ) .map_err(|e| e.to_string())?; } db.run("COMMIT", &[]).map_err(|e| e.to_string())?; Ok(()) }) .unwrap(); } // RULE: pages meet without a seam: walking `older` to the top reads every message once, in order, // and a run across a page's edge keeps one head and one tail. #[test] fn pages_walk_the_whole_thread_without_a_seam() { let (_dir, handle) = phone(); let id = "11111111-1111-4111-8111-0000000000d1"; long_thread(&handle, id, 130); sql(&handle, "UPDATE cotton_msg_threads SET read_seq = 130 WHERE id = ?", &[t(id)]); let mut page = answer(&handle, "chat.thread", json!({ "thread": id })); let mut seen: Vec = Vec::new(); let mut pages = 0; loop { pages += 1; let mut items: Vec = page["items"].as_array().unwrap().iter().filter(|i| i["item"] == "bubble").cloned().collect(); items.extend(seen); seen = items; match page.get("older").and_then(Value::as_str) { Some(cursor) => page = answer(&handle, "chat.thread", json!({ "thread": id, "before": cursor })), None => break, } } assert_eq!(pages, 3); let ids: Vec = seen.iter().map(|b| b["message"].as_str().unwrap().to_string()).collect(); let wanted: Vec = (0..130).map(|n| format!("{id}-{n:07}")).collect(); assert_eq!(ids, wanted); // Runs of three: head on the first, tail on the third, wherever the page edges fell. for (n, b) in seen.iter().enumerate() { assert_eq!(b["head"].as_bool(), Some(n % 3 == 0), "head at {n}"); assert_eq!(b["tail"].as_bool(), Some(n % 3 == 2 || n == 129), "tail at {n}"); } // A reply's quote opens around its message, with a page below to come back by. let around = answer(&handle, "chat.thread", json!({ "thread": id, "around": format!("{id}-0000010") })); assert_eq!(around["focus"], format!("{id}-0000010")); assert!(around.get("newer").is_some()); assert!(around["jump"]["count"].as_u64().unwrap() > 0); let newer = answer(&handle, "chat.thread", json!({ "thread": id, "after": around["newer"] })); let first = newer["items"].as_array().unwrap().iter().find(|i| i["item"] == "bubble").unwrap().clone(); assert_eq!(first["message"], format!("{id}-{:07}", 41)); } /// The figures (owner, 19 Nov 2026): 500 conversations and one thread of 100,000 messages, /// list, newest page and the next page each under 30 ms on a release build. /// `pnpm box:cargo test --release -p cotton-ffi chat_app::tests::speed -- --ignored --nocapture` #[test] #[ignore = "a measurement: run on a release build"] fn speed() { let (_dir, handle) = phone(); let big = "11111111-1111-4111-8111-0000000000e1"; long_thread(&handle, big, 100_000); let ws = workspace(&handle); handle .client() .with_writer(|replica| { let db = &replica.driver; db.run("BEGIN", &[]).map_err(|e| e.to_string())?; for c in 0..499 { let id = format!("22222222-2222-4222-8222-{c:012}"); let at = (chrono::Utc::now() - chrono::Duration::minutes(10 + c)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true); let group = c % 5 == 0; db.run("INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, created_at, updated_at) VALUES (?, ?, ?, ?, '2026-01-01', '2026-01-01')", &[t(&format!("c-{c}")), t(&ws), t(&format!("1555020{c:04}")), t(&format!("Invented Person {c}"))]).map_err(|e| e.to_string())?; db.run( "INSERT INTO cotton_msg_threads (id, workspace_id, kind, external_key, title, contact_id, last_message_at, read_seq, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?)", &[t(&id), t(&ws), t(if group { "group" } else { "dm" }), t(&if group { format!("group:{c}") } else { format!("cotton:+1555020{c:04}") }), if group { t(&format!("Invented group {c}")) } else { SqlValue::Null }, if group { SqlValue::Null } else { t(&format!("c-{c}")) }, t(&at), t(&at), t(&at)], ) .map_err(|e| e.to_string())?; for m in 0..20 { db.run( "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, seq, created_at) VALUES (?, ?, ?, ?, 'cotton', 'live', ?, ?, ?, ?)", &[t(&format!("{id}-{m}")), t(&id), t(&ws), t(if m % 2 == 0 { "in" } else { "out" }), t(&format!("Invented message {m}")), t(&at), SqlValue::Integer(m + 1), t(&at)], ) .map_err(|e| e.to_string())?; } } db.run("COMMIT", &[]).map_err(|e| e.to_string())?; db.run("ANALYZE", &[]).map_err(|e| e.to_string())?; Ok(()) }) .unwrap(); let time = |label: &str, f: &mut dyn FnMut() -> Value| -> Value { f(); // warm let mut best = std::time::Duration::MAX; let mut out = Value::Null; for _ in 0..5 { let at = std::time::Instant::now(); out = f(); best = best.min(at.elapsed()); } println!("FIGURE {label}: {:.1} ms", best.as_secs_f64() * 1000.0); out }; let list = time("chat.list (500 conversations)", &mut || answer(&handle, "chat.list", json!({}))); assert_eq!(list["counts"]["all"], 500); let page = time("chat.thread newest page (100,000 messages)", &mut || answer(&handle, "chat.thread", json!({ "thread": big }))); let older = page["older"].as_str().unwrap().to_string(); time("chat.thread next page", &mut || answer(&handle, "chat.thread", json!({ "thread": big, "before": older }))); time("chat.list search", &mut || answer(&handle, "chat.list", json!({ "search": "person 42" }))); let mut n = 0; time("chat.act send (to the bubble)", &mut || { n += 1; answer(&handle, "chat.act", json!({ "act": "send", "thread": big, "text": format!("Invented send {n}") })) }); } // RULE: Delete takes a chat off the list (asked first, naming them) until a later message brings it back, holding // only what came after. #[test] fn a_deleted_chat_leaves_the_list_until_a_later_message() { let (_dir, handle) = phone(); three_chats(&handle); let row = &answer(&handle, "chat.list", json!({}))["rows"][0]; let delete = row["hold"].as_array().unwrap().last().unwrap(); assert_eq!(delete["act"], "deleteChat"); assert_eq!(delete["label"], "Delete"); assert_eq!(delete["confirm"], "Delete your chat with Asha Example? Its messages go from this phone and your other devices."); let done = answer(&handle, "chat.act", json!({ "act": "deleteChat", "thread": ASHA })); assert_eq!(done["said"], "Chat deleted"); let list = answer(&handle, "chat.list", json!({})); assert!(list["rows"].as_array().unwrap().iter().all(|r| r["thread"] != ASHA), "{list}"); let later = (chrono::Utc::now() + chrono::Duration::minutes(1)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true); message(&handle, "m-a5", ASHA, false, "cotton", "live", "Did you leave?", &later, 5, None); sql(&handle, "UPDATE cotton_msg_threads SET last_message_at = ? WHERE id = ?", &[t(&later), t(ASHA)]); let list = answer(&handle, "chat.list", json!({})); assert_eq!(list["rows"][0]["thread"], ASHA); let page = answer(&handle, "chat.thread", json!({ "thread": ASHA })); let bodies: Vec<&str> = page["items"].as_array().unwrap().iter().filter_map(|i| i["text"].as_str()).collect(); assert_eq!(bodies, ["Did you leave?"], "{page}"); } /// An imported WhatsApp group: Bimal's words minutes apart, a call record under his name, a screenshot sent as a /// document (its name where a caption stands) and a photo with real words. fn imported_group(handle: &CottonHandle) { thread(handle, WEEKEND, "group", Some("group:weekend"), Some("Hill trip"), None, &iso(5)); seat(handle, "s-me", WEEKEND, "Me", true); seat(handle, "s-bimal", WEEKEND, "Bimal Example", false); seat(handle, "s-chitra", WEEKEND, "Chitra Example", false); let lines: [(&str, &str, i64, &str); 7] = [ ("m-g1", "s-bimal", 60, "Who has the tent?"), ("m-g2", "s-bimal", 50, "The big one is in my car"), ("m-g3", "s-bimal", 35, "And the poles, somewhere"), ("m-g4", "s-bimal", 30, "\u{200e}Voice call, \u{200e}41 sec"), ("m-g5", "s-bimal", 29, "Found them"), ("m-g6", "s-chitra", 20, "Screenshot 2026-11-03 at 10.15.22.png"), ("m-g7", "s-chitra", 10, "The view from the top"), ]; for (id, seat, ago, body) in lines { message(handle, id, WEEKEND, false, "whatsapp", "imported", body, &iso(ago), 0, Some(seat)); } let picture = |name: &str| json!([{ "key": format!("w/messages/{WEEKEND}/{name}"), "contentType": "image/png", "name": name, "width": 640, "height": 480 }]).to_string(); sql(handle, "UPDATE cotton_msg_messages SET media = ? WHERE id = 'm-g6'", &[t(&picture("00000011-Screenshot 2026-11-03 at 10.15.22.png"))]); sql(handle, "UPDATE cotton_msg_messages SET media = ? WHERE id = 'm-g7'", &[t(&picture("00000012-PHOTO-2026-11-03-10-25-00.jpg"))]); } fn item<'a>(page: &'a Value, message: &str) -> &'a Value { page["items"].as_array().unwrap().iter().find(|i| i["message"] == message).unwrap_or_else(|| panic!("{message} in {page}")) } // RULE: a call an export wrote under the caller's name (WhatsApp's "Voice call, 41 sec") is a quiet centred line, // never their words with their picture; it breaks their run as any event does. #[test] fn an_imported_call_record_is_a_centred_line() { let (_dir, handle) = phone(); imported_group(&handle); let page = answer(&handle, "chat.thread", json!({ "thread": WEEKEND })); let call = item(&page, "m-g4"); assert_eq!(call["item"], "event", "{call}"); assert_eq!(call["text"], "Voice call · 41 sec"); assert!(call.get("sender").is_none(), "{call}"); assert_eq!(item(&page, "m-g5")["face"], true, "after the call line, Bimal's picture stands again"); } // RULE: a WhatsApp call is the chat's last line as its call line, never the caller's words under their name: one an // export wrote ("Missed video call, Tap to call back"), and one the Mac's link wrote with the call's facts (`meta.call`). #[test] fn a_whatsapp_call_is_the_lists_last_line() { let (_dir, handle) = phone(); imported_group(&handle); message(&handle, "m-g8", WEEKEND, false, "whatsapp", "imported", "\u{200e}Missed video call, \u{200e}Tap to call back", &iso(5), 0, Some("s-bimal")); let row = |handle: &CottonHandle| answer(handle, "chat.list", json!({}))["rows"].as_array().unwrap().iter().find(|r| r["thread"] == WEEKEND).cloned().unwrap(); let last = row(&handle)["lastLine"].clone(); assert_eq!(last["text"], "Missed video call", "{last}"); assert!(last.get("sender").is_none(), "{last}"); message(&handle, "m-g9", WEEKEND, false, "whatsapp", "live", "", &iso(3), 0, Some("s-bimal")); let facts = json!({ "call": { "room": "wa-call-invented-1", "direction": "in", "video": false, "outcome": "answered", "reason": "hung_up", "durationS": 192, "missed": false } }); sql(&handle, "UPDATE cotton_msg_messages SET meta = ? WHERE id = 'm-g9'", &[t(&facts.to_string())]); assert_eq!(row(&handle)["lastLine"]["text"], "Voice call · 3:12"); let page = answer(&handle, "chat.thread", json!({ "thread": WEEKEND })); let call = item(&page, "m-g9"); assert_eq!((call["item"].clone(), call["text"].clone()), (json!("event"), json!("Voice call · 3:12")), "{call}"); // No Cotton call stands behind a WhatsApp call (Mac 10): its line offers no Call back (CONTRACT "WhatsApp calls from the link"). assert_eq!((call["call"]["call"].clone(), call["call"]["back"].clone()), (json!(""), json!("")), "{call}"); // A person who types the words in a live chat wrote words, not a call. message(&handle, "m-g10", WEEKEND, false, "whatsapp", "live", "Voice call, 41 sec", &iso(1), 0, Some("s-bimal")); assert_eq!(row(&handle)["lastLine"]["text"], "Voice call, 41 sec"); } // RULE: a line an export wrote with no sender ("Bimal Example created group …") is a quiet centred line, as the // importer marks it (meta.system, beside its `source` word), never a message from "(unknown)". #[test] fn an_imported_groups_own_lines_are_centred_lines() { let (_dir, handle) = phone(); imported_group(&handle); message(&handle, "m-g0", WEEKEND, false, "whatsapp", "imported", "Bimal Example created group \"Hill trip\"", &iso(70), 0, None); // The importer's meta, as `import.whatsappExport` writes it (normalize::TXT_SOURCE). sql(&handle, "UPDATE cotton_msg_messages SET meta = ? WHERE id = 'm-g0'", &[t(r#"{"source":"whatsapp-chat-txt","system":true}"#)]); let page = answer(&handle, "chat.thread", json!({ "thread": WEEKEND })); let made = item(&page, "m-g0"); assert_eq!(made["item"], "event", "{made}"); assert_eq!(made["text"], "Bimal Example created group \"Hill trip\""); assert!(!page.to_string().contains("(unknown)"), "{page}"); assert_eq!(item(&page, "m-g1")["face"], true, "Bimal's picture stands over his first words after the line"); } // RULE: a picture whose only words are its file's name has no caption; a picture with words keeps them. #[test] fn a_pictures_file_name_is_not_its_caption() { let (_dir, handle) = phone(); imported_group(&handle); let page = answer(&handle, "chat.thread", json!({ "thread": WEEKEND })); let shot = item(&page, "m-g6"); assert_eq!(shot["kind"], "photo"); assert!(shot.get("text").is_none(), "{shot}"); assert_eq!(item(&page, "m-g7")["text"], "The view from the top"); } // RULE: their picture and name stand once over one sender's unbroken words in a day, however many minutes apart the // lines are; a bubble answered alone (a star, a pin) keeps its place in its run, so it never shows the picture again. #[test] fn their_picture_stands_once_over_their_words() { let (_dir, handle) = phone(); imported_group(&handle); let page = answer(&handle, "chat.thread", json!({ "thread": WEEKEND })); let faces: Vec<&str> = page["items"].as_array().unwrap().iter().filter(|i| i["face"] == true).filter_map(|i| i["message"].as_str()).collect(); assert_eq!(faces, ["m-g1", "m-g5", "m-g6"], "{page}"); assert_eq!(item(&page, "m-g2")["head"], true, "ten minutes on, the run still starts afresh for its spacing"); let starred = answer(&handle, "chat.act", json!({ "act": "star", "thread": WEEKEND, "message": "m-g2" })); assert_eq!(starred["bubble"]["face"], false, "{starred}"); assert_eq!(starred["bubble"]["head"], item(&page, "m-g2")["head"]); assert_eq!(starred["bubble"]["tail"], item(&page, "m-g2")["tail"]); let first = answer(&handle, "chat.act", json!({ "act": "star", "thread": WEEKEND, "message": "m-g1" })); assert_eq!(first["bubble"]["face"], true); } // RULE: a file the store said it does not hold (cotton_client::media::absent, kept by media.ensure and chat.picture) // is said gone in its bubble until its wait is over, so a phone draws "not available" without asking; a Cotton // picture the chat store answered 404 for is refused by chat.picture with no request until then. #[test] fn a_picture_the_store_does_not_hold_is_said_gone() { let (dir, handle) = phone(); imported_group(&handle); let page = answer(&handle, "chat.thread", json!({ "thread": WEEKEND })); assert!(item(&page, "m-g7")["media"][0].get("gone").is_none(), "{page}"); let now = handle.client().now().timestamp_millis(); handle.client().absent_media().note(&format!("w/messages/{WEEKEND}/00000012-PHOTO-2026-11-03-10-25-00.jpg"), 404, now); let page = answer(&handle, "chat.thread", json!({ "thread": WEEKEND })); assert_eq!(item(&page, "m-g7")["media"][0]["gone"], true, "{page}"); assert!(item(&page, "m-g6")["media"][0].get("gone").is_none(), "only that file"); contact(&handle, "c-asha", "Asha Example", "15550100001"); thread(&handle, ASHA, "dm", Some("cotton:+15550100001"), None, Some("c-asha"), &iso(1)); // Half an hour old: a new message's file is never gone (a_picture_being_sent_is_never_gone). message(&handle, "m-p1", ASHA, false, "cotton", "live", "", &iso(30), 1, None); let picture = json!({ "cotton": { "pictures": [{ "file": "f-gone", "key": "A".repeat(43), "sha256": "00", "mime": "image/jpeg", "bytes": 10 }] } }); sql(&handle, "UPDATE cotton_msg_messages SET meta = ? WHERE id = 'm-p1'", &[t(&picture.to_string())]); let ask = json!({ "message": "m-p1", "index": 0, "dir": dir.path().join("opened").to_string_lossy() }); assert_ne!(refused(&handle, "chat.picture", ask.clone()), "not_found", "asked of the chat store (this phone has no door to it)"); handle.client().absent_media().note("f-gone", 404, now); assert_eq!(refused(&handle, "chat.picture", ask), "not_found", "refused at once, no request"); let page = answer(&handle, "chat.thread", json!({ "thread": ASHA })); assert_eq!(item(&page, "m-p1")["media"][0]["gone"], true, "{page}"); } // FEEDBACK1 item 1 (22 Nov 2026): a picture the person had just sent showed "Picture not // available". While it is going up, chat.picture answered "no such picture" (it counted only the // files already up), and a store's miss within minutes of a message was kept as gone for good. #[test] fn a_picture_being_sent_is_never_gone() { let (dir, handle) = phone(); contact(&handle, "c-asha", "Asha Example", "15550100001"); thread(&handle, ASHA, "dm", Some("cotton:+15550100001"), None, Some("c-asha"), &iso(0)); let mine = dir.path().join("chat-out-sent.jpg"); std::fs::write(&mine, b"the picture's own bytes").unwrap(); // Still going up: its file is on this phone, in meta.cotton.pending_pictures. message(&handle, "m-out", ASHA, true, "cotton", "live", "", &iso(0), 1, None); let pending = json!({ "cotton": { "written_at": iso(0), "pending_pictures": [{ "path": mine.to_string_lossy(), "mime": "image/jpeg", "kind": "photo" }] } }); sql(&handle, "UPDATE cotton_msg_messages SET meta = ?, send_state = 'queued' WHERE id = 'm-out'", &[t(&pending.to_string())]); let ask = json!({ "message": "m-out", "index": 0, "dir": dir.path().join("opened").to_string_lossy() }); let opened = answer(&handle, "chat.picture", ask.clone()); assert_eq!(opened["path"], json!(mine.to_string_lossy()), "the phone's own file, at once: {opened}"); let file = answer(&handle, "chat.file", ask); assert_eq!(file["path"], json!(mine.to_string_lossy()), "{file}"); // Up, and a minute old: the store's miss is "not yet", never kept as gone. message(&handle, "m-new", ASHA, false, "cotton", "live", "", &iso(1), 2, None); let up = json!({ "cotton": { "pictures": [{ "file": "f-new", "key": "A".repeat(43), "sha256": "00", "mime": "image/jpeg", "bytes": 10 }] } }); sql(&handle, "UPDATE cotton_msg_messages SET meta = ? WHERE id = 'm-new'", &[t(&up.to_string())]); let now = handle.client().now().timestamp_millis(); handle.client().absent_media().note("f-new", 404, now); let page = answer(&handle, "chat.thread", json!({ "thread": ASHA })); assert!(item(&page, "m-new")["media"][0].get("gone").is_none(), "a new message's picture is never gone: {page}"); let ask = json!({ "message": "m-new", "index": 0, "dir": dir.path().join("opened").to_string_lossy() }); assert_eq!(refused(&handle, "chat.picture", ask), "not_yet", "asked again, and only \"not yet\" (no door here), never refused as gone"); // An old one is gone as before. assert!(cotton_core::chat::files::may_be_gone(false, Some(now - cotton_core::chat::files::GONE_NOT_BEFORE_MS), now)); assert!(!cotton_core::chat::files::may_be_gone(true, Some(now - 3_600_000), now), "never while it is sending"); } // The iPhone Warm look's sample chats (apps/cotton …/Fixtures/chat-warm.json): the core's own // answers over invented people, for Chat Dev's -chat-warm-seed shots. Run by hand: // cargo test -p cotton-ffi --lib write_chat_warm_fixture -- --ignored #[test] #[ignore] fn write_chat_warm_fixture() { let (_dir, handle) = phone(); let day = |d: u32, h: u32, m: u32| format!("2026-11-{d:02}T{:02}:{m:02}:00.000Z", h); contact(&handle, "c-asha", "Asha Verma", "15550100001"); thread(&handle, ASHA, "dm", Some("cotton:+15550100001"), None, Some("c-asha"), &day(20, 9, 41)); let lines: [(&str, bool, &str, u32, u32, u32); 9] = [ ("a1", false, "Did you see the light this morning?", 19, 2, 10), ("a2", false, "The whole lake went orange", 19, 2, 11), ("a3", true, "I did! Stood on the balcony for ten minutes", 19, 2, 20), ("a4", true, "Coffee on Saturday?", 19, 2, 21), ("a5", false, "Yes. The place by the bookshop", 19, 2, 40), ("a6", true, "I'll bring the map you lent me", 20, 3, 5), ("a7", true, "And the umbrella, finally", 20, 3, 6), ("a8", false, "Keep the umbrella, it suits you", 20, 4, 10), ("a9", false, "See you at ten?", 20, 4, 11), ]; for (n, (id, out, body, d, h, m)) in lines.iter().enumerate() { message(&handle, &format!("m-{id}"), ASHA, *out, "cotton", "live", body, &day(*d, *h, *m), n as i64 + 1, None); } message(&handle, "m-a10", ASHA, true, "cotton", "live", "Running five minutes late", &day(20, 4, 12), 10, None); sql(&handle, "UPDATE cotton_msg_messages SET send_state = 'failed' WHERE id = 'm-a10'", &[]); sql(&handle, "UPDATE cotton_msg_messages SET reply_to_id = 'm-a4' WHERE id = 'm-a5'", &[]); sql(&handle, "UPDATE cotton_msg_messages SET reactions = '[\"❤️\"]' WHERE id = 'm-a2'", &[]); sql(&handle, "UPDATE cotton_msg_messages SET edited_at = ? WHERE id = 'm-a7'", &[t(&day(20, 3, 8))]); sql(&handle, "UPDATE cotton_msg_threads SET read_seq = 7 WHERE id = ?", &[t(ASHA)]); // Asha set up Comms on a tablet: her chat says so once, quietly (chat_safety's line, as it lands). message(&handle, "m-a-safety", ASHA, false, "cotton", "live", "", &day(20, 4, 0), 0, None); let safety = json!({ "system": true, "cotton": { "safety": { "wasVerified": true }, "from": "+15550100001", "written_at": day(20, 4, 0) } }); sql(&handle, "UPDATE cotton_msg_messages SET meta = ? WHERE id = 'm-a-safety'", &[t(&safety.to_string())]); // Imported from WhatsApp: Bimal's words minutes apart (his picture once), a call record under his name, a // picture whose file the store does not have (m-w7: Chat Dev's seed answers no file for it), a screenshot sent // as a document (its name where a caption stands) and a picture with words. thread(&handle, WEEKEND, "group", Some("group:weekend"), Some("Hill trip"), None, &day(20, 4, 2)); seat(&handle, "s-me", WEEKEND, "Me", true); seat(&handle, "s-bimal", WEEKEND, "Bimal Rao", false); seat(&handle, "s-chitra", WEEKEND, "Chitra Nair", false); let trip: [(&str, &str, u32, u32, &str); 9] = [ ("m-w1", "s-bimal", 3, 20, "Who has the tent?"), ("m-w2", "s-bimal", 3, 21, "The big one is in my car"), ("m-w4", "s-bimal", 3, 29, "And the poles, somewhere under the seats"), ("m-w5", "s-bimal", 3, 41, "Found them"), ("m-w6", "s-bimal", 3, 44, "\u{200e}Voice call, \u{200e}41 sec"), ("m-w3", "s-chitra", 3, 50, "I'll bring the stove and tea"), ("m-w7", "s-chitra", 3, 52, "[attachment: PHOTO-2026-11-20-03-52-00.jpg]"), ("m-w8", "s-chitra", 3, 55, "Screenshot 2026-11-20 at 03.55.10.png"), ("m-w10", "s-bimal", 4, 2, "The view from the top"), ]; for (id, seat, h, m, body) in trip { message(&handle, id, WEEKEND, false, "whatsapp", "imported", body, &day(20, h, m), 0, Some(seat)); } for (id, name, mime) in [("m-w7", "00000041-PHOTO-2026-11-20-03-52-00.jpg", "image/jpeg"), ("m-w8", "00000042-Screenshot 2026-11-20 at 03.55.10.png", "image/png"), ("m-w10", "00000043-PHOTO-2026-11-20-04-02-00.jpg", "image/jpeg")] { let media = json!([{ "key": format!("w/messages/{WEEKEND}/{id}.jpg"), "contentType": mime, "name": name, "width": 1200, "height": 900 }]); sql(&handle, "UPDATE cotton_msg_messages SET media = ? WHERE id = ?", &[t(&media.to_string()), t(id)]); } // An imported voice note (the voice player): drawn played, under Bimal's name, with no waveform (the thin track). message(&handle, "m-w11", WEEKEND, false, "whatsapp", "imported", "", &day(20, 4, 3), 0, Some("s-bimal")); let note = json!([{ "key": format!("w/messages/{WEEKEND}/m-w11.opus"), "contentType": "audio/ogg", "name": "00000044-AUDIO-2026-11-20-04-03-00.opus", "kind": "voice", "durationMs": 31_000 }]); sql(&handle, "UPDATE cotton_msg_messages SET media = ? WHERE id = 'm-w11'", &[t(¬e.to_string())]); // Bimal's Claude in the trip (CONTRACT "An agent in a chat"): its words under the agent mark, "Bimal Rao's agent". message(&handle, "m-w12", WEEKEND, false, "whatsapp", "imported", "Packing list for Saturday: the tent and poles with Bimal, the stove and tea with Chitra.", &day(20, 4, 5), 0, Some("s-bimal")); let agent = json!({ "cotton": { "agent": { "id": "agent-bimal", "name": "Claude" } } }); sql(&handle, "UPDATE cotton_msg_messages SET meta = ? WHERE id = 'm-w12'", &[t(&agent.to_string())]); // m-w7's file never reached the store: it answered 404 when last asked. handle.client().absent_media().note(&format!("w/messages/{WEEKEND}/m-w7.jpg"), 404, handle.client().now().timestamp_millis()); let ravi = "11111111-1111-4111-8111-0000000000d1"; contact(&handle, "c-ravi", "Ravi Menon", "15550100002"); thread(&handle, ravi, "dm", Some("cotton:+15550100002"), None, Some("c-ravi"), &day(19, 12, 0)); message(&handle, "m-r1", ravi, false, "cotton", "live", "The plants are watered", &day(19, 11, 50), 1, None); message(&handle, "m-r2", ravi, true, "cotton", "live", "Thank you, you're a star", &day(19, 12, 0), 2, None); sql(&handle, "UPDATE cotton_msg_threads SET pinned_at = ?, read_seq = 2 WHERE id = ?", &[t(&day(19, 12, 1)), t(ravi)]); // The voice player (23 Nov 2026): invented voice messages of known lengths in Ravi's chat. His 0:42 with its // words and his 0:02 are not played yet; the person's own 0:09; his 2:30 can't be fetched now (Chat Dev's seed // refuses its file `file_offline`); his 0:18 is gone for good (the store answered 404). Their files are the // seed's own invented tones of the same lengths. let voices: [(&str, bool, u64, usize, u32, Option<&str>); 5] = [ ("m-r3", false, 42_000, 64, 5, Some("Found the photos from Goa, sending them tonight")), ("m-r4", true, 9_000, 64, 6, Some("On my way, give me ten minutes")), ("m-r5", false, 2_000, 9, 7, None), ("m-r6", false, 150_000, 64, 8, None), ("m-r7", false, 18_000, 64, 9, None), ]; for (n, (id, out, ms, samples, minute, words)) in voices.iter().enumerate() { message(&handle, id, ravi, *out, "cotton", "live", "", &day(19, 12, *minute), n as i64 + 3, None); // A made-up recording's peaks, rising and falling as words do (0..255, as the sealed message carries them). let wave: Vec = (0..*samples).map(|i| (((i as f64 * (0.7 + n as f64 * 0.11)).sin().abs() * 0.6 + 0.25 + ((i * 7 + n * 3) % 5) as f64 * 0.03) * 200.0).round() as u8).collect(); let mut meta = json!({ "cotton": { "written_at": day(19, 12, *minute), "pictures": [{ "file": format!("f-{id}"), "key": "A".repeat(43), "sha256": "00", "mime": "audio/mp4", "bytes": ms * 8, "kind": "voice", "duration_ms": ms, "waveform": wave }] } }); if let Some(words) = words { meta["cotton"]["transcript"] = json!(words); } sql(&handle, "UPDATE cotton_msg_messages SET meta = ? WHERE id = ?", &[t(&meta.to_string()), t(id)]); } handle.client().absent_media().note("f-m-r7", 404, handle.client().now().timestamp_millis()); sql(&handle, "UPDATE cotton_msg_threads SET last_message_at = ?, read_seq = 7 WHERE id = ?", &[t(&day(19, 12, 9)), t(ravi)]); let meera = "11111111-1111-4111-8111-0000000000e1"; contact(&handle, "c-meera", "Meera Iyer", "15550100003"); thread(&handle, meera, "dm", Some("cotton:+15550100003"), None, Some("c-meera"), &day(18, 8, 0)); message(&handle, "m-e1", meera, false, "cotton", "live", "नमस्ते! कल मिलते हैं।", &day(18, 8, 0), 1, None); sql(&handle, "UPDATE cotton_msg_threads SET muted_until = '2099-01-01T00:00:00.000Z', read_seq = 0 WHERE id = ?", &[t(meera)]); thread(&handle, OLD_SMS, "dm", Some("+15550100009"), Some("Old number"), None, &day(1, 9, 0)); message(&handle, "m-s1", OLD_SMS, false, "sms", "imported", "Your parcel is here", &day(1, 9, 0), 0, None); sql(&handle, "UPDATE cotton_msg_threads SET archived = 1 WHERE id = ?", &[t(OLD_SMS)]); // Mail (MAIL.md): Kavi's invented mailbox. Asha is in People with her email and her chat's number, so her // mail and Kavi's to her stand in her chat by time; Nila is in People with no chat here (the Mail tab's // People); a shop, a paper, a bank and a stranger are machines. Asha's plan is kept by Cotton (a key: Chat // Dev's seed opens an invented PDF of it); her photo only the mailbox has. let ws = workspace(&handle); const KAVI: &str = "kavi@invented.example"; for (pid, name, email, phone) in [("p-asha", "Asha Verma", "asha.verma@invented.example", Some("+15550100001")), ("p-nila", "Nila Shah", "nila.shah@invented.example", None)] { sql(&handle, "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES (?, ?, ?, '2026-01-01', '2026-01-01')", &[t(pid), t(&ws), t(name)]); sql(&handle, "INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, created_at, updated_at) VALUES (?, ?, ?, 'email', ?, ?, 'manual', '2026-01-01', '2026-01-01')", &[t(&format!("{pid}-email")), t(&ws), t(pid), t(email), t(email)]); if let Some(phone) = phone { sql(&handle, "INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, created_at, updated_at) VALUES (?, ?, ?, 'phone', ?, ?, 'manual', '2026-01-01', '2026-01-01')", &[t(&format!("{pid}-phone")), t(&ws), t(pid), t(phone), t(phone)]); } } let email = |id: &str, thread: &str, from: (&str, &str), to: (&str, &str), subject: &str, body: &str, at: &str, unread: bool, attachments: Value| { sql( &handle, "INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, first_at, last_at, email_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?) ON CONFLICT (id) DO UPDATE SET last_at = max(last_at, excluded.last_at), email_count = email_count + 1", &[t(thread), t(&ws), t(&format!("key-{thread}")), t(subject), t(at), t(at), t(at), t(at)], ); sql( &handle, "INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, subject, from_email, from_name, recipients, sent_at, body, snippet, attachments, unread, account, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", &[t(id), t(&ws), t(thread), t(&format!("x-{id}")), t(subject), t(from.0), t(from.1), t(&json!([{ "email": to.0, "name": to.1, "kind": "to" }]).to_string()), t(at), t(body), t(body), t(&attachments.to_string()), SqlValue::Integer(unread as i64), t(KAVI), t(at)], ); }; let asha_mail = ("asha.verma@invented.example", "Asha Verma"); let kavi = (KAVI, "Kavi Rao"); email("e-lake-1", "et-lake", asha_mail, kavi, "Saturday at the lake", "Here is the plan for Saturday: the boat at ten, lunch by the water, and back before dark. The map is attached, and a photo of the jetty so you know where to find us.", &day(19, 9, 0), true, json!([{ "name": "Lake plan.pdf", "mime": "application/pdf", "size": 186_000, "key": "dev-mail/lake-plan" }, { "name": "Jetty.jpg", "mime": "image/jpeg", "size": 1_240_000 }])); email("e-lake-2", "et-lake", kavi, asha_mail, "Re: Saturday at the lake", "Perfect. I'll bring the map you lent me, and the tea.", &day(19, 10, 0), false, json!([])); email("e-shop", "et-shop", ("receipts@cornerbooks.invented", "The Corner Bookshop"), kavi, "Your receipt", "Order 2041: two books, ₹899 paid. Thank you for shopping with us.", &day(20, 6, 30), true, json!([{ "name": "Receipt 2041.pdf", "mime": "application/pdf", "size": 42_000 }])); email("e-news", "et-news", ("news@hillpaper.invented", "The Hill Paper"), kavi, "This week in the hills", "Five stories: the new trail above the lake, the winter market, and a recipe for ginger tea.", &day(20, 2, 0), false, json!([])); email("e-fair", "et-fair", ("dev.patel@elsewhere.invented", "Dev Patel"), kavi, "Photos from the craft fair", "We met at the craft fair on Sunday. Here are the photos I promised.", &day(19, 15, 0), true, json!([])); email("e-nila-1", "et-nila", ("nila.shah@invented.example", "Nila Shah"), kavi, "Book club in December", "Shall we read the one about the lighthouse next? I can host.", &day(18, 12, 0), false, json!([])); email("e-nila-2", "et-nila", kavi, ("nila.shah@invented.example", "Nila Shah"), "Re: Book club in December", "Yes, let's. I'll bring the biscuits.", &day(18, 13, 0), false, json!([])); email("e-bank", "et-bank", ("alerts@bank.invented", "Invented Bank"), kavi, "Your statement is ready", "Your November statement is ready to read in the app.", &day(17, 4, 0), false, json!([])); // A shop's offer, for the Promotions chip (the core's rule reads its offer subject). email("e-sale", "et-sale", ("offers@outfitters.invented", "Invented Outfitters"), kavi, "Winter sale: 30% off", "Code WINTER30. Unsubscribe any time.", &day(16, 8, 0), false, json!([])); // Sites (SITES.md): an invented club's sign-in mail, its link to the invented site `scripts/invented-site.py` // serves on the Mac, for the walk from Mail into a session. email("e-club", "et-club", ("hello@club.invented", "Invented Club"), kavi, "Sign in to Invented Club", "Tap to sign in to Invented Club:\n\nhttp://localhost:8765/in?t=walk-link\n\nNothing to type: the link signs you in.", &day(20, 7, 0), true, json!([])); // WhatsApp from Comms (CONTRACT.md): Tara's chat came from WhatsApp and Cotton knows her number. // On a Comms copy (one that draws the outbox, and has never held mail) it answers a writing box of words only; // three texts stand on their way through the Mac, one in each state, and the failed one is tried again. The list // draws her chat from the copy above, as every other. const TARA: &str = "11111111-1111-4111-8111-0000000000f1"; let wa_dir = tempfile::tempdir().unwrap(); let wa = super::mail::tests::comms(&wa_dir, cotton_core::flavor::Flavor::Real); for h in [&handle, &wa] { contact(h, "c-tara", "Tara Joshi", "15550100004"); thread(h, TARA, "dm", None, None, Some("c-tara"), &day(17, 6, 5)); message(h, "m-t1", TARA, false, "whatsapp", "imported", "Are you taking the early train?", &day(17, 6, 0), 0, None); message(h, "m-t2", TARA, true, "whatsapp", "imported", "Yes, the 7:40", &day(17, 6, 5), 0, None); } whatsapp_warm::link(&wa); let no_mail = answer(&wa, "chat.list", json!({ "filter": "all" })); let send = |words: &str| answer(&wa, "chat.act", json!({ "act": "send", "thread": TARA, "text": words })); let row_of = |sent: &Value| sent["message"].as_str().expect("an outbox id").trim_start_matches("outbox:").to_string(); let mark = |id: &str, patch: Value| { let ask = json!({ "table": super::whatsapp_send::OUTBOX, "id": id, "patch": patch }); crate::phone::cotton_chat::write(&wa.client(), "fixture.mark", |ctx| { cotton_tools::mcp::handlers::tables::update_produced_record(ctx, ask.as_object().unwrap()).map_err(|e| e.to_string())?; Ok(Value::Null) }) .expect("marked as the Mac marks it"); }; let sent = send("On the platform now"); let waiting = row_of(&sent); let sending = row_of(&send("Which carriage are you in?")); let failed = row_of(&send("Saving you a seat")); mark(&sending, json!({ "status": "sending" })); mark(&failed, json!({ "status": "failed", "error": "WhatsApp did not take it: the Mac's link is not signed in" })); let refused = over(&wa.client(), "chat.act", &json!({ "act": "retry", "thread": TARA, "message": format!("outbox:{waiting}") })).expect_err("a waiting text is not sent again"); let media = whatsapp_warm::media(&wa, TARA, &mark); let words_only = whatsapp_warm::words_only(&wa, TARA); let tara_page = answer(&wa, "chat.thread", json!({ "thread": TARA })); let retried = answer(&wa, "chat.act", json!({ "act": "retry", "thread": TARA, "message": format!("outbox:{failed}") })); let picture_retried = whatsapp_warm::retried(&wa, TARA, &media); let route = whatsapp_warm::route(&wa, &mark); // Editing and deleting his own message (FEEDBACK-3): before the timers, so no timer's line stands among them. let changes = whatsapp_warm::changes(&wa, TARA, &mark); // Deleted for everyone in WhatsApp (FEEDBACK-3, CONTRACT.md "Deleted for everyone in WhatsApp"): the Book club, a // WhatsApp group from the Mac's link. Esha's picture with its words, which Farid's reply quotes, Esha deletes for // everyone; the person deletes his own from WhatsApp; Divya's newest, the chat's last line, she deletes too. The // link's revokes land through the changes pass the Mac runs, and the sweep (chat.list) erases each one with its // file, leaving its marker. Then what search answers for each deleted message's words. const BOOK: &str = "11111111-1111-4111-8111-0000000000g1"; thread(&handle, BOOK, "group", Some("whatsapp:120363000000000001@g.us"), Some("Book club"), None, &day(17, 21, 10)); seat(&handle, "s-book-me", BOOK, "Me", true); seat(&handle, "s-divya", BOOK, "Divya Kapoor", false); seat(&handle, "s-esha", BOOK, "Esha Pillai", false); seat(&handle, "s-farid", BOOK, "Farid Khan", false); let club: [(&str, bool, Option<&str>, u32, &str); 6] = [ ("m-g1", false, Some("s-divya"), 0, "Next month: the lighthouse book?"), ("m-g2", false, Some("s-esha"), 2, "My copy, with the coffee ring on page nine"), ("m-g3", false, Some("s-farid"), 4, "Ha, mine has sand in it"), ("m-g4", true, None, 6, "Thursday works for me"), ("m-g5", true, None, 8, "I'll bring the walnut cake"), ("m-g6", false, Some("s-divya"), 10, "Wrong chat, sorry: the plumber comes at noon"), ]; for (id, out, seat, m, body) in club { message(&handle, id, BOOK, out, "whatsapp", "imported", body, &day(17, 21, m), 0, seat); } let book_picture = json!([{ "key": format!("{ws}/messages/{BOOK}/m-g2.jpg"), "contentType": "image/jpeg", "name": "00000051-PHOTO-2026-11-17-21-02-00.jpg", "width": 1200, "height": 900 }]); sql(&handle, "UPDATE cotton_msg_messages SET media = ? WHERE id = 'm-g2'", &[t(&book_picture.to_string())]); sql(&handle, "UPDATE cotton_msg_messages SET reply_to_id = 'm-g2', reply_to_external_id = 'x-m-g2' WHERE id = 'm-g3'", &[]); // A reply and reactions from WhatsApp as the link lands them (CONTRACT.md "Replies and reactions", "Today"): his // answer quotes Divya's question; Farid laughs at it and he loves it; Divya likes his answer; Farid's surprise at // Esha's picture goes with it. sql(&handle, "UPDATE cotton_msg_messages SET reply_to_id = 'm-g1', reply_to_external_id = 'x-m-g1' WHERE id = 'm-g4'", &[]); for (id, message, actor, emoji) in [("r-g1", "m-g1", "15550100013", "😂"), ("r-g2", "m-g1", cotton_core::constants::REACTION_ACTOR_SELF, "❤️"), ("r-g3", "m-g4", "15550100011", "👍"), ("r-g4", "m-g2", "15550100013", "😮")] { sql(&handle, "INSERT INTO cotton_msg_reactions (id, workspace_id, thread_id, message_id, actor, emoji, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)", &[t(id), t(&ws), t(BOOK), t(message), t(actor), t(emoji), t(&day(17, 21, 11))]); } sql(&handle, "UPDATE cotton_msg_threads SET last_message_preview = ?, read_seq = 0 WHERE id = ?", &[t("Wrong chat, sorry: the plumber comes at noon"), t(BOOK)]); // Polls shown (FEEDBACK-3, CONTRACT.md "Polls shown"): Divya's poll from WhatsApp, one choice each, as the Mac's // link lands it (meta.poll with its voters); Divya and the person chose the lighthouse, Esha the bees. Farid's // vote comes later (below, `vote`), as the link's change lands it. for (id, name, phone) in [("c-divya", "Divya Kapoor", "15550100011"), ("c-esha", "Esha Pillai", "15550100012"), ("c-farid", "Farid Khan", "15550100013")] { contact(&handle, id, name, phone); } message(&handle, "m-g7", BOOK, false, "whatsapp", "imported", "Which book next?", &day(17, 21, 1), 0, Some("s-divya")); let poll = json!({ "poll": { "question": "Which book next?", "options": [{ "text": "The lighthouse one", "votes": 2 }, { "text": "The one about bees", "votes": 1 }, { "text": "Short stories, for a change", "votes": 0 }], "selectable": 1, "voters": [{ "who": "15550100011", "options": [0], "at": day(17, 21, 1) }, { "who": "15550100012", "options": [1], "at": day(17, 21, 2) }, { "who": "me", "options": [0], "at": day(17, 21, 3) }], }, "source": { "messageType": "poll" } }); sql(&handle, "UPDATE cotton_msg_messages SET meta = ? WHERE id = 'm-g7'", &[t(&poll.to_string())]); // The Book club as it stood before the deletes, for Chat Dev's -chat-warm-revoke: the open chat answered again // after them must lose those messages where they stood. let before_revokes = answer(&handle, "chat.thread", json!({ "thread": BOOK })); let deleted_at = day(17, 21, 12); let revokes: Vec = ["x-m-g2", "x-m-g5", "x-m-g6"].iter().map(|id| cotton_core::import::messages_engine::MessageChange::Revoke { external_id: id.to_string(), at: deleted_at.clone() }).collect(); handle .client() .import_rows("fixture.revoke", &["cotton_msg_threads", "cotton_msg_messages", "cotton_msg_thread_participants", "cotton_msg_contacts", "cotton_msg_reactions", "cotton_workspaces"], &mut |seams| { let report = cotton_client::messages_import::apply_message_changes(&seams.replica.driver, &ws, "whatsapp", &revokes, seams.clock, seams.ids).map_err(|e| e.to_string())?; assert_eq!(report.revoked, 3, "the three deletes land"); Ok(json!({ "revoked": report.revoked })) }) .expect("the link's revokes land"); answer(&handle, "chat.list", json!({ "filter": "all" })); for gone in ["m-g2", "m-g5", "m-g6"] { let held = crate::phone::cotton_chat::read(&handle.client(), "fixture.held", |ctx| Ok(json!(crate::phone::cotton_chat::exists(ctx, "cotton_msg_messages", gone)?))).unwrap(); assert_eq!(held, json!(false), "{gone} is erased"); } let mut searches = serde_json::Map::new(); for words in ["coffee ring", "walnut cake", "plumber", "lighthouse"] { searches.insert(words.to_string(), answer(&handle, "chat.list", json!({ "filter": "all", "search": words }))); } let mut threads = serde_json::Map::new(); for id in [ASHA, WEEKEND, ravi, meera, BOOK] { threads.insert(id.to_string(), answer(&handle, "chat.thread", json!({ "thread": id }))); } threads.insert(TARA.to_string(), tara_page); // Farid's vote arrives (short stories) through the changes pass the Mac runs: the poll's bubble as the open chat is // then answered, for Chat Dev's -chat-warm-vote. let farid = vec![cotton_core::import::messages_engine::MessageChange::Vote { external_id: "x-m-g7".into(), voter: "15550100013".into(), options: vec![2], at: day(17, 21, 20) }]; handle .client() .import_rows("fixture.vote", &["cotton_msg_threads", "cotton_msg_messages", "cotton_msg_thread_participants", "cotton_msg_contacts", "cotton_msg_reactions", "cotton_workspaces"], &mut |seams| { let report = cotton_client::messages_import::apply_message_changes(&seams.replica.driver, &ws, "whatsapp", &farid, seams.clock, seams.ids).map_err(|e| e.to_string())?; Ok(json!({ "missing": report.missing })) }) .expect("Farid's vote lands"); let voted = answer(&handle, "chat.thread", json!({ "thread": BOOK })); let voted = voted["items"].as_array().unwrap().iter().find(|i| i["message"] == "m-g7").cloned().expect("the poll"); assert_eq!(voted["poll"]["said"], "4 votes", "Farid's vote counted: {voted}"); let mut fixture = json!({ "list": answer(&handle, "chat.list", json!({ "filter": "all" })), "unread": answer(&handle, "chat.list", json!({ "filter": "unread" })), "groups": answer(&handle, "chat.list", json!({ "filter": "groups" })), "archived": answer(&handle, "chat.list", json!({ "filter": "archived" })), "threads": threads, "whatsapp": { "send": sent, "retry": retried, "refused": { "code": refused.code, "message": refused.message }, "noMail": no_mail }, // Search over the invented chats, by words: chat.list's answer, so a deleted message's words are seen to find nothing. "searches": searches, // Polls shown: the Book club's poll once Farid's vote has come (the open chat answered again). "votes": { "thread": BOOK, "bubble": voted }, // Deleted while he looks: the Book club before the deletes (its page after them is under threads). "revoke": { "thread": BOOK, "before": before_revokes }, // The safety number's screen, between invented phones on a relay (chat_safety_tests::warm_fixture). "safety": crate::phone::chat_group::tests::safety::warm_fixture(), // Storage by chat (item 4, 23 Nov 2026): invented files of known sizes, before and after each chat is freed. "storage": storage::warm_fixture(), // The voice player (23 Nov 2026): which of Ravi's notes the seed cannot fetch and which is gone, the core's // refusals of their files in its words, and the voice speed as chat.settings answers it. "voice": { "offline": ["m-r6"], "refusals": { "file_offline": cotton_core::messages::app::list::say(&cotton_core::messages::app::list::lines(), "app.notice.file_offline", &[]), "file_gone": cotton_core::messages::app::list::say(&cotton_core::messages::app::list::lines(), "app.notice.file_gone", &[]), }, "settings": answer(&handle, "chat.settings", json!({})), }, }); // Voting on Tara's poll (FEEDBACK-3, CONTRACT.md "A vote"): before the timers, so no timer's line stands among them. let vote = whatsapp_warm::vote(&wa, TARA, (&handle, BOOK, "m-g7"), &mark); // Disappearing messages (CONTRACT.md, B.1): in each chat whose page answers a timer it can set, what each length // chosen answers, and what the chat then answers: its timer, its header and the line it gained (with the day it // stands under, once). Asked last, as each act writes a line; Off after each length, so each is chosen from Off. let mut timers = serde_json::Map::new(); for (h, id) in [(&handle, ASHA), (&handle, WEEKEND), (&wa, TARA)] { if let Some(lengths) = whatsapp_warm::timer_lengths(h, id) { timers.insert(id.to_string(), lengths); } } fixture["timers"] = Value::Object(timers); let documents = whatsapp_warm::documents(&wa, TARA); let polls = whatsapp_warm::polls(&wa, TARA); // Three pictures with words to WhatsApp, one grid before and after they land (FEEDBACK-4 B3): after the documents. let grid = whatsapp_warm::grid(&wa, TARA, &mark); whatsapp_warm::lay(&mut fixture, media, picture_retried, words_only, documents, route); fixture["whatsapp"]["vote"] = vote; fixture["whatsapp"]["poll"] = polls; fixture["whatsapp"]["changes"] = changes; fixture["whatsapp"]["grid"] = grid; // Replying (23 Nov 2026): for each message of these chats that offers Reply, the core's // writing box with its strip, and the quote the reply's own bubble carries once sent. Sent after every answer // above was read, so no chat above shows them. let mut replies = serde_json::Map::new(); for id in [ASHA, ravi, meera] { let mut quotes = serde_json::Map::new(); let page = fixture["threads"][id].clone(); for bubble in page["items"].as_array().unwrap().iter().filter(|i| i["item"] == "bubble" && i["actions"].as_array().is_some_and(|a| a.contains(&json!("reply")))) { let message = bubble["message"].as_str().unwrap(); let composer = answer(&handle, "chat.compose", json!({ "thread": id, "replyTo": message })); let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": id, "text": "Yes", "replyTo": message })); assert!(sent["bubble"]["reply"].is_object(), "the reply to {message} quotes it: {sent}"); quotes.insert(message.to_string(), json!({ "composer": composer, "quote": sent["bubble"]["reply"] })); } replies.insert(id.to_string(), Value::Object(quotes)); } fixture["replies"] = Value::Object(replies); // Link previews (FEEDBACK-4 B4, 24 Nov 2026): asked last, as it sends. fixture["linkPreview"] = link_preview_warm(&handle); // A new account (the reviewer pass, 24 Nov 2026): Cotton's own Downloads chat alone, and the words saying how to // begin under it. let fresh = super::downloads::tests::fresh_list(); assert_eq!(fresh["words"]["empty"], "No chats yet. Tap the pen to write to someone.", "{fresh}"); fixture["fresh"] = fresh; // A document and a link to open (Comms 28 fixes 2), in a chat of their own on a phone of their own, so no other // list or chat changes: Kabir's PDF from WhatsApp, kept by the Mac, and his words with a web link. let (_docs_dir, docs) = phone(); contact(&docs, "c-kabir", "Kabir Sen", "15550100009"); thread(&docs, KABIR, "dm", Some("whatsapp:+15550100009"), None, Some("c-kabir"), &day(21, 10, 6)); message(&docs, "m-k1", KABIR, false, "whatsapp", "imported", "", &day(21, 10, 2), 1, None); let pdf = json!([{ "key": format!("w/messages/{KABIR}/m-k1.pdf"), "contentType": "application/pdf", "name": "Garden plan.pdf", "sizeBytes": 48_213 }]); sql(&docs, "UPDATE cotton_msg_messages SET media = ? WHERE id = 'm-k1'", &[t(&pdf.to_string())]); message(&docs, "m-k2", KABIR, false, "whatsapp", "imported", "The seeds I meant are on https://example.com/seeds", &day(21, 10, 6), 2, None); let page = answer(&docs, "chat.thread", json!({ "thread": KABIR })); let kinds: Vec<&str> = page["items"].as_array().unwrap().iter().filter(|item| item["item"] == "bubble").filter_map(|item| item["kind"].as_str()).collect(); assert!(kinds.contains(&"file"), "Kabir's PDF is a document to open: {kinds:?}"); fixture["threads"][KABIR] = page; // His row as the core's read answers it, for a chat opened that stands in no list. let read = answer(&docs, "chat.act", json!({ "act": "read", "thread": KABIR })); assert!(read["row"].is_object(), "the read answers Kabir's row: {read}"); fixture["rows"] = json!({ KABIR: read["row"] }); // The invented PDF's words, which Comms Dev draws into the file it opens. fixture["documents"] = json!({ "m-k1": { "title": "Garden plan", "lines": ["Bed one: tomatoes and basil", "Bed two: beans along the fence", "Bed three: marigolds at the corners"] } }); let path =cotton_store::manifest_dir().join("../../apps/cotton/Sources/CottonUI/Resources/Fixtures/chat-warm.json"); std::fs::write(&path, serde_json::to_string_pretty(&fixture).unwrap() + "\n").unwrap_or_else(|error| panic!("{} writes: {error}", path.display())); } #[path = "chat_search_tests.rs"] mod search; #[path = "chat_export_tests.rs"] mod export; #[path = "chat_ahead_tests.rs"] mod ahead; #[path = "chat_storage_tests.rs"] pub(super) mod storage; #[path = "chat_voice_tests.rs"] mod voice; #[path = "chat_whatsapp_warm_tests.rs"] mod whatsapp_warm; /// The person's own media as the object serves it: fixed bytes for any key, and which keys were asked. #[derive(Debug, Default)] struct OwnMedia(std::sync::Mutex>); impl crate::phone::media::MediaFetch for OwnMedia { fn fetch_to(&self, _database: &str, key: &str, dest: &std::path::Path) -> Result<(), crate::phone::media::NotFetched> { self.0.lock().unwrap().push(key.to_string()); std::fs::write(dest, b"an invented picture's bytes").map_err(|error| error.to_string().into()) } } // RULE (iPhone lane, 21 Nov 2026): an imported message's picture (a WhatsApp picture the Mac uploaded into the person's // own media) opens: chat.picture and chat.file count a message's attachments as its bubble does, an import's first, and // open an imported one through the person's own media, not the Cotton chat store, where it never was. #[test] fn an_imported_pictures_file_opens_from_the_persons_own_media() { let (dir, handle) = phone(); imported_group(&handle); let key = format!("w/messages/{WEEKEND}/00000012-PHOTO-2026-11-03-10-25-00.jpg"); let fetched = std::sync::Arc::new(OwnMedia::default()); handle.client().set_media_fetch(Some(fetched.clone())); let out = dir.path().join("out"); let opened = answer(&handle, "chat.picture", json!({ "message": "m-g7", "index": 0, "dir": out.to_string_lossy() })); assert_eq!(std::fs::read(opened["path"].as_str().expect("a path")).expect("the file"), b"an invented picture's bytes", "{opened}"); assert_eq!(*fetched.0.lock().unwrap(), [key.clone()], "asked of the person's own media, by its key"); let file = answer(&handle, "chat.file", json!({ "message": "m-g7", "index": 0, "dir": out.to_string_lossy() })); assert_eq!(std::fs::read(file["path"].as_str().expect("a path")).expect("the file"), b"an invented picture's bytes", "{file}"); assert_eq!(fetched.0.lock().unwrap().len(), 1, "here now: not fetched again"); assert_eq!(refused(&handle, "chat.picture", json!({ "message": "m-g7", "index": 5, "dir": out.to_string_lossy() })), "not_found"); } /// A tiny JPEG's base64, as a phone's card picture is (it only has to look like one). fn jpeg() -> String { use base64::Engine as _; base64::engine::general_purpose::STANDARD.encode([0xFF, 0xD8, 0xFF, 0xE0, 0, 16, b'J', b'F', b'I', b'F', 0, 0xFF, 0xD9]) } /// A small real JPEG (96 x 64, 1,388 base64 characters): a sent card's picture in Chat Dev's seed. const HILL_THUMB: &str = "/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAYKADAAQAAAABAAAAQAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgAQABgAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMACQkJCQkJEAkJEBYQEBAWHhYWFhYeJh4eHh4eJi4mJiYmJiYuLi4uLi4uLjc3Nzc3N0BAQEBASEhISEhISEhISP/bAEMBCwwMEhESHxERH0szKjNLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS//dAAQABv/aAAwDAQACEQMRAD8AyMU7FPApQK9Fs8uLGgU4CnAU7FZNm0WMxTgKdinYrJs3ixoFLin4p2KybNosZinYp2KdismzaLG4pQKfilxWTZvFn//QogUoFPxTsV2tnjRYwCnAU7FOxWTZvFjcUuKfilxWTZtFjcU7FOxTgKybNosYBTsU8ClArJs2ixuKcBTgKdismzeLP//RhxTsU7FOxXS2eDFjcUuKfilArJs3ixuKdinAU4CsmzaLGAU7FPApQKybNosaBTgKdinYrNs3ixmKdinYp2KybNos/9J2KdingUoFatnzsWNAp2KcBTgKybNosZinAU4CnYrJs2ixuKXFPxTsVm2bRYzFOxTsU7FZNm8WNxS4p4FKBWTZtFn/2Q=="; /// Link previews in Asha's chat for Chat Dev's seed (chat CONTRACT.md "Link previews"): the writing box offering an /// invented link's card, the invented pages the seed serves on the phone (never the internet) and the cards the core /// reads from them, a link that moves on to his own network, a link to his own network offering none, the message /// sent with its card and picture, and the setting on and off. fn link_preview_warm(handle: &CottonHandle) -> Value { let url = "https://walks.example/hill-loop"; let moved = "https://walks.example/moved"; let words = format!("The loop we walked {url}"); let moved_words = format!("And the other one {moved}"); let inside_words = "The printer page http://192.168.1.20/status"; // Where the moved link goes: an address on his own network, never asked. let inside_url = "http://10.0.0.8/inside"; let page = r#"Walks"#; // What stands behind the move, were it ever followed: a page of his own network, with a title of its own. let inside = r#"Printer status"#; let settings_on = answer(handle, "chat.settings", json!({})); assert_eq!(settings_on["linkPreviews"], true, "on unless turned off"); let offered = answer(handle, "chat.compose", json!({ "thread": ASHA, "text": words })); assert_eq!(offered["preview"]["url"], url, "{offered}"); let moved_offered = answer(handle, "chat.compose", json!({ "thread": ASHA, "text": moved_words })); assert_eq!(moved_offered["preview"]["url"], moved, "{moved_offered}"); let inside_offered = answer(handle, "chat.compose", json!({ "thread": ASHA, "text": inside_words })); assert!(inside_offered["preview"].is_null(), "never his own network: {inside_offered}"); let card = answer(handle, "chat.linkCard", json!({ "thread": ASHA, "url": url, "page": page })); assert_eq!(card["image"], "https://walks.example/hill-loop.jpg", "{card}"); let inside_card = answer(handle, "chat.linkCard", json!({ "thread": ASHA, "url": moved, "page": inside })); let sent = answer(handle, "chat.act", json!({ "act": "send", "thread": ASHA, "text": words, "preview": { "url": card["url"], "site": card["site"], "title": card["title"], "description": card["description"], "thumb": HILL_THUMB } })); assert_eq!(sent["bubble"]["link"]["thumb"], HILL_THUMB, "the card goes with its picture: {sent}"); let id = sent["message"].as_str().unwrap().to_string(); let row = crate::phone::cotton_chat::read(&handle.client(), "fixture.meta", |ctx| { Ok(crate::phone::cotton_chat::one(ctx, "SELECT meta FROM cotton_msg_messages WHERE id = ?", &[t(&id)])?.map(|r| r["meta"].clone()).unwrap_or(Value::Null)) }) .unwrap(); let kept: Value = match row { Value::String(text) => serde_json::from_str(&text).unwrap(), other => other, }; assert_eq!(kept["preview"]["thumb"], HILL_THUMB, "kept as meta.preview: {kept}"); let settings_off = answer(handle, "chat.settings", json!({ "linkPreviews": false })); let off_offered = answer(handle, "chat.compose", json!({ "thread": ASHA, "text": words })); assert!(off_offered["preview"].is_null(), "turned off, none offered"); answer(handle, "chat.settings", json!({ "linkPreviews": true })); answer(handle, "chat.compose", json!({ "thread": ASHA, "text": "" })); json!({ "thread": ASHA, "offers": [ { "words": words, "composer": offered }, { "words": moved_words, "composer": moved_offered }, { "words": inside_words, "composer": inside_offered }, ], "offOffers": [{ "words": words, "composer": off_offered }], "pages": { url: page, inside_url: inside }, "moves": { moved: inside_url }, "cards": { url: card, moved: inside_card }, "sent": sent, "meta": kept["preview"], "settings": { "on": settings_on, "off": settings_off }, }) } // RULE (owner, FEEDBACK-4 B4, 23 Nov 2026: a link sent shows no preview; fetched by the sender's own phone, never // the server, with a setting to turn it off): a link written offers its card (`composer.preview`), never one to his // own network; the page his phone fetched reads as its card (`chat.linkCard`); the card sent goes with the message // and is drawn at once, picture and all. Turned off on this phone, nothing is offered, read or kept. #[test] fn a_link_written_offers_its_card_and_the_card_goes_with_it() { let (_dir, handle) = phone(); three_chats(&handle); let words = "the route: https://example.org/walks"; assert_eq!(answer(&handle, "chat.settings", json!({}))["linkPreviews"], true, "on unless turned off"); assert_eq!(answer(&handle, "chat.compose", json!({ "thread": ASHA, "text": words }))["preview"]["url"], "https://example.org/walks"); assert!(answer(&handle, "chat.compose", json!({ "thread": ASHA, "text": "http://192.168.1.1/admin" }))["preview"].is_null(), "never his own network"); assert!(answer(&handle, "chat.compose", json!({ "thread": ASHA, "text": "no link" }))["preview"].is_null()); let card = answer(&handle, "chat.linkCard", json!({ "thread": ASHA, "url": "https://example.org/walks", "page": "Hill walks" })); assert_eq!((card["title"].as_str(), card["site"].as_str(), card["image"].as_str()), (Some("Hill walks"), Some("example.org"), Some("https://example.org/h.jpg"))); let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": ASHA, "text": words, "preview": { "url": card["url"], "site": card["site"], "title": card["title"], "thumb": jpeg() } })); let link = &sent["bubble"]["link"]; assert_eq!((link["title"].as_str(), link["site"].as_str(), link["thumb"].as_str()), (Some("Hill walks"), Some("example.org"), Some(jpeg().as_str())), "{sent}"); let elsewhere = answer(&handle, "chat.act", json!({ "act": "send", "thread": ASHA, "text": "no link", "preview": { "url": "https://example.org/walks", "title": "Hill walks" } })); assert!(elsewhere["bubble"]["link"].is_null(), "a card goes only with its link"); assert_eq!(answer(&handle, "chat.settings", json!({ "linkPreviews": false }))["linkPreviews"], false); assert_eq!(answer(&handle, "chat.settings", json!({}))["linkPreviews"], false, "kept"); assert!(answer(&handle, "chat.compose", json!({ "thread": ASHA, "text": words }))["preview"].is_null()); assert_eq!(answer(&handle, "chat.linkCard", json!({ "thread": ASHA, "url": "https://example.org/walks", "page": "Hill walks" })), json!({})); let off = answer(&handle, "chat.act", json!({ "act": "send", "thread": ASHA, "text": words, "preview": { "url": "https://example.org/walks", "title": "Hill walks" } })); assert!(off["bubble"]["link"].is_null(), "turned off, none kept"); } /// RULE (owner via the coordinator, 24 Nov 2026: "people's display pictures no longer show in chats that come through /// WhatsApp"): a WhatsApp profile picture stands wherever that person stands. Their person's picture, else their /// contact's (a WhatsApp picture where no person is linked), on the chat list's row, the conversation's header, and the /// face over a group's lines; a group's own picture on its row and header. Every key and name is invented. #[test] fn whatsapp_pictures_stand_on_the_list_the_header_and_a_groups_faces() { let (_dir, handle) = phone(); let ws = workspace(&handle); // Meena is a person with WhatsApp's picture; Ravi is a contact only, his picture on the contact. sql(&handle, "INSERT INTO cotton_people (id, workspace_id, full_name, avatar_key, created_at, updated_at) VALUES ('p-meena', ?, 'Meena Invented', 'db/people/p-meena/whatsapp/aa11.jpg', '2026-01-01', '2026-01-01')", &[t(&ws)]); contact(&handle, "c-meena", "Meena", "15550107201"); sql(&handle, "UPDATE cotton_msg_contacts SET person_id = 'p-meena' WHERE id = 'c-meena'", &[]); contact(&handle, "c-ravi", "Ravi", "15550107202"); sql(&handle, "UPDATE cotton_msg_contacts SET avatar_key = 'db/messages/whatsapp/contacts/c-ravi/bb22.jpg' WHERE id = 'c-ravi'", &[]); const MEENA: &str = "11111111-1111-4111-8111-0000000000d1"; const RAVI: &str = "11111111-1111-4111-8111-0000000000d2"; const TRIP: &str = "11111111-1111-4111-8111-0000000000d3"; thread(&handle, MEENA, "dm", Some("15550107201@s.whatsapp.net"), None, Some("c-meena"), &iso(3)); thread(&handle, RAVI, "dm", Some("15550107202@s.whatsapp.net"), None, Some("c-ravi"), &iso(2)); thread(&handle, TRIP, "group", Some("120363000000000001@g.us"), Some("Lake trip"), None, &iso(1)); sql(&handle, "UPDATE cotton_msg_threads SET photo_key = ? WHERE id = ?", &[t(&format!("db/messages/{TRIP}/whatsapp/cc33.jpg")), t(TRIP)]); seat(&handle, "s-meena", TRIP, "Meena", false); sql(&handle, "UPDATE cotton_msg_thread_participants SET contact_id = 'c-meena' WHERE id = 's-meena'", &[]); message(&handle, "m-wm", MEENA, false, "whatsapp", "imported", "Leaving now", &iso(3), 1, None); message(&handle, "m-wr", RAVI, false, "whatsapp", "imported", "Got the tickets", &iso(2), 1, None); message(&handle, "m-wt", TRIP, false, "whatsapp", "imported", "Boat at nine", &iso(1), 1, Some("s-meena")); let list = answer(&handle, "chat.list", json!({})); let photo_of = |id: &str| list["rows"].as_array().unwrap().iter().find(|r| r["thread"] == id).map(|r| r["picture"]["photo"].clone()).unwrap_or(Value::Null); assert_eq!(photo_of(MEENA), json!("db/people/p-meena/whatsapp/aa11.jpg"), "her person's picture: {list}"); assert_eq!(photo_of(RAVI), json!("db/messages/whatsapp/contacts/c-ravi/bb22.jpg"), "his contact's picture"); assert_eq!(photo_of(TRIP), json!(format!("db/messages/{TRIP}/whatsapp/cc33.jpg")), "the group's picture"); let header = answer(&handle, "chat.thread", json!({ "thread": RAVI })); assert_eq!(header["header"]["picture"]["photo"], json!("db/messages/whatsapp/contacts/c-ravi/bb22.jpg"), "the header, and so the person page"); let group = answer(&handle, "chat.thread", json!({ "thread": TRIP })); assert_eq!(group["header"]["picture"]["photo"], json!(format!("db/messages/{TRIP}/whatsapp/cc33.jpg"))); let line = group["items"].as_array().unwrap().iter().find(|i| i["message"] == "m-wt").cloned().unwrap_or(Value::Null); assert_eq!(line["sender"]["picture"]["photo"], json!("db/people/p-meena/whatsapp/aa11.jpg"), "her face over her words: {line}"); } /// RULE (COMMS WITHOUT MAIL; sites CONTRACT row 8): a web link tapped in Comms is handed to Cotton Sites, saying it /// came from Comms, on either phone; a link that is not a web address is refused in Sites' words. #[test] fn a_link_is_handed_to_sites_saying_it_came_from_comms() { let (_dir, handle) = phone(); let link = answer(&handle, "chat.link", json!({ "url": "https://invented.example/a b?x=1" })); assert_eq!(link["url"], "https://invented.example/a b?x=1"); assert_eq!(link["sites"]["ios"]["live"], "cottonsites://open?url=https%3A%2F%2Finvented.example%2Fa+b%3Fx%3D1&from=comms", "{link}"); assert_eq!(link["sites"]["ios"]["dev"], "cottonsitesdev://open?url=https%3A%2F%2Finvented.example%2Fa+b%3Fx%3D1&from=comms"); assert_eq!(link["sites"]["android"]["package"], "com.cottondb.sites"); assert_eq!(link["sites"]["android"]["dev_package"], "com.cottondb.sites.dev"); assert_eq!(link["sites"]["android"]["extra"]["from"], "comms"); let refused = crate::methods::dispatch(&handle, "chat.link", &json!({ "url": "tel:+15550100001" })).unwrap_err(); assert_eq!((refused.code.as_str(), refused.message.as_str()), ("not_web", "That isn't a web address.")); }