use cotton_store::create::apply_schema;use cotton_store::driver::Driver;use rusqlite::types::Valueas RVal;usesuper::*;const WORKSPACE: &str = "11111111-1111-4111-8111-111111111111";const NOW: &str = "2026-10-07T00:00:00.000Z";const ACCOUNT: &str = "15550001111@s.whatsapp.net";/// The caller's half: run a statement over text parameters in `db`.fn reader(db: &Driver) -> implFnMut(&str, &[String]) -> Result<Vec<cotton_store::driver::Row>, String> + '_ {move |sql, params| {let bound: Vec<RVal> = params.iter().map(|param| RVal::Text(param.clone())).collect(); db.all(sql, &bound).map_err(|error| error.to_string()) }}fn target(db: &Driver, thread: &str) -> SendDecision { send_target(&mut reader(db), thread).unwrap()}fn text(value: &str) -> RVal { RVal::Text(value.to_string())}fn file() -> Driver {let db = Driver::open_in_memory().expect("an in-memory file opens"); apply_schema(&db).expect("the schema applies"); db.run("INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)", &[text(WORKSPACE), text("Test Owner"), text("owner"), text(NOW)], ) .unwrap(); db}/// A direct chat with a contact on `phone`, holding one message by `channel`/// whose meta is `meta`.fn chat(db: &Driver, id: &str, phone: &str, channel: &str, meta: &str) { db.run("INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, created_at, updated_at) VALUES (?,?,?,?,?,?)", &[text(&format!("c-{id}")), text(WORKSPACE), text(phone), text("Asha"), text(NOW), text(NOW)], ) .unwrap(); db.run("INSERT INTO cotton_msg_threads (id, workspace_id, contact_id, kind, created_at, updated_at) VALUES (?,?,?,'dm',?,?)", &[text(id), text(WORKSPACE), text(&format!("c-{id}")), text(NOW), text(NOW)], ) .unwrap(); db.run("INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at, meta) VALUES (?,?,?,'in',?,'imported','hello',?,?,?)", &[text(&format!("m-{id}")), text(id), text(WORKSPACE), text(channel), text(NOW), text(NOW), text(meta)], ) .unwrap();}fn connect(db: &Driver, state: &str) { db.run("INSERT INTO cotton_connections (id, workspace_id, kind, name, state, config, created_at, updated_at) VALUES ('conn:whatsapp:+15550001111', ?, 'whatsapp', 'WhatsApp', ?, ?, ?, ?)", &[text(WORKSPACE), text(state), text(&format!(r#"{{"account":"{ACCOUNT}","mac":"m"}}"#)), text(NOW), text(NOW)], ) .unwrap();}fn linked_meta(chat: &str) -> String { format!(r#"{{"source":{{"service":"WhatsApp linked device","account":"{ACCOUNT}","chat":"{chat}"}}}}"#)}/// RULE: A WhatsApp chat sends only through a number linked and reading on the Mac; with no connection row it says "WhatsApp is not linked on your Mac".#[test]fn a_chat_sends_only_through_a_linked_reading_number() {let db = file(); chat(&db, "t1", "919800000001", "whatsapp", &linked_meta("919800000001@s.whatsapp.net")); assert_eq!(target(&db, "t1"), Err(NOT_LINKED)); connect(&db, "reading"); assert_eq!( target(&db, "t1"),Ok(SendTarget { account: ACCOUNT.into(), chat: "919800000001@s.whatsapp.net".into() }) ); db.run("UPDATE cotton_connections SET state = 'paused'", &[]).unwrap(); assert_eq!(target(&db, "t1"), Err(PAUSED)); db.run("UPDATE cotton_connections SET state = 'needs_sign_in'", &[]).unwrap(); assert_eq!(target(&db, "t1"), Err(NEEDS_LINKING)); db.run("UPDATE cotton_connections SET state = 'failed'", &[]).unwrap(); assert_eq!(target(&db, "t1"), Err(NEEDS_LINKING));}// A different reading number cannot make this chat's broken link sendable.// The message box follows the account that actually brought the chat in.#[test]fn another_reading_number_cannot_override_a_chats_needs_sign_in_link() {let db = file(); connect(&db, "needs_sign_in"); db.run("INSERT INTO cotton_connections (id, workspace_id, kind, name, state, config, created_at, updated_at) VALUES ('conn:whatsapp:+15550009999', ?, 'whatsapp', 'Another number', 'reading', ?, ?, ?)", &[text(WORKSPACE), text(r#"{"account":"15550009999@s.whatsapp.net"}"#), text(NOW), text(NOW)], ) .unwrap(); chat(&db, "broken", "15550002222", "whatsapp", &linked_meta("15550002222@s.whatsapp.net")); assert_eq!(target(&db, "broken"), Err(NEEDS_LINKING));}// Owner's no-message-box rule: a live link must never make a status or// broadcast address sendable. The read, local queue and sender share this// predicate, so hiding the composer cannot leave another sending route.#[test]fn status_and_broadcast_chats_never_send_even_through_a_reading_link() {for (id, jid) in [("status", "status@broadcast"), ("broadcast", "15550002222@broadcast")] {let db = file(); connect(&db, "reading"); chat(&db, id, "15550002222", "whatsapp", &linked_meta(jid)); assert_eq!(target(&db, id), Err("This WhatsApp conversation cannot receive a message")); }}// An archived chat is for reading until it is unarchived; the linked// number and usable address alone must not offer a message box.#[test]fn an_archived_chat_cannot_send_until_it_is_unarchived() {let db = file(); connect(&db, "reading"); chat(&db, "archive", "15550002222", "whatsapp", &linked_meta("15550002222@s.whatsapp.net")); assert!(target(&db, "archive").is_ok()); db.run("UPDATE cotton_msg_threads SET archived = 1 WHERE id = 'archive'", &[]).unwrap(); assert_eq!(target(&db, "archive"), Err("This chat is archived")); db.run("UPDATE cotton_msg_threads SET archived = 0 WHERE id = 'archive'", &[]).unwrap(); assert!(target(&db, "archive").is_ok());}// A group another member left still sends; a group the person left takes// no message until their own seat is active again. Membership is native.#[test]fn a_group_the_person_left_cannot_send_until_their_own_seat_is_active() {let db = file(); connect(&db, "reading"); chat(&db, "group", "15550002222", "whatsapp", &linked_meta("120363000000000000@g.us")); db.run("UPDATE cotton_msg_threads SET kind = 'group', contact_id = NULL, title = 'Garden' WHERE id = 'group'", &[]) .unwrap(); db.run("INSERT INTO cotton_msg_thread_participants (id, thread_id, workspace_id, display_name, created_at, left_at, is_self) VALUES ('other', 'group', ?, 'Another gardener', ?, ?, 0), ('self', 'group', ?, 'You', ?, NULL, 1)", &[text(WORKSPACE), text(NOW), text(NOW), text(WORKSPACE), text(NOW)], ).unwrap(); assert!(target(&db, "group").is_ok()); db.run("UPDATE cotton_msg_thread_participants SET left_at = ? WHERE id = 'self'", &[text(NOW)]).unwrap(); assert_eq!(target(&db, "group"), Err("You have left this chat")); db.run("UPDATE cotton_msg_thread_participants SET left_at = NULL WHERE id = 'self'", &[]).unwrap(); assert!(target(&db, "group").is_ok());}/// RULE: Only a chat holding WhatsApp messages sends; an iMessage chat, or one the file does not hold, says so in words.#[test]fn only_a_whatsapp_chat_sends() {let db = file(); connect(&db, "reading"); chat(&db, "t1", "919800000001", "imessage", "{}");let found = send_targets(&mut reader(&db), &["t1".into(), "gone".into()]).unwrap(); assert_eq!(found["t1"], Err(NOT_WHATSAPP)); assert_eq!(found["gone"], Err(NOT_WHATSAPP));}/// RULE: A chat the backup brought in (no linked message) sends to its contact's number on the one number reading.#[test]fn a_backup_chat_sends_to_its_contacts_number_on_the_one_reading_number() {let db = file(); connect(&db, "reading"); chat(&db, "t1", "919800000001", "whatsapp", "{}"); assert_eq!( target(&db, "t1"),Ok(SendTarget { account: ACCOUNT.into(), chat: "919800000001@s.whatsapp.net".into() }) );}/// RULE: A group keyed by its JID sends to that JID; a group keyed by an export's title slug has no address.#[test]fn a_group_sends_to_the_jid_in_its_key_and_never_to_a_title_slug() {let reading = [LinkedNumber { id: "conn:whatsapp:+15550001111".into(), state: "reading".into(), account: Some(ACCOUNT.into()), }];let group = |key: &str| ChatFacts { whatsapp: true, kind: "group".into(), external_key: Some(key.into()), ..ChatFacts::default() }; assert_eq!( decide(&group("wa:group:120363000000000000@g.us"), &reading).map(|target| target.chat),Ok("120363000000000000@g.us".to_string()) ); assert_eq!(decide(&group("wa:group:fixture-crew"), &reading), Err(NO_ADDRESS));}/// RULE: With two numbers reading and nothing saying which one a chat is on, Cotton does not guess.#[test]fn two_reading_numbers_and_no_linked_message_is_not_a_guess() {let number = |digits: &str| LinkedNumber { id: format!("conn:whatsapp:+{digits}"), state: "reading".into(), account: Some(format!("{digits}@s.whatsapp.net")), };let facts =ChatFacts { whatsapp: true, kind: "dm".into(), phone: Some("919800000001".into()), ..ChatFacts::default() }; assert_eq!(decide(&facts, &[number("15550001111"), number("15550002222")]), Err(WHICH_NUMBER));}/// RULE: A text's WhatsApp id is derived from its row and its attempt: the same try always carries the same id, a retry a fresh one.#[test]fn the_whatsapp_id_is_the_same_for_a_try_and_fresh_for_a_retry() {let first = whatsapp_message_id("row-1", 0); assert_eq!(first, whatsapp_message_id("row-1", 0)); assert_ne!(first, whatsapp_message_id("row-1", 1)); assert_ne!(first, whatsapp_message_id("row-2", 0)); assert_eq!(first.len(), 24); assert!(first.starts_with("3EB0")); assert!(first.chars().all(|c| c.is_ascii_digit() || c.is_ascii_uppercase()));}/// RULE (owner, 22 Nov 2026): a phone decides a WhatsApp chat can take a text from the chat alone (it holds no/// connection rows): its address, and the number that brought it in when a message names one. The chat's own/// refusals stand as on the Mac.#[test]fn a_phone_decides_from_the_chat_alone() {let dm = ChatFacts { whatsapp: true, kind: "dm".into(), phone: Some("+1 555 0100 222".into()), ..ChatFacts::default() }; assert_eq!(decide_on_phone(&dm), Ok(PhoneTarget { account: None, chat: "15550100222@s.whatsapp.net".into() }));let linked = ChatFacts { linked_account: Some("15550001111@s.whatsapp.net".into()), linked_chat: Some("15550100222@s.whatsapp.net".into()), ..dm.clone() }; assert_eq!(decide_on_phone(&linked).unwrap().account.as_deref(), Some("15550001111@s.whatsapp.net")); assert_eq!(decide_on_phone(&ChatFacts { phone: None, ..dm.clone() }), Err(NO_ADDRESS)); assert_eq!(decide_on_phone(&ChatFacts { archived: true, ..dm.clone() }), Err(ARCHIVED)); assert_eq!(decide_on_phone(&ChatFacts { whatsapp: false, ..dm.clone() }), Err(NOT_WHATSAPP)); assert_eq!(decide_on_phone(&ChatFacts { linked_chat: Some("status@broadcast".into()), ..dm }), Err(NO_REPLY));}/// RULE (owner, 23 Nov 2026, FEEDBACK-2 A): writing to a number goes to the Cotton chat when the number is one of the/// person's Cotton connections; otherwise to that number's WhatsApp when the copy is linked through the Mac; otherwise/// the Cotton chat with the invite, as before the link.#[test]fn a_number_goes_to_cotton_first_then_whatsapp_when_linked_else_the_invite() {let link = Link { account: Some(ACCOUNT.into()) }; assert_eq!(route("+15550100222", true, Some(&link)), Route::Cotton, "a Cotton connection stays on Cotton, link or not"); assert_eq!(route("+15550100222", true, None), Route::Cotton); assert_eq!( route("+1 555 0100 222", false, Some(&link)),Route::Whatsapp(PhoneTarget { account: Some(ACCOUNT.into()), chat: "15550100222@s.whatsapp.net".into() }),"their WhatsApp, by its digits, from the linked number" ); assert_eq!(route("+15550100222", false, Some(&Link { account: None })).place(), "whatsapp", "two linked numbers: the Mac picks"); assert_eq!(route("+15550100222", false, None), Route::Invite, "no link: nothing changes"); assert_eq!(Route::Invite.place(), "cotton"); assert_eq!(Route::Cotton.place(), "cotton");}/// RULE: the copy is linked only by messages the Mac's link brought in (`meta.source.account`): a backup's or an/// export's WhatsApp messages are not a link; one number gives its JID, two leave the choice to the Mac.#[test]fn a_copy_is_linked_only_by_what_the_link_brought_in() {let db = file(); assert_eq!(link_of(&mut reader(&db), WORKSPACE).unwrap(), None, "an empty copy"); chat(&db, "t-backup", "15550100222", "whatsapp", "{}"); assert_eq!(link_of(&mut reader(&db), WORKSPACE).unwrap(), None, "a backup's messages are no link"); chat(&db, "t-live", "15550100333", "whatsapp", &linked_meta("15550100333@s.whatsapp.net")); assert_eq!(link_of(&mut reader(&db), WORKSPACE).unwrap(), Some(Link { account: Some(ACCOUNT.into()) })); assert_eq!(link_of(&mut reader(&db), "another-workspace").unwrap(), None, "the person's own copy only"); chat(&db, "t-other", "15550100444", "whatsapp", r#"{"source":{"account":"15550002222@s.whatsapp.net","chat":"15550100444@s.whatsapp.net"}}"#); assert_eq!(link_of(&mut reader(&db), WORKSPACE).unwrap(), Some(Link { account: None }), "two numbers: the Mac sends from its own");let plan: Vec<String> = db .all(&format!("EXPLAIN QUERY PLAN {LINK_SQL}"), &[text(WORKSPACE), text("")]) .unwrap() .iter() .filter_map(|row| row.text("detail").map(str::to_string)) .collect(); assert!(plan.iter().any(|d| d.contains("idx_cotton_msg_messages_source_account")), "a seek, however large the copy: {plan:?}");}