330 lines ยท 22.4 KB ยท RustRaw
//! Sends from the phone: queued rows read from the object, sent through a//! fake WhatsApp helper on a Unix socket, and marked at the object.mod support;use std::io::{BufRead, BufReader, Write};use std::os::unix::net::UnixListener;use std::sync::{Arc, Mutex};use cotton_core::messages::send::whatsapp_message_id;use cotton_mac::object::ObjectClient;use cotton_mac::outbox::{drain_whatsapp, Drained};use serde_json::{json, Value};use support::{Answer, TestServer};/// A helper that answers `hello` with one linked number and `send` with/// WhatsApp's id, recording every request.fn fake_helper(socket: &std::path::Path, fail_send: bool) -> Arc<Mutex<Vec<Value>>> { let listener = UnixListener::bind(socket).unwrap(); let seen = Arc::new(Mutex::new(Vec::new())); let recorded = Arc::clone(&seen); std::thread::spawn(move || { for stream in listener.incoming() { let Ok(stream) = stream else { continue }; let mut writer = stream.try_clone().unwrap(); let reader = BufReader::new(stream); for line in reader.lines() { let Ok(line) = line else { break }; let request: Value = serde_json::from_str(&line).unwrap(); recorded.lock().unwrap().push(request.clone()); let id = request["id"].clone(); let reply = match request["op"].as_str() { Some("hello") => json!({ "reply": id, "ok": true, "result": { "version": 1, "accounts": [{ "account": "919800000000", "state": "connected" }], "pending": 0 } }), Some("send") if fail_send => json!({ "reply": id, "ok": false, "error": "not on WhatsApp" }), Some("send") => json!({ "reply": id, "ok": true, "result": { "id": request["message_id"], "ts": 1761436800 } }), _ => json!({ "reply": id, "ok": false, "error": "unexpected" }), }; let mut out = serde_json::to_vec(&reply).unwrap(); out.push(b'\n'); writer.write_all(&out).unwrap(); } } }); seen}fn object_with(rows: Value) -> TestServer { TestServer::start(move |request| match (request.method.as_str(), request.path.as_str()) { ("GET", "/v1/outbox?status=queued") => Answer::json(200, json!({ "rows": rows.clone() })), ("POST", "/v1/act") => Answer::json(200, json!({ "version": 1, "changed": [] })), _ => Answer::json(404, json!({ "code": "not_found", "message": "no route" })), })}fn acts(server: &TestServer) -> Vec<Value> { server.requests().iter().filter(|r| r.method == "POST").map(|r| r.json()).collect()}#[test]fn a_queued_text_is_marked_sending_sent_through_the_helper_and_marked_sent() { let dir = tempfile::tempdir().unwrap(); let socket = dir.path().join("link.sock"); let helper = fake_helper(&socket, false); let server = object_with(json!([ { "id": "row-1", "data": { "channel": "whatsapp", "to": "+91 98000 00001", "body": "On my way", "status": "queued" } }, { "id": "row-2", "data": { "channel": "instagram", "to": "asha.example", "body": "hi", "status": "queued" } } ])); let object = ObjectClient::new(server.url.clone(), Some("tok".into())).unwrap(); let drained = drain_whatsapp(&object, &socket).unwrap(); assert_eq!(drained, Drained { sent: 1, failed: 0, left: 1 }); let message_id = whatsapp_message_id("row-1", 0); let sends: Vec<Value> = helper.lock().unwrap().iter().filter(|r| r["op"] == "send").cloned().collect(); assert_eq!(sends.len(), 1); assert_eq!(sends[0]["account"], "919800000000"); assert_eq!(sends[0]["chat"], "919800000001@s.whatsapp.net"); assert_eq!(sends[0]["text"], "On my way"); assert_eq!(sends[0]["message_id"], Value::String(message_id.clone())); let acts = acts(&server); assert_eq!(acts.len(), 2); assert_eq!(acts[0], json!({ "act": "update", "args": { "table": "outbox", "id": "row-1", "data": { "status": "sending", "sent_external_id": message_id } } })); assert_eq!( acts[1], json!({ "act": "update", "args": { "table": "outbox", "id": "row-1", "data": { "status": "sent", "sent_at": "2025-10-26T00:00:00.000Z", "sent_external_id": message_id, "error": null } } }) );}#[test]fn a_send_the_helper_refuses_is_marked_failed() { let dir = tempfile::tempdir().unwrap(); let socket = dir.path().join("link.sock"); let _helper = fake_helper(&socket, true); let server = object_with(json!([{ "id": "row-1", "channel": "whatsapp", "to": "919800000001", "body": "hi" }])); let object = ObjectClient::new(server.url.clone(), Some("tok".into())).unwrap(); let drained = drain_whatsapp(&object, &socket).unwrap(); assert_eq!(drained.failed, 1); let acts = acts(&server); assert_eq!(acts.last().unwrap()["args"]["data"]["status"], "failed"); assert_eq!(acts.last().unwrap()["args"]["data"]["error"], "WhatsApp did not take it: not on WhatsApp");}#[test]fn without_a_helper_every_row_waits_queued() { let dir = tempfile::tempdir().unwrap(); let server = object_with(json!([{ "id": "row-1", "channel": "whatsapp", "to": "919800000001", "body": "hi" }])); let object = ObjectClient::new(server.url.clone(), Some("tok".into())).unwrap(); let drained = drain_whatsapp(&object, &dir.path().join("absent.sock")).unwrap(); assert_eq!(drained, Drained::default()); assert!(acts(&server).is_empty());}/// RULE (CONTRACT "Pictures, voice notes and video"): a photo whose file the phone has not put up yet is left queued/// and untouched (the phone keeps saying "Waiting to send"), never sent and never failed; one over WhatsApp's limit/// by the phone's own size is failed "This file is too large for WhatsApp.", unfetched.#[test]fn a_file_not_up_yet_waits_and_one_too_large_says_so() { let dir = tempfile::tempdir().unwrap(); let socket = dir.path().join("link.sock"); let helper = fake_helper(&socket, false); let server = object_with(json!([ { "id": "row-1", "channel": "whatsapp", "to": "919800000001", "body": "look", "kind": "photo", "media_key": "db/messages/t/a.jpg", "mime": "image/jpeg" }, { "id": "row-2", "channel": "whatsapp", "to": "919800000001", "body": "", "kind": "video", "media_key": "db/messages/t/b.mp4", "mime": "video/mp4", "size_bytes": 17_000_000 } ])); let object = ObjectClient::new(server.url.clone(), Some("tok".into())).unwrap(); assert_eq!(drain_whatsapp(&object, &socket).unwrap(), Drained { sent: 0, failed: 1, left: 1 }); assert!(helper.lock().unwrap().iter().all(|r| r["op"] != "send")); let acts = acts(&server); assert!(acts.iter().all(|a| a["args"]["id"] != "row-1"), "the row not up yet is untouched"); let large = acts.iter().find(|a| a["args"]["id"] == "row-2").unwrap(); assert_eq!(large["args"]["data"]["error"], "This file is too large for WhatsApp.");}/// RULE (owner, FEEDBACK-3, 23 Nov 2026): a reaction, an edit, a delete, a poll and a vote each go to the helper as/// their own kind, naming the message they act on and who wrote it ("me": the owner's own); a reply's text quotes/// its message; a reaction with no message to act on is failed in words.#[test]fn each_kind_goes_to_the_helper_as_itself() { let dir = tempfile::tempdir().unwrap(); let socket = dir.path().join("link.sock"); let helper = fake_helper(&socket, false); let row = |id: &str, extra: Value| { let mut data = json!({ "channel": "whatsapp", "to": "919800000001", "body": "", "status": "queued" }); data.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); json!({ "id": id, "data": data }) }; let server = object_with(json!([ row("r-reply", json!({ "body": "yes", "target": "3EB0Q", "target_sender": "919800000001@s.whatsapp.net" })), row("r-react", json!({ "kind": "reaction", "target": "3EB0Q", "target_sender": "919800000001@s.whatsapp.net", "emoji": "๐" })), row("r-edit", json!({ "kind": "edit", "body": "new words", "target": "3EB0MINE", "target_sender": "me" })), row("r-delete", json!({ "kind": "delete", "target": "3EB0MINE", "target_sender": "me" })), // As the phones write them: no target_sender, an edit or a delete is his own. row("r-edit-phone", json!({ "kind": "edit", "body": "the phone's words", "target": "3EB0MINE2" })), row("r-delete-phone", json!({ "kind": "delete", "target": "3EB0MINE3" })), row("r-poll", json!({ "kind": "poll", "body": "Which day?", "options": "[\"Thursday\",\"Friday\"]", "selectable": 1 })), row("r-vote", json!({ "kind": "poll_vote", "target": "3EB0POLL", "target_sender": "919800000001@s.whatsapp.net", "options": ["Friday"] })), row("r-lost", json!({ "kind": "reaction", "emoji": "๐" })), ])); let object = ObjectClient::new(server.url.clone(), Some("tok".into())).unwrap(); let drained = drain_whatsapp(&object, &socket).unwrap(); assert_eq!(drained, Drained { sent: 8, failed: 1, left: 0 }); let sends: Vec<Value> = helper.lock().unwrap().iter().filter(|r| r["op"] == "send").cloned().collect(); let by = |text: &str, kind: Option<&str>| sends.iter().find(|s| s["text"] == text && s.get("kind").and_then(Value::as_str) == kind).cloned().unwrap_or_else(|| panic!("no {kind:?} send {text:?} in {sends:?}")); let reply = by("yes", None); assert_eq!((reply["quoted_id"].as_str(), reply["quoted_sender"].as_str()), (Some("3EB0Q"), Some("919800000001@s.whatsapp.net"))); let react = by("", Some("reaction")); assert_eq!((react["target"].as_str(), react["emoji"].as_str(), react["target_from_me"].as_bool()), (Some("3EB0Q"), Some("๐"), Some(false))); let edit = by("new words", Some("edit")); assert_eq!((edit["target"].as_str(), edit["target_from_me"].as_bool(), edit.get("target_sender")), (Some("3EB0MINE"), Some(true), None)); assert_eq!(by("", Some("delete"))["target_from_me"], true); let phone_edit = by("the phone's words", Some("edit")); assert_eq!((phone_edit["target"].as_str(), phone_edit["target_from_me"].as_bool()), (Some("3EB0MINE2"), Some(true))); let phone_delete = sends.iter().find(|s| s["target"] == "3EB0MINE3").expect("the phone's delete"); assert_eq!((phone_delete["kind"].as_str(), phone_delete["target_from_me"].as_bool()), (Some("delete"), Some(true))); let poll = by("Which day?", Some("poll")); assert_eq!((poll["options"].clone(), poll["selectable"].as_u64()), (json!(["Thursday", "Friday"]), Some(1))); assert_eq!(by("", Some("poll_vote"))["options"], json!(["Friday"])); let lost = acts(&server).into_iter().find(|a| a["args"]["id"] == "r-lost").unwrap(); assert_eq!(lost["args"]["data"]["error"], "This needs the message it acts on.");}/// RULE (owner, 22 Nov 2026): a text is sent once under the WhatsApp id Comms fixed at the owner's tap, from the/// number the chat came in through: a retried row goes out under the same id (WhatsApp keeps one), and a row whose/// number is not linked here is failed in words, never sent from another of the owner's numbers.#[test]fn a_text_goes_out_under_the_id_fixed_at_the_tap_from_its_own_number() { let dir = tempfile::tempdir().unwrap(); let socket = dir.path().join("link.sock"); let helper = fake_helper(&socket, false); let server = object_with(json!([ { "id": "row-1", "data": { "channel": "whatsapp", "to": "919800000001@s.whatsapp.net", "account": "919800000000@s.whatsapp.net", "body": "again", "status": "queued", "sent_external_id": "3EB0FIXEDATTAP000001" } }, { "id": "row-2", "data": { "channel": "whatsapp", "to": "919800000002@s.whatsapp.net", "account": "15550001111@s.whatsapp.net", "body": "hi", "status": "queued" } } ])); let object = ObjectClient::new(server.url.clone(), Some("tok".into())).unwrap(); let drained = drain_whatsapp(&object, &socket).unwrap(); assert_eq!(drained, Drained { sent: 1, failed: 1, left: 0 }); let sends: Vec<Value> = helper.lock().unwrap().iter().filter(|r| r["op"] == "send").cloned().collect(); assert_eq!(sends.len(), 1, "the row on a number not linked here is not sent"); assert_eq!(sends[0]["message_id"], "3EB0FIXEDATTAP000001"); assert_eq!(sends[0]["account"], "919800000000"); let acts = acts(&server); let failed = acts.iter().find(|a| a["args"]["id"] == "row-2").unwrap(); assert_eq!(failed["args"]["data"]["status"], "failed"); assert_eq!(failed["args"]["data"]["error"], "This chat is on WhatsApp number +15550001111, which is not linked on your Mac.");}/// RULE (CONTRACT "Disappearing messages on a WhatsApp chat", the Mac's ask; ERASES): a sent row's words, caption,/// preview and waveform are emptied once its message stands in the chat, and only then; the row, its status, its/// WhatsApp id and its file's key stay.#[test]fn a_sent_rows_words_go_once_its_message_stands_in_the_chat() { let server = TestServer::start(move |request| match (request.method.as_str(), request.path.as_str()) { ("GET", "/v1/outbox?status=sent") => Answer::json(200, json!({ "rows": [ { "id": "landed", "channel": "whatsapp", "status": "sent", "body": "On my way", "sent_external_id": "3EB0LANDED" }, { "id": "photo", "channel": "whatsapp", "status": "sent", "kind": "photo", "body": "the view", "preview": "/9j/AA==", "media_key": "db/messages/t/a.jpg", "sent_external_id": "3EB0PHOTO" }, { "id": "not-yet", "channel": "whatsapp", "status": "sent", "body": "still on its way", "sent_external_id": "3EB0NOTYET" }, { "id": "done", "channel": "whatsapp", "status": "sent", "body": "", "sent_external_id": "3EB0DONE" } ] })), ("POST", "/v1/act") => Answer::json(200, json!({ "version": 1, "changed": [] })), _ => Answer::json(404, json!({ "code": "not_found", "message": "no route" })), }); let object = ObjectClient::new(server.url.clone(), Some("tok".into())).unwrap(); let held = ["3EB0LANDED", "3EB0PHOTO", "3EB0DONE"]; assert_eq!(cotton_mac::outbox::empty_landed(&object, |id| held.contains(&id)).unwrap(), 2); let acts = acts(&server); let ids: Vec<&str> = acts.iter().map(|a| a["args"]["id"].as_str().unwrap()).collect(); assert_eq!(ids, vec!["landed", "photo"], "only rows whose message stands, and only rows still holding words"); assert_eq!(acts[1]["args"]["data"], json!({ "body": "", "preview": null, "waveform": null }));}/// RULE (CONTRACT "Replies and reactions"): a reply row names its quote by `quoted_id` alone and a reaction row its/// message by `reaction_to`: the Mac reads who wrote it and what it says from its copy, quotes his own message as/// written by his own number, sends a reaction to the message's writer, and empties a sent reaction's emoji in the/// update that marks it sent. A message the copy does not hold fails in words, unsent.#[test]fn a_reply_and_a_reaction_take_their_message_from_the_copy() { let dir = tempfile::tempdir().unwrap(); let socket = dir.path().join("link.sock"); let helper = fake_helper(&socket, false); let server = object_with(json!([ { "id": "r-reply", "channel": "whatsapp", "to": "120363000000000001@g.us", "body": "Thai please", "status": "queued", "quoted_id": "3EB0ASKED" }, { "id": "r-mine", "channel": "whatsapp", "to": "919800000001@s.whatsapp.net", "body": "as I said", "status": "queued", "quoted_id": "3EB0MINE" }, { "id": "r-react", "channel": "whatsapp", "to": "120363000000000001@g.us", "body": "", "status": "queued", "reaction_to": "3EB0ASKED", "emoji": "๐" }, { "id": "r-lost", "channel": "whatsapp", "to": "120363000000000001@g.us", "body": "", "status": "queued", "reaction_to": "3EB0GONE", "emoji": "๐" }, { "id": "r-lost-reply", "channel": "whatsapp", "to": "919800000001@s.whatsapp.net", "body": "what?", "status": "queued", "quoted_id": "3EB0GONE" } ])); let object = ObjectClient::new(server.url.clone(), Some("tok".into())).unwrap(); let find = |id: &str| match id { "3EB0ASKED" => Some(cotton_mac::outbox::Held::of(&json!({ "body": "Dinner on Friday?", "direction": "in", "meta": { "source": { "sender": "919800000002@s.whatsapp.net", "messageType": "text" } } }))), "3EB0MINE" => Some(cotton_mac::outbox::Held::of(&json!({ "body": "", "direction": "out", "media": [{ "contentType": "image/jpeg" }] }))), _ => None, }; let drained = cotton_mac::outbox::drain_whatsapp_with(&object, &socket, &find).unwrap(); assert_eq!(drained, Drained { sent: 3, failed: 2, left: 0 }); let sends: Vec<Value> = helper.lock().unwrap().iter().filter(|r| r["op"] == "send").cloned().collect(); let reply = sends.iter().find(|s| s["text"] == "Thai please").unwrap(); assert_eq!((reply["quoted_id"].as_str(), reply["quoted_sender"].as_str()), (Some("3EB0ASKED"), Some("919800000002@s.whatsapp.net"))); assert_eq!((reply["quoted_kind"].as_str(), reply["quoted_text"].as_str()), (Some("text"), Some("Dinner on Friday?"))); let mine = sends.iter().find(|s| s["text"] == "as I said").unwrap(); assert_eq!((mine["quoted_sender"].as_str(), mine["quoted_kind"].as_str()), (Some("919800000000@s.whatsapp.net"), Some("image"))); let react = sends.iter().find(|s| s["kind"] == "reaction").unwrap(); assert_eq!((react["target"].as_str(), react["target_sender"].as_str(), react["emoji"].as_str()), (Some("3EB0ASKED"), Some("919800000002@s.whatsapp.net"), Some("๐"))); let acts = acts(&server); let sent = acts.iter().find(|a| a["args"]["id"] == "r-react" && a["args"]["data"]["status"] == "sent").unwrap(); assert_eq!(sent["args"]["data"]["emoji"], ""); let error = |id: &str| acts.iter().find(|a| a["args"]["id"] == id).unwrap()["args"]["data"]["error"].clone(); assert_eq!(error("r-lost"), "That message isn't in WhatsApp, so you can't react to it there."); assert_eq!(error("r-lost-reply"), "That message isn't in WhatsApp, so you can't reply to it there.");}/// RULE (owner, 24 Nov 2026; CONTRACT "Blocking a WhatsApp sender, deleting a WhatsApp chat"): a block goes to the/// helper as `block` for the person's chat and names no message; a chat deleted for him names its newest WhatsApp/// message, who wrote it and its time, all from the Mac's copy. A group, and a chat whose newest message the copy/// does not hold, fail in words and nothing goes.#[test]fn a_block_and_a_chat_deleted_for_him_go_as_source_acts() { let dir = tempfile::tempdir().unwrap(); let socket = dir.path().join("link.sock"); let helper = fake_helper(&socket, false); let server = object_with(json!([ { "id": "s-block", "channel": "whatsapp", "to": "919800000001@s.whatsapp.net", "body": "", "status": "queued", "kind": "block" }, { "id": "s-delete", "channel": "whatsapp", "to": "919800000001@s.whatsapp.net", "body": "", "status": "queued", "kind": "delete_chat", "target": "3EB0NEWEST" }, { "id": "s-group", "channel": "whatsapp", "to": "120363000000000001@g.us", "body": "", "status": "queued", "kind": "delete_chat", "target": "3EB0NEWEST" }, { "id": "s-lost", "channel": "whatsapp", "to": "919800000003@s.whatsapp.net", "body": "", "status": "queued", "kind": "delete_chat", "target": "3EB0GONE" } ])); let object = ObjectClient::new(server.url.clone(), Some("tok".into())).unwrap(); let find = |id: &str| match id { "3EB0NEWEST" => Some(cotton_mac::outbox::Held::of(&json!({ "body": "See you then", "direction": "in", "sent_at": "2026-11-24T08:30:00.000Z", "meta": { "source": { "sender": "919800000001@s.whatsapp.net", "messageType": "text" } } }))), _ => None, }; let drained = cotton_mac::outbox::drain_whatsapp_with(&object, &socket, &find).unwrap(); assert_eq!(drained, Drained { sent: 2, failed: 2, left: 0 }); let sends: Vec<Value> = helper.lock().unwrap().iter().filter(|r| r["op"] == "send").cloned().collect(); assert_eq!(sends.len(), 2, "{sends:?}"); let block = sends.iter().find(|s| s["kind"] == "block").unwrap(); assert_eq!(block["chat"], "919800000001@s.whatsapp.net"); assert!(block.get("target").is_none() && block.get("target_ts").is_none(), "{block}"); let delete = sends.iter().find(|s| s["kind"] == "delete_chat").unwrap(); assert_eq!((delete["target"].as_str(), delete["target_from_me"].as_bool(), delete["target_ts"].as_i64()), (Some("3EB0NEWEST"), Some(false), Some(1_795_509_000))); let acts = acts(&server); let error = |id: &str| acts.iter().find(|a| a["args"]["id"] == id).unwrap()["args"]["data"]["error"].clone(); assert_eq!(error("s-group"), "This is for a person's chat, not a group."); assert_eq!(error("s-lost"), "This chat's messages aren't in WhatsApp, so it can't be deleted there.");}/// RULE (SENDERS.md, 24 Nov 2026): People's Delete everything erases his copy of what they sent at/// once and queues the chat deleted for him on WhatsApp, naming its newest WhatsApp message, which by then is the/// wordless marker the erase leaves under that message's WhatsApp id (`chat_timer::marker_columns`: no words, no/// sender, its own `sent_at`). The drain still finds it, and sends the chat's address as its writer and that time.#[test]fn a_chat_deleted_after_people_erased_it_goes_by_the_marker_left() { let dir = tempfile::tempdir().unwrap(); let socket = dir.path().join("link.sock"); let helper = fake_helper(&socket, false); let server = object_with(json!([ { "id": "s-people", "channel": "whatsapp", "to": "15550100222@s.whatsapp.net", "body": "", "status": "queued", "kind": "delete_chat", "target": "x-erased" } ])); let object = ObjectClient::new(server.url.clone(), Some("tok".into())).unwrap(); let marker = json!({ "thread_id": "t", "direction": "in", "channel": "whatsapp", "origin": "imported", "body": "", "external_id": "x-erased", "sent_at": "2026-11-24T08:30:00.000Z", "deleted_at": "2026-11-24T08:30:00.000Z", "hidden_at": "2026-11-24T08:30:00.000Z", "meta": { "cotton": { "erased": "sender_deleted" } } }); let find = |id: &str| (id == "x-erased").then(|| cotton_mac::outbox::Held::of(&marker)); let drained = cotton_mac::outbox::drain_whatsapp_with(&object, &socket, &find).unwrap(); assert_eq!(drained, Drained { sent: 1, failed: 0, left: 0 }); let sends: Vec<Value> = helper.lock().unwrap().iter().filter(|r| r["op"] == "send").cloned().collect(); let delete = &sends[0]; assert_eq!((delete["kind"].as_str(), delete["target"].as_str(), delete["target_from_me"].as_bool(), delete["target_ts"].as_i64()), (Some("delete_chat"), Some("x-erased"), Some(false), Some(1_795_509_000))); assert_eq!(delete["target_sender"], "15550100222@s.whatsapp.net");}