Cotton code
1555 lines · 96.7 KB · RustRaw
//! A text written in Comms in a WhatsApp chat, queued for the Mac's link.//! Every name, number and line is invented.use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use super::*;use crate::handle::CottonHandle;use crate::phone::cotton_chat::over;/// A Comms phone, whose kit draws the outbox; and a Keys phone, whose copy never does (as a copy made before).fn phone() -> (tempfile::TempDir, CottonHandle) {    let dir = tempfile::tempdir().unwrap();    let handle = crate::phone::chat_app::mail::tests::comms(&dir, cotton_core::flavor::Flavor::Real);    (dir, handle)}const BIMAL: &str = "11111111-1111-4111-8111-0000000000d1";const NO_NUMBER: &str = "11111111-1111-4111-8111-0000000000d2";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)}/// A WhatsApp chat with Bimal, whose number Cotton knows; one with no number at all.fn chats(handle: &CottonHandle) {    let ws = workspace(handle);    sql(handle, "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, created_at, updated_at) VALUES ('c-bimal', ?, '15550100222', 'Bimal Example', '2026-01-01', '2026-01-01')", &[t(&ws)]);    for (id, contact) in [(BIMAL, Some("c-bimal")), (NO_NUMBER, None)] {        sql(            handle,            "INSERT INTO cotton_msg_threads (id, workspace_id, kind, contact_id, title, last_message_at, read_seq, created_at, updated_at) VALUES (?, ?, 'dm', ?, 'Someone', ?, 0, ?, ?)",            &[t(id), t(&ws), contact.map_or(SqlValue::Null, t), t(&iso(30)), t(&iso(30)), t(&iso(30))],        );        message(handle, &format!("m-{id}"), id, "Are you coming?", &format!("x-{id}"), 30);    }}fn message(handle: &CottonHandle, id: &str, thread: &str, body: &str, external: &str, ago: i64) {    let ws = workspace(handle);    sql(        handle,        "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at, external_id) VALUES (?, ?, ?, 'in', 'whatsapp', 'live', ?, ?, ?, ?)",        &[t(id), t(thread), t(&ws), t(body), t(&iso(ago)), t(&iso(ago)), t(external)],    );}/// The outbox rows of `thread`, as the Mac will read them.fn queued(handle: &CottonHandle, thread: &str) -> Vec<(String, Map<String, Value>)> {    let th = thread.to_string();    let found = crate::phone::cotton_chat::read(&handle.client(), "test.outbox", |ctx| Ok(json!(rows_of(ctx, &th)?.into_iter().map(|(id, data, _)| json!([id, data])).collect::<Vec<_>>()))).unwrap();    let mut rows: Vec<(String, Map<String, Value>)> = found.as_array().unwrap().iter().map(|pair| (pair[0].as_str().unwrap().to_string(), pair[1].as_object().unwrap().clone())).collect();    // In the order they go, as the Mac takes them: a tap's rows by their place in it.    rows.sort_by_key(|(_, row)| row.get("part").and_then(Value::as_f64).unwrap_or(0.0) as u32);    rows}/// What the Mac writes back on the row.fn mark(handle: &CottonHandle, id: &str, patch: Value) {    let row = id.to_string();    crate::phone::cotton_chat::write(&handle.client(), "test.mark", |ctx| {        tables::update_produced_record(ctx, &object(json!({ "table": OUTBOX, "id": row, "patch": patch.clone() }))).map_err(tool)?;        Ok(Value::Null)    })    .unwrap();}fn foot(page: &Value) -> Value {    page["items"].as_array().unwrap().last().cloned().unwrap()}/// RULE (owner, 22 Nov 2026): a text the owner writes in Comms in a WhatsApp chat goes out through the Mac's/// link: the tap queues one outbox row with the chat's address and a WhatsApp id fixed then, writes no message,/// and the bubble says "Waiting to send" (never sent) until the Mac takes it.#[test]fn a_whatsapp_text_is_queued_for_the_mac_and_waits_in_words() {    let (_dir, handle) = phone();    chats(&handle);    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    assert!(page["composer"].is_object(), "a WhatsApp chat whose number is known can be written in: {page}");    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "On my way " }));    assert_eq!(sent["flush"], false, "never the Cotton network");    let queued_as = sent["message"].as_str().unwrap().to_string();    let message_of = queued_as.as_str();    assert!(message_of.starts_with(PENDING), "{sent}");    assert_eq!(sent["bubble"]["state"], "Waiting to send");    assert_eq!(sent["bubble"]["tick"], "sending");    assert_eq!(sent["bubble"]["text"], "On my way", "trimmed, as it goes");    let rows = queued(&handle, BIMAL);    assert_eq!(rows.len(), 1);    let (id, row) = &rows[0];    assert_eq!(format!("{PENDING}{id}"), message_of);    assert_eq!(row["channel"], "whatsapp");    assert_eq!(row["status"], "queued");    assert_eq!(row["to"], "15550100222@s.whatsapp.net");    assert_eq!(row["body"], "On my way");    assert_eq!(row["thread_id"], BIMAL);    let external = row["sent_external_id"].as_str().unwrap().to_string();    assert!(external.starts_with("3EB0") && external.len() == 24, "{external}");    let ws = workspace(&handle);    let count = crate::phone::cotton_chat::read(&handle.client(), "test.count", |ctx| {        Ok(json!(one(ctx, &format!("SELECT COUNT(*) AS n FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ?"), &[text(ws.clone()), text(BIMAL.into())])?.and_then(|r| r.get("n").cloned())))    })    .unwrap();    assert_eq!(count, json!(1), "no message row until the Mac's link brings the sent text back");    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    let last = foot(&page);    assert_eq!(last["message"], message_of);    assert_eq!(last["state"], "Waiting to send");    assert_eq!(last["actions"], json!(["copy"]), "nothing to retry while it waits");    // The Mac took it: "Sending…". It sent it, and its link brought it back under the id fixed at the tap: the    // pending bubble leaves, the message stands, once.    mark(&handle, id, json!({ "status": "sending" }));    assert_eq!(foot(&answer(&handle, "chat.thread", json!({ "thread": BIMAL })))["state"], "Sending…");    mark(&handle, id, json!({ "status": "sent", "sent_at": iso(0) }));    assert_eq!(foot(&answer(&handle, "chat.thread", json!({ "thread": BIMAL })))["tick"], "sent");    message(&handle, "m-echo", BIMAL, "On my way", &external, 0);    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    let bubbles: Vec<&Value> = page["items"].as_array().unwrap().iter().filter(|i| i["item"] == "bubble").collect();    assert_eq!(bubbles.len(), 2, "the question and the answer, once: {page}");    assert_eq!(foot(&page)["message"], "m-echo");}/// RULE: a send the Mac could not make says so with its reason and offers Retry; Retry queues the same row again/// under the same WhatsApp id, so it can never go twice. A text on its way offers no Retry.#[test]fn a_failed_whatsapp_text_says_why_and_retries_under_the_same_id() {    let (_dir, handle) = phone();    chats(&handle);    answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "Here at six" }));    let (id, row) = queued(&handle, BIMAL).remove(0);    let external = row["sent_external_id"].clone();    let pending_id = format!("{PENDING}{id}");    assert_eq!(refused(&handle, "chat.act", json!({ "act": "retry", "thread": BIMAL, "message": pending_id })), "cannot", "a waiting text is not sent again");    mark(&handle, &id, json!({ "status": "failed", "error": "WhatsApp did not take it: not on WhatsApp" }));    let last = foot(&answer(&handle, "chat.thread", json!({ "thread": BIMAL })));    assert_eq!(last["state"], "Not sent: WhatsApp did not take it: not on WhatsApp");    assert_eq!(last["tick"], "failed");    assert_eq!(last["actions"][0], "retry");    let retried = answer(&handle, "chat.act", json!({ "act": "retry", "thread": BIMAL, "message": pending_id }));    assert_eq!(retried["bubble"]["state"], "Waiting to send");    let (again, row) = queued(&handle, BIMAL).remove(0);    assert_eq!(again, id, "the same row");    assert_eq!(row["status"], "queued");    assert_eq!(row["sent_external_id"], external, "the same WhatsApp id: WhatsApp keeps one");    assert!(row.get("error").is_none_or(Value::is_null));    assert_eq!(queued(&handle, BIMAL).len(), 1);}/// RULE: a WhatsApp chat whose address Cotton does not know stays read only: no composer, a send refused, nothing/// queued.#[test]fn a_whatsapp_chat_with_no_address_stays_read_only() {    let (_dir, handle) = phone();    chats(&handle);    let page = answer(&handle, "chat.thread", json!({ "thread": NO_NUMBER }));    assert!(page["composer"].is_null(), "{page}");    assert_eq!(refused(&handle, "chat.act", json!({ "act": "send", "thread": NO_NUMBER, "text": "hello?" })), "cannot");    assert!(queued(&handle, NO_NUMBER).is_empty());}/// RULE: a copy that draws no outbox (made before Comms drew it) keeps a WhatsApp chat read only rather than offer/// a send the copy would refuse.#[test]fn a_copy_without_the_outbox_keeps_whatsapp_read_only() {    let (_dir, handle) = crate::phone::passwords::tests::phone();    chats(&handle);    assert!(answer(&handle, "chat.thread", json!({ "thread": BIMAL }))["composer"].is_null());    assert_eq!(refused(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "hi" })), "cannot");}// ---- Pictures, videos and voice notes (owner, FEEDBACK-3, 23 Nov 2026) ----const GROUP: &str = "11111111-1111-4111-8111-0000000000d3";const GROUP_JID: &str = "120363000000000042@g.us";const LINKED: &str = "15550100999@s.whatsapp.net";/// A tiny JPEG's base64, as the phone's preview is (it only has to look like one).fn preview() -> 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, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0xFF, 0xD9])}/// An invented file of `bytes` bytes at `dir/name`.fn file(dir: &tempfile::TempDir, name: &str, bytes: usize) -> String {    let path = dir.path().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": "beach.jpg", "width": 1600, "height": 1200, "preview": preview() })}/// A WhatsApp group the Mac's link brought in, with one message from it.fn group(handle: &CottonHandle) {    let ws = workspace(handle);    sql(        handle,        "INSERT INTO cotton_msg_threads (id, workspace_id, kind, external_key, title, last_message_at, read_seq, created_at, updated_at) VALUES (?, ?, 'group', ?, 'Hill walkers', ?, 0, ?, ?)",        &[t(GROUP), t(&ws), t(&format!("wa:group:{GROUP_JID}")), t(&iso(30)), t(&iso(30)), t(&iso(30))],    );    sql(        handle,        "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, meta, sent_at, created_at, external_id) VALUES ('m-g1', ?, ?, 'in', 'whatsapp', 'live', 'Saturday?', ?, ?, ?, 'x-g1')",        &[t(GROUP), t(&ws), t(&json!({ "source": { "account": LINKED, "chat": GROUP_JID } }).to_string()), t(&iso(30)), t(&iso(30))],    );}fn messages_in(handle: &CottonHandle, thread: &str) -> Value {    let (ws, th) = (workspace(handle), thread.to_string());    crate::phone::cotton_chat::read(&handle.client(), "test.count", |ctx| {        Ok(one(ctx, &format!("SELECT COUNT(*) AS n FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ?"), &[text(ws.clone()), text(th.clone())])?.and_then(|r| r.get("n").cloned()).unwrap_or(Value::Null))    })    .unwrap()}/// The owner's message as the Mac's link lands it: out, under `external`.fn message_with(handle: &CottonHandle, id: &str, thread: &str, body: &str, external: &str) {    let ws = workspace(handle);    sql(        handle,        "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at, external_id) VALUES (?, ?, ?, 'out', 'whatsapp', 'live', ?, ?, ?, ?)",        &[t(id), t(thread), t(&ws), t(body), t(&iso(0)), t(&iso(0)), t(external)],    );}/// RULE (FEEDBACK-3): a WhatsApp chat that sends offers pictures and voice notes in its composer, as a Cotton/// chat does.#[test]fn a_whatsapp_chat_that_sends_offers_files_and_voice() {    let (_dir, handle) = phone();    chats(&handle);    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    assert_eq!(page["composer"]["attach"], true, "{page}");    assert_eq!(page["composer"]["button"], "mic", "hold to record a voice note: {page}");    assert!(answer(&handle, "chat.thread", json!({ "thread": NO_NUMBER }))["composer"].is_null(), "read only stays read only");}/// RULE (FEEDBACK-3): a picture with a caption, his own tap: the file is kept in his own media at once (the key the/// Mac opens, sealed when it goes up), one outbox row names it with the caption, its kind, type, size, shape and/// preview, and its WhatsApp id is fixed now. The bubble is the picture from the phone's own copy, captioned,/// "Waiting to send"; no message row until the Mac's link brings it back; then the bubble leaves, once.#[test]fn a_picture_with_a_caption_is_queued_once_and_shows_at_once() {    let (dir, handle) = phone();    chats(&handle);    let path = file(&dir, "beach.jpg", 4_000);    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": " The beach ", "attachments": [picture(&path)] }));    assert_eq!(sent["flush"], false, "never the Cotton network");    let message = sent["message"].as_str().unwrap().to_string();    assert!(message.starts_with(PENDING), "{sent}");    let bubble = &sent["bubble"];    assert_eq!(bubble["kind"], "photo", "{bubble}");    assert_eq!(bubble["text"], "The beach", "the caption, trimmed");    assert_eq!(bubble["state"], "Waiting to send");    assert_eq!(bubble["media"][0]["width"], 1600.0);    assert_eq!(bubble["media"][0]["height"], 1200.0);    assert_eq!(bubble["media"][0]["preview"], preview(), "drawn at once from its preview");    let rows = queued(&handle, BIMAL);    assert_eq!(rows.len(), 1, "one row for one picture");    let (id, row) = &rows[0];    assert_eq!(format!("{PENDING}{id}"), message);    assert_eq!(row["kind"], "photo");    assert_eq!(row["body"], "The beach");    assert_eq!(row["mime"], "image/jpeg");    assert_eq!(row["size_bytes"].as_f64(), Some(4000.0));    assert_eq!(row["width"].as_f64(), Some(1600.0));    assert_eq!(row["preview"], preview());    assert_eq!(row["to"], "15550100222@s.whatsapp.net");    assert!(row.get("voice").is_none_or(|v| v.is_null() || v == &json!(false)), "{row:?}");    let key = row["media_key"].as_str().unwrap().to_string();    assert!(key.contains(&format!("/messages/{BIMAL}/")) && key.ends_with(".jpg"), "his own media, under this chat: {key}");    let external = row["sent_external_id"].as_str().unwrap().to_string();    assert!(external.starts_with("3EB0"), "{external}");    // The file is his own media's, here now: drawn from the phone's copy, asked of no one.    let opened = answer(&handle, "chat.picture", json!({ "message": message, "index": 0, "dir": dir.path().join("open").to_string_lossy() }));    assert_eq!(std::fs::read(opened["path"].as_str().unwrap()).unwrap(), std::fs::read(&path).unwrap(), "{opened}");    let held = handle.client().with_writer(|replica| replica.driver.all("SELECT key FROM _media WHERE key = ?", &[t(&key)]).map_err(|e| e.to_string())).unwrap();    assert_eq!(held.len(), 1, "in the media ledger, so the drain puts it up sealed");    assert_eq!(messages_in(&handle, BIMAL), json!(1), "no message row: the outbox row is the send");    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    assert_eq!(foot(&page)["message"], message.as_str());    assert_eq!(foot(&page)["kind"], "photo");    // The Mac sent it and its link brought it back under the id fixed at the tap: the pending bubble leaves.    mark(&handle, id, json!({ "status": "sent", "sent_at": iso(0) }));    message_with(&handle, "m-echo", BIMAL, "The beach", &external);    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    let bubbles: Vec<&Value> = page["items"].as_array().unwrap().iter().filter(|i| i["item"] == "bubble").collect();    assert_eq!(bubbles.len(), 2, "the question and the picture, once: {page}");    assert_eq!(foot(&page)["message"], "m-echo");}/// RULE (FEEDBACK-3): a voice note goes as a WhatsApp voice note, never as a file: its row is audio with `voice`,/// its length, and its waveform as WhatsApp holds one (64 bytes, 0..100); its bubble is a voice bubble with bars./// It carries no caption: words sent with it go first, as their own text.#[test]fn a_voice_note_is_marked_as_one_and_words_go_before_it() {    use base64::Engine as _;    let (dir, handle) = phone();    chats(&handle);    let path = file(&dir, "note.m4a", 2_000);    let samples: Vec<f64> = (0..20).map(|i| f64::from(i) / 19.0).collect();    let sent = answer(        &handle,        "chat.act",        json!({ "act": "send", "thread": BIMAL, "text": "Listen", "attachments": [{ "path": path, "mime": "audio/mp4", "kind": "voice", "durationMs": 4200, "waveform": samples }] }),    );    let rows = queued(&handle, BIMAL);    assert_eq!(rows.len(), 2, "the words, then the note: {rows:?}");    assert_eq!(sent["message"], format!("{PENDING}{}", rows[0].0), "the answer is the first row's");    assert_eq!(rows[0].1["body"], "Listen");    assert!(rows[0].1.get("kind").is_none_or(Value::is_null), "a text row is a text's");    let note = &rows[1].1;    assert_eq!(note["kind"], "audio");    assert_eq!(note["voice"], true, "a WhatsApp voice note");    assert_eq!(note["body"], "", "no caption on a voice note");    assert_eq!(note["duration_ms"].as_f64(), Some(4200.0));    assert_eq!(note["mime"], "audio/mp4");    assert!(note.get("preview").is_none_or(Value::is_null));    let wave = base64::engine::general_purpose::STANDARD.decode(note["waveform"].as_str().unwrap()).unwrap();    assert_eq!(wave.len(), 64, "WhatsApp's 64 samples");    assert!(wave.iter().all(|b| *b <= 100), "each 0..100: {wave:?}");    assert_eq!((wave[0], wave[63]), (0, 100), "quiet to loud, as recorded");    assert_ne!(rows[0].1["sent_external_id"], note["sent_external_id"], "each its own WhatsApp message");    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    let last = foot(&page);    assert_eq!(last["kind"], "voice", "{last}");    assert_eq!(last["media"][0]["durationMs"], 4200);    assert!(last["media"][0]["bars"].as_array().is_some_and(|b| !b.is_empty()), "{last}");    assert!(last["text"].is_null());    assert_eq!(last["state"], "Waiting to send");}/// RULE (CONTRACT "WhatsApp through the Mac", the gap mac-import left): the voice note the Mac sent comes back under/// the WhatsApp id fixed at the tap and stands in the chat once, in place of the waiting one, not beside it; it/// carries the kind, waveform and preview the Mac copied from the outbox row, so it is still a voice note with its/// bars, on his file.#[test]fn a_sent_voice_note_lands_on_the_one_he_sent_still_a_voice_note_with_its_bars() {    let (dir, handle) = phone();    chats(&handle);    let path = file(&dir, "note.m4a", 2_000);    let samples: Vec<f64> = (0..20).map(|i| f64::from(i) / 19.0).collect();    answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "attachments": [{ "path": path, "mime": "audio/mp4", "kind": "voice", "durationMs": 4200, "waveform": samples }] }));    let rows = queued(&handle, BIMAL);    assert_eq!(rows.len(), 1);    let (id, row) = &rows[0];    let (key, external) = (row["media_key"].as_str().unwrap().to_string(), row["sent_external_id"].as_str().unwrap().to_string());    let before = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    let count = |page: &Value| page["items"].as_array().unwrap().iter().filter(|i| i["item"] == "bubble").count();    // The Mac sent it, marked the row and erased what it erases; its import lands the message under the same id,    // naming the same file, with the three fields from the row (each WhatsApp byte over 100).    mark(&handle, id, json!({ "status": "sent", "sent_at": iso(0), "body": null, "preview": null }));    let waveform: Vec<f64> = (0..64).map(|i| f64::from(i) / 63.0).collect();    message_with(&handle, "m-voice-back", BIMAL, "", &external);    let media = json!([{ "key": key, "contentType": "audio/mp4", "sizeBytes": 2000, "durationMs": 4200, "kind": "voice", "waveform": waveform }]);    sql(&handle, "UPDATE cotton_msg_messages SET media = ? WHERE id = 'm-voice-back'", &[t(&media.to_string())]);    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    assert_eq!(count(&page), count(&before), "the same number of bubbles: the sent one in place of the waiting one: {page}");    let last = foot(&page);    assert_eq!(last["message"], "m-voice-back");    assert_eq!(last["kind"], "voice", "still a voice note: {last}");    assert_eq!(last["media"][0]["durationMs"], 4200);    assert_eq!(last["media"][0]["bars"].as_array().map(Vec::len), Some(36), "its bars, from the waveform it came back with");    assert!(last["state"].is_null() || last["state"] != "Waiting to send", "{last}");    assert_eq!(messages_in(&handle, BIMAL), json!(2), "the question and the note: one message for one send");}/// RULE (FEEDBACK-3): a video goes like a picture, with its caption, length and preview; several files in one tap/// are a row each, in the order picked, the words on the first picture or video only.#[test]fn a_video_and_pictures_go_a_row_each_the_caption_on_the_first() {    let (dir, handle) = phone();    chats(&handle);    let (clip, one_more) = (file(&dir, "clip.mp4", 3_000), file(&dir, "two.jpg", 1_000));    answer(        &handle,        "chat.act",        json!({ "act": "send", "thread": BIMAL, "text": "Saturday", "attachments": [            { "path": clip, "mime": "video/mp4", "kind": "video", "width": 1280, "height": 720, "durationMs": 9000, "preview": preview() },            picture(&one_more),        ] }),    );    let rows = queued(&handle, BIMAL);    assert_eq!(rows.len(), 2);    assert_eq!(rows.iter().map(|(_, r)| r["part"].as_f64()).collect::<Vec<_>>(), [Some(0.0), Some(1.0)], "each row's place in the tap");    assert_eq!((rows[0].1["kind"].clone(), rows[0].1["body"].clone(), rows[0].1["duration_ms"].as_f64()), (json!("video"), json!("Saturday"), Some(9000.0)));    assert_eq!(rows[0].1["preview"], preview());    assert_eq!(rows[1].1["kind"], "photo", "{rows:?}");    assert_eq!(rows[1].1.get("body").and_then(Value::as_str).unwrap_or_default(), "", "the caption once: {rows:?}");    // FEEDBACK-4 B3: one tap's video and picture stand as one grid, in the order picked.    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    let pending: Vec<&Value> = page["items"].as_array().unwrap().iter().filter(|i| i["message"].as_str().is_some_and(|m| m.starts_with(PENDING))).collect();    assert_eq!(pending.len(), 1, "one grid: {page}");    assert_eq!(pending[0]["kind"], "album");    assert_eq!(pending[0]["media"].as_array().unwrap().iter().map(|m| m["kind"].clone()).collect::<Vec<_>>(), [json!("video"), json!("photo")], "in the order picked");    assert_eq!(pending[0]["text"], "Saturday");    assert_eq!(pending[0]["media"][0]["durationMs"], 9000);}/// His picture as the Mac's link lands it: out, no words but `body`, its file named, under `external`.fn landed_picture(handle: &CottonHandle, id: &str, body: &str, external: &str, key: &str) {    let ws = workspace(handle);    let media = json!([{ "key": key, "contentType": "image/jpeg", "width": 1600, "height": 1200 }]);    sql(        handle,        "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(id), t(BIMAL), t(&ws), t(body), t(&media.to_string()), t(&iso(0)), t(&iso(0)), t(external)],    );}fn bubbles(page: &Value) -> Vec<Value> {    page["items"].as_array().unwrap().iter().filter(|i| i["item"] == "bubble").cloned().collect()}/// RULE (owner, FEEDBACK-4 B3, 23 Nov 2026: several photos with words, sent to WhatsApp, stood as one bubble each):/// one tap's pictures stand as one grid at once, headed by its words, each tile naming the row it opens through; a/// failed one says so on the grid, and Retry sends again each that failed. Landed, a message each, they still stand/// as one grid, each tile naming its message; Star and Delete for me take every picture of it. Pictures of two taps/// stay two grids.#[test]fn one_taps_pictures_stand_as_one_grid_before_and_after_they_land() {    let (dir, handle) = phone();    chats(&handle);    let paths: Vec<String> = ["a.jpg", "b.jpg", "c.jpg"].iter().enumerate().map(|(i, n)| file(&dir, n, 1_000 + i * 100)).collect();    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "Our walk", "attachments": paths.iter().map(|p| picture(p)).collect::<Vec<_>>() }));    let rows = queued(&handle, BIMAL);    assert_eq!(rows.len(), 3, "a row each, as WhatsApp takes one picture a message");    let grid = &sent["bubble"];    assert_eq!(grid["kind"], "album", "{grid}");    assert_eq!(grid["text"], "Our walk");    assert_eq!(grid["state"], "Waiting to send");    assert_eq!(sent["message"], format!("{PENDING}{}", rows[0].0));    let tiles: Vec<Value> = grid["media"].as_array().unwrap().iter().map(|m| m["message"].clone()).collect();    assert_eq!(tiles, rows.iter().map(|(id, _)| json!(format!("{PENDING}{id}"))).collect::<Vec<_>>(), "each tile opens through its row");    let opened = answer(&handle, "chat.picture", json!({ "message": tiles[2], "index": 0, "dir": dir.path().join("open").to_string_lossy() }));    assert_eq!(std::fs::read(opened["path"].as_str().unwrap()).unwrap(), std::fs::read(&paths[2]).unwrap(), "the third tile is the third picture");    assert_eq!(bubbles(&answer(&handle, "chat.thread", json!({ "thread": BIMAL }))).iter().filter(|b| b["message"].as_str().is_some_and(|m| m.starts_with(PENDING))).count(), 1, "one grid on the page");    // The second could not go: the grid says so, and Retry sends it again, the others as they were.    mark(&handle, &rows[0].0, json!({ "status": "sending" }));    mark(&handle, &rows[1].0, json!({ "status": "failed", "error": "No connection." }));    let last = foot(&answer(&handle, "chat.thread", json!({ "thread": BIMAL })));    assert_eq!(last["state"], "Not sent: No connection.");    assert_eq!(last["actions"][0], "retry");    answer(&handle, "chat.act", json!({ "act": "retry", "thread": BIMAL, "message": sent["message"] }));    let after = queued(&handle, BIMAL);    assert_eq!(after.iter().map(|(_, r)| r["status"].clone()).collect::<Vec<_>>(), [json!("sending"), json!("queued"), json!("queued")]);    // Landed, a message each under the ids fixed at the tap: still one grid, the words on the first.    for (i, (id, row)) in rows.iter().enumerate() {        mark(&handle, id, json!({ "status": "sent", "sent_at": iso(0) }));        landed_picture(&handle, &format!("m-{i}"), if i == 0 { "Our walk" } else { "" }, row["sent_external_id"].as_str().unwrap(), row["media_key"].as_str().unwrap());    }    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    let shown = bubbles(&page);    assert_eq!(shown.len(), 2, "the question and the grid: {page}");    let grid = &shown[1];    assert_eq!((grid["message"].clone(), grid["kind"].clone(), grid["text"].clone()), (json!("m-0"), json!("album"), json!("Our walk")));    assert_eq!(grid["media"].as_array().unwrap().iter().map(|m| m["message"].clone()).collect::<Vec<_>>(), [Value::Null, json!("m-1"), json!("m-2")], "the first's own, then each its message");    // Starred, every picture; deleted for him, every picture.    let starred = answer(&handle, "chat.act", json!({ "act": "star", "thread": BIMAL, "message": "m-0" }));    assert_eq!(starred["bubble"]["media"].as_array().map(Vec::len), Some(3), "the answer is the grid");    let stars = crate::phone::cotton_chat::read(&handle.client(), "test.stars", |ctx| {        Ok(one(ctx, &format!("SELECT COUNT(*) AS n FROM {MESSAGES} WHERE thread_id = ? AND starred_at IS NOT NULL"), &[text(BIMAL.to_string())])?.and_then(|r| r.get("n").cloned()).unwrap_or(Value::Null))    })    .unwrap();    assert_eq!(stars, json!(3));    answer(&handle, "chat.act", json!({ "act": "deleteMine", "thread": BIMAL, "message": "m-0" }));    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    assert_eq!(bubbles(&page).len(), 1, "the grid went whole: {page}");}/// RULE (FEEDBACK-4 B3): two taps' pictures, one after the other, stay two grids; one picture stays a photo.#[test]fn two_taps_stay_two_grids() {    let (dir, handle) = phone();    chats(&handle);    let (a, b, c) = (file(&dir, "a.jpg", 900), file(&dir, "b.jpg", 950), file(&dir, "c.jpg", 990));    answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "attachments": [picture(&a), picture(&b)] }));    answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "attachments": [picture(&c)] }));    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    let pending: Vec<Value> = bubbles(&page).into_iter().filter(|b| b["message"].as_str().is_some_and(|m| m.starts_with(PENDING))).collect();    assert_eq!(pending.iter().map(|b| b["kind"].clone()).collect::<Vec<_>>(), [json!("album"), json!("photo")], "{page}");    assert!(pending[1]["media"][0]["message"].is_null(), "a picture alone names no other message");}/// RULE (FEEDBACK-3): the same in a group: the row goes to the group's WhatsApp address, from the number that/// brought the group in.#[test]fn a_picture_goes_to_a_whatsapp_group() {    let (dir, handle) = phone();    group(&handle);    let path = file(&dir, "top.jpg", 1_500);    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": GROUP, "text": "We made it", "attachments": [picture(&path)] }));    assert_eq!(sent["bubble"]["state"], "Waiting to send");    assert_eq!(sent["bubble"]["kind"], "photo");    let rows = queued(&handle, GROUP);    assert_eq!(rows.len(), 1);    assert_eq!(rows[0].1["to"], GROUP_JID);    assert_eq!(rows[0].1["account"], LINKED);    assert_eq!(rows[0].1["kind"], "photo");    assert_eq!(rows[0].1["body"], "We made it");}/// RULE (FEEDBACK-3): a picture the Mac could not send says why with Retry; Retry puts the same row back, with the/// same file and WhatsApp id, so it never goes twice and no second entry is made. A file of another kind (a/// document) is refused in words before anything is kept or queued.#[test]fn a_failed_picture_says_why_and_retries_as_the_same_entry() {    let (dir, handle) = phone();    chats(&handle);    let path = file(&dir, "late.jpg", 2_500);    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "attachments": [picture(&path)] }));    let message = sent["message"].as_str().unwrap().to_string();    assert!(sent["bubble"]["text"].is_null(), "no caption, no words");    assert!(!sent["bubble"]["actions"].as_array().unwrap().contains(&json!("copy")), "nothing to copy");    let (id, before) = queued(&handle, BIMAL).remove(0);    assert_eq!(refused(&handle, "chat.act", json!({ "act": "retry", "thread": BIMAL, "message": message })), "cannot", "waiting is not failed");    // The Mac took it ("Sending…"), then said why it could not.    mark(&handle, &id, json!({ "status": "sending" }));    assert_eq!(foot(&answer(&handle, "chat.thread", json!({ "thread": BIMAL })))["state"], "Sending…");    mark(&handle, &id, json!({ "status": "failed", "error": "This file is too large for WhatsApp." }));    let last = foot(&answer(&handle, "chat.thread", json!({ "thread": BIMAL })));    assert_eq!(last["state"], "Not sent: This file is too large for WhatsApp.");    assert_eq!(last["actions"][0], "retry");    assert_eq!(last["kind"], "photo", "still the picture, from the phone's copy");    let retried = answer(&handle, "chat.act", json!({ "act": "retry", "thread": BIMAL, "message": message }));    assert_eq!(retried["bubble"]["state"], "Waiting to send");    let rows = queued(&handle, BIMAL);    assert_eq!(rows.len(), 1, "no second entry");    let (again, after) = &rows[0];    assert_eq!(again, &id);    assert_eq!(after["status"], "queued");    assert_eq!(after["sent_external_id"], before["sent_external_id"], "the same WhatsApp id: WhatsApp keeps one");    assert_eq!(after["media_key"], before["media_key"], "the same file");    // A PDF now goes as a document (`a_document_goes_to_whatsapp_under_its_name`); a server without `file_name` still    // refuses it (`an_outbox_of_before_takes_no_document`).    let _ = dir;}#[test]fn a_waveform_is_whatsapps_sixty_four_bytes() {    use base64::Engine as _;    let decode = |w: Option<String>| base64::engine::general_purpose::STANDARD.decode(w.unwrap()).unwrap();    assert_eq!(waveform_of(&[]), None);    assert_eq!(decode(waveform_of(&[0.5])), vec![50; 64], "a short note's one sample, repeated");    let long: Vec<f64> = (0..640).map(|i| if i % 10 == 9 { 1.0 } else { 0.1 }).collect();    assert_eq!(decode(waveform_of(&long)), vec![100; 64], "each the loudest of its stretch");    assert_eq!(decode(waveform_of(&[f64::NAN, 2.0, -1.0])).iter().copied().max(), Some(100), "clamped, nothing out of 0..100");}/// RULE (FEEDBACK-2 A): writing to a number he already has a WhatsApp chat with opens that chat, never a second one:/// the store keeps one chat per number, so a person on both is one entry in the list. Before, the start was refused/// ("UNIQUE constraint failed: cotton_msg_threads.workspace_id, cotton_msg_threads.contact_id").#[test]fn a_number_with_a_whatsapp_chat_opens_that_chat() {    let (_dir, handle) = phone();    chats(&handle);    let rows = |handle: &CottonHandle| answer(handle, "chat.list", json!({}))["rows"].as_array().map_or(0, Vec::len);    let before = rows(&handle);    let started = answer(&handle, "chat.start", json!({ "number": "+15550100222" }));    assert_eq!(started["thread"], BIMAL, "{started}");    assert_eq!(rows(&handle), before, "one entry per person");    link(&handle);    let started = answer(&handle, "chat.start", json!({ "number": "+15550100222" }));    assert_eq!(started["thread"], BIMAL);    assert_eq!(started["place"]["mark"], "via WhatsApp", "{started}");}// ── one place to write to a number (owner, 23 Nov 2026, FEEDBACK-2 A) ──/// The number the Mac's link reads through, invented.const LINK_ACCOUNT: &str = "15550009999@s.whatsapp.net";/// Someone on WhatsApp only, someone on Cotton, invented.const NOOR: &str = "+15550107001";const ASHA: &str = "+15550107002";/// The copy is linked: the Mac's link brought one message in (its `meta.source`), in Bimal's WhatsApp chat.fn link(handle: &CottonHandle) {    let ws = workspace(handle);    sql(        handle,        "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at, external_id, meta) VALUES ('m-linked', ?, ?, 'in', 'whatsapp', 'live', 'Leaving now', ?, ?, 'WA-LINK_ACCOUNT-1', ?)",        &[t(BIMAL), t(&ws), t(&iso(20)), t(&iso(20)), t(&json!({ "source": { "service": "WhatsApp linked device", "account": LINK_ACCOUNT, "chat": "15550100222@s.whatsapp.net" } }).to_string())],    );}/// Asha is one of the person's Cotton connections: her contact says she is on Cotton.fn asha_on_cotton(handle: &CottonHandle) {    let ws = workspace(handle);    sql(handle, "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, on_cotton_at, created_at, updated_at) VALUES ('c-asha', ?, '15550107002', 'Asha Example', '2026-11-01', '2026-11-01', '2026-11-01')", &[t(&ws)]);}fn outbox_rows(handle: &CottonHandle) -> usize {    let found = crate::phone::cotton_chat::read(&handle.client(), "test.outbox", |ctx| {        Ok(json!(tables::list_records(ctx, &object(json!({ "table": OUTBOX, "limit": 500 }))).map_err(tool)?["records"].as_array().map_or(0, Vec::len)))    })    .unwrap();    found.as_u64().unwrap() as usize}/// RULE: on a copy linked to WhatsApp through the Mac, writing to a number that is not one of the person's Cotton/// connections opens a chat whose words go to that number's WhatsApp: the start, the header and the composer all say/// "via WhatsApp" before anything is sent, no invite is offered, and Send queues one outbox row for the Mac to that/// number's WhatsApp address, from the linked number, "Waiting to send" until the Mac takes it.#[test]fn a_number_not_on_cotton_goes_to_its_whatsapp_on_a_linked_copy() {    let (_dir, handle) = phone();    chats(&handle);    link(&handle);    let started = answer(&handle, "chat.start", json!({ "number": NOOR }));    assert_eq!(started["place"], json!({ "id": "whatsapp", "mark": "via WhatsApp" }), "{started}");    assert!(started.get("reach").is_none(), "no invite where the words go to WhatsApp: {started}");    let thread = started["thread"].as_str().unwrap().to_string();    let page = answer(&handle, "chat.thread", json!({ "thread": thread }));    assert_eq!(page["header"]["place"]["mark"], "via WhatsApp", "{page}");    assert_eq!(page["composer"]["place"]["mark"], "via WhatsApp");    assert!(page.get("reach").is_none_or(Value::is_null), "no \"Not on Cotton yet\" banner: {page}");    assert_eq!((&page["composer"]["attach"], &page["composer"]["button"]), (&json!(true), &json!("mic")), "pictures, videos and voice notes, as a WhatsApp chat's (2dcdf0d411)");    // Disappearing messages stand on every chat (CONTRACT "B.1"): here, as on a WhatsApp chat, his own copy's.    assert_eq!(page["timer"]["seconds"], 0, "off by default: {page}");    assert_eq!(page["timer"]["note"], "Only your copy in Cotton. WhatsApp keeps its own.");    assert_eq!(page["timer"]["choices"].as_array().unwrap().len(), 4);    let typed = answer(&handle, "chat.compose", json!({ "thread": thread, "text": "Hello" }));    assert_eq!(typed["place"]["id"], "whatsapp", "the field says it as it is written in: {typed}");    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": thread, "text": "Hello from Cotton" }));    assert_eq!(sent["flush"], false, "never the Cotton network");    assert_eq!(sent["bubble"]["state"], "Waiting to send");    let rows = queued(&handle, &thread);    assert_eq!(rows.len(), 1, "one row, the one tap");    let (id, row) = &rows[0];    assert_eq!(row["to"], "15550107001@s.whatsapp.net", "their WhatsApp, by the number");    assert_eq!(row["account"], LINK_ACCOUNT, "from the number the link reads through");    assert_eq!(row["channel"], "whatsapp");    assert_eq!(row["body"], "Hello from Cotton");    assert_eq!(row["status"], "queued");    let external = row["sent_external_id"].as_str().unwrap().to_string();    assert_eq!(foot(&answer(&handle, "chat.thread", json!({ "thread": thread })))["state"], "Waiting to send");    // The Mac sent it, and its link brought it back under the id fixed at the tap, into this same chat: it stands once.    mark(&handle, id, json!({ "status": "sent" }));    message(&handle, "m-noor-echo", &thread, "Hello from Cotton", &external, 0);    let page = answer(&handle, "chat.thread", json!({ "thread": thread }));    let bubbles: Vec<&Value> = page["items"].as_array().unwrap().iter().filter(|i| i["item"] == "bubble").collect();    assert_eq!(bubbles.len(), 1, "{page}");    assert_eq!(bubbles[0]["message"], "m-noor-echo");    // His timer on it sends nothing: no flush, nothing more queued for the Mac, and the chat still goes to WhatsApp.    let set = answer(&handle, "chat.act", json!({ "act": "timer", "thread": thread, "seconds": 86_400 }));    assert_eq!(set["flush"], false, "nothing to send anywhere: {set}");    assert_eq!(queued(&handle, &thread).len(), 1, "no row for the Mac");    let page = answer(&handle, "chat.thread", json!({ "thread": thread }));    assert_eq!(page["timer"]["seconds"], 86_400, "{page}");    assert_eq!(page["composer"]["place"]["mark"], "via WhatsApp");}/// RULE: a number WhatsApp holds no account for says so, in the words the Mac writes (`send::NOT_ON_WHATSAPP`):/// "Not sent: This number is not on WhatsApp", with Retry, as other failures.#[test]fn a_number_whatsapp_does_not_know_is_not_sent_with_its_reason() {    let (_dir, handle) = phone();    chats(&handle);    link(&handle);    let thread = answer(&handle, "chat.start", json!({ "number": NOOR }))["thread"].as_str().unwrap().to_string();    answer(&handle, "chat.act", json!({ "act": "send", "thread": thread, "text": "Are you there?" }));    let (id, _) = queued(&handle, &thread).remove(0);    mark(&handle, &id, json!({ "status": "failed", "error": cotton_core::messages::send::NOT_ON_WHATSAPP }));    let last = foot(&answer(&handle, "chat.thread", json!({ "thread": thread })));    assert_eq!(last["state"], "Not sent: This number is not on WhatsApp");    assert_eq!(last["tick"], "failed");    assert_eq!(last["actions"][0], "retry");}/// RULE: a number that is one of the person's Cotton connections stays on Cotton on a linked copy, and says so:/// "on Cotton" on the start, the header and the field; Send goes on Cotton, never to the outbox.#[test]fn a_cotton_connection_stays_on_cotton_and_says_so() {    let (_dir, handle) = phone();    chats(&handle);    link(&handle);    asha_on_cotton(&handle);    let started = answer(&handle, "chat.start", json!({ "number": ASHA }));    assert_eq!(started["place"], json!({ "id": "cotton", "mark": "on Cotton" }), "{started}");    assert_eq!(started["reach"], "on");    let thread = started["thread"].as_str().unwrap().to_string();    let page = answer(&handle, "chat.thread", json!({ "thread": thread }));    assert_eq!(page["header"]["place"]["mark"], "on Cotton", "{page}");    assert_eq!(page["composer"]["place"]["mark"], "on Cotton");    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": thread, "text": "See you" }));    assert_eq!(sent["flush"], true, "the Cotton network carries it");    assert_eq!(outbox_rows(&handle), 0, "nothing for the Mac");    // A WhatsApp chat on the same linked copy says where its words go too.    assert_eq!(answer(&handle, "chat.thread", json!({ "thread": BIMAL }))["header"]["place"]["mark"], "via WhatsApp");}/// RULE: a copy with no WhatsApp link sees no change: a number not on Cotton opens the Cotton chat with the invite,/// no mark anywhere, and Send goes on Cotton to wait for them.#[test]fn an_unlinked_copy_sees_no_change() {    let (_dir, handle) = phone();    chats(&handle);    let started = answer(&handle, "chat.start", json!({ "number": NOOR }));    assert!(started.get("place").is_none(), "{started}");    assert_eq!(started["reach"], "notYet");    let thread = started["thread"].as_str().unwrap().to_string();    let page = answer(&handle, "chat.thread", json!({ "thread": thread }));    assert!(page["header"].get("place").is_none(), "{page}");    assert!(page["composer"].get("place").is_none());    assert_eq!(page["reach"]["state"], "notYet", "the invite, as before");    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": thread, "text": "Join me" }));    assert_eq!(sent["flush"], true);    assert_eq!(outbox_rows(&handle), 0);    assert!(answer(&handle, "chat.thread", json!({ "thread": BIMAL }))["header"].get("place").is_none(), "an unlinked WhatsApp chat: no mark");}/// RULE (coordinator for the owner, 23 Nov 2026, settling FEEDBACK-2 A's open case): someone whose chat came from/// WhatsApp first and who is one of his Cotton connections is written to on Cotton, in that same chat: their earlier/// WhatsApp messages stay in it, each marked "via WhatsApp", the new ones "on Cotton", and the field says "on Cotton"./// Once they are no longer a Cotton connection the field says "via WhatsApp" again before the next send, and it goes/// to their WhatsApp through the Mac.#[test]fn a_whatsapp_first_person_on_cotton_is_written_to_on_cotton_in_the_same_chat() {    let (_dir, handle) = phone();    chats(&handle);    link(&handle);    sql(&handle, "UPDATE cotton_msg_contacts SET on_cotton_at = '2026-11-20' WHERE id = 'c-bimal'", &[]);    let started = answer(&handle, "chat.start", json!({ "number": "+15550100222" }));    assert_eq!(started["thread"], BIMAL, "the same chat, never a second: {started}");    assert_eq!(started["place"]["mark"], "on Cotton");    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    assert_eq!(page["composer"]["place"]["mark"], "on Cotton", "{page}");    assert_eq!(page["header"]["place"]["mark"], "on Cotton");    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "Moved over here" }));    assert_eq!(sent["flush"], true, "the Cotton network carries it: {sent}");    assert_eq!(outbox_rows(&handle), 0, "nothing for the Mac");    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    let bubbles: Vec<&Value> = page["items"].as_array().unwrap().iter().filter(|i| i["item"] == "bubble").collect();    let marks: Vec<(&str, &str)> = bubbles.iter().map(|b| (b["text"].as_str().unwrap_or(""), b["place"]["mark"].as_str().unwrap_or(""))).collect();    assert_eq!(        marks,        vec![("Are you coming?", "via WhatsApp"), ("Leaving now", "via WhatsApp"), ("Moved over here", "on Cotton")],        "WhatsApp's messages stay, each with its own mark: {page}"    );    assert_eq!(answer(&handle, "chat.list", json!({}))["rows"].as_array().unwrap().iter().filter(|r| r["thread"] == BIMAL).count(), 1, "one entry");    // No longer a Cotton connection: the mark goes back before the next send, and the words go to WhatsApp.    sql(&handle, "UPDATE cotton_msg_contacts SET on_cotton_at = NULL WHERE id = 'c-bimal'", &[]);    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    assert_eq!(page["composer"]["place"]["mark"], "via WhatsApp", "{page}");    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "Back on WhatsApp" }));    assert_eq!(sent["flush"], false);    let rows = queued(&handle, BIMAL);    assert_eq!(rows.len(), 1);    assert_eq!(rows[0].1["to"], "15550100222@s.whatsapp.net");    assert_eq!(rows[0].1["account"], LINK_ACCOUNT, "from the number their messages came in through");}/// Every row of `table` in this copy, as JSON objects sorted by id, with `skip` columns left out.fn rows_of_table(handle: &CottonHandle, table: &str, skip: &[&str]) -> Vec<Value> {    let (table, skip): (String, Vec<String>) = (table.to_string(), skip.iter().map(|s| s.to_string()).collect());    let found = crate::phone::cotton_chat::read(&handle.client(), "test.rows", move |ctx| {        let all = rows(ctx, &format!("SELECT * FROM {table} ORDER BY id"), &[])?;        Ok(json!(all.into_iter().map(|mut r| { for k in &skip { r.remove(k); } Value::Object(r) }).collect::<Vec<_>>()))    })    .unwrap();    found.as_array().unwrap().clone()}/// RULE (coordinator, 23 Nov 2026: the take-over touches the owner's data, so prove nothing is lost or split): when a/// chat that came from WhatsApp first becomes its person's Cotton chat, ONE column of ONE row changes, the chat's/// `external_key` (to `cotton:+…`); its id, and so everything kept by it (its files under `{file}/messages/{thread}/`,/// previews, Storage by chat, the timer, pins, mute, unread, drafts), and every message row stay exactly as they were./// The Mac's next import of that WhatsApp chat lands in the same chat with no duplicate and no second chat; and the/// person's other phone, given the synced row, agrees: one chat, written to on Cotton, and their Cotton message lands/// in it.#[test]fn taking_over_a_whatsapp_chat_keeps_every_part_of_it() {    let (_dir, handle) = phone();    chats(&handle);    link(&handle);    sql(&handle, "UPDATE cotton_msg_messages SET starred_at = '2026-11-22T10:00:00.000Z' WHERE id = 'm-linked'", &[]);    sql(&handle, "UPDATE cotton_msg_threads SET pinned_at = '2026-11-22T10:00:00.000Z', muted_until = '2099-01-01T00:00:00.000Z', draft = 'half a thought' WHERE id = ?", &[t(BIMAL)]);    sql(&handle, "UPDATE cotton_msg_contacts SET on_cotton_at = '2026-11-20' WHERE id = 'c-bimal'", &[]);    // `updated_at`, `_hlc` and `_born` are sync's own stamps on any write (a pin writes them too), never the chat's.    let threads_before = rows_of_table(&handle, "cotton_msg_threads", &["external_key", "updated_at", "_hlc", "_born"]);    let messages_before = rows_of_table(&handle, "cotton_msg_messages", &[]);    let listed = |h: &CottonHandle| answer(h, "chat.list", json!({}))["rows"].as_array().unwrap().iter().find(|r| r["thread"] == BIMAL).cloned().unwrap();    let row_before = listed(&handle);    let starred_before = answer(&handle, "chat.starred", json!({}));    assert_eq!(answer(&handle, "chat.start", json!({ "number": "+15550100222" }))["thread"], BIMAL);    assert_eq!(rows_of_table(&handle, "cotton_msg_threads", &["external_key", "updated_at", "_hlc", "_born"]), threads_before, "only the key moved");    assert_eq!(rows_of_table(&handle, "cotton_msg_messages", &[]), messages_before, "no message touched");    let key = rows_of_table(&handle, "cotton_msg_threads", &[]).into_iter().find(|r| r["id"] == BIMAL).unwrap()["external_key"].clone();    assert_eq!(key, "cotton:+15550100222");    let row_after = listed(&handle);    for field in ["unread", "pinned", "muted", "draft", "name"] {        assert_eq!(row_after[field], row_before[field], "{field} follows the chat");    }    assert_eq!(answer(&handle, "chat.starred", json!({})), starred_before, "starred follows it");    // A kept file's key is `{file}/messages/{thread}/…`, written on its message row: every message row is unchanged,    // and so is the id they name.    // The Mac's next import of that WhatsApp chat: a message already held and a new one, the reader's own shape.    let ws = workspace(&handle);    let ns = cotton_store::file_identity::Namespace::of_database(&crate::phone::cotton_chat::namespace(&handle.client()).unwrap());    let batch: cotton_core::import::envelope::ImportBatch = serde_json::from_value(json!({        "workspaceId": ws, "channel": "whatsapp",        "dm": { "label": "Bimal Example", "phone": "+15550100222" },        "messages": [            { "senderLabel": "Bimal Example", "direction": "in", "body": "Leaving now", "sentAt": iso(20), "externalId": "WA-LINK_ACCOUNT-1" },            { "senderLabel": "Bimal Example", "direction": "in", "body": "Here now", "sentAt": iso(1), "externalId": "WA-AFTER-1" }        ],        "newThreadId": cotton_core::import::whatsapp_keys::whatsapp_thread_id(&ns, "dm:+15550100222"),    }))    .unwrap();    handle        .client()        .import_rows("test.import", &["cotton_msg_threads", "cotton_msg_messages", "cotton_msg_thread_participants", "cotton_msg_contacts", "cotton_workspaces", "cotton_imports"], &mut |seams| {            let report = cotton_client::messages_import::import_messages(&seams.replica.driver, &ns, &batch, seams.clock, seams.random, seams.ids).map_err(|e| e.to_string())?;            Ok(json!({ "inserted": report.totals.inserted }))        })        .expect("the import");    let threads = rows_of_table(&handle, "cotton_msg_threads", &[]);    assert_eq!(threads.len(), threads_before.len(), "no second chat");    let held: Vec<Value> = rows_of_table(&handle, "cotton_msg_messages", &[]).into_iter().filter(|m| m["external_id"] == "WA-LINK_ACCOUNT-1" || m["external_id"] == "WA-AFTER-1").collect();    assert_eq!(held.len(), 2, "the one already held once, the new one once: {held:?}");    assert!(held.iter().all(|m| m["thread_id"] == BIMAL), "both in the same chat");    // The person's other phone, given the synced rows: one chat, on Cotton, and a Cotton message from them lands in it.    let (_other_dir, other) = phone();    chats(&other);    link(&other);    sql(&other, "UPDATE cotton_msg_contacts SET on_cotton_at = '2026-11-20' WHERE id = 'c-bimal'", &[]);    sql(&other, "UPDATE cotton_msg_threads SET external_key = 'cotton:+15550100222' WHERE id = ?", &[t(BIMAL)]);    assert_eq!(answer(&other, "chat.thread", json!({ "thread": BIMAL }))["composer"]["place"]["mark"], "on Cotton");    let ns_other = crate::phone::cotton_chat::namespace(&other.client()).unwrap();    let landed = crate::phone::cotton_chat::write(&other.client(), "test.land", move |ctx| crate::phone::cotton_chat::ensure_thread(ctx, &ns_other, "+15550100222", None, None, None, true).map(Value::from)).unwrap();    assert_eq!(landed, BIMAL, "their Cotton message meets the same chat");    assert_eq!(rows_of_table(&other, "cotton_msg_threads", &[]).len(), threads_before.len(), "no orphan: the same chats on both phones");}/// RULE (seen on emulator-5558, 23 Nov 2026): a phone whose server still serves the outbox of before (no file/// columns: a Worker not yet deployed with them) offers words only in a WhatsApp chat, as before, and refuses a file/// before anything is kept or queued; words still go. Once the server's outbox carries the columns (the kit merged/// add-only on its next deploy), the same chat offers pictures and voice notes and a picture goes.#[test]fn a_server_outbox_without_file_columns_offers_words_only() {    let (dir, handle) = phone();    chats(&handle);    let ws = workspace(&handle);    let held = handle.client().with_writer(|replica| replica.driver.all("SELECT definition FROM cotton_table_definitions WHERE workspace_id = ? AND id = 'outbox'", &[t(&ws)]).map_err(|e| e.to_string())).unwrap();    let merged = held[0].text("definition").unwrap().to_string();    let mut before: Value = serde_json::from_str(&merged).unwrap();    before["columns"].as_array_mut().unwrap().retain(|c| !["kind", "voice", "mime", "size_bytes", "width", "height", "duration_ms", "waveform", "preview", "part"].contains(&c["key"].as_str().unwrap()));    sql(&handle, "UPDATE cotton_table_definitions SET definition = ? WHERE workspace_id = ? AND id = 'outbox'", &[t(&before.to_string()), t(&ws)]);    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    assert_eq!(page["composer"]["attach"], false, "{page}");    assert_ne!(page["composer"]["button"], "mic", "no voice note either: {page}");    let path = file(&dir, "early.jpg", 1_000);    assert_eq!(refused(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "Look", "attachments": [picture(&path)] })), "cannot");    assert!(queued(&handle, BIMAL).is_empty(), "nothing queued");    let kept = handle.client().with_writer(|replica| replica.driver.all("SELECT key FROM _media WHERE key LIKE ?", &[t(&format!("%/messages/{BIMAL}/%"))]).map_err(|e| e.to_string())).unwrap();    assert!(kept.is_empty(), "nothing kept: {kept:?}");    answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "Words still go" }));    assert_eq!(queued(&handle, BIMAL).len(), 1);    sql(&handle, "UPDATE cotton_table_definitions SET definition = ? WHERE workspace_id = ? AND id = 'outbox'", &[t(&merged), t(&ws)]);    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    assert_eq!(page["composer"]["attach"], true, "the merged kit's outbox takes files: {page}");    answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "attachments": [picture(&path)] }));    assert_eq!(queued(&handle, BIMAL).len(), 2);}/// RULE (FEEDBACK-2 A, the coordinator's gap a): a chat whose words go to WhatsApp offers no Cotton call (the person/// is reached on WhatsApp, where Cotton cannot ring them); a Cotton connection's chat still offers them.#[test]fn a_chat_that_goes_to_whatsapp_offers_no_cotton_call() {    let (_dir, handle) = phone();    chats(&handle);    link(&handle);    let noor = answer(&handle, "chat.start", json!({ "number": NOOR }))["thread"].as_str().unwrap().to_string();    let page = answer(&handle, "chat.thread", json!({ "thread": noor }));    assert_eq!(page["header"]["place"]["id"], "whatsapp");    assert!(page["header"].get("calls").is_none_or(Value::is_null), "no call buttons: {}", page["header"]);    asha_on_cotton(&handle);    let asha = answer(&handle, "chat.start", json!({ "number": ASHA }))["thread"].as_str().unwrap().to_string();    let page = answer(&handle, "chat.thread", json!({ "thread": asha }));    assert_eq!(page["header"]["place"]["id"], "cotton");    assert!(page["header"]["calls"].as_array().is_some_and(|c| !c.is_empty()), "a Cotton connection is still called: {}", page["header"]);}/// RULE (FEEDBACK-2 A, the coordinator's gap b): the chat list shows a text on its way to WhatsApp as the chat's last/// line, his own, with where it stands in its bubble's words, and the chat comes to the top as any message he writes;/// a failed one says why; once the Mac's link brings it back, the message itself is the last line and no state.#[test]fn the_chat_list_says_where_a_waiting_text_stands() {    let (_dir, handle) = phone();    chats(&handle);    link(&handle);    let thread = answer(&handle, "chat.start", json!({ "number": NOOR }))["thread"].as_str().unwrap().to_string();    answer(&handle, "chat.act", json!({ "act": "send", "thread": thread, "text": "On my way" }));    let row = |h: &CottonHandle| {        let list = answer(h, "chat.list", json!({}));        let rows = list["rows"].as_array().unwrap().clone();        (rows.iter().position(|r| r["thread"] == thread.as_str()).unwrap(), rows.into_iter().find(|r| r["thread"] == thread.as_str()).unwrap())    };    let (at, listed) = row(&handle);    assert_eq!(at, 0, "at the top, as any message he writes");    assert!(listed["when"].is_string(), "{listed}");    let last = &listed["lastLine"];    assert_eq!((&last["text"], &last["mine"], &last["tick"], &last["state"]), (&json!("On my way"), &json!(true), &json!("sending"), &json!("Waiting to send")), "{listed}");    let (id, row_data) = queued(&handle, &thread).remove(0);    mark(&handle, &id, json!({ "status": "failed", "error": cotton_core::messages::send::NOT_ON_WHATSAPP }));    let last = row(&handle).1["lastLine"].clone();    assert_eq!((&last["tick"], &last["state"]), (&json!("failed"), &json!("Not sent: This number is not on WhatsApp")));    mark(&handle, &id, json!({ "status": "sent", "error": null }));    let external = row_data["sent_external_id"].as_str().unwrap().to_string();    message(&handle, "m-noor-back", &thread, "On my way", &external, 0);    let last = row(&handle).1["lastLine"].clone();    assert_eq!(last["text"], "On my way");    assert!(last.get("state").is_none_or(Value::is_null), "gone: no state: {last}");}/// RULE (FEEDBACK-2 A, the coordinator's gap c): a number written in a message is answered where it stands, so a tap/// on it opens that number's chat as `chat.start` routes it: here, a number not on Cotton, to its WhatsApp.#[test]fn a_number_in_a_message_opens_its_routed_chat() {    let (_dir, handle) = phone();    chats(&handle);    link(&handle);    message(&handle, "m-number", BIMAL, "Noor's new number is +1 555 010 7001, write to her", "WA-NUMBER-1", 0);    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    let bubble = page["items"].as_array().unwrap().iter().find(|i| i["message"] == "m-number").cloned().unwrap();    assert_eq!(bubble["numbers"], json!([{ "at": [21, 36], "number": NOOR }]), "{bubble}");    let opened = answer(&handle, "chat.start", json!({ "number": bubble["numbers"][0]["number"] }));    assert_eq!(opened["place"]["id"], "whatsapp", "{opened}");    let other = page["items"].as_array().unwrap().iter().find(|i| i["message"] == "m-linked").cloned().unwrap();    assert!(other.get("numbers").is_none(), "no number, nothing answered: {other}");}/// RULE (owner, 24 Nov 2026: links open inside Comms): a link written in a message is answered where it stands and/// where it goes, so a tap opens it in Comms; a bare domain is words, and the sentence's full stop is not the link's.#[test]fn a_link_in_a_message_is_answered_where_it_stands() {    let (_dir, handle) = phone();    chats(&handle);    message(&handle, "m-link", BIMAL, "The plan is at https://example.com/plan. Or example.org", "WA-LINK-1", 0);    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    let bubble = page["items"].as_array().unwrap().iter().find(|i| i["message"] == "m-link").cloned().unwrap();    assert_eq!(bubble["links"], json!([{ "at": [15, 39], "url": "https://example.com/plan" }]), "{bubble}");    let other = page["items"].as_array().unwrap().iter().find(|i| i["message"] == "m-linked").cloned();    assert!(other.is_none_or(|o| o.get("links").is_none()), "no link, nothing answered");}// ── polls shown (FEEDBACK-3, CONTRACT "Polls shown") ──fn poll_message(handle: &CottonHandle, poll: Value) {    message(handle, "m-poll", BIMAL, "Dinner on Friday?", "WA-POLL-1", 5);    sql(handle, "UPDATE cotton_msg_messages SET meta = ? WHERE id = 'm-poll'", &[t(&json!({ "poll": poll }).to_string())]);}fn poll_of(handle: &CottonHandle) -> Value {    let page = answer(handle, "chat.thread", json!({ "thread": BIMAL }));    page["items"].as_array().unwrap().iter().find(|i| i["message"] == "m-poll").cloned().unwrap()}/// RULE (FEEDBACK-3 "polls shown"): a WhatsApp poll in a chat is drawn as a poll, not as words: the question, how many/// may be chosen, each option with its count, its bar and who chose it by the name the chat knows them by ("You"/// first; a number Cotton has no name for as the number), and the total; a vote arriving (its row changed, as the/// Mac's change or a sync brings it) is answered at once, the bars moved.#[test]fn a_whatsapp_poll_is_drawn_as_a_poll_and_follows_its_votes() {    let (_dir, handle) = phone();    chats(&handle);    poll_message(        &handle,        json!({ "question": "Dinner on Friday?", "options": [{ "text": "Thai", "votes": 1 }, { "text": "Pizza", "votes": 1 }], "selectable": 1,                "voters": [{ "who": "15550100222", "options": [0], "at": iso(4) }, { "who": "me", "options": [1], "at": iso(3) }] }),    );    let bubble = poll_of(&handle);    assert_eq!(bubble["kind"], "poll");    assert!(bubble.get("text").is_none_or(Value::is_null), "the words are the card's: {bubble}");    let poll = &bubble["poll"];    assert_eq!(poll["question"], "Dinner on Friday?");    assert_eq!(poll["choose"], "Select one");    assert_eq!(poll["said"], "2 votes");    assert_eq!(poll["options"][0], json!({ "text": "Thai", "votes": 1, "said": "1 vote", "percent": 50, "voters": ["Bimal Example"] }));    assert_eq!(poll["options"][1], json!({ "text": "Pizza", "votes": 1, "said": "1 vote", "percent": 50, "voters": ["You"], "mine": true }));    assert_eq!(poll["votesTitle"], "Votes");    // A vote comes: someone Cotton has no name for picks Thai; the page answers it.    let changed = cotton_core::import::messages_engine::voted(        serde_json::from_value(poll_meta(&handle)).unwrap(),        "15550109999",        &[0],        &iso(1),    );    sql(&handle, "UPDATE cotton_msg_messages SET meta = ? WHERE id = 'm-poll'", &[t(&json!({ "poll": changed }).to_string())]);    let poll = poll_of(&handle)["poll"].clone();    assert_eq!(poll["said"], "3 votes");    assert_eq!((&poll["options"][0]["votes"], &poll["options"][0]["percent"]), (&json!(2), &json!(67)));    assert_eq!(poll["options"][0]["voters"], json!(["Bimal Example", "+1 555-010-9999"]));    assert_eq!(poll["options"][1]["percent"], 33);}fn poll_meta(handle: &CottonHandle) -> Value {    let row = crate::phone::cotton_chat::read(&handle.client(), "test.poll", |ctx| {        Ok(crate::phone::cotton_chat::one(ctx, "SELECT meta FROM cotton_msg_messages WHERE id = 'm-poll'", &[])?.map(|r| r["meta"].clone()).unwrap_or(Value::Null))    })    .unwrap();    let meta: Value = match row {        Value::String(text) => serde_json::from_str(&text).unwrap(),        other => other,    };    meta["poll"].clone()}/// RULE: a poll from an exported chat keeps its totals and names nobody; no "Select" line.#[test]fn an_exported_poll_is_drawn_with_its_totals() {    let (_dir, handle) = phone();    chats(&handle);    poll_message(&handle, json!({ "question": "Trek or beach?", "options": [{ "text": "Trek", "votes": 3 }, { "text": "Beach", "votes": 1 }] }));    let poll = poll_of(&handle)["poll"].clone();    assert!(poll.get("choose").is_none(), "{poll}");    assert_eq!(poll["said"], "4 votes");    assert_eq!(poll["options"][0], json!({ "text": "Trek", "votes": 3, "said": "3 votes", "percent": 75 }));}// ---- Replies and reactions (owner, FEEDBACK-3, 23 Nov 2026; CONTRACT "Replies and reactions") ----fn bubble_of(page: &Value, message: &str) -> Value {    page["items"].as_array().unwrap().iter().find(|i| i["message"] == message).cloned().unwrap_or_else(|| panic!("no bubble {message}: {page}"))}fn said(handle: &CottonHandle, method: &str, request: Value) -> (String, String) {    let error = over(&handle.client(), method, &request).err().unwrap_or_else(|| panic!("{method} answered"));    (error.code, error.message)}/// A picture of Bimal's, as the Mac's link lands one: no words, its file named.fn picture_message(handle: &CottonHandle, id: &str, external: &str) {    let ws = workspace(handle);    let media = json!([{ "key": "db/messages/bimal/abc.jpg", "contentType": "image/jpeg", "kind": "image", "width": 800, "height": 600 }]);    sql(        handle,        "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, media, sent_at, created_at, external_id) VALUES (?, ?, ?, 'in', 'whatsapp', 'live', '', ?, ?, ?, ?)",        &[t(id), t(BIMAL), t(&ws), t(&media.to_string()), t(&iso(20)), t(&iso(20)), t(external)],    );}/// RULE (FEEDBACK-3): a reply he writes in a WhatsApp chat quotes the original and goes to WhatsApp as a reply: the/// tap's row names the original's WhatsApp id (`quoted_id`), the bubble shows the quote at once, and it goes once/// (Retry puts back the same row and id). Before, the quote was dropped and the reply went as a plain text.#[test]fn a_reply_in_a_whatsapp_chat_quotes_the_original_and_goes_once() {    let (_dir, handle) = phone();    chats(&handle);    let original = format!("m-{BIMAL}");    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    let actions = bubble_of(&page, &original)["actions"].clone();    assert!(actions.as_array().unwrap().contains(&json!("reply")) && actions.as_array().unwrap().contains(&json!("react")), "{actions}");    let strip = answer(&handle, "chat.compose", json!({ "thread": BIMAL, "replyTo": original }));    assert_eq!(strip["strip"]["kind"], "reply", "{strip}");    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "Yes, at seven" }));    assert_eq!(sent["bubble"]["state"], "Waiting to send");    assert_eq!(sent["bubble"]["reply"]["line"], "Are you coming?", "the quote at once: {sent}");    let rows = queued(&handle, BIMAL);    assert_eq!(rows.len(), 1, "one entry for one tap");    let (id, row) = &rows[0];    assert_eq!(row["quoted_id"], format!("x-{BIMAL}"), "the original's WhatsApp id");    assert_eq!(row["body"], "Yes, at seven");    assert!(row.get("quoted_text").is_none(), "no copy of the quoted words travels");    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    assert_eq!(foot(&page)["reply"]["line"], "Are you coming?", "the pending bubble keeps its quote");    assert!(page["composer"]["strip"].is_null(), "the strip is gone after Send: {}", page["composer"]);    mark(&handle, id, json!({ "status": "failed", "error": "WhatsApp did not take it: offline" }));    let retried = answer(&handle, "chat.act", json!({ "act": "retry", "thread": BIMAL, "message": format!("{PENDING}{id}") }));    assert_eq!(retried["bubble"]["state"], "Waiting to send");    let again = queued(&handle, BIMAL);    assert_eq!(again.len(), 1, "no second entry");    assert_eq!((&again[0].0, &again[0].1["sent_external_id"], &again[0].1["quoted_id"]), (id, &row["sent_external_id"], &row["quoted_id"]), "the same row, id and quote");    // The Mac sent it and its link brought it back as a reply: it draws its quote as a Cotton reply does.    let external = row["sent_external_id"].as_str().unwrap().to_string();    mark(&handle, id, json!({ "status": "sent" }));    message_with(&handle, "m-back", BIMAL, "Yes, at seven", &external);    sql(&handle, "UPDATE cotton_msg_messages SET reply_to_id = ? WHERE id = 'm-back'", &[t(&original)]);    let back = bubble_of(&answer(&handle, "chat.thread", json!({ "thread": BIMAL })), "m-back");    assert_eq!(back["reply"]["line"], "Are you coming?", "{back}");    assert_eq!(back["reply"]["message"], original.as_str());}/// RULE (FEEDBACK-3): a reply to a picture (or a voice note or video) goes the same way; a picture sent as a reply/// carries the quote on the tap's first row.#[test]fn a_reply_to_a_picture_and_a_picture_as_a_reply_carry_the_quote() {    let (dir, handle) = phone();    chats(&handle);    picture_message(&handle, "m-pic", "WAPIC1");    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "Lovely", "replyTo": "m-pic" }));    assert_eq!(sent["bubble"]["reply"]["line"], "Photo", "{sent}");    assert_eq!(queued(&handle, BIMAL)[0].1["quoted_id"], "WAPIC1");    let path = file(&dir, "mine.jpg", 1_200);    answer(&handle, "chat.compose", json!({ "thread": BIMAL, "replyTo": format!("m-{BIMAL}") }));    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "Here", "attachments": [picture(&path), picture(&path)] }));    assert_eq!(sent["bubble"]["reply"]["line"], "Are you coming?", "{sent}");    let rows: Vec<_> = queued(&handle, BIMAL).into_iter().filter(|(_, r)| r.get("kind").is_some()).collect();    assert_eq!(rows.len(), 2);    assert_eq!(rows[0].1["quoted_id"], format!("x-{BIMAL}"), "the quote on the first row, with the caption");    assert!(rows[1].1.get("quoted_id").is_none_or(Value::is_null), "only once: {:?}", rows[1].1);}/// RULE (FEEDBACK-3): a reaction he puts on a WhatsApp message shows at once and goes to WhatsApp as a reaction, one/// row naming the message's WhatsApp id. Changed twice before the Mac comes, only the last goes (the same row and/// id, rewritten); taken off, the removal goes. Once the Mac has taken it, a change is a new row with its own id. The/// state stands on the message: "Reaction waiting to send", "Sending reaction…", "Reaction not sent: <why>" with/// Retry, which puts back the same row and id. Sent, the state goes and its emoji leaves the row. The chat never/// moves for a reaction.#[test]fn a_reaction_goes_to_whatsapp_and_only_the_last_while_it_waits() {    let (_dir, handle) = phone();    chats(&handle);    let original = format!("m-{BIMAL}");    let line_before = answer(&handle, "chat.list", json!({}))["rows"].as_array().unwrap().iter().find(|r| r["thread"] == BIMAL).cloned().unwrap()["lastLine"].clone();    let reacted = answer(&handle, "chat.act", json!({ "act": "react", "thread": BIMAL, "message": original, "emoji": "👍" }));    assert_eq!(reacted["flush"], false, "never the Cotton network");    assert_eq!(reacted["bubble"]["reactions"], json!([{ "emoji": "👍", "count": 1, "mine": true }]), "drawn at once: {reacted}");    assert_eq!(reacted["bubble"]["state"], "Reaction waiting to send");    let rows = queued(&handle, BIMAL);    assert_eq!(rows.len(), 1);    let (first, row) = rows[0].clone();    assert_eq!((&row["reaction_to"], &row["emoji"], &row["body"], &row["to"]), (&json!(format!("x-{BIMAL}")), &json!("👍"), &json!(""), &json!("15550100222@s.whatsapp.net")));    let fixed = row["sent_external_id"].clone();    // Changed twice while the Mac is away: still one row, the same id, the last emoji.    answer(&handle, "chat.act", json!({ "act": "react", "thread": BIMAL, "message": original, "emoji": "❤️" }));    answer(&handle, "chat.act", json!({ "act": "react", "thread": BIMAL, "message": original, "emoji": "😂" }));    let rows = queued(&handle, BIMAL);    assert_eq!(rows.len(), 1, "only the last goes");    assert_eq!((&rows[0].0, &rows[0].1["emoji"], &rows[0].1["sent_external_id"]), (&first, &json!("😂"), &fixed));    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    assert_eq!(bubble_of(&page, &original)["reactions"], json!([{ "emoji": "😂", "count": 1, "mine": true }]));    assert!(page["items"].as_array().unwrap().iter().all(|i| !i["message"].as_str().unwrap_or_default().starts_with(PENDING)), "a reaction is no bubble of its own");    let line_after = answer(&handle, "chat.list", json!({}))["rows"].as_array().unwrap().iter().find(|r| r["thread"] == BIMAL).cloned().unwrap()["lastLine"].clone();    assert_eq!(line_after, line_before, "the chat's line is unchanged");    // The Mac took it: a change now is a new row, its own id.    mark(&handle, &first, json!({ "status": "sending" }));    assert_eq!(bubble_of(&answer(&handle, "chat.thread", json!({ "thread": BIMAL })), &original)["state"], "Sending reaction…");    answer(&handle, "chat.act", json!({ "act": "unreact", "thread": BIMAL, "message": original }));    let rows = queued(&handle, BIMAL);    assert_eq!(rows.len(), 2);    let (second, row2) = rows.iter().find(|(id, _)| *id != first).cloned().unwrap();    assert_eq!(row2["emoji"], "", "taken off");    assert_ne!(row2["sent_external_id"], fixed, "a new WhatsApp id once the first was taken");    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    let gone = bubble_of(&page, &original);    assert!(gone.get("reactions").is_none_or(|r| r.as_array().is_some_and(Vec::is_empty)), "taken off at once: {gone}");    // The older one failing offers nothing: only the newest counts. The newest failing says why, with Retry.    mark(&handle, &first, json!({ "status": "failed", "error": "old" }));    let b = bubble_of(&answer(&handle, "chat.thread", json!({ "thread": BIMAL })), &original);    assert_eq!(b["state"], "Reaction waiting to send", "{b}");    assert_ne!(b["actions"][0], "retry");    assert_eq!(refused(&handle, "chat.act", json!({ "act": "retry", "thread": BIMAL, "message": original })), "cannot", "waiting is not failed");    mark(&handle, &second, json!({ "status": "failed", "error": "WhatsApp did not take it: offline" }));    let b = bubble_of(&answer(&handle, "chat.thread", json!({ "thread": BIMAL })), &original);    assert_eq!(b["state"], "Reaction not sent: WhatsApp did not take it: offline");    assert_eq!(b["actions"][0], "retry", "{b}");    let retried = answer(&handle, "chat.act", json!({ "act": "retry", "thread": BIMAL, "message": original }));    assert_eq!(retried["bubble"]["state"], "Reaction waiting to send");    let rows = queued(&handle, BIMAL);    assert_eq!(rows.len(), 2, "no new entry");    let back = rows.iter().find(|(id, _)| *id == second).unwrap();    assert_eq!((&back.1["status"], &back.1["sent_external_id"]), (&json!("queued"), &row2["sent_external_id"]), "the same row and id");    // Sent: the state goes, and its emoji leaves the row when he next reacts here.    mark(&handle, &second, json!({ "status": "sent" }));    mark(&handle, &first, json!({ "status": "sent" }));    let b = bubble_of(&answer(&handle, "chat.thread", json!({ "thread": BIMAL })), &original);    assert!(b.get("state").is_none_or(Value::is_null), "{b}");    message(&handle, "m-later", BIMAL, "See you", "x-later", 1);    answer(&handle, "chat.act", json!({ "act": "react", "thread": BIMAL, "message": "m-later", "emoji": "👋" }));    let rows = queued(&handle, BIMAL);    assert_eq!(rows.iter().find(|(id, _)| *id == first).unwrap().1["emoji"], "", "a sent reaction's emoji leaves the row");}/// RULE (FEEDBACK-3): in a WhatsApp group, a reply and a reaction go to the group's address from the number that/// brought it in, naming the member's message by its WhatsApp id.#[test]fn a_reply_and_a_reaction_go_to_a_whatsapp_group() {    let (_dir, handle) = phone();    group(&handle);    answer(&handle, "chat.act", json!({ "act": "send", "thread": GROUP, "text": "Saturday works", "replyTo": "m-g1" }));    answer(&handle, "chat.act", json!({ "act": "react", "thread": GROUP, "message": "m-g1", "emoji": "🙌" }));    let rows = queued(&handle, GROUP);    assert_eq!(rows.len(), 2);    for (_, row) in &rows {        assert_eq!((&row["to"], &row["account"]), (&json!(GROUP_JID), &json!(LINKED)));    }    assert!(rows.iter().any(|(_, r)| r.get("quoted_id") == Some(&json!("x-g1")) && r.get("body") == Some(&json!("Saturday works"))), "{rows:?}");    assert!(rows.iter().any(|(_, r)| r.get("reaction_to") == Some(&json!("x-g1")) && r.get("emoji") == Some(&json!("🙌"))), "{rows:?}");}/// RULE (FEEDBACK-3): only a message WhatsApp holds can be replied or reacted to, and the rest refuse plainly: a/// deleted one, one erased from this copy, an export's (whose id is a fingerprint WhatsApp never knew). Nothing is/// queued for any of them, and their bubbles offer neither.#[test]fn a_reply_to_a_deleted_or_erased_message_refuses_plainly() {    let (_dir, handle) = phone();    chats(&handle);    message(&handle, "m-gone", BIMAL, "Old words", "WAGONE1", 10);    sql(&handle, "UPDATE cotton_msg_messages SET body = '', deleted_at = ? WHERE id = 'm-gone'", &[t(&iso(5))]);    message(&handle, "m-export", BIMAL, "From the export", "txt2:abcdef", 40);    let deleted = "That message was deleted, so you can't reply to it.";    assert_eq!(said(&handle, "chat.compose", json!({ "thread": BIMAL, "replyTo": "m-gone" })), ("deleted".to_string(), deleted.to_string()));    assert_eq!(said(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "Hm", "replyTo": "m-gone" })), ("deleted".to_string(), deleted.to_string()));    assert_eq!(said(&handle, "chat.act", json!({ "act": "react", "thread": BIMAL, "message": "m-gone", "emoji": "👍" })).1, "That message was deleted, so you can't react to it.");    assert_eq!(said(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "Hm", "replyTo": "m-never" })), ("not_found".to_string(), "That message is no longer here.".to_string()), "erased: no longer in this copy");    assert_eq!(said(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "Hm", "replyTo": "m-export" })).0, "not_in_whatsapp");    assert_eq!(said(&handle, "chat.act", json!({ "act": "react", "thread": BIMAL, "message": "m-export", "emoji": "👍" })).1, "That message isn't in WhatsApp, so you can't react to it there.");    assert!(queued(&handle, BIMAL).is_empty(), "nothing queued");    // Opening the chat sweeps the deleted message away (erased, "Deleted for everyone in WhatsApp"): its own id is    // no longer here, and the marker in its place offers nothing and refuses as deleted.    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    let export = bubble_of(&page, "m-export")["actions"].clone();    assert!(!export.as_array().unwrap().contains(&json!("reply")) && !export.as_array().unwrap().contains(&json!("react")), "{export}");    assert_eq!(said(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "Hm", "replyTo": "m-gone" })).0, "not_found", "erased");    let marker = page["items"].as_array().unwrap().iter().find(|i| i["actions"] == json!(["select"])).cloned().unwrap_or_else(|| panic!("no marker: {page}"));    assert_eq!(said(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "Hm", "replyTo": marker["message"] })), ("deleted".to_string(), deleted.to_string()));    assert!(queued(&handle, BIMAL).is_empty(), "nothing queued");}/// RULE (coordinator, 23 Nov 2026): a phone whose server still serves the outbox of before (no `quoted_id`,/// `reaction_to`, `emoji`: a Worker not yet deployed with them) offers neither Reply nor React in a WhatsApp chat, and/// refuses both before anything is written; words still go. Once the served outbox carries them, both are offered.#[test]fn a_server_outbox_without_reply_columns_offers_neither() {    let (_dir, handle) = phone();    chats(&handle);    let ws = workspace(&handle);    let held = handle.client().with_writer(|replica| replica.driver.all("SELECT definition FROM cotton_table_definitions WHERE workspace_id = ? AND id = 'outbox'", &[t(&ws)]).map_err(|e| e.to_string())).unwrap();    let merged = held[0].text("definition").unwrap().to_string();    let mut before: Value = serde_json::from_str(&merged).unwrap();    before["columns"].as_array_mut().unwrap().retain(|c| !ANSWER_COLUMNS.contains(&c["key"].as_str().unwrap()));    sql(&handle, "UPDATE cotton_table_definitions SET definition = ? WHERE workspace_id = ? AND id = 'outbox'", &[t(&before.to_string()), t(&ws)]);    let original = format!("m-{BIMAL}");    let actions = bubble_of(&answer(&handle, "chat.thread", json!({ "thread": BIMAL })), &original)["actions"].clone();    assert!(!actions.as_array().unwrap().contains(&json!("reply")) && !actions.as_array().unwrap().contains(&json!("react")), "{actions}");    assert_eq!(refused(&handle, "chat.act", json!({ "act": "react", "thread": BIMAL, "message": original, "emoji": "👍" })), "cannot");    assert_eq!(refused(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "Hm", "replyTo": original })), "cannot");    assert_eq!(refused(&handle, "chat.compose", json!({ "thread": BIMAL, "replyTo": original })), "cannot");    assert!(queued(&handle, BIMAL).is_empty(), "nothing queued");    answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "Words still go" }));    assert_eq!(queued(&handle, BIMAL).len(), 1);    sql(&handle, "UPDATE cotton_table_definitions SET definition = ? WHERE workspace_id = ? AND id = 'outbox'", &[t(&merged), t(&ws)]);    let actions = bubble_of(&answer(&handle, "chat.thread", json!({ "thread": BIMAL })), &original)["actions"].clone();    assert!(actions.as_array().unwrap().contains(&json!("reply")) && actions.as_array().unwrap().contains(&json!("react")), "{actions}");}/// RULE (FEEDBACK-3): a reply and a reaction that come in from WhatsApp draw as a Cotton chat's do: the reply's quote/// (linked by the import from `reply_to_external_id`) and the reaction under the message, his own from WhatsApp/// marked his.#[test]fn replies_and_reactions_from_whatsapp_draw_as_cottons() {    let (_dir, handle) = phone();    chats(&handle);    let ws = workspace(&handle);    let original = format!("m-{BIMAL}");    message(&handle, "m-their-reply", BIMAL, "I am, yes", "WAREPLY2", 5);    sql(&handle, "UPDATE cotton_msg_messages SET reply_to_id = ? WHERE id = 'm-their-reply'", &[t(&original)]);    for (actor, emoji) in [("15550100222", "🎉"), ("self", "👍")] {        let id = cotton_core::messages::ids::reaction_row_id(&original, actor).unwrap();        sql(&handle, "INSERT INTO cotton_msg_reactions (id, workspace_id, thread_id, message_id, actor, emoji, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)", &[t(&id), t(&ws), t(BIMAL), t(&original), t(actor), t(emoji), t(&iso(4))]);    }    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    let reply = bubble_of(&page, "m-their-reply");    assert_eq!((&reply["reply"]["line"], &reply["reply"]["message"]), (&json!("Are you coming?"), &json!(original)), "{reply}");    let reactions = bubble_of(&page, &original)["reactions"].clone();    let mut got: Vec<(String, bool)> = reactions.as_array().unwrap().iter().map(|r| (r["emoji"].as_str().unwrap().to_string(), r["mine"].as_bool().unwrap())).collect();    got.sort();    assert_eq!(got, vec![("🎉".to_string(), false), ("👍".to_string(), true)], "{reactions}");}// ---- Documents and votes (coordinator for the owner, FEEDBACK-3, 23 Nov 2026; CONTRACT "Documents and votes") ----fn friday_poll(handle: &CottonHandle) {    poll_message(        handle,        json!({ "question": "Dinner on Friday?", "options": [{ "text": "Thai", "votes": 1 }, { "text": "Pizza", "votes": 0 }], "selectable": 1,                "voters": [{ "who": "15550100222", "options": [0], "at": iso(4) }] }),    );}fn votes(handle: &CottonHandle) -> Vec<(String, Map<String, Value>)> {    queued(handle, BIMAL).into_iter().filter(|(_, row)| row["kind"] == "poll_vote").collect()}fn picked(row: &Map<String, Value>) -> Vec<String> {    serde_json::from_str(row["options"].as_str().unwrap()).unwrap()}/// RULE (FEEDBACK-3 "polls voted"): on a WhatsApp poll his Mac's link sends to, a tap on an option is his vote: drawn/// on the poll at once ("You" with the others), one outbox row naming the poll's WhatsApp id and the words he picked,/// "Vote waiting to send" on the poll. While the Mac has not taken it a change rewrites that row, so only the last/// goes; his own choice tapped again takes his vote back. Once taken, a change is a row of its own. Failed, it says/// why and Retry sends the same row again; sent, the poll stands as the echo leaves it.#[test]fn a_whatsapp_poll_is_voted_from_cotton_and_goes_once() {    let (_dir, handle) = phone();    chats(&handle);    friday_poll(&handle);    let bubble = poll_of(&handle);    assert_eq!(bubble["poll"]["votable"], true, "{bubble}");    assert!(bubble["poll"]["spoken"].as_str().unwrap().ends_with("Tap an option to vote"), "{bubble}");    let voted = answer(&handle, "chat.act", json!({ "act": "vote", "thread": BIMAL, "message": "m-poll", "option": 0 }));    assert_eq!(voted["flush"], false, "never the Cotton network");    let poll = &voted["bubble"]["poll"];    assert_eq!(poll["options"][0]["voters"], json!(["You", "Bimal Example"]), "drawn at once: {poll}");    assert_eq!(poll["options"][0]["mine"], true);    assert_eq!(poll["said"], "2 votes");    assert_eq!(voted["bubble"]["state"], "Vote waiting to send");    let rows = votes(&handle);    assert_eq!(rows.len(), 1);    let (id, row) = rows[0].clone();    assert_eq!((row["target"].as_str(), picked(&row)), (Some("WA-POLL-1"), vec!["Thai".to_string()]));    assert_eq!(row["to"], "15550100222@s.whatsapp.net");    assert_eq!(row["body"], "");    assert!(row["sent_external_id"].as_str().unwrap().starts_with("3EB0"), "{row:?}");    assert_eq!(messages_in(&handle, BIMAL), json!(2), "a vote is no message");    // A change while it waits rewrites the row: one choice, so Pizza takes Thai's place; Pizza again takes it back.    answer(&handle, "chat.act", json!({ "act": "vote", "thread": BIMAL, "message": "m-poll", "option": 1 }));    let rows = votes(&handle);    assert_eq!((rows.len(), rows[0].0.as_str(), picked(&rows[0].1)), (1, id.as_str(), vec!["Pizza".to_string()]));    let back = answer(&handle, "chat.act", json!({ "act": "vote", "thread": BIMAL, "message": "m-poll", "option": 1 }));    assert!(picked(&votes(&handle)[0].1).is_empty(), "taken back");    assert!(back["bubble"]["poll"]["options"].as_array().unwrap().iter().all(|o| o.get("mine").is_none()), "{back}");    // The Mac took it; the next tap is a row of its own, with its own WhatsApp id.    mark(&handle, &id, json!({ "status": "sending" }));    answer(&handle, "chat.act", json!({ "act": "vote", "thread": BIMAL, "message": "m-poll", "option": 0 }));    let rows = votes(&handle);    assert_eq!(rows.len(), 2);    let (second, row) = rows.iter().find(|(r, _)| *r != id).cloned().unwrap();    assert_ne!(row["sent_external_id"], rows.iter().find(|(r, _)| *r == id).unwrap().1["sent_external_id"]);    assert_eq!(picked(&row), vec!["Thai".to_string()]);    // Failed: why, and Retry first; Retry sends the same row again.    mark(&handle, &second, json!({ "status": "failed", "error": "WhatsApp did not take it" }));    let b = poll_of(&handle);    assert_eq!(b["state"], "Vote not sent: WhatsApp did not take it", "{b}");    assert_eq!(b["actions"][0], "retry", "{b}");    answer(&handle, "chat.act", json!({ "act": "retry", "thread": BIMAL, "message": "m-poll" }));    assert_eq!(votes(&handle).iter().find(|(r, _)| *r == second).unwrap().1["status"], "queued");    // Sent, and the echo brings his vote back as the link writes it: the poll stands as it was drawn.    mark(&handle, &second, json!({ "status": "sent", "sent_at": iso(0) }));    let echoed = cotton_core::import::messages_engine::voted(serde_json::from_value(poll_meta(&handle)).unwrap(), "me", &[0], &iso(0));    sql(&handle, "UPDATE cotton_msg_messages SET meta = ? WHERE id = 'm-poll'", &[t(&json!({ "poll": echoed }).to_string())]);    let b = poll_of(&handle);    assert!(b.get("state").is_none_or(Value::is_null), "{b}");    assert_eq!(b["poll"]["options"][0]["voters"], json!(["You", "Bimal Example"]));}/// RULE: a poll of several choices adds and takes away each tapped option.#[test]fn a_poll_of_several_choices_adds_and_takes_away() {    let (_dir, handle) = phone();    chats(&handle);    poll_message(&handle, json!({ "question": "Which days?", "options": [{ "text": "Sat", "votes": 0 }, { "text": "Sun", "votes": 0 }], "selectable": 0, "voters": [] }));    answer(&handle, "chat.act", json!({ "act": "vote", "thread": BIMAL, "message": "m-poll", "option": 0 }));    answer(&handle, "chat.act", json!({ "act": "vote", "thread": BIMAL, "message": "m-poll", "option": 1 }));    assert_eq!(picked(&votes(&handle)[0].1), vec!["Sat".to_string(), "Sun".to_string()]);    answer(&handle, "chat.act", json!({ "act": "vote", "thread": BIMAL, "message": "m-poll", "option": 0 }));    assert_eq!(picked(&votes(&handle)[0].1), vec!["Sun".to_string()]);}/// RULE: no vote where WhatsApp cannot take one: an exported poll (no link, no id WhatsApp holds), or a server whose/// outbox has no `target` and `options` yet. Nothing is drawn to tap, and the act is refused.#[test]fn no_vote_on_an_exported_poll_or_an_outbox_of_before() {    let (_dir, handle) = phone();    chats(&handle);    poll_message(&handle, json!({ "question": "Trek or beach?", "options": [{ "text": "Trek", "votes": 3 }, { "text": "Beach", "votes": 1 }] }));    assert!(poll_of(&handle)["poll"].get("votable").is_none());    assert_eq!(refused(&handle, "chat.act", json!({ "act": "vote", "thread": BIMAL, "message": "m-poll", "option": 0 })), "cannot");    sql(&handle, "DELETE FROM cotton_msg_messages WHERE id = 'm-poll'", &[]);    friday_poll(&handle);    let ws = workspace(&handle);    let held = handle.client().with_writer(|replica| replica.driver.all("SELECT definition FROM cotton_table_definitions WHERE workspace_id = ? AND id = 'outbox'", &[t(&ws)]).map_err(|e| e.to_string())).unwrap();    let mut before: Value = serde_json::from_str(held[0].text("definition").unwrap()).unwrap();    before["columns"].as_array_mut().unwrap().retain(|c| !["target", "options", "file_name"].contains(&c["key"].as_str().unwrap()));    sql(&handle, "UPDATE cotton_table_definitions SET definition = ? WHERE workspace_id = ? AND id = 'outbox'", &[t(&before.to_string()), t(&ws)]);    assert!(poll_of(&handle)["poll"].get("votable").is_none());    assert_eq!(refused(&handle, "chat.act", json!({ "act": "vote", "thread": BIMAL, "message": "m-poll", "option": 0 })), "cannot");    assert!(votes(&handle).is_empty());}/// RULE (FEEDBACK-3 "files"): a file picked as a file goes to WhatsApp as a document, under its own name, larger than/// a picture may be (WhatsApp's 100 MB): one outbox row, kind document, its name, type and size, no preview; the/// bubble is the file from the phone's own copy, "Waiting to send". Words with it go first as their own text.#[test]fn a_document_goes_to_whatsapp_under_its_name() {    let (dir, handle) = phone();    chats(&handle);    let path = file(&dir, "trip-plan.pdf", 17 * 1024 * 1024);    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": "The plan", "attachments": [{ "path": path, "mime": "application/pdf", "name": "Trip plan.pdf", "kind": "file" }] }));    let rows = queued(&handle, BIMAL);    assert_eq!(rows.len(), 2, "the words, then the document: {rows:?}");    assert_eq!(rows[0].1["body"], "The plan");    let row = &rows[1].1;    assert_eq!(row["kind"], "document");    assert_eq!(row["file_name"], "Trip plan.pdf");    assert_eq!(row["mime"], "application/pdf");    assert_eq!(row["size_bytes"].as_f64(), Some((17 * 1024 * 1024) as f64), "past a picture's 16 MB");    assert!(row.get("preview").is_none_or(Value::is_null), "{row:?}");    let bubble = &sent["bubble"];    assert_eq!(bubble["state"], "Waiting to send", "{bubble}");    let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL }));    let last = foot(&page);    assert_eq!(last["kind"], "file", "{last}");    assert_eq!(last["media"][0]["name"], "Trip plan.pdf", "{last}");    // A picture picked as a file goes as a document too, as WhatsApp's own Document does.    let photo = file(&dir, "scan.jpg", 2_000);    answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "attachments": [{ "path": photo, "mime": "image/jpeg", "name": "scan.jpg", "kind": "file" }] }));    assert_eq!(queued(&handle, BIMAL).last().unwrap().1["kind"], "document");}/// RULE: a server whose outbox has no `file_name` yet takes no document: refused in words, nothing kept; pictures/// still go.#[test]fn an_outbox_of_before_takes_no_document() {    let (dir, handle) = phone();    chats(&handle);    let ws = workspace(&handle);    let held = handle.client().with_writer(|replica| replica.driver.all("SELECT definition FROM cotton_table_definitions WHERE workspace_id = ? AND id = 'outbox'", &[t(&ws)]).map_err(|e| e.to_string())).unwrap();    let mut before: Value = serde_json::from_str(held[0].text("definition").unwrap()).unwrap();    before["columns"].as_array_mut().unwrap().retain(|c| c["key"] != "file_name");    sql(&handle, "UPDATE cotton_table_definitions SET definition = ? WHERE workspace_id = ? AND id = 'outbox'", &[t(&before.to_string()), t(&ws)]);    let path = file(&dir, "plan.pdf", 1_000);    let (code, words) = said(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "attachments": [{ "path": path, "mime": "application/pdf", "name": "plan.pdf", "kind": "file" }] }));    assert_eq!((code.as_str(), words.as_str()), ("cannot", "Only pictures, videos and voice notes go to WhatsApp for now."));    assert!(queued(&handle, BIMAL).is_empty());    let photo = file(&dir, "beach.jpg", 1_000);    answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "attachments": [picture(&photo)] }));    assert_eq!(queued(&handle, BIMAL).len(), 1);}/// RULE (FEEDBACK-4 B2, 23 Nov 2026): Delete on a WhatsApp chat says what it means, that it leaves Cotton only and/// WhatsApp keeps it, in the swipe's question and the held row's; once done the chat is off the list and stays off.#[test]fn a_whatsapp_chats_delete_says_it_leaves_cotton_only_and_it_goes() {    let (_dir, handle) = phone();    chats(&handle);    let list = answer(&handle, "chat.list", json!({}));    let row = list["rows"].as_array().unwrap().iter().find(|r| r["thread"] == BIMAL).unwrap_or_else(|| panic!("{list}")).clone();    let asked = "Delete your chat with Bimal Example from Cotton? It goes from this phone and your other devices, and stays in WhatsApp. A new message brings it back here.";    let delete = row["hold"].as_array().unwrap().iter().find(|a| a["act"] == "deleteChat").unwrap();    assert_eq!(delete["confirm"], asked, "{row}");    let held = row["hold"].as_array().unwrap().iter().find(|a| a["act"] == "deleteChat").unwrap();    assert_eq!(held["confirm"], asked);    answer(&handle, "chat.act", json!({ "act": "deleteChat", "thread": BIMAL }));    for _ in 0..2 {        let list = answer(&handle, "chat.list", json!({}));        assert!(list["rows"].as_array().unwrap().iter().all(|r| r["thread"] != BIMAL), "{list}");    }}#[path = "chat_whatsapp_change_tests.rs"]mod changes;#[path = "chat_whatsapp_source_tests.rs"]mod source_acts;#[path = "chat_senders_source_tests.rs"]mod senders_source_acts;/// RULE (FEEDBACK-4 B4): in a WhatsApp chat whose outbox carries `link`, a link written offers its card, and the/// text goes with it: the row holds the card for the Mac, and the bubble draws it at once.#[test]fn a_whatsapp_text_carries_its_link_card() {    let (_dir, handle) = phone();    chats(&handle);    let words = "the route https://example.org/walks";    assert_eq!(answer(&handle, "chat.compose", json!({ "thread": BIMAL, "text": words }))["preview"]["url"], "https://example.org/walks");    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": BIMAL, "text": words, "preview": { "url": "https://example.org/walks", "title": "Hill walks", "site": "Example", "thumb": preview() } }));    assert_eq!(sent["bubble"]["link"]["title"], "Hill walks", "{sent}");    assert_eq!(sent["bubble"]["link"]["thumb"], preview());    let (_, row) = queued(&handle, BIMAL).pop().unwrap();    let card: Value = serde_json::from_str(row["link"].as_str().unwrap()).unwrap();    assert_eq!((card["url"].as_str(), card["title"].as_str(), card["siteName"].as_str()), (Some("https://example.org/walks"), Some("Hill walks"), Some("Example")));    assert_eq!(foot(&answer(&handle, "chat.thread", json!({ "thread": BIMAL })))["link"]["title"], "Hill walks", "drawn while it waits");}