//! WhatsApp, as a device linked to the owner's number.//!//! The Go helper (`Contents/Helpers/cotton-whatsapp-link`) holds the linked//! session and an outbox of everything it read; this importer keeps it running,//! links a number from the card — by the code WhatsApp asks for under Linked//! devices › Link with phone number, or by its QR — and drains its//! outbox through `cotton-client`'s reader into the object. The reader acks a//! page to the helper only after every batch from it reached the object, so a//! message is never lost between the two.//!//! ONE HELPER PER FOLDER. The helper outlives the app unless the app stops it://! [`Importer::stop`] ends it when the app stops, and a helper a run that did//! not stop (a crash, a forced quit, a logout) left behind is stopped by the//! pid it recorded beside its socket before the next one starts, so two//! helpers never hold the same linked session.//!//! WhatsApp may ask for a passkey before it links (November 2026): the//! helper's `pair_status` then says `passkey` with WebAuthn options, this//! importer signs it from the Cotton Keys row when the vault is open//! ([`crate::vault_passkey`]), else asks the person's passkey in Chrome//! ([`crate::whatsapp_passkey`]), hands the assertion to the helper, and the//! card shows the code to match against the phone's before it confirms.//!//! A number WhatsApp removed (the helper's `unlinked`, kept across restarts)//! is said on the card with its time and reason, and one todo asks the owner//! to link it again — once per removal, never beside one still open.use std::path::{Path, PathBuf};use std::process::{Child, Command, Stdio};use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};use std::time::{Duration, Instant};use cotton_client::ingest::sources::whatsapp_link::{LinkClient, LinkError, WhatsappLinkSource, WhatsappLinkSourceInput, SOCKET_NAME,};use cotton_client::ingest::IngestBatch;use cotton_client::ingest::IngestSourceas _;use cotton_store::file_identity::Namespace;use serde_json::{json, Value};usecrate::object::{ObjectClient, ObjectError};usecrate::whatsapp_passkey::{ChromePasskey, PasskeyBrowser};usecrate::importer::{Importer, Need, Probe, RunContext, RunError, Schedule, SourceKey};/// How often the helper's outbox is looked at. A look with nothing in it is/// one `events` call over a Unix socket.pubconst POLL: Duration = Duration::from_secs(5);/// How often the phone's queued sends are asked for.pubconst OUTBOX_EVERY: Duration = Duration::from_secs(15);/// How often the phone is asked again for old polls kept without their options ([`crate::old_polls`]).pubconst OLD_POLLS_EVERY: Duration = Duration::from_secs(60);/// The todo that asks the owner to link WhatsApp again; one open at a time.pubconst RELINK_TODO: &str = "Agents. Re-link WhatsApp on the Mac";/// A pairing the person started from the card.#[derive(Debug, Clone, PartialEq)]structPairing { id: String,/// `"code"` or `"qr"`. by: &'static str,}pubstructWhatsappImporter {/// The helper binary; `None` in a build that does not carry it. binary: Option<PathBuf>,/// `<data dir>/whatsapp-link`: the socket, the session store, the outbox. dir: PathBuf, machine: String, child: Mutex<Option<Child>>,/// The pairing the card is showing, while no number is linked. pairing: Mutex<Option<Pairing>>,/// Why the last pairing ended without a link, said until the next starts. unlinked: Mutex<Option<String>>,/// When the outbox was last drained. outbox_at: Mutex<Option<Instant>>,/// When the phone was last asked for old polls. polls_at: Mutex<Option<Instant>>,/// The last pass that asked the phone for older messages ([`crate::older`]). older_at: Mutex<Option<Instant>>,/// The app is stopping: no helper starts again. stopped: AtomicBool,/// Where WhatsApp's passkey is asked for. browser: Arc<dynPasskeyBrowser>,/// The passkey asked for the pairing under way. passkey: Arc<Mutex<Option<Attempt>>>,/// The number WhatsApp removed, while none is linked (the helper's `unlinked`). removed: Mutex<Option<Removed>>,/// The removal whose todo is filed. filed: Mutex<Option<i64>>,}/// One ask for WhatsApp's passkey, for one pairing.#[derive(Debug, Clone, PartialEq)]structAttempt { pairing: String, stage: Stage,}#[derive(Debug, Clone, PartialEq)]enumStage {/// Chrome shows the passkey sheet.Asking,/// Chrome could not ask, or WhatsApp's helper did not take the answer.Failed(String),/// The helper has the assertion.Sent,}/// The helper's `unlinked`: the number WhatsApp removed, why, and when.#[derive(Debug, Clone, PartialEq)]structRemoved { reason: String, at: i64,}implRemoved {fn from_hello(hello: &Value) -> Option<Removed> {let unlinked = hello.get("unlinked")?;let reason = unlinked .get("reason") .and_then(Value::as_str) .unwrap_or_default();// whatsmeow says "401: logged out from another device".let reason = match reason.split_once(": ") {Some((code, rest)) if code.chars().all(|c| c.is_ascii_digit()) => rest, _ => reason, };Some(Removed { reason: reason.to_string(), at: unlinked.get("at").and_then(Value::as_i64)?, }) }/// "7 Nov 2026, 04:00 UTC": the instant WhatsApp said, in UTC and saying/// so. The Mac importer holds no workspace zone, and the Mac's own zone is/// a guess (no_ambient_timezone).fn when(&self) -> String {use chrono::TimeZoneas _; chrono::Utc .timestamp_opt(self.at, 0) .single() .map(|at| at.format("%-d %b %Y, %H:%M UTC").to_string()) .unwrap_or_default() }fn sentence(&self) -> String { format!("Unlinked by WhatsApp on {}: {}. Link it again.",self.when(),self.reason ) }}implWhatsappImporter {pubfn new(binary: Option<PathBuf>, data_dir: &Path, machine: implInto<String>) -> WhatsappImporter {WhatsappImporter { binary: binary.filter(|path| path.is_file()), dir: data_dir.join("whatsapp-link"), machine: machine.into(), child: Mutex::new(None), pairing: Mutex::new(None), unlinked: Mutex::new(None), outbox_at: Mutex::new(None), polls_at: Mutex::new(None), older_at: Mutex::new(None), stopped: AtomicBool::new(false), browser: Arc::new(ChromePasskey::new(PathBuf::new(), data_dir.to_path_buf())), passkey: Arc::new(Mutex::new(None)), removed: Mutex::new(None), filed: Mutex::new(None), } }/// Ask WhatsApp's passkey through `browser` (Chrome through the session/// host, in the app).pubfn with_passkey_browser(mutself, browser: Arc<dynPasskeyBrowser>) -> WhatsappImporter {self.browser = browser;self }fn socket(&self) -> PathBuf {self.dir.join(SOCKET_NAME) }/// `<socket>.pid`: the running helper's pid, beside the socket it holds.fn pid_record(&self) -> PathBuf {self.socket().with_extension("sock.pid") }/// Stop the helper an earlier run recorded, when it is still running on/// this folder's socket: its command line names the socket, so a pid the/// system has since given to another process is never touched.fn stop_left_behind(&self) {let record = self.pid_record();letSome(pid) = std::fs::read_to_string(&record) .ok() .and_then(|text| text.trim().parse::<i32>().ok()) .filter(|pid| *pid > 0)else {return; };let ours = format!("--socket {}", self.socket().display());if command_line(pid).is_some_and(|line| line.contains(&ours)) { terminate(pid); }let _ = std::fs::remove_file(&record); }/// Start the helper, or start it again when it exited.fn ensure_helper(&self) -> Result<(), String> {letSome(binary) = &self.binary else {returnErr("This build carries no WhatsApp helper.".to_string()); };ifself.stopped.load(Ordering::SeqCst) {returnErr("Cotton is stopping.".to_string()); }letmut held = self.child.lock().unwrap_or_else(|p| p.into_inner());ifletSome(child) = held.as_mut() {match child.try_wait() {Ok(None) => returnOk(()), _ => *held = None, } }self.stop_left_behind(); std::fs::create_dir_all(&self.dir).map_err(|e| e.to_string())?; {use std::os::unix::fs::PermissionsExtas _;let _ = std::fs::set_permissions(&self.dir, std::fs::Permissions::from_mode(0o700)); }let log = std::fs::OpenOptions::new() .create(true) .append(true) .open(self.dir.join("helper.log")) .map_err(|e| e.to_string())?;let child = Command::new(binary) .arg("--socket") .arg(self.socket()) .arg("--data") .arg(&self.dir) .stdin(Stdio::null()) .stdout(log.try_clone().map_err(|e| e.to_string())?) .stderr(log) .spawn() .map_err(|e| format!("the WhatsApp helper did not start: {e}"))?;let _ = std::fs::write(self.pid_record(), format!("{}\n", child.id())); *held = Some(child);Ok(()) }fn client(&self) -> Result<LinkClient, LinkError> {LinkClient::connect(&self.socket()) }/// What the card shows while no number is linked: the pairing under way,/// as the helper says it, or none — the person picks code or QR. A/// pairing that failed is dropped and its sentence said; with none under/// way, the number WhatsApp removed is said.fn pairing_need(&self, client: &mutLinkClient) -> Probe {letmut pairing = self.pairing.lock().unwrap_or_else(|p| p.into_inner());letSome(held) = pairing.clone() else {let said = self .unlinked .lock() .unwrap_or_else(|p| p.into_inner()) .clone();let said = said.or_else(|| {self.removed .lock() .unwrap_or_else(|p| p.into_inner()) .as_ref() .map(Removed::sentence) });returnProbe { detail: said, ..Probe::needs(pair_need(None, None, None, None, None)) }; };let by = Some(held.by.to_string());let state = match client.call("pair_status", json!({ "pairing": held.id }),Duration::from_secs(10), ) {Ok(state) => state,// The helper is busy for a moment: the pairing stands.Err(_) => returnProbe::needs(pair_need(by, None, None, None, None)), };let text = |key: &str| { state .get(key) .and_then(Value::as_str) .filter(|v| !v.is_empty()) .map(str::to_string) };let step = |stage: &str, confirm: Option<String>| {Probe::needs(pair_need(by.clone(), None, None, Some(stage), confirm)) };match state.get("status").and_then(Value::as_str) {Some("starting" | "code" | "qr") => {Probe::needs(pair_need(by.clone(), text("code"), text("qr"), None, None)) }Some("passkey") => {let options = state.get("passkey").cloned().unwrap_or(Value::Null);let stage = self.passkey_stage(&held.id, &options);let signer = self.browser.answered_by(&held.id);match stage {Stage::Asking => Probe { detail: signer, ..step("asking", None) },Stage::Sent => Probe { detail: signer, ..step("sent", None) },Stage::Failed(why) => Probe { detail: Some(why), ..step("retry", None) }, } }Some("passkey_sent") => Probe { detail: self.browser.answered_by(&held.id), ..step("sent", None) },Some("passkey_code") => step("confirm", text("confirm")),Some("passkey_confirmed") => step("linking", None),Some("paired") => { *pairing = None;self.end_passkey(&held.id);Probe::needs(pair_need(None, None, None, None, None)) } _ => { *pairing = None;self.end_passkey(&held.id);let said = text("error").unwrap_or_else(|| "the link ended".to_string());let said = format!("WhatsApp did not link: {said}. Try again."); *self.unlinked.lock().unwrap_or_else(|p| p.into_inner()) = Some(said.clone());Probe { detail: Some(said), ..Probe::needs(pair_need(None, None, None, None, None)) } } } }/// Where the passkey for `pairing` stands; asked for in the browser the/// first time WhatsApp's request is seen.fn passkey_stage(&self, pairing: &str, options: &Value) -> Stage {let held = self .passkey .lock() .unwrap_or_else(|p| p.into_inner()) .clone();match held {Some(attempt) if attempt.pairing == pairing => attempt.stage, _ => {self.ask_passkey(pairing, options.clone());Stage::Asking } } }/// Ask the person's passkey for WhatsApp's `options` on a thread of its/// own (the browser waits on the person), and hand the assertion to the/// helper.fn ask_passkey(&self, pairing: &str, options: Value) { *self.passkey.lock().unwrap_or_else(|p| p.into_inner()) = Some(Attempt { pairing: pairing.to_string(), stage: Stage::Asking, });let (browser, held, socket, pairing) = (Arc::clone(&self.browser),Arc::clone(&self.passkey),self.socket(), pairing.to_string(), ); std::thread::spawn(move || {let stage = match browser.assert(&pairing, &options) {Ok(response) => matchLinkClient::connect(&socket) .map_err(|e| e.to_string()) .and_then(|mut client| { client .call("passkey_response", json!({ "pairing": pairing, "response": response }),Duration::from_secs(40), ) .map_err(|e| e.to_string()) }) {Ok(_) => Stage::Sent,Err(error) => {Stage::Failed(format!("WhatsApp did not take the passkey: {error}")) } },Err(error) => Stage::Failed(format!("The passkey was not given: {error}")), };letmut held = held.lock().unwrap_or_else(|p| p.into_inner());ifletSome(attempt) = held.as_mut().filter(|attempt| attempt.pairing == pairing) { attempt.stage = stage; } }); }/// The pairing ended: close what the passkey opened, keeping nothing.fn end_passkey(&self, pairing: &str) {letmut held = self.passkey.lock().unwrap_or_else(|p| p.into_inner());if held .as_ref() .is_some_and(|attempt| attempt.pairing == pairing) { *held = None; } drop(held);self.browser.close(pairing); }/// The pairing under way, for a command on it.fn held_pairing(&self) -> Result<Pairing, String> {self.pairing .lock() .unwrap_or_else(|p| p.into_inner()) .clone() .ok_or_else(|| "No WhatsApp link is under way.".to_string()) }/// `passkeyUse`: ask for the passkey again, after Chrome could not.fn use_passkey(&self) -> Result<Value, String> {let held = self.held_pairing()?;letmut client = self.client().map_err(|e| e.to_string())?;let state = client .call("pair_status", json!({ "pairing": held.id }),Duration::from_secs(10), ) .map_err(|e| e.to_string())?;if state.get("status").and_then(Value::as_str) != Some("passkey") {returnErr("WhatsApp is not asking for a passkey now.".to_string()); }self.browser.close(&held.id);self.ask_passkey( &held.id, state.get("passkey").cloned().unwrap_or(Value::Null), );Ok(json!({})) }/// `passkeyConfirm`: the code the card shows matches the phone's.fn confirm_passkey(&self) -> Result<Value, String> {let held = self.held_pairing()?;letmut client = self.client().map_err(|e| e.to_string())?; client .call("passkey_confirm", json!({ "pairing": held.id }),Duration::from_secs(40), ) .map_err(|e| e.to_string())?;Ok(json!({})) }/// `pairCancel`: end the pairing under way and close its passkey tab.fn cancel_pairing(&self) -> Result<Value, String> {letSome(held) = self .pairing .lock() .unwrap_or_else(|p| p.into_inner()) .take()else {returnOk(json!({})); };ifletOk(mut client) = self.client() {let _ = client.call("pair_cancel", json!({ "pairing": held.id }),Duration::from_secs(10), ); }self.end_passkey(&held.id);Ok(json!({})) }/// `linked`: the numbers this Mac is a linked device of, `{ numbers: ["+919800000000"] }`.fn linked(&self) -> Result<Value, String> {let numbers: Vec<String> = self.accounts()?.iter().filter_map(|account| number_of(account)).collect();Ok(json!({ "numbers": numbers })) }/// `unlink`: take this Mac out of each linked number's devices (the person asked, on the panel). New/// messages stop; everything already at the object stays there.fn unlink(&self) -> Result<Value, String> {let accounts = self.accounts()?;letmut client = self.client().map_err(|e| e.to_string())?;for account in &accounts { client.call("unlink", json!({ "account": account }), Duration::from_secs(40)).map_err(|e| e.to_string())?; }Ok(json!({ "unlinked": accounts.len() })) }/// The helper's linked accounts (`919800000000@s.whatsapp.net`).fn accounts(&self) -> Result<Vec<String>, String> {self.ensure_helper()?;letmut client = self.client().map_err(|e| e.to_string())?;let hello = client.hello().map_err(|e| e.to_string())?;Ok(hello .get("accounts") .and_then(Value::as_array) .map(|accounts| accounts.iter().filter_map(|a| a.get("account").and_then(Value::as_str).map(str::to_string)).collect()) .unwrap_or_default()) }/// Start a pairing — by `phone`'s code, or by QR when `phone` is `None` —/// in place of any under way.fn start_pairing(&self, phone: Option<&str>) -> Result<Value, String> {self.ensure_helper()?;letmut client = self.client().map_err(|_| "The WhatsApp helper is still starting; try again in a moment.".to_string())?;letmut pairing = self.pairing.lock().unwrap_or_else(|p| p.into_inner()); *self.unlinked.lock().unwrap_or_else(|p| p.into_inner()) = None;ifletSome(held) = pairing.take() {let _ = client.call("pair_cancel", json!({ "pairing": held.id }), Duration::from_secs(10));self.end_passkey(&held.id); }let args = match phone {Some(phone) => json!({ "phone": phone }),None => json!({}), };let started = client.call("pair", args, Duration::from_secs(20)).map_err(|e| e.to_string())?;let id = started .get("pairing") .and_then(Value::as_str) .ok_or_else(|| "the WhatsApp helper started no pairing".to_string())?; *pairing = Some(Pairing { id: id.to_string(), by: if phone.is_some() { "code" } else { "qr" } });Ok(json!({})) }fn source(&self, database_id: &str) -> WhatsappLinkSource {WhatsappLinkSource::new(WhatsappLinkSourceInput { workspace_id: database_id.to_string(), namespace: Namespace::of_database(database_id), device: self.machine.clone(), dir: self.dir.clone(), media_dir: self.dir.join("media"), }) }}implWhatsappImporter {/// End the helper this importer started, and its pid record.fn stop_helper(&self) {ifletSome(mut child) = self.child.lock().unwrap_or_else(|p| p.into_inner()).take() {let _ = child.kill();let _ = child.wait();let _ = std::fs::remove_file(self.pid_record()); } }}fn pair_need( by: Option<String>, code: Option<String>, qr: Option<String>, passkey: Option<&str>, confirm: Option<String>,) -> Need {Need::Pair { by, code, qr, passkey: passkey.map(str::to_string), confirm, }}/// Whether an open todo already asks the owner to link WhatsApp again.fn relink_todo_open(object: &ObjectClient) -> Result<bool, ObjectError> {// A device reads its own todos and opens them here: todos are sealed, and// the object's `/mcp` neither takes a device's sign-in nor opens a title.ifletSome(todos) = object.device_rows("todo") {returnOk(todos?.iter().any(|todo| {let data = &todo["data"]; data["status"] == "open" && data.get("trashed_at").is_none_or(Value::is_null) && data["title"].as_str().is_some_and(|t| t.starts_with(RELINK_TODO)) })); }letmut cursor: Option<String> = None;loop {letmut args = json!({ "status": "open", "limit": 500 });ifletSome(cursor) = &cursor { args["cursor"] = Value::from(cursor.as_str()); }let page = object.tool("list_todos", &args)?;let todos = page .get("todos") .and_then(Value::as_array) .cloned() .unwrap_or_default();if todos.iter().any(|todo| { todo.get("title") .and_then(Value::as_str) .is_some_and(|t| t.starts_with(RELINK_TODO)) }) {returnOk(true); }match page.get("nextCursor").and_then(Value::as_str) {Some(next) if page.get("more") == Some(&Value::Bool(true)) => { cursor = Some(next.to_string()) } _ => returnOk(false), } }}/// `pid`'s command line as `ps` prints it; `None` when no such process runs./// `919800000000@s.whatsapp.net` (or `…:12@s.whatsapp.net`) → `+919800000000`.fn number_of(account: &str) -> Option<String> {let user = account.split('@').next()?.split(':').next()?; (!user.is_empty() && user.chars().all(|c| c.is_ascii_digit())).then(|| format!("+{user}"))}fn command_line(pid: i32) -> Option<String> {let out = Command::new("/bin/ps") .args(["-o", "args=", "-p", &pid.to_string()]) .stdin(Stdio::null()) .stderr(Stdio::null()) .output() .ok()?;let line = String::from_utf8_lossy(&out.stdout).trim().to_string(); (out.status.success() && !line.is_empty()).then_some(line)}/// SIGTERM, a few seconds to go, then SIGKILL.fn terminate(pid: i32) {let alive = || unsafe { libc::kill(pid, 0) } == 0;unsafe { libc::kill(pid, libc::SIGTERM) };let deadline = Instant::now() + Duration::from_secs(3);while alive() && Instant::now() < deadline { std::thread::sleep(Duration::from_millis(50)); }if alive() {unsafe { libc::kill(pid, libc::SIGKILL) }; }}implDropforWhatsappImporter {fn drop(&mutself) {self.stop_helper(); }}implImporterforWhatsappImporter {fn key(&self) -> SourceKey {SourceKey::Whatsapp }fn schedule(&self) -> Schedule {Schedule::Continuous(POLL) }fn probe(&self) -> Probe {ifletErr(error) = self.ensure_helper() {returnProbe::unavailable(error); }letmut client = matchself.client() {Ok(client) => client,// The helper is still opening its socket.Err(_) => returnProbe::needs(pair_need(None, None, None, None, None)), };let hello = match client.hello() {Ok(hello) => hello,Err(error) => returnProbe::unavailable(error.to_string()), };let linked = hello .get("accounts") .and_then(Value::as_array) .is_some_and(|accounts| !accounts.is_empty()); *self.removed.lock().unwrap_or_else(|p| p.into_inner()) = if linked { None } else { Removed::from_hello(&hello) };if linked { *self.pairing.lock().unwrap_or_else(|p| p.into_inner()) = None; *self.unlinked.lock().unwrap_or_else(|p| p.into_inner()) = None;returnProbe::ready(); }self.pairing_need(&mut client) }/// `pairByCode { phone }`: the code to type into WhatsApp on the phone/// that number runs on. `pairByQr`: a QR to scan instead. `passkeyUse`:/// ask WhatsApp's passkey again; `passkeyConfirm`: the code matches the/// phone's; `pairCancel`: end the pairing under way.fn command(&self, name: &str, args: &Value) -> Result<Value, String> {match name {"pairByCode" => {let phone: String = args .get("phone") .and_then(Value::as_str) .unwrap_or("") .chars() .filter(char::is_ascii_digit) .collect();if phone.len() < 8 {returnErr("Type the number WhatsApp runs on, with its country code.".to_string()); }self.start_pairing(Some(&phone)) }"pairByQr" => self.start_pairing(None),"passkeyUse" => self.use_passkey(),"passkeyConfirm" => self.confirm_passkey(),"pairCancel" => self.cancel_pairing(),"linked" => self.linked(),"unlink" => self.unlink(), other => Err(format!("WhatsApp has no command {other}")), } }fn stop(&self) {self.stopped.store(true, Ordering::SeqCst);self.stop_helper(); }/// While WhatsApp has removed the number: one todo for the owner to link/// it again, filed once per removal and never beside one still open.fn while_needed(&self, object: &ObjectClient) -> Result<(), ObjectError> {// The vault signer reads Cotton Keys' rows through the current client.self.browser.see_object(object);letSome(removed) = self .removed .lock() .unwrap_or_else(|p| p.into_inner()) .clone()else {returnOk(()); };if *self.filed.lock().unwrap_or_else(|p| p.into_inner()) == Some(removed.at) {returnOk(()); }if !relink_todo_open(object)? {let title = format!("{RELINK_TODO} (device removed {})", removed.when());let notes = format!("WhatsApp removed Cotton's linked device on {} ({}). Open Cotton on that Mac, \ WhatsApp card, link by code; if WhatsApp asks for a passkey, give it in the \ Chrome window Cotton opens and confirm the code.",self.machine, removed.reason );if object.device_rows("todo").is_some() {// The todo goes up sealed, as a row of this device's own (e2e rulings R1, R2); one id per removal.let id = crate::ids::row_id("whatsapp-relink", &format!("{}:{}", self.machine, removed.at));// Filed once per removal: after a restart it is not filed again, so a todo he closed stays closed.let held = object.device_row("todo", &id, 0).transpose()?.flatten();if held.is_none() { object.upsert("todo", &id, &json!({ "title": title, "notes": notes, "status": "open" }))?; } } else { object.tool("create_todo", &json!({ "title": title, "notes": notes }))?; } } *self.filed.lock().unwrap_or_else(|p| p.into_inner()) = Some(removed.at);Ok(()) }fn run(&self, cursor: Option<&str>, ctx: &mutRunContext<'_>) -> Result<String, RunError> {letmut source = self.source(ctx.sink.database_id());// Whose WhatsApp profile picture Cotton would take (owner's decision, 11 Oct 2026), from the copy: the helper// is told these and asks WhatsApp about no one else.ifletOk(copy) = ctx.sink.copy() {match copy.wanted_pictures() {Ok(wanted) => source = source.with_pictures_wanted(wanted),Err(error) => eprintln!("cotton-mac: the profile pictures wanted were not read: {error}"), } }let outcome = {letmut emit = |batch: IngestBatch| ctx.emit(batch); source.read(cursor, &mut emit) };let cursor = match outcome {Ok(outcome) => outcome.cursor,Err(error) => returnErr(ctx.failed(error)), };self.drain_outbox(ctx)?;self.ask_old_polls(ctx);self.ask_older(ctx);Ok(cursor) }}implWhatsappImporter {/// Old polls kept without their options, asked of the phone again a few at a time, at most every/// [`OLD_POLLS_EVERY`]. Never fails the run: what was not asked is asked on a later pass.fn ask_old_polls(&self, ctx: &RunContext<'_>) { {letmut at = self.polls_at.lock().unwrap_or_else(|p| p.into_inner());if at.is_some_and(|at| at.elapsed() < OLD_POLLS_EVERY) {return; } *at = Some(Instant::now()); }letOk(copy) = ctx.sink.copy() else { return };let now = chrono::Utc::now().timestamp();ifletErr(error) = crate::old_polls::ask(copy, &self.socket(), now) { eprintln!("cotton-mac: old polls not asked for: {error}"); } }/// Older messages of his chats, asked of the phone a few chats at a time, at most every/// [`crate::older::OLDER_EVERY`]. Never fails the run.fn ask_older(&self, ctx: &RunContext<'_>) { {letmut at = self.older_at.lock().unwrap_or_else(|p| p.into_inner());if at.is_some_and(|at| at.elapsed() < crate::older::OLDER_EVERY) {return; } *at = Some(Instant::now()); }letOk(copy) = ctx.sink.copy() else { return };let now = chrono::Utc::now().timestamp();ifletErr(error) = crate::older::ask(copy, &self.socket(), now) { eprintln!("cotton-mac: older messages not asked for: {error}"); } }/// The phone's queued sends, at most every [`OUTBOX_EVERY`]. An object/// that has no outbox route yet (`404 not_found`) has nothing queued.fn drain_outbox(&self, ctx: &RunContext<'_>) -> Result<(), RunError> { {letmut at = self.outbox_at.lock().unwrap_or_else(|p| p.into_inner());if at.is_some_and(|at| at.elapsed() < OUTBOX_EVERY) {returnOk(()); } *at = Some(Instant::now()); }let copy = ctx.sink.copy().ok();// A reply's quote and the message a reaction acts on are read from the copy, by their WhatsApp id.let find = |external_id: &str| -> Option<crate::outbox::Held> {let copy = copy?;let id = copy.held_message_id("whatsapp", external_id).ok().flatten()?; copy.row("message", &id).ok().flatten().map(|data| crate::outbox::Held::of(&serde_json::Value::Object(data))) };let drained = crate::outbox::drain_whatsapp_with(ctx.sink.object(), &self.socket(), &find).and_then(|_| match copy {// A sent row's words go once its message stands in the chat (the message holds them).Some(copy) => crate::outbox::empty_landed(ctx.sink.object(), |id| copy.held_message_id("whatsapp", id).ok().flatten().is_some()).map(|_| ()),None => Ok(()), });match drained {Ok(_) => Ok(()),Err(ObjectError::Refused { status: 404, code, .. }) if code == "not_found" => Ok(()),Err(error) => Err(error.into()), } }}#[cfg(test)]mod tests {usesuper::*;use std::os::unix::fs::PermissionsExtas _;/// A stand-in helper: runs until told to stop, holding the arguments the/// importer gives it on its command line as the real one does.fn fake_helper(dir: &Path) -> PathBuf {let binary = dir.join(crate::sources::WHATSAPP_HELPER); std::fs::write(&binary, "#!/bin/sh\ntrap 'exit 0' TERM\nwhile :; do sleep 0.1; done\n").unwrap(); std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o700)).unwrap(); binary }fn exits_soon(child: &mutChild) -> bool {let deadline = Instant::now() + Duration::from_secs(5);whileInstant::now() < deadline {if child.try_wait().unwrap().is_some() {returntrue; } std::thread::sleep(Duration::from_millis(50)); }false }/// A helper socket with no number linked: `pair` starts `p1` (or `p2`),/// `pair_status` says `status` with a code or QR as the pairing was asked.fn pairing_socket(socket: &Path, status: &'static str) -> std::sync::Arc<Mutex<Vec<Value>>> {use std::io::{BufReadas _, BufReader, Writeas _};let listener = std::os::unix::net::UnixListener::bind(socket).unwrap();let seen = std::sync::Arc::new(Mutex::new(Vec::<Value>::new()));let recorded = std::sync::Arc::clone(&seen); std::thread::spawn(move || {for stream in listener.incoming() {letOk(stream) = stream else { continue };letmut writer = stream.try_clone().unwrap();for line inBufReader::new(stream).lines() {letOk(line) = line else { break };let request: Value = serde_json::from_str(&line).unwrap(); recorded.lock().unwrap().push(request.clone());let by_code = recorded.lock().unwrap().iter().rev().find(|r| r["op"] == "pair").is_some_and(|r| r.get("phone").is_some());let pairs = recorded.lock().unwrap().iter().filter(|r| r["op"] == "pair").count();let result = match request["op"].as_str() {Some("hello") => json!({ "version": 1, "accounts": [], "pending": 0 }),Some("pair") => json!({ "pairing": format!("p{pairs}") }),Some("pair_status") if status == "failed" => json!({ "status": "failed", "error": "the code expired" }),Some("pair_status") if by_code => json!({ "status": status, "code": "ABCD-1234" }),Some("pair_status") => json!({ "status": status, "qr": "2@qr" }), _ => Value::Null, };letmut out = serde_json::to_vec(&json!({ "reply": request["id"], "ok": true, "result": result })).unwrap(); out.push(b'\n'); writer.write_all(&out).unwrap(); } } }); seen }fn need(probe: &Probe) -> Value { serde_json::to_value(probe).unwrap() }// RULE: the card links WhatsApp by a code first: nothing starts until the// person asks, the code pairing carries their number (digits only), and a// QR asked for instead cancels the code pairing under way. #[test]fn whatsapp_links_by_code_or_by_qr_as_the_card_asks() {let dir = tempfile::tempdir().unwrap();let importer = WhatsappImporter::new(Some(fake_helper(dir.path())), &dir.path().join("data"), "m"); std::fs::create_dir_all(&importer.dir).unwrap();let seen = pairing_socket(&importer.socket(), "code"); assert_eq!(need(&importer.probe())["need"], json!({ "kind": "pair", "by": null, "code": null, "qr": null, "passkey": null, "confirm": null })); assert!(seen.lock().unwrap().iter().all(|r| r["op"] != "pair"), "a pairing started before the person asked"); assert!(importer.command("pairByCode", &json!({ "phone": "98" })).is_err()); importer.command("pairByCode", &json!({ "phone": "+91 98000 00000" })).unwrap();let pair = seen.lock().unwrap().iter().find(|r| r["op"] == "pair").cloned().unwrap(); assert_eq!(pair["phone"], "919800000000"); assert_eq!(need(&importer.probe())["need"], json!({ "kind": "pair", "by": "code", "code": "ABCD-1234", "qr": null, "passkey": null, "confirm": null })); importer.command("pairByQr", &json!({})).unwrap(); assert!(seen.lock().unwrap().iter().any(|r| r["op"] == "pair_cancel" && r["pairing"] == "p1")); assert_eq!(need(&importer.probe())["need"], json!({ "kind": "pair", "by": "qr", "code": null, "qr": "2@qr", "passkey": null, "confirm": null })); importer.stop(); }// RULE: a pairing that ended without a link says why on the card until// the person starts another. #[test]fn a_failed_pairing_says_why_until_the_next() {let dir = tempfile::tempdir().unwrap();let importer = WhatsappImporter::new(Some(fake_helper(dir.path())), &dir.path().join("data"), "m"); std::fs::create_dir_all(&importer.dir).unwrap();let _seen = pairing_socket(&importer.socket(), "failed"); importer.command("pairByCode", &json!({ "phone": "919800000000" })).unwrap();for _ in0..2 {let probe = need(&importer.probe()); assert_eq!(probe["need"]["by"], Value::Null); assert_eq!(probe["detail"], "WhatsApp did not link: the code expired. Try again."); } importer.stop(); }// RULE: two helpers never hold one linked session: a helper an earlier// run left behind (a crash, a forced quit) is stopped by its recorded pid// before the next one starts. #[test]fn a_helper_left_behind_is_stopped_before_the_next_starts() {// The importer knows its helper by the command line /bin/ps prints. A// sandbox that cannot run /bin/ps (a Claude Code session's, which// refuses the exec outright) cannot read even this test's own, so the// left-behind helper is rightly never matched: that is the sandbox,// not the importer, and the test says so rather than fail.if command_line(std::process::id() as i32).is_none() { println!("SKIPPED a_helper_left_behind_is_stopped_before_the_next_starts: /bin/ps cannot \ run here, so no process's command line can be read — a sandbox without process \ inspection. Run it outside the sandbox." );return; }let dir = tempfile::tempdir().unwrap();let binary = fake_helper(dir.path());let data = dir.path().join("data");let first = WhatsappImporter::new(Some(binary.clone()), &data, "m"); first.ensure_helper().unwrap();// The app died without stopping it: the helper runs on, unowned.letmut left = first.child.lock().unwrap().take().unwrap(); std::mem::forget(first);let second = WhatsappImporter::new(Some(binary), &data, "m"); second.ensure_helper().unwrap(); assert!(exits_soon(&mut left), "the helper left behind still runs");let ours = second.child.lock().unwrap().as_ref().unwrap().id(); assert_eq!(std::fs::read_to_string(second.pid_record()).unwrap(), format!("{ours}\n")); second.stop(); }// RULE: a recorded pid that is no longer this folder's helper (the system// gave it to another process) is never signalled. #[test]fn a_recorded_pid_of_another_process_is_left_alone() {let dir = tempfile::tempdir().unwrap();let binary = fake_helper(dir.path());let data = dir.path().join("data");letmut stranger = Command::new("/bin/sleep").arg("30").spawn().unwrap(); std::fs::create_dir_all(data.join("whatsapp-link")).unwrap();let importer = WhatsappImporter::new(Some(binary), &data, "m"); std::fs::write(importer.pid_record(), format!("{}\n", stranger.id())).unwrap(); importer.ensure_helper().unwrap(); assert!(stranger.try_wait().unwrap().is_none(), "another process was stopped"); stranger.kill().unwrap(); stranger.wait().unwrap(); importer.stop(); }// RULE: stopping the app ends its helper, and no probe after that starts// another. #[test]fn stop_ends_the_helper_and_starts_no_other() {let dir = tempfile::tempdir().unwrap();let binary = fake_helper(dir.path());let importer = WhatsappImporter::new(Some(binary), &dir.path().join("data"), "m"); importer.ensure_helper().unwrap();let pid = importer.child.lock().unwrap().as_ref().unwrap().id(); importer.stop(); assert!(importer.child.lock().unwrap().is_none()); assert!(command_line(pid as i32).is_none(), "the helper still runs"); assert!(!importer.pid_record().exists()); assert!(importer.ensure_helper().is_err()); assert!(importer.child.lock().unwrap().is_none()); }/// A helper socket that answers `hello` and `pair_status` with what the/// test sets, and records every request.structScripted { hello: std::sync::Arc<Mutex<Value>>, status: std::sync::Arc<Mutex<Value>>, seen: std::sync::Arc<Mutex<Vec<Value>>>, }implScripted {fn ops(&self, op: &str) -> Vec<Value> {self.seen .lock() .unwrap() .iter() .filter(|r| r["op"] == op) .cloned() .collect() }fn set_status(&self, status: Value) { *self.status.lock().unwrap() = status; } }fn scripted_socket(socket: &Path, hello: Value) -> Scripted {use std::io::{BufReadas _, BufReader, Writeas _};let listener = std::os::unix::net::UnixListener::bind(socket).unwrap();let scripted = Scripted { hello: std::sync::Arc::new(Mutex::new(hello)), status: std::sync::Arc::new(Mutex::new(json!({ "status": "starting" }))), seen: std::sync::Arc::default(), };let (hello, status, seen) = ( scripted.hello.clone(), scripted.status.clone(), scripted.seen.clone(), ); std::thread::spawn(move || {for stream in listener.incoming() {letOk(stream) = stream else { continue };let (hello, status, seen) = (hello.clone(), status.clone(), seen.clone()); std::thread::spawn(move || {letmut writer = stream.try_clone().unwrap();for line inBufReader::new(stream).lines() {letOk(line) = line else { break };let request: Value = serde_json::from_str(&line).unwrap(); seen.lock().unwrap().push(request.clone());let result = match request["op"].as_str() {Some("hello") => hello.lock().unwrap().clone(),Some("pair") => json!({ "pairing": "p1" }),Some("pair_status") => status.lock().unwrap().clone(), _ => Value::Null, };letmut out = serde_json::to_vec( &json!({ "reply": request["id"], "ok": true, "result": result }), ) .unwrap(); out.push(b'\n');if writer.write_all(&out).is_err() {break; } } }); } }); scripted }/// A browser that answers the passkey at once (or refuses), recording/// what it was asked and what it closed. #[derive(Default)]structFakeBrowser { asked: Mutex<Vec<(String, Value)>>, closed: Mutex<Vec<String>>, refuse: Mutex<Option<String>>, }implPasskeyBrowserforFakeBrowser {fn assert(&self, pairing: &str, options: &Value) -> Result<Value, String> {self.asked .lock() .unwrap() .push((pairing.to_string(), options.clone()));matchself.refuse.lock().unwrap().clone() {Some(why) => Err(why),None => Ok(assertion()), } }fn close(&self, pairing: &str) {self.closed.lock().unwrap().push(pairing.to_string()); } }/// WhatsApp's request options as the helper passes them on (whatsmeow's/// types.WebAuthnPublicKey).fn options() -> Value { json!({"challenge": "Y2hhbGxlbmdl", "timeout": 60000, "rpId": "whatsapp.com","allowCredentials": [{ "id": "Y3JlZGVudGlhbC1pZA", "type": "public-key", "transports": ["internal", "hybrid"] }],"userVerification": "required", "extensions": null }) }fn assertion() -> Value { json!({"id": "Y3JlZGVudGlhbC1pZA", "rawId": "Y3JlZGVudGlhbC1pZA", "type": "public-key","response": { "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0In0", "authenticatorData": "YXV0aA", "signature": "c2ln", "userHandle": "dXNlcg" } }) }fn until(what: &str, done: implFn() -> bool) {let deadline = Instant::now() + Duration::from_secs(5);while !done() { assert!(Instant::now() < deadline, "{what} did not happen"); std::thread::sleep(Duration::from_millis(20)); } }fn passkey_importer( dir: &Path, hello: Value, ) -> (WhatsappImporter, Scripted, std::sync::Arc<FakeBrowser>) {let browser = std::sync::Arc::new(FakeBrowser::default());let importer = WhatsappImporter::new(Some(fake_helper(dir)), &dir.join("data"), "m") .with_passkey_browser(browser.clone()); std::fs::create_dir_all(&importer.dir).unwrap();let scripted = scripted_socket(&importer.socket(), hello); (importer, scripted, browser) }fn unlinked_hello() -> Value { json!({ "version": 1, "accounts": [], "pending": 0 }) }// RULE: when WhatsApp asks for a passkey to link, the importer asks the// person's passkey in the browser with WhatsApp's own options, hands the// assertion to the helper for that pairing, shows the code to match, and// confirms only when the person does; the browser tab closes when the// pairing ends (7 Nov 2026: every re-link fell back to the code screen). #[test]fn whatsapp_passkey_is_asked_answered_and_confirmed() {let dir = tempfile::tempdir().unwrap();let (importer, helper, browser) = passkey_importer(dir.path(), unlinked_hello()); importer .command("pairByCode", &json!({ "phone": "919800000000" })) .unwrap(); helper.set_status(json!({ "pairing": "p1", "status": "passkey", "passkey": options() }));let probe = need(&importer.probe()); assert_eq!(probe["need"]["passkey"], "asking"); assert_eq!(probe["need"]["code"], Value::Null); until("the assertion reaching the helper", || { !helper.ops("passkey_response").is_empty() }); assert_eq!( browser.asked.lock().unwrap().clone(), vec![("p1".to_string(), options())] );let sent = helper.ops("passkey_response"); assert_eq!(sent.len(), 1); assert_eq!(sent[0]["pairing"], "p1"); assert_eq!(sent[0]["response"], assertion());// The helper has not moved on yet: the card says the answer went. assert_eq!(need(&importer.probe())["need"]["passkey"], "sent"); assert_eq!( browser.asked.lock().unwrap().len(),1,"the passkey was asked twice" ); helper.set_status( json!({ "pairing": "p1", "status": "passkey_code", "confirm": "WXYZ-2345" }), );let probe = need(&importer.probe()); assert_eq!(probe["need"]["passkey"], "confirm"); assert_eq!(probe["need"]["confirm"], "WXYZ-2345"); assert!( helper.ops("passkey_confirm").is_empty(),"confirmed before the person did" ); importer.command("passkeyConfirm", &json!({})).unwrap(); assert_eq!(helper.ops("passkey_confirm")[0]["pairing"], "p1"); helper.set_status( json!({ "pairing": "p1", "status": "passkey_confirmed", "confirm": "WXYZ-2345" }), ); assert_eq!(need(&importer.probe())["need"]["passkey"], "linking"); helper.set_status(json!({ "pairing": "p1", "status": "paired", "account": "919800000000@s.whatsapp.net" })); importer.probe(); assert!(browser.closed.lock().unwrap().contains(&"p1".to_string())); importer.stop(); }// RULE: a passkey the browser could not ask says why on the card, and// asking again opens it again; cancelling ends the pairing at the helper// and closes the tab. #[test]fn a_passkey_not_given_can_be_asked_again_or_cancelled() {let dir = tempfile::tempdir().unwrap();let (importer, helper, browser) = passkey_importer(dir.path(), unlinked_hello()); *browser.refuse.lock().unwrap() = Some("the WhatsApp tab was closed".to_string()); importer .command("pairByCode", &json!({ "phone": "919800000000" })) .unwrap(); helper.set_status(json!({ "pairing": "p1", "status": "passkey", "passkey": options() })); importer.probe(); until("the refusal", || { need(&importer.probe())["need"]["passkey"] == "retry" }); assert_eq!( need(&importer.probe())["detail"],"The passkey was not given: the WhatsApp tab was closed" ); assert!(helper.ops("passkey_response").is_empty()); *browser.refuse.lock().unwrap() = None; importer.command("passkeyUse", &json!({})).unwrap(); until("the second ask", || { !helper.ops("passkey_response").is_empty() }); assert_eq!(browser.asked.lock().unwrap().len(), 2); importer.command("pairCancel", &json!({})).unwrap(); assert_eq!(helper.ops("pair_cancel")[0]["pairing"], "p1"); assert!(browser.closed.lock().unwrap().contains(&"p1".to_string())); assert_eq!(need(&importer.probe())["need"]["by"], Value::Null); assert!(importer.command("passkeyConfirm", &json!({})).is_err()); importer.stop(); }/// A stand-in object answering Cotton MCP's `list_todos` with `open` and/// recording every tool call.fn fake_object(open: Vec<Value>) -> (ObjectClient, std::sync::Arc<Mutex<Vec<Value>>>) {use std::io::{BufReadas _, BufReader, Readas _, Writeas _};let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();let base = format!("http://{}", listener.local_addr().unwrap());let calls = std::sync::Arc::new(Mutex::new(Vec::<Value>::new()));let recorded = calls.clone(); std::thread::spawn(move || {for stream in listener.incoming() {letOk(stream) = stream else { continue };letmut writer = stream.try_clone().unwrap();letmut reader = BufReader::new(stream);loop {letmut length = 0usize;letmut line = String::new();if reader.read_line(&mut line).unwrap_or(0) == 0 {break; }loop { line.clear(); reader.read_line(&mut line).unwrap();if line == "\r\n" {break; }ifletSome(value) = line.to_ascii_lowercase().strip_prefix("content-length:") { length = value.trim().parse().unwrap(); } }letmut body = vec![0; length]; reader.read_exact(&mut body).unwrap();let call: Value = serde_json::from_slice(&body).unwrap(); recorded.lock().unwrap().push(call["params"].clone());let answer = match call["params"]["name"].as_str() {Some("list_todos") => json!({ "more": false, "todos": open }), _ => json!({ "id": "t1" }), };let reply = json!({ "jsonrpc": "2.0", "id": 1, "result": { "content": [{ "type": "text", "text": answer.to_string() }] } }).to_string();let head = format!("HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n", reply.len()); writer.write_all(head.as_bytes()).unwrap(); writer.write_all(reply.as_bytes()).unwrap(); } } }); (ObjectClient::new(base, Some("token".to_string())).unwrap(), calls, ) }// RULE: a number WhatsApp removed is said on the card with its time and// reason, and one todo asks the owner to link it again — once per// removal, and none while one is still open (5 Nov 2026 outage). #[test]fn a_removed_number_says_so_and_files_one_relink_todo() {let at = 1_793_871_000; // 5 Nov 2026let hello = json!({ "version": 1, "accounts": [], "pending": 0,"unlinked": { "account": "919800000000@s.whatsapp.net", "reason": "401: logged out from another device", "at": at } });let dir = tempfile::tempdir().unwrap();let (importer, _helper, _browser) = passkey_importer(dir.path(), hello.clone());let removed = Removed { reason: "logged out from another device".to_string(), at, };let probe = need(&importer.probe()); assert_eq!(probe["need"]["kind"], "pair"); assert_eq!( probe["detail"], format!("Unlinked by WhatsApp on {}: logged out from another device. Link it again.", removed.when() ) );let (object, calls) = fake_object(vec![ json!({ "id": "x", "title": "Agents. Buy milk", "status": "open" }), ]); importer.while_needed(&object).unwrap(); importer.while_needed(&object).unwrap();let made: Vec<Value> = calls .lock() .unwrap() .iter() .filter(|c| c["name"] == "create_todo") .cloned() .collect(); assert_eq!(made.len(), 1, "the todo was filed {} times", made.len()); assert_eq!( made[0]["arguments"]["title"], format!("Agents. Re-link WhatsApp on the Mac (device removed {})", removed.when() ) ); importer.stop();// After a restart, the open todo stands and no other is filed.let dir = tempfile::tempdir().unwrap();let (importer, _helper, _browser) = passkey_importer(dir.path(), hello); importer.probe();let (object, calls) = fake_object(vec![ json!({ "id": "t1", "title": made[0]["arguments"]["title"], "status": "open" }), ]); importer.while_needed(&object).unwrap(); assert!( calls .lock() .unwrap() .iter() .all(|c| c["name"] != "create_todo"),"a second todo beside an open one" );// Linked again: nothing more is said or filed. *_helper.hello.lock().unwrap() = json!({ "version": 1, "accounts": [{ "account": "919800000000@s.whatsapp.net", "state": "connected" }], "pending": 0 }); assert!(importer.probe().ready);let (object, calls) = fake_object(vec![]); importer.while_needed(&object).unwrap(); assert!(calls.lock().unwrap().is_empty()); importer.stop(); }}