//! A HEADLESS PARTNER for an emulator walk (20 Nov 2026): one invented phone through the C ABI //! against the dev Worker, driven line by line from a command file (COTTON_PARTNER_CMDS), answering one line each //! into COTTON_PARTNER_OUT: `name `, `start `, `send `, //! `file `, `inbox`, `flush`, `list`, `bodies `, `accept `, //! `read `, `group <n1,n2>`, `gadd|gremove <thread> <number>`, `ginfo <thread>`, //! `call <number> [video]`, `end`, `ratchet`, `refuse-next [n]` (dev server: this number's next n messages refused), `raw <method> <json>`, `quit`. Needs COTTON_WALK_SERVER, COTTON_WALK_CODE_FILE //! and COTTON_PARTNER_NUMBER too; skipped without them. Run it through cargo (`pnpm box:cargo test -p cotton-ffi //! --test headless_partner -- --nocapture`), which sets CARGO_MANIFEST_DIR. A call's `end` reaches no room (the //! partner holds no call socket): the ring is swept after two minutes, which is a missed call on the other side. #![allow(dead_code)] use std::ffi::{c_char, CStr, CString}; use std::path::PathBuf; use std::time::{Duration, Instant}; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine as _; use cotton_ffi::{cotton_call, cotton_close, cotton_open, cotton_string_free, CottonHandle}; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; const APP_VERSION: &str = "headless-chat"; const FLAVOUR: &str = "messages"; const ARRIVAL: Duration = Duration::from_secs(45); struct Walk { server: String, code: String, run: String, } impl Walk { fn from_env() -> Option<Walk> { let var = |name: &str| std::env::var(name).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty()); let (server, file) = (var("COTTON_WALK_SERVER")?, var("COTTON_WALK_CODE_FILE")?); let file = match file.strip_prefix("~/") { Some(rest) => PathBuf::from(std::env::var("HOME").expect("HOME")).join(rest), None => PathBuf::from(file), }; let code = std::fs::read_to_string(&file).unwrap_or_else(|e| panic!("the dev code file {} could not be read: {e}", file.display())).trim().to_string(); let run = var("COTTON_WALK_RUN").unwrap_or_else(|| format!("{:03}", (std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() % 900) + 100)); Some(Walk { server, code, run }) } /// An invented number for this run: +1 555 019 <run, three digits> <slot>, like +15550102151. fn number(&self, slot: u32) -> String { format!("+1555019{}{slot}", self.run) } } /// One phone: a core over its own container, as the app opens it. struct Phone { handle: *mut CottonHandle, _container: tempfile::TempDir, number: String, name: &'static str, key: String, credential: String, server: String, } impl Phone { fn open(walk: &Walk, number: &str, name: &'static str, device: &str) -> Result<Phone, String> { let container = tempfile::tempdir().map_err(|e| format!("no tempdir: {e}"))?; std::fs::create_dir_all(container.path().join("cotton")).map_err(|e| e.to_string())?; let config = json!({ "containerPath": container.path().join("cotton").to_string_lossy(), "appVersion": APP_VERSION, "timeZone": "Asia/Kolkata", "deviceSecret": URL_SAFE_NO_PAD.encode(Sha256::digest(format!("cotton headless chat {number} {device}").as_bytes())), "flavor": "dev", "manifest": manifest(&walk.server), }); let text = CString::new(config.to_string()).expect("no NUL"); let mut error: *mut c_char = std::ptr::null_mut(); // SAFETY: a NUL-terminated config and a writable error slot, as the JNI hands them. let handle = unsafe { cotton_open(text.as_ptr(), &mut error) }; if handle.is_null() { return Err(format!("cotton_open refused: {}", take(error))); } Ok(Phone { handle, _container: container, number: number.to_string(), name, key: String::new(), credential: String::new(), server: walk.server.clone() }) } fn call(&self, method: &str, request: Value) -> Result<Value, String> { let method_c = CString::new(method).expect("no NUL"); let request_c = CString::new(request.to_string()).expect("no NUL"); // SAFETY: a live handle and NUL-terminated strings; the answer is owned and freed by `take`. let answer = take(unsafe { cotton_call(self.handle, method_c.as_ptr(), request_c.as_ptr()) }); let answer: Value = serde_json::from_str(&answer).map_err(|e| format!("{method}: the answer is not JSON ({e})"))?; if answer["ok"] == json!(true) { return Ok(answer["data"].clone()); } let error = &answer["error"]; Err(format!("{} {method}: {} {}", self.name, error["code"].as_str().unwrap_or("?"), error["message"].as_str().unwrap_or("?"))) } /// The call with this phone's chat key added, as ChatEngine adds it. fn keyed(&self, method: &str, mut request: Value) -> Result<Value, String> { request["privateKey"] = json!(self.key); self.call(method, request) } /// Sign in (the SignIn form's calls, then `personal.connect`), mint the chat key and register it. fn sign_in(&mut self, walk: &Walk) -> Result<String, String> { self.call("personal.standLocal", json!({ "signedOut": true }))?; let challenge = self.call("personal.code", json!({ "server": walk.server, "phone": self.number }))?; let mut ask = json!({ "server": walk.server, "challengeId": challenge["challengeId"], "code": walk.code }); if let Some(database) = challenge.get("databaseId").filter(|d| !d.is_null()) { ask["databaseId"] = database.clone(); } let answer = self.call("personal.signIn", ask)?; let database = answer["databaseId"].as_str().or(challenge["databaseId"].as_str()).ok_or("personal.signIn named no database")?.to_string(); let credential = answer["credential"].as_str().ok_or("personal.signIn granted no credential")?; self.credential = credential.to_string(); self.call("personal.connect", json!({ "server": walk.server, "databaseId": database, "credential": credential, "deviceName": format!("headless chat {}", self.name), "appVersion": APP_VERSION }))?; self.key = self.call("chat.key", json!({}))?["privateKey"].as_str().ok_or("chat.key minted no key")?.to_string(); self.keyed("chat.register", json!({ "ratchet": ratchet() }))?; Ok(database) } /// `POST /v1/chat/dev/refuse-next { count }` on this number's own object (the dev server alone answers it): the /// next `count` messages any phone of this number sends are refused, so a walk sees a failed message and its Retry /// on the emulator signed in on the same number. The credential goes to curl on its stdin, never its arguments. fn refuse_next(&self, count: u32) -> Result<Value, String> { use std::io::Write as _; let mut curl = std::process::Command::new("curl") .args(["-sS", "-K", "-", "-X", "POST", "-H", "content-type: application/json", "--data", &json!({ "count": count }).to_string(), &format!("{}/v1/chat/dev/refuse-next", self.server.trim_end_matches('/'))]) .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .spawn() .map_err(|e| format!("curl: {e}"))?; writeln!(curl.stdin.take().ok_or("curl: no stdin")?, "header = \"Authorization: Bearer {}\"", self.credential).map_err(|e| e.to_string())?; let done = curl.wait_with_output().map_err(|e| e.to_string())?; serde_json::from_slice(&done.stdout).map_err(|_| format!("refuse-next: {}", String::from_utf8_lossy(&done.stdout))) } /// The inbox, as a (re)connect asks it. fn incoming(&self) -> Result<Value, String> { self.keyed("chat.incoming", json!({})) } fn flush(&self) -> Result<Value, String> { self.keyed("chat.flush", json!({})) } /// The inbox asked until `until` holds of the thread list, or ARRIVAL passes. fn wait_for(&self, what: &str, until: impl Fn(&Phone) -> Result<bool, String>) -> Result<(), String> { let started = Instant::now(); loop { self.incoming()?; if until(self)? { return Ok(()); } if started.elapsed() > ARRIVAL { return Err(format!("{}: {what} did not arrive in {}s", self.name, ARRIVAL.as_secs())); } std::thread::sleep(Duration::from_secs(2)); } } /// The bodies of a thread's messages, oldest first. fn bodies(&self, thread: &str) -> Result<Vec<String>, String> { let answer = self.call("chat.thread", json!({ "thread": thread }))?; Ok(bubbles(&answer).iter().filter_map(|b| b["text"].as_str().or(b["body"].as_str()).map(str::to_string)).collect()) } /// The list's thread whose title or number says `who`. fn thread_named(&self, who: &str) -> Result<Option<String>, String> { let list = self.call("chat.list", json!({}))?; Ok(rows(&list).iter().find(|r| r.to_string().contains(who)).and_then(|r| r["thread"].as_str().or(r["id"].as_str()).map(str::to_string))) } } impl Drop for Phone { fn drop(&mut self) { // SAFETY: the pointer cotton_open answered, closed once. unsafe { cotton_close(self.handle) }; } } /// Every bubble a `chat.thread` answer carries, wherever its sections keep them. fn bubbles(answer: &Value) -> Vec<Value> { let mut out = Vec::new(); fn walk(v: &Value, out: &mut Vec<Value>) { match v { Value::Object(map) => { if map.contains_key("message") && (map.contains_key("text") || map.contains_key("body")) { out.push(v.clone()); return; } map.values().for_each(|c| walk(c, out)); } Value::Array(items) => items.iter().for_each(|c| walk(c, out)), _ => {} } } walk(answer.get("bubbles").or(answer.get("items")).or(answer.get("days")).unwrap_or(answer), &mut out); out } fn rows(list: &Value) -> Vec<Value> { list.get("rows").or(list.get("threads")).and_then(Value::as_array).cloned().unwrap_or_default() } fn take(text: *mut c_char) -> String { if text.is_null() { return String::new(); } // SAFETY: an owned string from the C ABI, freed once with its own free. let owned = unsafe { CStr::from_ptr(text) }.to_string_lossy().into_owned(); unsafe { cotton_string_free(text) }; owned } fn manifest(server: &str) -> Value { let path = cotton_store::manifest_dir().join("../../apps/cotton/App/Flavours").join(FLAVOUR).join("flavour.json"); let mut whole: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{} reads: {error}", path.display()))).expect("JSON"); if whole["business"]["server"].is_object() { whole["business"]["server"] = json!(server); } whole } fn short(v: &Value) -> String { let s = v.to_string(); if s.len() > 1200 { format!("{}…", &s[..s.char_indices().nth(1200).map(|c| c.0).unwrap_or(s.len())]) } else { s } } fn out(line: String) { use std::io::Write; let path = std::env::var("COTTON_PARTNER_OUT").unwrap(); let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path).unwrap(); writeln!(f, "{line}").unwrap(); } #[test] fn a_partner_phone_takes_commands() { let (Some(walk), Ok(cmds), Ok(number)) = (Walk::from_env(), std::env::var("COTTON_PARTNER_CMDS"), std::env::var("COTTON_PARTNER_NUMBER")) else { eprintln!("SKIPPED: no partner"); return; }; // COTTON_PARTNER_DEVICE: another device of the same number (e.g. "2", the emulator's own number's second phone, which // asks its object to refuse the emulator's next message). let device = std::env::var("COTTON_PARTNER_DEVICE").unwrap_or_else(|_| "1".into()); let mut me = Phone::open(&walk, &number, "P", &device).expect("opens"); match me.sign_in(&walk) { Ok(db) => out(format!("READY {number} {}", &db[..8])), Err(e) => { out(format!("ERR sign-in {e}")); return; } } let mut done = 0usize; loop { let text = std::fs::read_to_string(&cmds).unwrap_or_default(); let lines: Vec<String> = text.lines().map(str::to_string).collect(); if lines.len() <= done { std::thread::sleep(Duration::from_millis(700)); continue; } for line in lines[done..].to_vec() { done += 1; let words: Vec<&str> = line.split_whitespace().collect(); let rest = |n: usize| words.get(n..).map(|w| w.join(" ")).unwrap_or_default(); let arg = |n: usize| words.get(n).copied().unwrap_or("").to_string(); let said: Result<Value, String> = match words.first().copied().unwrap_or("") { "quit" => { out("BYE".into()); return; } "name" => me.call("chat.profile.set", json!({ "name": rest(1) })), "start" => me.call("chat.start", json!({ "number": arg(1) })), "send" => me.keyed("chat.send", json!({ "thread": arg(1), "body": rest(2) })), "file" => me.keyed("chat.send", json!({ "thread": arg(1), "body": rest(5), "pictures": [{ "path": arg(2), "mime": arg(3), "name": arg(4) }] })), "inbox" => me.incoming(), // c2: whether this phone speaks c2 and what its ratchet holds. "ratchet" => me.keyed("chat.ratchet", json!({})), "flush" => me.flush(), "list" => me.call("chat.list", json!({})).map(|l| json!(rows(&l).iter().map(|r| json!({"thread": r["thread"].clone().as_str().map(str::to_string).or(r["id"].as_str().map(str::to_string)), "title": r["title"], "line": r["line"].clone()})).collect::<Vec<_>>())), "bodies" => me.bodies(&arg(1)).map(|b| json!(b)), "thread" => me.call("chat.thread", json!({ "thread": arg(1) })), "accept" => me.keyed("chat.accept", json!({ "thread": arg(1) })), "read" => me.call("chat.act", json!({ "act": "read", "thread": arg(1) })), "group" => me.keyed("chat.group.create", json!({ "title": arg(1), "members": arg(2).split(',').collect::<Vec<_>>() })), "gadd" => me.keyed("chat.group.add", json!({ "thread": arg(1), "members": [arg(2)] })), "gremove" => me.keyed("chat.group.remove", json!({ "thread": arg(1), "member": arg(2) })), "ginfo" => me.call("chat.group.info", json!({ "thread": arg(1) })), "call" => me.call("calls.start", json!({ "number": arg(1), "video": arg(2) == "video" })), "end" => me.call("calls.end", json!({})), "refuse-next" => me.refuse_next(arg(1).parse().unwrap_or(1)), "raw" => me.call(&arg(1), serde_json::from_str(&rest(2)).unwrap_or(json!({}))), other => Err(format!("unknown {other}")), }; match said { Ok(v) => out(format!("OK {line} => {}", short(&v))), Err(e) => out(format!("ERR {line} => {e}")), } } } } /// Whether this phone says it opens c2 boxes, as the Android app does: yes unless COTTON_WALK_RATCHET=0. fn ratchet() -> bool { std::env::var("COTTON_WALK_RATCHET").map_or(true, |v| v != "0") }