Cotton code
194 lines · 10.8 KB · RustRaw
//! Deleting a chat from the list (FEEDBACK-4 B2, Comms 26 on iPhone): it leaves the list at once and stays gone//! until a genuinely new message arrives; a WhatsApp chat leaves Cotton only. On a Comms copy linked to WhatsApp//! through an invented Mac. Every name, number and line is invented.use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use crate::handle::CottonHandle;use crate::phone::cotton_chat::over;const BIMAL: &str = "11111111-1111-4111-8111-0000000000d1";const ASHA: &str = "11111111-1111-4111-8111-0000000000a1";const LINK_ACCOUNT: &str = "15550009999@s.whatsapp.net";fn phone() -> (tempfile::TempDir, CottonHandle) {    let dir = tempfile::tempdir().unwrap();    let handle = super::mail::tests::comms(&dir, cotton_core::flavor::Flavor::Real);    (dir, handle)}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 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())}/// `minutes` from now (negative: before), as the phone stamps it.fn at(minutes: i64) -> String {    (chrono::Utc::now() + chrono::Duration::minutes(minutes)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true)}/// A WhatsApp message as the Mac's link writes it: whole seconds, its WhatsApp id, the link's account.fn whatsapp_at(minutes: i64) -> String {    (chrono::Utc::now() + chrono::Duration::minutes(minutes)).to_rfc3339_opts(chrono::SecondsFormat::Secs, true).replace('Z', ".000Z")}fn message(handle: &CottonHandle, id: &str, thread: &str, channel: &str, body: &str, sent_at: &str) {    let ws = workspace(handle);    let meta = if channel == "whatsapp" {        json!({ "source": { "service": "WhatsApp linked device", "account": LINK_ACCOUNT, "chat": "15550100222@s.whatsapp.net" } }).to_string()    } else {        "{}".to_string()    };    sql(        handle,        "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at, external_id, meta) VALUES (?, ?, ?, 'in', ?, 'live', ?, ?, ?, ?, ?)",        &[t(id), t(thread), t(&ws), t(channel), t(body), t(sent_at), t(sent_at), t(&format!("WA-{id}")), t(&meta)],    );}/// Bimal's chat came from WhatsApp through the Mac's link (Cotton knows his number), its newest message at `newest`;/// Asha's is on Cotton.fn chats(handle: &CottonHandle, newest: &str) {    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)]);    sql(handle, "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, on_cotton_at, created_at, updated_at) VALUES ('c-asha', ?, '15550100001', 'Asha Example', '2026-11-01', '2026-01-01', '2026-01-01')", &[t(&ws)]);    for (id, key, contact, last) in [(BIMAL, None, "c-bimal", newest.to_string()), (ASHA, Some("cotton:+15550100001"), "c-asha", at(-90))] {        sql(            handle,            "INSERT INTO cotton_msg_threads (id, workspace_id, kind, external_key, contact_id, last_message_at, read_seq, created_at, updated_at) VALUES (?, ?, 'dm', ?, ?, ?, 0, ?, ?)",            &[t(id), t(&ws), key.map_or(SqlValue::Null, t), t(contact), t(&last), t(&last), t(&last)],        );    }    message(handle, "m-b1", BIMAL, "whatsapp", "Are you coming?", &whatsapp_at(-30));    message(handle, "m-b2", BIMAL, "whatsapp", "Leaving now", newest);    message(handle, "m-a1", ASHA, "cotton", "See you at the lake", &at(-90));}fn listed(handle: &CottonHandle) -> Vec<String> {    answer(handle, "chat.list", json!({}))["rows"].as_array().unwrap().iter().filter_map(|r| r["thread"].as_str().map(str::to_string)).collect()}fn bodies(handle: &CottonHandle, thread: &str) -> Vec<String> {    let page = answer(handle, "chat.thread", json!({ "thread": thread }));    page["items"].as_array().unwrap().iter().filter(|i| i["item"] == "bubble").filter_map(|i| i["text"].as_str().map(str::to_string)).collect()}/// What the Mac's link lands: the messages engine's own import, as the Mac runs it over its copy.fn mac_imports(handle: &CottonHandle, messages: Value) {    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": messages,        "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");}fn delete(handle: &CottonHandle, thread: &str) -> Value {    answer(handle, "chat.act", json!({ "act": "deleteChat", "thread": thread }))}/// RULE (owner, FEEDBACK-4 B2): a WhatsApp chat deleted from the list on a linked copy leaves it at once, and the/// counts with it.#[test]fn a_deleted_whatsapp_chat_leaves_the_list_at_once() {    let (_dir, handle) = phone();    chats(&handle, &whatsapp_at(-20));    assert_eq!(listed(&handle), [BIMAL, ASHA]);    assert_eq!(delete(&handle, BIMAL)["said"], "Chat deleted");    assert_eq!(listed(&handle), [ASHA], "gone at once");    assert_eq!(answer(&handle, "chat.list", json!({}))["counts"]["all"], 1);}/// RULE: a chat whose newest message is stamped later than this phone's clock (WhatsApp's stamp is the sending/// phone's, and a Mac or a phone may run a few minutes fast) still leaves the list at once: Delete covers everything/// the chat holds, whatever its stamp.#[test]fn a_chat_stamped_later_than_this_phones_clock_still_leaves() {    let (_dir, handle) = phone();    chats(&handle, &whatsapp_at(3));    delete(&handle, BIMAL);    assert_eq!(listed(&handle), [ASHA], "a message held before the delete never keeps it");    // A genuinely new message, later than anything it held, brings it back, holding only that one.    message(&handle, "m-b3", BIMAL, "whatsapp", "Here now", &whatsapp_at(5));    sql(&handle, "UPDATE cotton_msg_threads SET last_message_at = ? WHERE id = ?", &[t(&whatsapp_at(5)), t(BIMAL)]);    assert_eq!(listed(&handle), [BIMAL, ASHA]);    assert_eq!(bodies(&handle, BIMAL), ["Here now"]);}/// RULE: what WhatsApp already held before the delete never brings the chat back: the Mac's link landing those/// messages again (a re-read, history WhatsApp sends a linked device late) leaves it gone; a new message brings it/// back, holding only what came after.#[test]fn what_whatsapp_already_held_never_brings_a_deleted_chat_back() {    let (_dir, handle) = phone();    chats(&handle, &whatsapp_at(-20));    delete(&handle, BIMAL);    mac_imports(&handle, json!([        { "senderLabel": "Bimal Example", "direction": "in", "body": "Leaving now", "sentAt": whatsapp_at(-20), "externalId": "WA-m-b2" },        { "senderLabel": "Bimal Example", "direction": "in", "body": "Sent before you deleted", "sentAt": whatsapp_at(-1), "externalId": "WA-late-history" },    ]));    assert_eq!(listed(&handle), [ASHA], "WhatsApp held these before the delete");    mac_imports(&handle, json!([{ "senderLabel": "Bimal Example", "direction": "in", "body": "Here now", "sentAt": whatsapp_at(1), "externalId": "WA-new" }]));    assert_eq!(listed(&handle), [BIMAL, ASHA], "a new message brings it back");    assert_eq!(bodies(&handle, BIMAL), ["Here now"]);}/// RULE: one chat holding both Cotton's messages and WhatsApp's (a person on both, FEEDBACK-2 A) leaves whole.#[test]fn a_chat_on_both_cotton_and_whatsapp_leaves_whole() {    let (_dir, handle) = phone();    chats(&handle, &whatsapp_at(-20));    message(&handle, "m-b-cotton", BIMAL, "cotton", "Moved over here", &at(-10));    sql(&handle, "UPDATE cotton_msg_threads SET last_message_at = ? WHERE id = ?", &[t(&at(-10)), t(BIMAL)]);    delete(&handle, BIMAL);    assert_eq!(listed(&handle), [ASHA]);}/// RULE: Delete's question says what it means. A chat holding WhatsApp's messages (its newest from WhatsApp, or a/// person on both whose newest is Cotton's) leaves Cotton only and stays in WhatsApp; a Cotton chat's messages go from/// this phone and the person's other devices.#[test]fn deleting_a_whatsapp_chat_says_it_leaves_cotton_only() {    let (_dir, handle) = phone();    chats(&handle, &whatsapp_at(-20));    let list = answer(&handle, "chat.list", json!({}));    let confirm = |thread: &str| {        let row = list["rows"].as_array().unwrap().iter().find(|r| r["thread"] == thread).unwrap();        let swipe = row["hold"].as_array().unwrap().iter().find(|s| s["act"] == "deleteChat").unwrap().clone();        let held = row["hold"].as_array().unwrap().iter().find(|s| s["act"] == "deleteChat").unwrap().clone();        assert_eq!(swipe["confirm"], held["confirm"], "the long press asks the same");        swipe["confirm"].as_str().unwrap().to_string()    };    assert_eq!(confirm(BIMAL), "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.");    assert_eq!(confirm(ASHA), "Delete your chat with Asha Example? Its messages go from this phone and your other devices.");    // A person on both: the newest message is Cotton's, and WhatsApp still keeps its own.    message(&handle, "m-b-cotton", BIMAL, "cotton", "Moved over here", &at(-10));    let list = answer(&handle, "chat.list", json!({}));    let row = list["rows"].as_array().unwrap().iter().find(|r| r["thread"] == BIMAL).unwrap();    assert_eq!(row["source"], "cotton", "{row}");    let swipe = row["hold"].as_array().unwrap().iter().find(|s| s["act"] == "deleteChat").unwrap();    assert_eq!(swipe["confirm"], "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.");}