Cotton code
485 lines · 25.8 KB · RustRaw
//! THE HEADLESS CHAT WALK: Cotton Chat between three, four phones driven//! straight through the C ABI the Android JNI wraps (`cotton_open` ///! `cotton_call`), against the DEV Worker, with no emulator and no screen.//! Each phone asks the core what `ChatEngine.kt` asks it: `chat.key` once,//! `chat.register`, then `chat.send` / `chat.flush` / `chat.incoming` with the//! chat key, as the socket or a push would hand them in.//!//! The flows (one line each, `FLOW <n> <name> PASS|FAIL (<ms>ms): <said>`)://!//! 1. sign-in — A, B, C sign in with invented numbers, mint a chat key and register it.//! 2. ask — nobody is found by their number (DISCOVERY OFF 2): A starts chats//!    with B and C (not on Cotton yet here) and writes; each sees A's ask as a//!    request and accepts; A's pass hears it and what waited goes.//! 3. one-to-one — A writes to B, B receives and answers, A receives.//! 4. waiting — A writes to D, who is not on Cotton: `reach` notYet, the message//!    waits; D signs up, registers and accepts A's ask; A's flush delivers it.//! 5. group — A makes a group of A, B, C; writes; B and C read it; A adds D, D//!    reads what comes after; A removes C, C reads nothing written after; B leaves.//! 6. notices — B's shade lists A's unread chat; `chat.act read` clears it; B's//!    second phone hears the read and its notice clears too.//! 7. files — A sends a PDF and an MP4; B opens both with `chat.file`, bytes equal.//!//! SKIPPED unless COTTON_WALK_SERVER (the dev Worker) and COTTON_WALK_CODE_FILE//! (the dev code's file: read, never printed) are set. The numbers are invented//! for each run (+1555019 and four digits); nothing real is touched.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,}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() })    }    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.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)    }    /// 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() > 400 { format!("{}…", &s[..400]) } else { s }}struct Flows {    failed: Vec<String>,}impl Flows {    fn run(&mut self, n: u32, name: &str, flow: impl FnOnce() -> Result<String, String>) -> bool {        let started = Instant::now();        let outcome = flow();        let ms = started.elapsed().as_millis();        match &outcome {            Ok(said) => println!("FLOW {n} {name} PASS ({ms}ms): {said}"),            Err(said) => {                println!("FLOW {n} {name} FAIL ({ms}ms): {said}");                self.failed.push(format!("{n} {name}"));            }        }        outcome.is_ok()    }}fn ensure(ok: bool, said: impl FnOnce() -> String) -> Result<(), String> {    if ok { Ok(()) } else { Err(said()) }}#[test]fn chat_between_phones_walks_through_the_core_against_the_dev_worker() {    let Some(walk) = Walk::from_env() else {        eprintln!("SKIPPED: set COTTON_WALK_SERVER and COTTON_WALK_CODE_FILE to walk chat against the dev Worker");        return;    };    let mut flows = Flows { failed: Vec::new() };    let (na, nb, nc, nd) = (walk.number(1), walk.number(2), walk.number(3), walk.number(4));    println!("run {} numbers A {na} B {nb} C {nc} D {nd}", walk.run);    let mut a = Phone::open(&walk, &na, "A", "1").expect("A opens");    let mut b = Phone::open(&walk, &nb, "B", "1").expect("B opens");    let mut c = Phone::open(&walk, &nc, "C", "1").expect("C opens");    let mut d = Phone::open(&walk, &nd, "D", "1").expect("D opens");    let signed = flows.run(1, "sign-in", || {        let ids = [a.sign_in(&walk)?, b.sign_in(&walk)?, c.sign_in(&walk)?];        Ok(format!("three databases {}", ids.iter().map(|i| &i[..8]).collect::<Vec<_>>().join(" ")))    });    assert!(signed, "nothing walks without sign-in");    flows.run(2, "ask", || {        b.call("chat.profile.set", json!({ "name": "Bea Walk" }))?;        let mut asked = Vec::new();        for n in [&nb, &nc] {            let started = a.call("chat.start", json!({ "number": n }))?;            ensure(started["reach"] == json!("notYet"), || format!("reach {} for a number not known here", started["reach"]))?;            let thread = started["thread"].as_str().ok_or("no thread")?.to_string();            a.keyed("chat.send", json!({ "thread": thread, "body": "hello, it's A" }))?;            asked.push(thread);        }        for p in [&b, &c] {            p.wait_for("A's ask", |p| Ok(p.thread_named(&na)?.is_some()))?;            let thread = p.thread_named(&na)?.ok_or("no request from A")?;            p.call("chat.accept", json!({ "thread": thread }))?;        }        let started = Instant::now();        loop {            a.flush()?;            let mut on = 0;            for thread in &asked {                if a.call("chat.thread", json!({ "thread": thread }))?["reach"]["state"] == json!("on") {                    on += 1;                }            }            if on == asked.len() {                break;            }            if started.elapsed() > ARRIVAL {                return Err(format!("{on} of {} accepted asks reached A", asked.len()));            }            std::thread::sleep(Duration::from_secs(2));        }        Ok("B and C asked by A, accepted, reached; nobody found by their number".into())    });    let mut ab = String::new();    flows.run(3, "one-to-one", || {        let started = a.call("chat.start", json!({ "number": nb }))?;        ensure(started["reach"] == json!("on"), || format!("reach {}", started["reach"]))?;        ab = started["thread"].as_str().ok_or("no thread")?.to_string();        let sent = a.keyed("chat.send", json!({ "thread": ab, "body": "hello from A" }))?;        ensure(sent["state"] == json!("sent"), || format!("A's send {}", short(&sent)))?;        b.wait_for("A's hello", |p| Ok(p.thread_named(&na)?.is_some()))?;        let ba = b.thread_named(&na)?.ok_or("B has no chat with A")?;        let said = b.bodies(&ba)?;        ensure(said.iter().any(|s| s == "hello from A"), || format!("B reads {said:?}"))?;        // A stranger's first message is a request on B's side; B answers it (accept, then write).        let _ = b.call("chat.accept", json!({ "thread": ba }));        b.keyed("chat.send", json!({ "thread": ba, "body": "hi A, B here" }))?;        a.wait_for("B's answer", |p| Ok(p.bodies(&ab)?.iter().any(|s| s == "hi A, B here")))?;        Ok(format!("A→B and B→A delivered; B's thread {}", &ba[..8.min(ba.len())]))    });    let mut ad = String::new();    flows.run(4, "waiting", || {        let started = a.call("chat.start", json!({ "number": nd }))?;        ensure(started["reach"] == json!("notYet"), || format!("reach {}", started["reach"]))?;        ad = started["thread"].as_str().ok_or("no thread")?.to_string();        let sent = a.keyed("chat.send", json!({ "thread": ad, "body": "for when you join" }))?;        let thread = a.call("chat.thread", json!({ "thread": ad }))?;        ensure(thread["reach"]["state"] == json!("notYet") && thread["reach"]["waiting"] == json!(1), || format!("reach {} state {}", thread["reach"], sent["state"]))?;        let invite = a.call("chat.invite", json!({ "thread": ad }))?;        ensure(invite["sms"].as_str().is_some_and(|s| s.starts_with("sms:")), || format!("invite {}", short(&invite)))?;        // D joins: signs up and registers its first chat device.        d.call("personal.standLocal", json!({ "signedOut": true }))?;        let challenge = d.call("personal.code", json!({ "server": walk.server, "phone": d.number }))?;        let answer = d.call("personal.signIn", json!({ "server": walk.server, "challengeId": challenge["challengeId"], "code": walk.code, "databaseId": challenge["databaseId"] }))?;        let database = answer["databaseId"].as_str().or(challenge["databaseId"].as_str()).ok_or("no database")?.to_string();        d.call("personal.connect", json!({ "server": walk.server, "databaseId": database, "credential": answer["credential"], "deviceName": "headless chat D", "appVersion": APP_VERSION }))?;        d.key = d.call("chat.key", json!({}))?["privateKey"].as_str().ok_or("no key")?.to_string();        d.keyed("chat.register", json!({ "ratchet": ratchet() }))?;        // A's ask reaches D once D's first chat device comes; D accepts it.        d.wait_for("A's ask", |p| Ok(p.thread_named(&na)?.is_some()))?;        let request = d.thread_named(&na)?.ok_or("D has no request from A")?;        d.call("chat.accept", json!({ "thread": request }))?;        // A's phone hears the reach frame (or its next pass) and flushes.        let started = Instant::now();        loop {            a.flush()?;            let reach = a.call("chat.thread", json!({ "thread": ad }))?["reach"].clone();            if reach["state"] == json!("on") && reach["waiting"] == json!(0) {                break;            }            if started.elapsed() > ARRIVAL {                return Err(format!("A's waiting message never went: reach {reach}"));            }            std::thread::sleep(Duration::from_secs(2));        }        d.wait_for("the waiting message", |p| Ok(match p.thread_named(&na)? { Some(t) => p.bodies(&t)?.iter().any(|s| s == "for when you join"), None => false }))?;        Ok("notYet, waited 1, D joined and accepted, reach on, delivered".into())    });    flows.run(5, "group", || {        let made = a.keyed("chat.group.create", json!({ "title": "Walk group", "members": [nb, nc] }))?;        let g = made["thread"].as_str().ok_or("no group thread")?.to_string();        a.keyed("chat.send", json!({ "thread": g, "body": "group hello" }))?;        let find = |p: &Phone| -> Result<Option<String>, String> { p.thread_named("Walk group") };        for p in [&b, &c] {            p.wait_for("the group", |p| Ok(find(p)?.is_some()))?;            let t = find(p)?.unwrap();            let _ = p.keyed("chat.accept", json!({ "thread": t }));            p.wait_for("group hello", |p| Ok(p.bodies(&t)?.iter().any(|s| s == "group hello")))?;        }        a.keyed("chat.group.add", json!({ "thread": g, "members": [nd] }))?;        a.flush()?;        d.wait_for("the group", |p| Ok(find(p)?.is_some()))?;        let dg = find(&d)?.unwrap();        let _ = d.keyed("chat.accept", json!({ "thread": dg }));        let before = d.bodies(&dg)?;        ensure(!before.iter().any(|s| s == "group hello"), || format!("D reads from before it joined: {before:?}"))?;        a.keyed("chat.group.remove", json!({ "thread": g, "member": nc }))?;        a.flush()?;        a.keyed("chat.send", json!({ "thread": g, "body": "after C left" }))?;        d.wait_for("after C left", |p| Ok(p.bodies(&dg)?.iter().any(|s| s == "after C left")))?;        let bg = find(&b)?.unwrap();        b.wait_for("after C left", |p| Ok(p.bodies(&bg)?.iter().any(|s| s == "after C left")))?;        std::thread::sleep(Duration::from_secs(3));        c.incoming()?;        let cg = find(&c)?.unwrap();        let c_reads = c.bodies(&cg)?;        ensure(!c_reads.iter().any(|s| s == "after C left"), || format!("removed C reads {c_reads:?}"))?;        let info = c.call("chat.group.info", json!({ "thread": cg }))?;        ensure(info["you"] == json!("removed"), || format!("C is {}", info["you"]))?;        b.keyed("chat.group.leave", json!({ "thread": bg }))?;        b.flush()?;        let started = Instant::now();        loop {            a.incoming()?;            let info = a.call("chat.group.info", json!({ "thread": g }))?;            let members: Vec<String> = info["members"].as_array().into_iter().flatten().filter_map(|m| m["number"].as_str().map(str::to_string)).collect();            if !members.contains(&nb) {                ensure(members.contains(&nd) && !members.contains(&nc), || format!("members {members:?}"))?;                break;            }            if started.elapsed() > ARRIVAL {                return Err(format!("A still lists B after B left: {members:?}"));            }            std::thread::sleep(Duration::from_secs(2));        }        Ok("made, written, D added reads only after, C removed reads nothing after, B left".into())    });    flows.run(6, "notices", || {        let mut b2 = Phone::open(&walk, &nb, "B2", "2")?;        b2.sign_in(&walk)?;        a.keyed("chat.send", json!({ "thread": ab, "body": "are you there?" }))?;        let ba = b.thread_named(&na)?.ok_or("B has no chat with A")?;        b.wait_for("a notice", |p| Ok(p.call("chat.notices", json!({}))?["notices"].as_array().is_some_and(|n| n.iter().any(|x| x["thread"] == json!(ba)))))?;        b2.wait_for("a notice on B2", |p| Ok(p.call("chat.notices", json!({}))?["notices"].as_array().is_some_and(|n| !n.is_empty())))?;        let notice = b.call("chat.notices", json!({}))?;        let one = notice["notices"].as_array().unwrap().iter().find(|x| x["thread"] == json!(ba)).unwrap().clone();        ensure(one["actions"] == json!(true) && one["request"] == json!(false), || format!("notice {}", short(&one)))?;        // Reply from the notification, as the contract says.        b.call("chat.act", json!({ "act": "send", "thread": ba, "text": "replied from the shade" }))?;        b.call("chat.act", json!({ "act": "read", "thread": ba }))?;        b.flush()?;        let after = b.call("chat.notices", json!({}))?;        ensure(!after["notices"].as_array().into_iter().flatten().any(|x| x["thread"] == json!(ba)), || format!("B's notice stays: {}", short(&after)))?;        a.wait_for("the shade's reply", |p| Ok(p.bodies(&ab)?.iter().any(|s| s == "replied from the shade")))?;        b2.wait_for("the read from B", |p| Ok(p.call("chat.notices", json!({}))?["notices"].as_array().is_none_or(|n| n.is_empty())))?;        Ok("listed with actions, reply sent from it, cleared on B and on B's second phone".into())    });    flows.run(7, "files", || {        let dir = tempfile::tempdir().map_err(|e| e.to_string())?;        let pdf = dir.path().join("walk.pdf");        let mp4 = dir.path().join("walk.mp4");        let pdf_bytes = b"%PDF-1.4\n% invented walk file\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\n".to_vec();        let mp4_bytes: Vec<u8> = [&[0, 0, 0, 0x18][..], b"ftypmp42", &[0; 12]].concat();        std::fs::write(&pdf, &pdf_bytes).map_err(|e| e.to_string())?;        std::fs::write(&mp4, &mp4_bytes).map_err(|e| e.to_string())?;        let sent = a.keyed("chat.send", json!({ "thread": ab, "body": "two files", "pictures": [            { "path": pdf.to_string_lossy(), "mime": "application/pdf", "name": "walk.pdf" },            { "path": mp4.to_string_lossy(), "mime": "video/mp4", "name": "walk.mp4" },        ] }))?;        ensure(sent["state"] == json!("sent"), || format!("send {}", short(&sent)))?;        let ba = b.thread_named(&na)?.ok_or("B has no chat with A")?;        b.wait_for("two files", |p| Ok(p.bodies(&ba)?.iter().any(|s| s == "two files")))?;        let answer = b.call("chat.thread", json!({ "thread": ba }))?;        let message = bubbles(&answer).into_iter().find(|x| x["text"] == json!("two files") || x["body"] == json!("two files")).and_then(|x| x["message"].as_str().map(str::to_string)).ok_or("no bubble")?;        let out = tempfile::tempdir().map_err(|e| e.to_string())?;        let first = b.call("chat.file", json!({ "message": message, "index": 0, "dir": out.path().to_string_lossy() }))?;        let second = b.call("chat.file", json!({ "message": message, "index": 1, "dir": out.path().to_string_lossy() }))?;        let read = |v: &Value| std::fs::read(v["path"].as_str().unwrap_or_default()).unwrap_or_default();        ensure(read(&first) == pdf_bytes && first["mime"] == json!("application/pdf"), || format!("pdf {}", short(&first)))?;        ensure(read(&second) == mp4_bytes && second["mime"] == json!("video/mp4") && second["path"].as_str().is_some_and(|p| p.ends_with(".mp4")), || format!("mp4 {}", short(&second)))?;        Ok(format!("pdf and mp4 opened, bytes equal ({} {})", first["path"].as_str().unwrap_or("").rsplit('/').next().unwrap_or(""), second["path"].as_str().unwrap_or("").rsplit('/').next().unwrap_or("")))    });    // The c2 box: with COTTON_WALK_RATCHET unset each phone said ratchet: true, so every word above    // between them went on a Double Ratchet. A's three words while B is away open in order when B comes back; then each    // phone's ratchet holds sessions and pins (evidence without a key or a word).    if ratchet() {        flows.run(8, "c2", || {            let ab = a.call("chat.start", json!({ "number": nb }))?["thread"].as_str().ok_or("no thread")?.to_string();            for n in 0..3 {                let sent = a.keyed("chat.send", json!({ "thread": ab, "body": format!("while B was away {n}") }))?;                ensure(sent["state"] == json!("sent"), || format!("A's send {}", short(&sent)))?;            }            let ba = b.thread_named(&na)?.ok_or("B has no chat with A")?;            b.wait_for("A's three words", |p| Ok(p.bodies(&ba)?.iter().filter(|s| s.starts_with("while B was away")).count() == 3))?;            let mut said = Vec::new();            for (name, phone) in [("A", &a), ("B", &b), ("C", &c), ("D", &d)] {                let held = phone.keyed("chat.ratchet", json!({}))?;                ensure(held["speaks"] == json!(true) && held["sessions"].as_u64().unwrap_or(0) > 0 && held["pinned"].as_u64().unwrap_or(0) > 0, || format!("{name}'s ratchet {held}"))?;                said.push(format!("{name} {}/{}", held["sessions"], held["pinned"]));            }            Ok(format!("B caught up on 3; sessions/pinned: {}", said.join(", ")))        });    }    assert!(flows.failed.is_empty(), "flows failed: {:?}", flows.failed);}/// 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")}