//! Comms Dev's WhatsApp through the Mac, for the iPhone's seed (`write_chat_warm_fixture`, 23 Nov//! 2026): the core's own answers on a Comms copy linked to WhatsApp through an invented Mac. Writing to a number//! (FEEDBACK-2 A: "via WhatsApp", "on Cotton", the chat started for a number with none, a number WhatsApp does not//! know), pictures, videos and voice notes to WhatsApp (FEEDBACK-3), documents (FEEDBACK-3, CONTRACT "Documents and//! votes"), and Disappearing messages on a WhatsApp chat, his own copy only (FEEDBACK-2 B.2). Every name, number and line is invented; nothing is sent anywhere.usesuper::*;/// The number the invented Mac's link reads through.const LINK_ACCOUNT: &str = "15550100900@s.whatsapp.net";/// Noor is on WhatsApp only and has no chat yet; Leela is one of his Cotton connections; WhatsApp knows no Kiran.pub(super) const NOOR: &str = "+15550107101";pub(super) const LEELA: &str = "+15550107102";pub(super) const KIRAN: &str = "+15550107103";/// An invented picture's preview, as the phone makes one (a 32 by 24 JPEG of a lake under a sun).const PREVIEW: &str = "/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAGAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgAGAAgAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMABAQEBAQEBgQEBgkGBgYJDAkJCQkMDwwMDAwMDxIPDw8PDw8SEhISEhISEhUVFRUVFRkZGRkZHBwcHBwcHBwcHP/bAEMBBAUFBwcHDAcHDB0UEBQdHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHR0dHf/dAAQAAv/aAAwDAQACEQMRAD8A9M+0+9H2n3rlv7WtP+e8f/fQ/wAaP7WtP+e8f/fQ/wAa+a+pT/lZ9n9cpfzr7zu9Otn1AyYk2CPGTjPXp6elR38bWE4hZ9+VDA9ODx0/CuYsPFEenM7QTQsHABDEEcdDwQaivfEcV/N5888QOAoCsAAB+NcqwOJ9q7x90X1yn/OvvP/Q5TNGaZRXt+0kfGWH5ozTKKPaSCx//9k=";/// The copy is linked: the Mac's link brought Tara's first message in (its `meta.source`), so writing goes to WhatsApp/// through the Mac and each chat says where its words go.pub(super) fn link(wa: &CottonHandle) {let meta = json!({ "source": { "service": "WhatsApp linked device", "account": LINK_ACCOUNT, "chat": "15550100004@s.whatsapp.net" } }); sql(wa, "UPDATE cotton_msg_messages SET meta = ? WHERE id = 'm-t1'", &[t(&meta.to_string())]);}/// An invented file of `bytes` bytes.fn file(dir: &std::path::Path, name: &str, bytes: usize) -> String {let path = dir.join(name); std::fs::write(&path, (0..bytes).map(|i| (i * 7 % 251) as u8).collect::<Vec<u8>>()).unwrap(); path.to_string_lossy().to_string()}fn picture(path: &str) -> Value { json!({ "path": path, "mime": "image/jpeg", "name": "lake.jpg", "width": 1600, "height": 1200, "kind": "photo", "preview": PREVIEW })}/// What a picture, a video and a voice note sent to WhatsApp answer, and what stands in Tara's chat for the page: a/// captioned picture and a voice note waiting for the Mac, and a picture the Mac could not send. Before the page is/// read; the failed picture is tried again after (`retried`).pub(super) structMedia { dir: tempfile::TempDir, picture: Value, video: Value, voice: Value, too_large: (String, String), failed: String,}pub(super) fn media(wa: &CottonHandle, tara: &str, mark: &dynFn(&str, Value)) -> Media {let dir = tempfile::tempdir().unwrap();let send = |ask: Value| answer(wa, "chat.act", ask);let lake = file(dir.path(), "lake.jpg", 4_000);let picture_sent = send(json!({ "act": "send", "thread": tara, "text": "The lake this morning", "attachments": [picture(&lake)] }));let clip = file(dir.path(), "platform.mp4", 9_000);let video = send(json!({ "act": "send", "thread": tara, "attachments": [{ "path": clip, "mime": "video/mp4", "name": "platform.mp4", "kind": "video", "width": 1280, "height": 720, "durationMs": 12_000, "preview": PREVIEW }] }));let note = file(dir.path(), "note.m4a", 6_000);let wave: Vec<f64> = (0..48).map(|i| ((i as f64 * 0.6).sin().abs() * 0.7 + 0.2).min(1.0)).collect();let voice = send(json!({ "act": "send", "thread": tara, "attachments": [{ "path": note, "mime": "audio/mp4", "kind": "voice", "durationMs": 7_000, "waveform": wave }] }));// A picture the Mac could not send: it says why, and offers Retry.let bench = file(dir.path(), "bench.jpg", 3_000);let failed = send(json!({ "act": "send", "thread": tara, "text": "Our bench", "attachments": [picture(&bench)] }));let failed = failed["message"].as_str().expect("an outbox id").to_string(); mark(failed.trim_start_matches("outbox:"), json!({ "status": "failed", "error": "Your Mac could not open this file." }));// Refused before anything is kept or queued: a file over WhatsApp's 16 MB.let big = file(dir.path(), "big.jpg", cotton_core::chat::files::FILE_MAX + 1);let refusal = over(&wa.client(), "chat.act", &json!({ "act": "send", "thread": tara, "text": "Too big", "attachments": [picture(&big)] })).expect_err("over 16 MB is refused");Media { dir, picture: picture_sent, video, voice, too_large: (refusal.code, refusal.message), failed }}/// The failed picture tried again: waiting again, the same entry.pub(super) fn retried(wa: &CottonHandle, tara: &str, media: &Media) -> Value { answer(wa, "chat.act", json!({ "act": "retry", "thread": tara, "message": media.failed }))}/// Writing to a number on the linked copy: what `chat.start` answers for each, each chat's page, and how `chat.act/// read` answers its row (a started chat with nothing in it yet is in no list).pub(super) fn route(wa: &CottonHandle, mark: &dynFn(&str, Value)) -> Value {let ws = workspace(wa); sql( wa,"INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, on_cotton_at, created_at, updated_at) VALUES ('c-leela', ?, '15550107102', 'Leela Rao', '2026-11-01', '2026-11-01', '2026-11-01')", &[t(&ws)], );letmut starts = serde_json::Map::new();for number in [NOOR, LEELA, KIRAN] { starts.insert(number.to_string(), answer(wa, "chat.start", json!({ "number": number }))); }let thread_of = |number: &str| starts[number]["thread"].as_str().expect("a chat").to_string(); assert_eq!(starts[NOOR]["place"]["id"], "whatsapp", "{}", starts[NOOR]); assert_eq!(starts[LEELA]["place"]["id"], "cotton", "{}", starts[LEELA]);// Kiran's number has no WhatsApp: the Mac says so in its words (send::NOT_ON_WHATSAPP).let kiran = thread_of(KIRAN);let sent = answer(wa, "chat.act", json!({ "act": "send", "thread": kiran, "text": "Hello, is this Kiran?" })); mark(sent["message"].as_str().unwrap().trim_start_matches("outbox:"), json!({ "status": "failed", "error": cotton_core::messages::send::NOT_ON_WHATSAPP }));letmut threads = serde_json::Map::new();letmut rows = serde_json::Map::new();for number in [NOOR, LEELA, KIRAN] {let thread = thread_of(number); threads.insert(thread.clone(), answer(wa, "chat.thread", json!({ "thread": thread, "mail": true }))); rows.insert(thread.clone(), answer(wa, "chat.act", json!({ "act": "read", "thread": thread }))["row"].clone()); } assert_eq!(threads[&kiran]["items"].as_array().unwrap().last().unwrap()["state"], "Not sent: This number is not on WhatsApp"); json!({ "starts": starts, "threads": threads, "rows": rows, "list": answer(wa, "chat.list", json!({ "filter": "all" })) })}/// A file picked as a file, sent to WhatsApp as a document (CONTRACT "Documents and votes"): what its send answers (the/// pending file bubble under its own name, "Waiting to send"), the refusal of one over WhatsApp's 100 MB, and the/// refusal on a server whose outbox has no `file_name` yet. Sent after every other answer of Tara's chat was read, so/// no page, list or timer above shows it.pub(super) fn documents(wa: &CottonHandle, tara: &str) -> Value {let dir = tempfile::tempdir().unwrap();let document = |path: &str, name: &str| json!({ "path": path, "mime": "application/pdf", "name": name, "kind": "file" });let times = file(dir.path(), "train-times.pdf", 24_000);let sent = answer(wa, "chat.act", json!({ "act": "send", "thread": tara, "attachments": [document(×, "Train times.pdf")] }));let bubble = &sent["bubble"]; assert_eq!((bubble["kind"].as_str(), bubble["state"].as_str()), (Some("file"), Some("Waiting to send")), "{sent}"); assert_eq!(bubble["media"][0]["name"], "Train times.pdf", "{sent}");// Over WhatsApp's 100 MB: refused before anything is kept (the length is all the core reads first).let map = dir.path().join("hill-line-map.pdf"); std::fs::File::create(&map).unwrap().set_len((100 << 20) + 1).unwrap();let ask = json!({ "act": "send", "thread": tara, "attachments": [document(&map.to_string_lossy(), "Hill line map.pdf")] });let large = over(&wa.client(), "chat.act", &ask).expect_err("over 100 MB is refused");// A server whose outbox has no `file_name` yet (44cc5e5989): pictures still go, a document is refused in words.let before = served_without(wa, &["file_name"], || {let ask = json!({ "act": "send", "thread": tara, "attachments": [document(×, "Train times.pdf")] }); over(&wa.client(), "chat.act", &ask).expect_err("an outbox of before takes no document") }); assert_eq!(before.message, "Only pictures, videos and voice notes go to WhatsApp for now."); json!({"send": sent,"tooLarge": { "code": large.code, "message": large.message },"notYet": { "code": before.code, "message": before.message }, })}/// `then` asked of a copy whose served outbox lacks `columns` (a Worker not yet deployed with them), the outbox put/// back after.fn served_without<T>(wa: &CottonHandle, columns: &[&str], then: implFnOnce() -> T) -> T {let ws = workspace(wa);let held = wa.client().with_writer(|replica| replica.driver.all("SELECT definition FROM cotton_table_definitions WHERE workspace_id = ? AND id = 'outbox'", &[t(&ws)]).map_err(|e| e.to_string())).unwrap();let merged = held[0].text("definition").unwrap().to_string();letmut before: Value = serde_json::from_str(&merged).unwrap(); before["columns"].as_array_mut().unwrap().retain(|c| !columns.contains(&c["key"].as_str().unwrap())); sql(wa, "UPDATE cotton_table_definitions SET definition = ? WHERE workspace_id = ? AND id = 'outbox'", &[t(&before.to_string()), t(&ws)]);let out = then(); sql(wa, "UPDATE cotton_table_definitions SET definition = ? WHERE workspace_id = ? AND id = 'outbox'", &[t(&merged), t(&ws)]); out}/// Lays the media's and the route's answers into the fixture: `whatsapp`'s sends of each kind, the refusal, the/// failed picture's retry, a document's send and refusals, and `route`, whose pages stand among the chats.pub(super) fn lay(fixture: &mutValue, media: Media, retried: Value, words_only: Value, documents: Value, mut route: Value) {let wa = &mut fixture["whatsapp"]; wa["document"] = documents; wa["picture"] = media.picture; wa["video"] = media.video; wa["voice"] = media.voice; wa["tooLarge"] = json!({ "code": media.too_large.0, "message": media.too_large.1 }); wa["retryPicture"] = retried; wa["wordsOnly"] = words_only; drop(media.dir);ifletValue::Object(pages) = route["threads"].take() {for (thread, page) in pages { fixture["threads"][thread] = page; } } fixture["route"] = route;}/// Tara's chat as a server whose outbox takes no file yet answers it (c0dec3265d): words only.pub(super) fn words_only(wa: &CottonHandle, tara: &str) -> Value {let columns = ["kind", "voice", "mime", "size_bytes", "width", "height", "duration_ms", "waveform", "preview", "part"];let page = served_without(wa, &columns, || answer(wa, "chat.thread", json!({ "thread": tara, "mail": true }))); assert_eq!(page["composer"]["attach"], false, "{page}"); page["composer"].clone()}/// Disappearing messages in a 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). Off/// after each length, so each is chosen from Off. None where the chat answers no timer it can set.pub(super) fn timer_lengths(h: &CottonHandle, id: &str) -> Option<Value> {let start = answer(h, "chat.thread", json!({ "thread": id, "mail": true }));if start["timer"]["choices"].as_array().is_none_or(|c| c.is_empty()) {returnNone; }letmut lengths = serde_json::Map::new();letmut before = start;for seconds in [604_800, 0, 86_400, 0, 7_776_000, 0] {let acted = answer(h, "chat.act", json!({ "act": "timer", "thread": id, "seconds": seconds }));let after = answer(h, "chat.thread", json!({ "thread": id, "mail": true }));let held: Vec<&Value> = before["items"].as_array().unwrap().iter().filter_map(|i| i.get("message")).collect();let items = after["items"].as_array().unwrap();// The line is the event the chat gained; in a WhatsApp chat it stands above his texts still on their way to// the Mac, which keep to the foot. The day it stands under is the day item the chat gained, if any.let lines: Vec<Value> = items.iter().filter(|i| i["item"] == "event" && !i.get("message").is_some_and(|m| held.contains(&m))).cloned().collect(); assert_eq!(lines.len(), 1, "one line for {seconds} in {id}: {items:?}");let days: Vec<&Value> = before["items"].as_array().unwrap().iter().filter(|i| i["item"] == "day").collect();ifletSome(day) = items.iter().find(|i| i["item"] == "day" && !days.contains(&i)) { lengths.insert("day".into(), day.clone()); } lengths.insert(seconds.to_string(), json!({ "act": acted, "timer": after["timer"], "header": after["header"], "lines": lines })); before = after; }Some(Value::Object(lengths))}/// The ids of Tara's outbox rows of `kind` still standing.fn rows_of_kind(wa: &CottonHandle, tara: &str, kind: &str) -> Vec<String> {let ask = json!({ "table": crate::phone::chat_app::whatsapp_send::OUTBOX, "where": { "thread_id": tara }, "limit": 500 });let listed = crate::phone::cotton_chat::read(&wa.client(), "fixture.outbox", |ctx| { cotton_tools::mcp::handlers::tables::list_records(ctx, ask.as_object().unwrap()).map_err(|e| e.to_string()) }) .expect("the outbox is read"); listed["records"].as_array().unwrap().iter().filter(|r| r["data"]["kind"] == kind && r.get("deleted_at").is_none_or(Value::is_null)).filter_map(|r| r["id"].as_str().map(str::to_string)).collect()}/// One message's bubble as Tara's chat answers it now.fn bubble_in(wa: &CottonHandle, tara: &str, id: &str) -> Value {let page = answer(wa, "chat.thread", json!({ "thread": tara, "mail": true })); page["items"].as_array().unwrap().iter().find(|i| i["message"] == id).cloned().unwrap_or_else(|| panic!("{id} in {page}"))}fn acts_of(bubble: &Value) -> Vec<&str> { bubble["actions"].as_array().unwrap().iter().filter_map(Value::as_str).collect()}/// Voting on a WhatsApp poll in Tara's chat (CONTRACT "Documents and votes", "A vote"): her poll as the Mac's link/// lands it (one choice, her own vote on the café), which he can vote on (`page`, `votable`); what his tap on the/// second option answers (his choice drawn at once, "You" among its voters, "Vote waiting to send"); the vote the Mac/// could not send ("Vote not sent: <why>", Retry first) and its retry; and the refusal of a vote on a poll of a chat/// that does not send (`refused`, from `other`, the Book club's poll on a copy with no Mac). Before the timers, so no/// timer's line stands among them.pub(super) fn vote(wa: &CottonHandle, tara: &str, other: (&CottonHandle, &str, &str), mark: &dynFn(&str, Value)) -> Value {let ws = workspace(wa);let at = (wa.client().now() - chrono::Duration::minutes(5)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true);let poll = json!({ "poll": {"question": "Lunch before the train?","options": [{ "text": "The station café", "votes": 1 }, { "text": "Sandwiches on the train", "votes": 0 }, { "text": "Skip it", "votes": 0 }],"selectable": 1,"voters": [{ "who": "15550100004", "options": [0], "at": at }], }, "source": { "messageType": "poll" } }); sql( wa,"INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at, external_id, meta) VALUES ('m-t-poll', ?, ?, 'in', 'whatsapp', 'live', 'Lunch before the train?', ?, ?, 'WA-TARA-POLL', ?)", &[t(tara), t(&ws), t(&at), t(&at), t(&poll.to_string())], );let page = answer(wa, "chat.thread", json!({ "thread": tara, "mail": true }));let shown = page["items"].as_array().unwrap().iter().find(|i| i["message"] == "m-t-poll").cloned().expect("her poll"); assert_eq!(shown["poll"]["votable"], true, "{shown}"); assert!(shown["poll"]["spoken"].as_str().unwrap().ends_with("Tap an option to vote"), "{shown}");let voted = answer(wa, "chat.act", json!({ "act": "vote", "thread": tara, "message": "m-t-poll", "option": 1 }));let bubble = &voted["bubble"]; assert_eq!(bubble["state"], "Vote waiting to send", "{voted}"); assert_eq!((bubble["poll"]["options"][1]["mine"].as_bool(), bubble["poll"]["options"][1]["voters"][0].as_str()), (Some(true), Some("You")), "{voted}");let why = "WhatsApp did not take it: the Mac's link is not signed in";let rows = rows_of_kind(wa, tara, "poll_vote"); assert_eq!(rows.len(), 1, "one vote row"); mark(&rows[0], json!({ "status": "failed", "error": why }));let failed = bubble_in(wa, tara, "m-t-poll"); assert_eq!((failed["state"].as_str(), acts_of(&failed).first().copied()), (Some(format!("Vote not sent: {why}").as_str()), Some("retry")), "{failed}");let retried = answer(wa, "chat.act", json!({ "act": "retry", "thread": tara, "message": "m-t-poll" })); assert_eq!(retried["bubble"]["state"], "Vote waiting to send", "{retried}");let (handle, book, poll) = other;let refused = over(&handle.client(), "chat.act", &json!({ "act": "vote", "thread": book, "message": poll, "option": 0 })).expect_err("a chat that does not send takes no vote"); json!({"message": "m-t-poll","option": 1,"page": page,"vote": voted,"failed": failed,"retried": retried,"refused": { "code": refused.code, "message": refused.message }, })}/// Making a poll in Tara's chat (CONTRACT "Making a poll"): the writing box of a server whose outbox takes a poll but/// no file yet (the plus with Poll alone), what a poll's send answers (its card at once, "Waiting to send", any number/// may be chosen), and the refusal of a poll whose two options are one (case aside). Sent after every other answer of/// Tara's chat was read, so no page, list or timer above shows it.pub(super) fn polls(wa: &CottonHandle, tara: &str) -> Value {let files = ["voice", "mime", "size_bytes", "width", "height", "duration_ms", "waveform", "preview", "part"];let alone = served_without(wa, &files, || answer(wa, "chat.compose", json!({ "thread": tara, "text": "" }))); assert_eq!(alone["attach"], false, "{alone}"); assert_eq!(alone["poll"]["label"], "Poll", "{alone}");let page = answer(wa, "chat.thread", json!({ "thread": tara, "mail": true })); assert_eq!(page["composer"]["poll"]["most"], 12, "{}", page["composer"]);let ask = json!({ "act": "poll", "thread": tara, "question": "Which train on Friday?", "options": ["The 7:40", "The 9:15", "The 11:05"], "many": true });let sent = answer(wa, "chat.act", ask);let bubble = &sent["bubble"]; assert_eq!((bubble["kind"].as_str(), bubble["state"].as_str()), (Some("poll"), Some("Waiting to send")), "{sent}"); assert_eq!((bubble["poll"]["question"].as_str(), bubble["poll"]["choose"].as_str()), (Some("Which train on Friday?"), Some("Select one or more")), "{sent}");let ask = json!({ "act": "poll", "thread": tara, "question": "Which train on Friday?", "options": ["The 7:40", "the 7:40"], "many": false });let once = over(&wa.client(), "chat.act", &ask).expect_err("one option twice is one option"); assert_eq!((once.code.as_str(), once.message.as_str()), ("empty", "A poll needs at least two options.")); json!({ "alone": alone, "send": sent, "refused": { "code": once.code, "message": once.message } })}/// Editing and deleting his own message in Tara's chat (CONTRACT "Editing and deleting his own message"): his text of/// two minutes ago (Edit, Delete for everyone, Delete for me), his of three hours ago (Delete for everyone, no Edit) and/// hers of a minute ago (Delete for me) stand in the chat (`page`). Then what each act answers: the edit's writing box/// and its send ("Edit waiting to send"), the edit the Mac could not send ("Edit not sent: <why>", Retry) and its retry;/// the delete for everyone (the marker, "You deleted this message", "Waiting to delete for everyone"), the one the Mac/// could not send and its retry; Delete for me; and the refusals once WhatsApp's windows are over (`too_late`,/// `too_late_delete`). Before the timers, so no timer's line stands among them.pub(super) fn changes(wa: &CottonHandle, tara: &str, mark: &dynFn(&str, Value)) -> Value {let ws = workspace(wa);let now = wa.client().now();let ago = |minutes: i64| (now - chrono::Duration::minutes(minutes)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true);let said: [(&str, bool, &str, i64); 3] = [("m-t4", true, "I'll wait by the bridge", 180), ("m-t3", true, "Running ten minutes late", 2), ("m-t5", false, "Platform 4, not 3", 1)];for (id, out, body, minutes) in said { sql( wa,"INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at, external_id) VALUES (?, ?, ?, ?, 'whatsapp', 'live', ?, ?, ?, ?)", &[t(id), t(tara), t(&ws), t(if out { "out" } else { "in" }), t(body), t(&ago(minutes)), t(&ago(minutes)), t(&format!("WA-TARA-{id}"))], ); }let page = answer(wa, "chat.thread", json!({ "thread": tara, "mail": true })); assert_eq!((page["actions"]["delete"].as_str(), page["actions"]["deleteMine"].as_str()), (Some("Delete for everyone"), Some("Delete for me")), "{}", page["actions"]);let item = |id: &str| page["items"].as_array().unwrap().iter().find(|i| i["message"] == id).cloned().unwrap_or_else(|| panic!("{id} in {page}"));let fresh = item("m-t3"); assert!(["edit", "delete", "deleteMine"].iter().all(|a| acts_of(&fresh).contains(a)), "{fresh}");let hours = item("m-t4"); assert!(!acts_of(&hours).contains(&"edit") && acts_of(&hours).contains(&"delete"), "{hours}");let hers = item("m-t5"); assert!(!acts_of(&hers).contains(&"delete") && acts_of(&hers).contains(&"deleteMine"), "{hers}");let days = item("m-t2"); assert!(!acts_of(&days).contains(&"delete"), "{days}");let compose = answer(wa, "chat.compose", json!({ "thread": tara, "edit": "m-t3" })); assert_eq!((compose["strip"]["kind"].as_str(), compose["text"].as_str()), (Some("edit"), Some("Running ten minutes late")), "{compose}");let typing = answer(wa, "chat.compose", json!({ "thread": tara, "edit": "m-t3", "text": "Running fifteen minutes late" }));let edit = answer(wa, "chat.act", json!({ "act": "edit", "thread": tara, "message": "m-t3", "text": "Running fifteen minutes late" })); assert_eq!((edit["bubble"]["text"].as_str(), edit["bubble"]["state"].as_str()), (Some("Running fifteen minutes late"), Some("Edit waiting to send")), "{edit}");let cancelled = answer(wa, "chat.compose", json!({ "thread": tara, "text": "", "cancel": true }));let late = over(&wa.client(), "chat.act", &json!({ "act": "edit", "thread": tara, "message": "m-t4", "text": "I'll wait at the gate" })).expect_err("too late to edit"); assert_eq!(late.code, "too_late");let late_delete = over(&wa.client(), "chat.act", &json!({ "act": "delete", "thread": tara, "message": "m-t2" })).expect_err("too late to delete for everyone"); assert_eq!(late_delete.code, "too_late_delete");let why = "WhatsApp did not take it: the Mac's link is not signed in";let edits = rows_of_kind(wa, tara, "edit"); assert_eq!(edits.len(), 1, "one edit row"); mark(&edits[0], json!({ "status": "failed", "error": why }));let edit_failed = bubble_in(wa, tara, "m-t3"); assert_eq!((edit_failed["state"].as_str(), acts_of(&edit_failed).first().copied()), (Some(format!("Edit not sent: {why}").as_str()), Some("retry")), "{edit_failed}");let edit_retried = answer(wa, "chat.act", json!({ "act": "retry", "thread": tara, "message": "m-t3" })); assert_eq!(edit_retried["bubble"]["state"], "Edit waiting to send", "{edit_retried}");let delete = answer(wa, "chat.act", json!({ "act": "delete", "thread": tara, "message": "m-t4" }));let marker = delete["message"].as_str().expect("the marker").to_string(); assert_ne!(marker, "m-t4"); assert_eq!((delete["bubble"]["text"].as_str(), delete["bubble"]["state"].as_str()), (Some("You deleted this message"), Some("Waiting to delete for everyone")), "{delete}");let deletes = rows_of_kind(wa, tara, "delete"); assert_eq!(deletes.len(), 1, "one delete row"); mark(&deletes[0], json!({ "status": "failed", "error": why }));let delete_failed = bubble_in(wa, tara, &marker); assert_eq!((delete_failed["state"].as_str(), acts_of(&delete_failed).first().copied()), (Some(format!("Not deleted for everyone: {why}").as_str()), Some("retry")), "{delete_failed}");let delete_retried = answer(wa, "chat.act", json!({ "act": "retry", "thread": tara, "message": marker })); assert_eq!(delete_retried["bubble"]["state"], "Waiting to delete for everyone", "{delete_retried}");let mine = answer(wa, "chat.act", json!({ "act": "deleteMine", "thread": tara, "message": "m-t5" }));let after = answer(wa, "chat.thread", json!({ "thread": tara, "mail": true })); assert!(after["items"].as_array().unwrap().iter().all(|i| i["message"] != "m-t5"), "Delete for me takes it from his copy: {after}"); json!({// Which message each act was asked of: his fresh text edited, his of hours ago deleted for everyone, hers// deleted for him only."edited": "m-t3","deleted": "m-t4","deletedMine": "m-t5","page": page,"editCompose": compose,"editTyping": typing,"edit": edit,"editCancelled": cancelled,"editFailed": edit_failed,"editRetried": edit_retried,"tooLate": { "code": late.code, "message": late.message },"delete": delete,"deleteFailed": delete_failed,"deleteRetried": delete_retried,"tooLateDelete": { "code": late_delete.code, "message": late_delete.message },"deleteMine": mine, })}/// Several pictures with words to WhatsApp, one grid (FEEDBACK-4 B3, CONTRACT "Several pictures to WhatsApp, one/// grid"): what the send of three pictures with words answers (one pending grid, each tile naming its row), and the/// grid as it stands once the Mac sent each and they landed, a message each (each tile naming its message, the first/// its own). Sent after every other answer of Tara's chat was read, so no page, list or timer above shows it.pub(super) fn grid(wa: &CottonHandle, tara: &str, mark: &dynFn(&str, Value)) -> Value {let dir = tempfile::tempdir().unwrap();let names = ["hill.jpg", "tea.jpg", "valley.jpg"];let attachments: Vec<Value> = names.iter().enumerate().map(|(i, n)| picture(&file(dir.path(), n, 3_000 + i * 200))).collect();let words = "From the train window";let sent = answer(wa, "chat.act", json!({ "act": "send", "thread": tara, "text": words, "attachments": attachments }));let pending = &sent["bubble"]; assert_eq!((pending["kind"].as_str(), pending["text"].as_str()), (Some("album"), Some(words)), "one grid with its words: {sent}");let rows: Vec<String> = pending["media"].as_array().unwrap().iter().map(|m| m["message"].as_str().expect("each tile names its row").to_string()).collect(); assert_eq!(rows.len(), 3, "three tiles: {sent}"); assert_eq!(rows[0], sent["message"].as_str().unwrap(), "the first tile is the grid's own row");// The Mac sends each, and each lands as a message of its own under the WhatsApp id fixed at the tap, carrying// WhatsApp's own small picture, as the link lands a picture.let ws = workspace(wa);let landed: Vec<String> = (1..=rows.len()).map(|i| format!("m-t-grid-{i}")).collect();for (i, row) in rows.iter().enumerate() {let id = row.trim_start_matches(crate::phone::chat_app::whatsapp_send::PENDING).to_string();let ask = json!({ "table": crate::phone::chat_app::whatsapp_send::OUTBOX, "id": id });let found = crate::phone::cotton_chat::read(&wa.client(), "fixture.row", |ctx| { cotton_tools::mcp::handlers::tables::get_record_by_table(ctx, ask.as_object().unwrap()).map_err(|e| e.to_string()) }) .expect("the row");let record = if found["record"].is_object() { &found["record"] } else { &found };let data = &record["data"];let (external, key) = (data["sent_external_id"].as_str().expect("its WhatsApp id").to_string(), data["media_key"].as_str().expect("its file").to_string()); mark(&id, json!({ "status": "sent", "sent_at": iso(0) }));let media = json!([{ "key": key, "contentType": "image/jpeg", "width": 1600, "height": 1200, "preview": PREVIEW }]); sql( wa,"INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, media, sent_at, created_at, external_id) VALUES (?, ?, ?, 'out', 'whatsapp', 'live', ?, ?, ?, ?, ?)", &[t(&landed[i]), t(tara), t(&ws), t(if i == 0 { words } else { "" }), t(&media.to_string()), t(&iso(0)), t(&iso(0)), t(&external)], ); }let page = answer(wa, "chat.thread", json!({ "thread": tara, "mail": true }));let items = page["items"].as_array().unwrap();let grid = items.iter().find(|i| i["message"] == landed[0].as_str()).cloned().expect("the landed grid"); assert_eq!((grid["kind"].as_str(), grid["text"].as_str()), (Some("album"), Some(words)), "still one grid: {grid}");let tiles: Vec<Value> = grid["media"].as_array().unwrap().iter().map(|m| m["message"].clone()).collect(); assert_eq!(tiles, [Value::Null, json!(landed[1]), json!(landed[2])], "each tile names its message: {grid}");for other in &landed[1..] { assert!(!items.iter().any(|i| i["message"] == other.as_str()), "{other} stands only in the grid"); } assert!(!items.iter().any(|i| i["message"].as_str().is_some_and(|m| rows.iter().any(|r| r == m))), "nothing still waits: {page}"); json!({ "send": sent, "landed": grid })}