Cotton code
1538 lines · 82.7 KB · RustRaw
//! Cotton groups across several phones over a relay that stands in for the//! Worker's chat routes (apps/business/src/chat/chat.ts): it routes boxes by//! number and device handle, holds them until acked, and keeps what each//! person's object would keep (accepted people, the groups a phone said it is//! in). It never opens a box. Every number and key is invented.use std::collections::{HashMap, HashSet};use std::sync::{Arc, Mutex};use cotton_client::transport::http1::Http1Request;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::{Answer, Exchange, Origin};use cotton_core::chat::payload::Payload;use cotton_core::chat::seal;use cotton_core::vault::wrap::public_of;use serde_json::{json, Value};use crate::handle::CottonHandle;use crate::phone::passwords::tests::phone;use crate::phone::personal_object::ObjectDoor;const ASHA: &str = "+15550200001";const BEN: &str = "+15550200002";const CHEN: &str = "+15550200003";const DEV: &str = "+15550200004";const EVE: &str = "+15550200005";#[derive(Debug, Default)]struct World {    /// credential → (number, handle, public key)    devices: Vec<(String, String, String, String)>,    held: HashMap<String, Vec<Value>>,    /// (owner, peer): the owner accepted the peer one to one.    accepted: HashSet<(String, String)>,    /// (owner, group) → the members the owner's phone said are in it.    groups: HashMap<(String, String), Vec<String>>,    files: HashMap<String, Vec<u8>>,    /// Files asked of the chat store, all told.    file_gets: usize,    /// Every envelope sent: (from, to, kind, group).    sent: Vec<(String, String, String, Option<String>)>,    /// Kinds kept back from a credential's inbox until let go.    hidden: HashMap<String, HashSet<String>>,    clock: i64,    /// One-time keys claimed, all told.    claims: usize,    /// c2: each credential's record, its fallback key and its one-time keys, as the Worker keeps them.    c2: HashMap<String, Value>,    fallback: HashMap<String, Value>,    prekeys: HashMap<String, Vec<Value>>,    /// (device handle, id): each message the object took as a re-send after a reset, once.    resent: HashSet<(String, String)>,    /// An agent in a chat: (owner, agent, thread, on, the sealed about) as each owner's phone told it.    agent_chats: Vec<(String, String, String, bool, Option<String>)>,    /// Feed items as posted: (owner, item).    feed: Vec<(String, Value)>,    /// Acts reported: (owner, act, state, error).    done: Vec<(String, String, String, Option<String>)>,}#[derive(Debug, Default)]struct Relay(Mutex<World>, Line);/// A slow line for the chat store's uploads: while `held`, a picture going/// up waits (counted in `waiting`) until it is let go.#[derive(Debug, Default)]struct Line {    held: Mutex<bool>,    moved: std::sync::Condvar,    waiting: std::sync::atomic::AtomicUsize,}impl Line {    fn hold(&self, held: bool) {        *self.held.lock().unwrap() = held;        self.moved.notify_all();    }    fn pass(&self) {        let mut held = self.held.lock().unwrap();        self.waiting.fetch_add(1, std::sync::atomic::Ordering::SeqCst);        while *held {            held = self.moved.wait(held).unwrap();        }        self.waiting.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);    }}struct Reply {    status: u16,    body: std::io::Cursor<Vec<u8>>,}impl std::io::Read for Reply {    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {        self.body.read(buf)    }}impl Answer for Reply {    fn status(&self) -> u16 {        self.status    }    fn header(&self, name: &str) -> Option<String> {        name.eq_ignore_ascii_case("content-type").then(|| "application/json".into())    }    fn content_length(&self) -> Option<u64> {        Some(self.body.get_ref().len() as u64)    }    fn set_read_timeout(&mut self, _: std::time::Duration) -> std::io::Result<()> {        Ok(())    }}fn ok(value: Value) -> Result<Box<dyn Answer>, String> {    Ok(Box::new(Reply { status: 200, body: std::io::Cursor::new(value.to_string().into_bytes()) }))}fn status(code: u16) -> Result<Box<dyn Answer>, String> {    Ok(Box::new(Reply { status: code, body: std::io::Cursor::new(json!({ "code": "refused", "message": "refused" }).to_string().into_bytes()) }))}impl World {    /// As the Worker: an act of an agent, sealed for each of its owner's devices that says it opens them.    fn act(&mut self, owner: &str, act: Value) {        let id = act["id"].as_str().unwrap_or_default().to_string();        for d in self.devices.clone().iter().filter(|d| d.1 == owner) {            let key = seal::key_from_text(&d.3).unwrap();            let sealed = seal::seal(&scalar(99), &key, json!({ "v": 1, "act": act }).to_string().as_bytes()).unwrap();            self.clock += 1;            let at = chrono::Utc::now().timestamp_millis() + self.clock;            self.held.entry(d.0.clone()).or_default().push(json!({ "id": id, "kind": "agent", "peer": owner, "out": false, "request": false, "box": sealed, "at": at }));        }    }    fn number_of(&self, credential: &str) -> String {        self.devices.iter().find(|d| d.0 == credential).map(|d| d.1.clone()).unwrap_or_default()    }    fn keys_of(&self, number: &str, not: &str) -> Vec<Value> {        let found: Vec<Value> = self            .devices            .iter()            .filter(|d| d.1 == number && d.0 != not)            .map(|d| match self.c2.get(&d.0) {                Some(c2) => json!({ "device": d.2, "key": d.3, "c2": c2 }),                None => json!({ "device": d.2, "key": d.3 }),            })            .collect();        if found.is_empty() && number != self.number_of(not) {            // A number nobody holds: a made-up device, the same each time.            let fake = public_of(&[number.len() as u8 + 9; 32]);            return vec![json!({ "device": format!("{:0>22}", number.trim_start_matches('+')), "key": seal::key_text(&fake) })];        }        found    }    fn welcome(&self, owner: &str, from: &str, group: Option<&str>) -> bool {        self.accepted.contains(&(owner.to_string(), from.to_string())) || group.is_some_and(|g| self.groups.get(&(owner.to_string(), g.to_string())).is_some_and(|m| m.iter().any(|n| n == from)))    }    fn land(&mut self, to: &str, from: &str, kind: &str, id: &str, group: Option<&str>, boxes: &serde_json::Map<String, Value>, out: bool) {        self.clock += 1;        let request = !out && !self.welcome(to, from, group);        if request && kind != "message" && kind != "group" {            return;        }        for d in self.devices.clone().iter().filter(|d| d.1 == to) {            if let Some(b) = boxes.get(&d.2) {                // The object's clock, ms, as the Worker's Date.now() is.                let at = chrono::Utc::now().timestamp_millis() + self.clock;                // As the Worker: `peer` is the other person (the recipient on a person's own copy; their own number on a group's).                let item = json!({ "id": id, "kind": kind, "peer": from.to_string(), "out": out, "request": request, "box": b, "at": at, "group": group });                self.held.entry(d.0.clone()).or_default().push(item);            }        }    }}impl Exchange for Relay {    fn send(&self, _origin: &Origin, request: &Http1Request<'_>, _ceiling: std::time::Duration) -> Result<Box<dyn Answer>, String> {        if (request.method, request.path) == ("PUT", "/v1/chat/files") {            self.1.pass();        }        let mut w = self.0.lock().unwrap();        let credential = request.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case("authorization")).map(|(_, v)| v.trim_start_matches("Bearer ").to_string()).unwrap_or_default();        let me = w.number_of(&credential);        let body: Value = request.body.and_then(|b| serde_json::from_slice(b).ok()).unwrap_or(Value::Null);        let (path, query) = request.path.split_once('?').unwrap_or((request.path, ""));        match (request.method, path) {            ("GET", "/v1/chat/keys") => {                let number = query.trim_start_matches("number=").replace("%2B", "+");                let own = w.keys_of(&me, &credential);                let devices = if number == me { vec![] } else { w.keys_of(&number, &credential) };                ok(json!({ "me": me, "devices": devices, "own": own }))            }            ("POST", "/v1/chat/keys") => {                let mut peers = serde_json::Map::new();                for n in body["numbers"].as_array().into_iter().flatten().filter_map(Value::as_str) {                    if n != me {                        peers.insert(n.into(), json!(w.keys_of(n, &credential)));                    }                }                ok(json!({ "me": me, "peers": peers, "own": w.keys_of(&me, &credential) }))            }            ("POST", "/v1/chat/group/send") => {                let (id, kind, group) = (body["id"].as_str().unwrap_or_default().to_string(), body["kind"].as_str().unwrap_or_default().to_string(), body["group"].as_str().map(str::to_string));                // As the Worker: a message sealed for a member's devices of before is refused.                let to = body["to"].as_object().cloned().unwrap_or_default();                if kind == "message" && body["check"] == json!(true) && to.iter().any(|(n, b)| w.keys_of(n, &credential).iter().any(|k| b.get(k["device"].as_str().unwrap_or_default()).is_none())) {                    return Ok(Box::new(Reply { status: 409, body: std::io::Cursor::new(json!({ "code": "stale_devices", "message": "The devices to seal for have changed; ask their keys again." }).to_string().into_bytes()) }));                }                for (to, boxes) in body["to"].as_object().cloned().unwrap_or_default() {                    w.sent.push((me.clone(), to.clone(), kind.clone(), group.clone()));                    w.land(&to, &me, &kind, &id, group.as_deref(), boxes.as_object().unwrap(), false);                }                if let Some(own) = body["own"].as_object() {                    let others: serde_json::Map<String, Value> = own.iter().filter(|(h, _)| !w.devices.iter().any(|d| d.0 == credential && &d.2 == *h)).map(|(h, b)| (h.clone(), b.clone())).collect();                    let me2 = me.clone();                    w.land(&me2, &me, &kind, &id, group.as_deref(), &others, true);                }                let at = w.clock;                ok(json!({ "ok": true, "id": id, "at": 1_800_000_000_000i64 + at }))            }            ("POST", "/v1/chat/send") => {                let (to, id, kind, group) = (body["to"].as_str().unwrap_or_default().to_string(), body["id"].as_str().unwrap_or_default().to_string(), body["kind"].as_str().unwrap_or_default().to_string(), body["group"].as_str().map(str::to_string));                if kind == "message" && group.is_none() {                    w.accepted.insert((me.clone(), to.clone()));                }                w.sent.push((me.clone(), to.clone(), kind.clone(), group.clone()));                let boxes = body["boxes"].as_object().cloned().unwrap_or_default();                // As the Worker: a re-send after a reset goes to its one device, once (from any of the sender's phones).                if body["resend"] == json!(true) {                    let handle = boxes.keys().next().cloned().unwrap_or_default();                    if boxes.len() != 1 || kind != "message" {                        return status(400);                    }                    if w.resent.insert((handle, id.clone())) {                        let mine: serde_json::Map<String, Value> = boxes.iter().filter(|(h, _)| w.devices.iter().any(|d| d.1 == me && &d.2 == *h && d.0 != credential)).map(|(h, b)| (h.clone(), b.clone())).collect();                        if mine.is_empty() {                            w.land(&to, &me, &kind, &id, None, &boxes, false);                        } else {                            w.land(&me.clone(), &to, &kind, &id, None, &mine, true);                        }                    }                    return ok(json!({ "ok": true, "id": id, "at": 1_800_000_000_000i64 + w.clock }));                }                let mine: serde_json::Map<String, Value> = boxes.iter().filter(|(h, _)| w.devices.iter().any(|d| d.1 == me && &d.2 == *h && d.0 != credential)).map(|(h, b)| (h.clone(), b.clone())).collect();                w.land(&to, &me, &kind, &id, group.as_deref(), &boxes, false);                w.land(&me.clone(), &to, &kind, &id, group.as_deref(), &mine, true);                ok(json!({ "ok": true, "id": id, "at": 1_800_000_000_000i64 + w.clock }))            }            ("GET", "/v1/chat/inbox") => {                let hidden = w.hidden.get(&credential).cloned().unwrap_or_default();                let items: Vec<Value> = w.held.get(&credential).cloned().unwrap_or_default().into_iter().filter(|i| !hidden.contains(i["kind"].as_str().unwrap_or_default())).collect();                let mut answer = json!({ "me": me, "items": items });                if w.c2.contains_key(&credential) {                    answer["prekeys"] = json!(w.prekeys.get(&credential).map_or(0, Vec::len));                }                ok(answer)            }            ("POST", "/v1/chat/device") => {                // As the Worker: a device that says no c2 loses what it published.                match body.get("c2") {                    Some(c2) => {                        w.c2.insert(credential.clone(), json!({ "identity": c2["identity"], "signing": c2["signing"], "sig": c2["sig"] }));                        if c2.get("fallback").is_some() {                            w.fallback.insert(credential.clone(), c2["fallback"].clone());                        }                        w.prekeys.entry(credential.clone()).or_default().extend(c2["prekeys"].as_array().cloned().unwrap_or_default());                        let left = w.prekeys[&credential].len();                        ok(json!({ "ok": true, "prekeys": left }))                    }                    None => {                        w.c2.remove(&credential);                        w.prekeys.remove(&credential);                        w.fallback.remove(&credential);                        ok(json!({ "ok": true }))                    }                }            }            ("POST", "/v1/chat/prekeys") => {                let list = w.prekeys.entry(credential.clone()).or_default();                list.extend(body["prekeys"].as_array().cloned().unwrap_or_default());                let left = list.len();                ok(json!({ "ok": true, "prekeys": left }))            }            ("POST", "/v1/chat/prekeys/claim") => {                let number = body["number"].as_str().unwrap_or_default().to_string();                let handles: Vec<String> = body["devices"].as_array().into_iter().flatten().filter_map(|h| h.as_str().map(str::to_string)).collect();                w.claims += handles.len();                let mut out = serde_json::Map::new();                for d in w.devices.clone().iter().filter(|d| d.1 == number && d.0 != credential && handles.contains(&d.2)) {                    let taken = w.prekeys.get_mut(&d.0).and_then(|l| (!l.is_empty()).then(|| l.remove(0)));                    match taken.or_else(|| w.fallback.get(&d.0).map(|f| json!({ "key": f["key"], "sig": f["sig"], "fallback": true }))) {                        Some(p) => {                            out.insert(d.2.clone(), p);                        }                        None => {}                    }                }                ok(json!({ "prekeys": out }))            }            ("POST", "/v1/chat/wait") => ok(json!({ "state": "reached" })),            ("POST", "/v1/agents/chat") => {                let said = (me.clone(), body["agent"].as_str().unwrap_or_default().to_string(), body["thread"].as_str().unwrap_or_default().to_string(), body["on"] == json!(true), body["about"].as_str().map(str::to_string));                w.agent_chats.push(said);                ok(json!({ "ok": true }))            }            ("POST", "/v1/agents/feed") => {                for item in body["items"].as_array().cloned().unwrap_or_default() {                    w.feed.push((me.clone(), item));                }                ok(json!({ "ok": true }))            }            ("POST", "/v1/agents/done") => {                w.done.push((me.clone(), body["id"].as_str().unwrap_or_default().to_string(), body["state"].as_str().unwrap_or_default().to_string(), body["error"].as_str().map(str::to_string)));                ok(json!({ "ok": true }))            }            ("POST", "/v1/chat/ack") => {                let taken: HashSet<(String, String)> = body["items"].as_array().into_iter().flatten().map(|i| (i["id"].as_str().unwrap_or_default().to_string(), i["kind"].as_str().unwrap_or_default().to_string())).collect();                if let Some(list) = w.held.get_mut(&credential) {                    list.retain(|i| !taken.contains(&(i["id"].as_str().unwrap_or_default().to_string(), i["kind"].as_str().unwrap_or_default().to_string())));                }                ok(json!({ "ok": true }))            }            ("POST", "/v1/chat/group") => {                let group = body["group"].as_str().unwrap_or_default().to_string();                let members: Vec<String> = body["members"].as_array().into_iter().flatten().filter_map(|m| m.as_str().map(str::to_string)).collect();                if members.is_empty() {                    w.groups.remove(&(me.clone(), group));                } else {                    for list in w.held.values_mut() {                        for item in list.iter_mut().filter(|i| i["group"] == json!(group) && members.iter().any(|m| i["peer"] == json!(m))) {                            item["request"] = json!(false);                        }                    }                    w.groups.insert((me.clone(), group), members);                }                ok(json!({ "ok": true }))            }            ("POST", p) if p.starts_with("/v1/chat/") => {                let number = body["number"].as_str().unwrap_or_default().to_string();                if p.ends_with("/accept") {                    w.accepted.insert((me.clone(), number));                }                ok(json!({ "ok": true }))            }            ("PUT", "/v1/chat/files") => {                let id = format!("{:032x}", w.files.len() + 1);                w.files.insert(id.clone(), request.body.unwrap_or_default().to_vec());                ok(json!({ "file": id }))            }            ("GET", p) if p.starts_with("/v1/chat/files/") => match { w.file_gets += 1; w.files.get(p.trim_start_matches("/v1/chat/files/")) } {                Some(bytes) => Ok(Box::new(Reply { status: 200, body: std::io::Cursor::new(bytes.clone()) })),                None => status(404),            },            _ => status(404),        }    }    fn send_stream(&self, origin: &Origin, request: &Http1Request<'_>, body: &mut dyn std::io::Read, length: u64, ceiling: std::time::Duration) -> Result<Box<dyn Answer>, String> {        let mut bytes = Vec::new();        std::io::Read::read_to_end(&mut std::io::Read::take(body, length), &mut bytes).map_err(|e| e.to_string())?;        let whole = Http1Request { body: Some(&bytes), headers: request.headers.clone(), ..*request };        self.send(origin, &whole, ceiling)    }}struct Phone {    _dir: tempfile::TempDir,    handle: CottonHandle,    number: &'static str,    secret: String,    credential: String,}fn scalar(seed: u8) -> [u8; 32] {    let mut bytes = [seed; 32];    bytes[0] = seed.wrapping_mul(7).wrapping_add(1);    bytes}impl Phone {    fn call(&self, method: &str, mut request: Value) -> Value {        request["privateKey"] = json!(self.secret);        super::super::cotton_chat::over(&self.handle.client(), method, &request).unwrap_or_else(|e| panic!("{} {method}: {} {}", self.number, e.code, e.message))    }    fn refused(&self, method: &str, mut request: Value) -> String {        request["privateKey"] = json!(self.secret);        super::super::cotton_chat::over(&self.handle.client(), method, &request).err().map(|e| e.code).unwrap_or_else(|| panic!("{method} answered"))    }    fn sync(&self) -> Value {        let got = self.call("chat.incoming", json!({}));        self.call("chat.flush", json!({}));        got    }    fn thread(&self, group: &str) -> String {        super::thread_id(&super::super::cotton_chat::namespace(&self.handle.client()).unwrap(), group)    }    fn info(&self, group: &str) -> Value {        self.call("chat.group.info", json!({ "thread": self.thread(group) }))    }    fn bodies(&self, group: &str) -> Vec<String> {        let thread = self.thread(group);        self.handle            .client()            .with_writer(|replica| {                Ok(replica                    .driver                    .all("SELECT body FROM cotton_msg_messages WHERE thread_id = ? AND json_extract(meta, '$.system') IS NULL AND trashed_at IS NULL ORDER BY sent_at, id", &[rusqlite::types::Value::Text(thread.clone())])                    .map_err(|e| e.to_string())?                    .iter()                    .map(|r| crate::phone::passwords::json_row(r)["body"].as_str().unwrap_or_default().to_string())                    .collect())            })            .unwrap()    }    fn lines(&self, group: &str) -> Vec<String> {        let thread = self.thread(group);        self.handle            .client()            .with_writer(|replica| Ok(replica.driver.all("SELECT body FROM cotton_msg_messages WHERE thread_id = ? AND json_extract(meta, '$.system') IS NOT NULL ORDER BY sent_at, id", &[rusqlite::types::Value::Text(thread.clone())]).map_err(|e| e.to_string())?.iter().map(|r| crate::phone::passwords::json_row(r)["body"].as_str().unwrap_or_default().to_string()).collect()))            .unwrap()    }    fn say(&self, group: &str, words: &str) -> String {        let answer = self.call("chat.act", json!({ "act": "send", "thread": self.thread(group), "text": words }));        self.call("chat.flush", json!({}));        answer["message"].as_str().unwrap().to_string()    }    fn message(&self, id: &str) -> serde_json::Map<String, Value> {        self.handle.client().with_writer(|replica| Ok(replica.driver.get("SELECT * FROM cotton_msg_messages WHERE id = ?", &[rusqlite::types::Value::Text(id.to_string())]).map_err(|e| e.to_string())?.map(|r| crate::phone::passwords::json_row(&r)).unwrap())).unwrap()    }}/// Phones on one relay, each signed in on its number; `friends` are pairs who accepted each other one to one.fn world(numbers: &[&'static str], friends: &[(&str, &str)]) -> (Arc<Relay>, Vec<Phone>) {    let relay = Arc::new(Relay::default());    let mut phones = Vec::new();    for (i, number) in numbers.iter().enumerate() {        let (dir, handle) = phone();        let seed = 10 + i as u8;        let credential = format!("ctd_{i:08}-1111-4111-8111-111111111111_test-credential");        relay.0.lock().unwrap().devices.push((credential.clone(), number.to_string(), format!("{:0>22}", format!("h{i}")), seal::key_text(&public_of(&scalar(seed)))));        let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: relay.clone(), credential: credential.clone() };        handle.client().set_object_door(Some(Arc::new(door)));        let thread: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/thread.json")).unwrap();        handle.client().with_writer(|replica| cotton_client::transport::object::hold_defined_columns(&replica.driver, [&thread]).map(|_| ())).unwrap();        phones.push(Phone { _dir: dir, handle, number, secret: seal::key_text(&scalar(seed)), credential });    }    {        let mut w = relay.0.lock().unwrap();        for (a, b) in friends {            w.accepted.insert((a.to_string(), b.to_string()));            w.accepted.insert((b.to_string(), a.to_string()));        }    }    (relay, phones)}fn create(phone: &Phone, title: &str, members: &[&str]) -> String {    phone.call("chat.group.create", json!({ "title": title, "members": members }))["group"].as_str().unwrap().to_string()}fn members(info: &Value) -> Vec<String> {    let mut m: Vec<String> = info["members"].as_array().unwrap().iter().map(|m| m["number"].as_str().unwrap().to_string()).collect();    m.sort();    m}// RULE: Creating a group tells every member at once; each one Asha knows joins it, sees its name, its members and who may do what, and her object and theirs are told who is in it.#[test]fn a_new_group_reaches_every_member() {    let (relay, p) = world(&[ASHA, BEN, CHEN], &[(ASHA, BEN), (ASHA, CHEN)]);    let g = create(&p[0], "Family", &[BEN, CHEN]);    for phone in &p[1..] {        let got = phone.sync();        assert!(got["changed"].as_array().unwrap().iter().any(|c| c["group"] == json!(g)), "{got}");        let info = phone.info(&g);        assert_eq!(info["title"], "Family");        assert_eq!(members(&info), [ASHA, BEN, CHEN]);        assert_eq!(info["you"], "member");        assert_eq!(info["can"], json!({ "send": true, "add": false, "remove": false, "rename": false, "picture": false, "admins": false, "leave": true }));        assert_eq!(phone.lines(&g).len(), 1, "the created line");    }    let info = p[0].info(&g);    assert_eq!(info["can"]["add"], true);    assert_eq!(info["members"][0]["you"], true);    let w = relay.0.lock().unwrap();    assert_eq!(w.groups.get(&(BEN.to_string(), g.clone())), Some(&vec![ASHA.to_string(), CHEN.to_string()]));    assert_eq!(w.groups.get(&(ASHA.to_string(), g.clone())), Some(&vec![BEN.to_string(), CHEN.to_string()]));}// RULE: A group's lines name a member the way this phone's chats know them (here the address book's name, from "Find people I know"), never their bare number, when they are not one of the person's people.#[test]fn a_groups_lines_name_members_as_the_chats_know_them() {    let (_relay, p) = world(&[ASHA, BEN, CHEN], &[(ASHA, BEN), (ASHA, CHEN)]);    let client = p[1].handle.client();    let ns = crate::phone::cotton_chat::namespace(&client).unwrap();    crate::phone::cotton_chat::write(&client, "test.contact", |ctx| super::ensure_contact(ctx, &ns, ASHA, Some("Asha from work"), None).map(Value::from)).unwrap();    let g = create(&p[0], "Family", &[BEN, CHEN]);    p[1].sync();    assert_eq!(p[1].lines(&g), ["Asha from work created the group"]);}// RULE: A group's lines name someone this phone knows nothing of by their number as a number is written, with its "+", never bare digits.#[test]fn a_groups_lines_name_a_stranger_by_their_number_with_its_plus() {    let (_relay, p) = world(&[ASHA, BEN, CHEN], &[(ASHA, BEN), (ASHA, CHEN)]);    let g = create(&p[0], "Family", &[BEN, CHEN]);    p[1].sync();    assert_eq!(p[1].lines(&g), [format!("{ASHA} created the group")]);}// RULE: A message in a group reaches every member, sealed for each alone and naming its sender; members who are strangers to each other one to one are no request to each other there.#[test]fn a_message_reaches_every_member() {    let (relay, p) = world(&[ASHA, BEN, CHEN], &[(ASHA, BEN), (ASHA, CHEN)]);    let g = create(&p[0], "Family", &[BEN, CHEN]);    p[1].sync();    p[2].sync();    p[1].say(&g, "dinner at eight?");    let got = p[2].sync();    let landed = &got["landed"][0];    assert_eq!((landed["peer"].as_str(), landed["group"].as_bool(), landed["request"].as_bool(), landed["name"].as_str()), (Some(BEN), Some(true), Some(false), Some("Family")));    assert_eq!(p[2].bodies(&g), ["dinner at eight?"]);    p[0].sync();    assert_eq!(p[0].bodies(&g), ["dinner at eight?"]);    // The chat screens draw it as a group's: Ben's seat names the bubble.    let thread = p[2].call("chat.thread", json!({ "thread": p[2].thread(&g) }));    assert_eq!(thread["header"]["group"], true);    let w = relay.0.lock().unwrap();    assert!(w.sent.iter().filter(|s| s.0 == BEN && s.2 == "message").all(|s| s.3.as_deref() == Some(g.as_str())));}// RULE: A member who signs in on a new phone gets the group's next message there: refused as sealed for their devices of before, it is sealed again for the keys asked afresh, once, under the same id.#[test]fn a_members_new_phone_gets_the_next_message() {    let (relay, p) = world(&[ASHA, BEN, CHEN], &[(ASHA, BEN), (ASHA, CHEN)]);    let g = create(&p[0], "Family", &[BEN, CHEN]);    p[1].sync();    p[2].sync();    p[0].say(&g, "before");    let tablet = "ctd_99999999-1111-4111-8111-111111111111_test-credential".to_string();    relay.0.lock().unwrap().devices.push((tablet.clone(), BEN.to_string(), format!("{:0>22}", "bentablet"), seal::key_text(&public_of(&scalar(77)))));    let message = p[0].say(&g, "after the new phone");    assert_eq!(p[0].message(&message)["send_state"], json!("sent"));    let w = relay.0.lock().unwrap();    let held = w.held.get(&tablet).cloned().unwrap_or_default();    assert_eq!(held.iter().filter(|i| i["kind"] == json!("message")).count(), 1, "the new phone holds the message after it signed in");    assert_eq!(w.sent.iter().filter(|s| s.0 == ASHA && s.1 == BEN && s.2 == "message").count(), 2, "one message each, the refused try not counted");}// RULE: Each member's delivered tick is their own; the message is delivered when every member it went to has it.#[test]fn delivery_is_per_member() {    let (_relay, p) = world(&[ASHA, BEN, CHEN], &[(ASHA, BEN), (ASHA, CHEN)]);    let g = create(&p[0], "Family", &[BEN, CHEN]);    p[1].sync();    p[2].sync();    let id = p[0].say(&g, "hello both");    assert_eq!(p[0].message(&id)["send_state"], "sent");    p[1].sync();    p[0].sync();    let info = p[0].call("chat.group.receipts", json!({ "message": id }));    let states: HashMap<String, String> = info["members"].as_array().unwrap().iter().map(|m| (m["number"].as_str().unwrap().to_string(), m["state"].as_str().unwrap().to_string())).collect();    assert_eq!(states, HashMap::from([(BEN.to_string(), "delivered".to_string()), (CHEN.to_string(), "sent".to_string())]));    assert_eq!(p[0].message(&id)["send_state"], "sent", "not every member has it yet");    p[2].sync();    p[0].sync();    assert_eq!(p[0].message(&id)["send_state"], "delivered");}// RULE: In a Cotton group the person's own words offer Message info (who has them), before Select; others' words do not.#[test]fn your_own_words_in_a_group_offer_message_info() {    let (_relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    let g = create(&p[0], "Family", &[BEN]);    p[1].sync();    p[0].say(&g, "mine");    p[1].say(&g, "theirs");    p[0].sync();    let thread = p[0].call("chat.thread", json!({ "thread": p[0].thread(&g) }));    let acts = |body: &str| -> Vec<String> {        let bubble = thread["items"].as_array().unwrap().iter().find(|i| i["text"] == body).unwrap_or_else(|| panic!("{body}: {thread}"));        bubble["actions"].as_array().unwrap().iter().map(|a| a.as_str().unwrap().to_string()).collect()    };    let mine = acts("mine");    assert_eq!(mine[mine.len() - 2..], ["info".to_string(), "select".to_string()], "{mine:?}");    assert!(!acts("theirs").contains(&"info".to_string()));    assert_eq!(thread["actions"]["info"], "Message info");}// RULE: Someone added reads only what is said after they joined; everyone else learns they are in, and their words reach them.#[test]fn someone_added_reads_only_what_comes_after() {    let (_relay, p) = world(&[ASHA, BEN, CHEN, DEV], &[(ASHA, BEN), (ASHA, CHEN), (ASHA, DEV)]);    let g = create(&p[0], "Family", &[BEN, CHEN]);    p[1].sync();    p[2].sync();    p[1].say(&g, "before Dev");    p[0].call("chat.group.add", json!({ "thread": p[0].thread(&g), "members": [DEV] }));    p[3].sync();    assert_eq!(members(&p[3].info(&g)), [ASHA, BEN, CHEN, DEV]);    assert!(p[3].bodies(&g).is_empty(), "nothing from before");    p[1].sync();    p[2].sync();    p[2].say(&g, "welcome Dev");    p[3].sync();    assert_eq!(p[3].bodies(&g), ["welcome Dev"]);    assert!(p[1].lines(&g).iter().any(|l| l.contains("added")), "{:?}", p[1].lines(&g));}// RULE: Someone removed reads nothing said after; they see they were removed and can no longer write.#[test]fn someone_removed_reads_nothing_after() {    let (relay, p) = world(&[ASHA, BEN, CHEN], &[(ASHA, BEN), (ASHA, CHEN)]);    let g = create(&p[0], "Family", &[BEN, CHEN]);    p[1].sync();    p[2].sync();    p[0].call("chat.group.remove", json!({ "thread": p[0].thread(&g), "member": BEN }));    p[1].sync();    p[2].sync();    let info = p[1].info(&g);    assert_eq!(info["you"], "removed");    assert_eq!(info["can"]["send"], false);    assert_eq!(p[1].refused("chat.act", json!({ "act": "send", "thread": p[1].thread(&g), "text": "let me back" })), "cannot");    // Where the writing box was, the conversation says why (walk, 21 Nov 2026: it said "Read only: imported from Cotton.").    let page = p[1].call("chat.thread", json!({ "thread": p[1].thread(&g) }));    assert_eq!((page["composer"].is_null(), page["readOnly"].as_str()), (true, Some("You're no longer in this group.")), "{page}");    assert_eq!(members(&p[2].info(&g)), [ASHA, CHEN]);    let before = relay.0.lock().unwrap().sent.len();    p[2].say(&g, "after Ben");    {        let w = relay.0.lock().unwrap();        assert!(w.sent[before..].iter().all(|s| s.1 != BEN), "nothing is sealed for Ben");        assert_eq!(w.groups.get(&(BEN.to_string(), g.clone())), None, "Ben's object no longer takes the group as his");    }    p[1].sync();    assert!(!p[1].bodies(&g).contains(&"after Ben".to_string()));}// RULE: Anyone may leave; the others see them go, and the last admin leaving makes the longest-standing member one.#[test]fn leaving() {    let (_relay, p) = world(&[ASHA, BEN, CHEN], &[(ASHA, BEN), (ASHA, CHEN)]);    let g = create(&p[0], "Family", &[BEN, CHEN]);    p[1].sync();    p[2].sync();    p[0].call("chat.group.leave", json!({ "thread": p[0].thread(&g) }));    assert_eq!(p[0].info(&g)["you"], "left");    p[1].sync();    p[2].sync();    let info = p[1].info(&g);    assert_eq!(members(&info), [BEN, CHEN]);    // Ben's number sorts before Chen's, and both were added at the start.    assert_eq!(info["can"]["add"], true);    assert_eq!(p[2].info(&g)["can"]["add"], false);    assert!(p[2].lines(&g).iter().any(|l| l.ends_with("left")));}// RULE: Only admins add, remove and rename; an admin may make another, who may then add.#[test]fn admins() {    let (_relay, p) = world(&[ASHA, BEN, CHEN, DEV], &[(ASHA, BEN), (ASHA, CHEN), (BEN, DEV)]);    let g = create(&p[0], "Family", &[BEN, CHEN]);    p[1].sync();    p[2].sync();    assert_eq!(p[1].refused("chat.group.add", json!({ "thread": p[1].thread(&g), "members": [DEV] })), "not_admin");    assert_eq!(p[2].refused("chat.group.rename", json!({ "thread": p[2].thread(&g), "title": "Chen's" })), "not_admin");    p[0].call("chat.group.admin", json!({ "thread": p[0].thread(&g), "member": BEN, "admin": true }));    p[1].sync();    p[1].call("chat.group.add", json!({ "thread": p[1].thread(&g), "members": [DEV] }));    p[3].sync();    p[0].sync();    p[2].sync();    for phone in &p {        assert_eq!(members(&phone.info(&g)), [ASHA, BEN, CHEN, DEV], "{}", phone.number);    }}// RULE: A rename and a new picture reach everyone, and the picture opens on their phones.#[test]fn names_and_pictures() {    let (_relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    let g = create(&p[0], "Family", &[BEN]);    p[1].sync();    p[0].call("chat.group.rename", json!({ "thread": p[0].thread(&g), "title": "The Raos" }));    let dir = tempfile::tempdir().unwrap();    let picture = dir.path().join("group.jpg");    std::fs::write(&picture, b"a made-up picture").unwrap();    p[0].call("chat.group.picture", json!({ "thread": p[0].thread(&g), "path": picture.to_string_lossy(), "mime": "image/jpeg" }));    p[1].sync();    let info = p[1].info(&g);    assert_eq!((info["title"].as_str(), info["picture"].as_bool()), (Some("The Raos"), Some(true)));    let opened = p[1].call("chat.group.photo", json!({ "thread": p[1].thread(&g), "dir": dir.path().join("out").to_string_lossy() }));    assert_eq!(std::fs::read(opened["path"].as_str().unwrap()).unwrap(), b"a made-up picture");    let list = p[1].call("chat.list", json!({}));    assert!(list.to_string().contains("The Raos"));}// RULE: A group from someone who is a stranger to them is a request: it says nothing back (no tick, no change) until joined, and refusing it says nothing ever.#[test]fn a_strangers_group_is_a_request() {    let (relay, p) = world(&[ASHA, BEN, EVE], &[(ASHA, BEN)]);    let g = create(&p[0], "Family", &[BEN, EVE]);    let got = p[2].sync();    assert!(got["requests"].as_array().unwrap().contains(&json!(p[2].thread(&g))), "{got}");    assert_eq!(p[2].info(&g)["you"], "invited");    let id = p[0].say(&g, "hello Eve");    p[2].sync();    p[0].sync();    let states = p[0].call("chat.group.receipts", json!({ "message": id }));    assert!(states["members"].as_array().unwrap().iter().any(|m| m["number"] == json!(EVE) && m["state"] == json!("sent")), "no tick from an unjoined phone");    assert!(relay.0.lock().unwrap().sent.iter().all(|s| s.0 != EVE), "Eve's phone said nothing");    assert_eq!(p[2].refused("chat.act", json!({ "act": "send", "thread": p[2].thread(&g), "text": "hi" })), "not_joined");    p[2].call("chat.refuse", json!({ "thread": p[2].thread(&g) }));    p[0].say(&g, "still there?");    p[2].sync();    assert!(relay.0.lock().unwrap().sent.iter().all(|s| s.0 != EVE), "refused, still nothing said");    assert!(p[2].bodies(&g).is_empty(), "what it brought went");}// RULE: Joining a stranger's group makes it a group like any other: the object is told, and ticks go.#[test]fn joining_a_strangers_group() {    let (relay, p) = world(&[ASHA, EVE], &[]);    let g = create(&p[0], "Book club", &[EVE]);    p[2 - 1].sync();    p[1].call("chat.accept", json!({ "thread": p[1].thread(&g) }));    assert_eq!(p[1].info(&g)["you"], "member");    assert!(relay.0.lock().unwrap().groups.contains_key(&(EVE.to_string(), g.clone())));    let id = p[0].say(&g, "first book?");    p[1].sync();    p[0].sync();    assert_eq!(p[0].message(&id)["send_state"], "delivered");}// RULE: Words from a member this phone does not yet hold in the group wait, held, until the change that adds them arrives.#[test]fn words_wait_for_the_change_that_explains_them() {    let (relay, p) = world(&[ASHA, BEN, DEV], &[(ASHA, BEN), (ASHA, DEV)]);    let g = create(&p[0], "Family", &[BEN]);    p[1].sync();    p[0].call("chat.group.add", json!({ "thread": p[0].thread(&g), "members": [DEV] }));    // Ben hears of Dev, Dev writes, but Dev's welcome is held back from Dev's own phone... and Ben's word of the add from Ben's.    p[2].sync();    relay.0.lock().unwrap().hidden.insert(p[1].credential.clone(), HashSet::from(["group".to_string()]));    p[2].say(&g, "hi from Dev");    let got = p[1].sync();    assert_eq!(got["waiting"], 1, "{got}");    assert!(p[1].bodies(&g).is_empty());    relay.0.lock().unwrap().hidden.clear();    p[1].sync();    assert_eq!(p[1].bodies(&g), ["hi from Dev"]);}// RULE: A reaction in a group reaches everyone; an edit from someone other than the writer changes nothing.#[test]fn reactions_and_edits_in_a_group() {    let (_relay, p) = world(&[ASHA, BEN, CHEN], &[(ASHA, BEN), (ASHA, CHEN)]);    let g = create(&p[0], "Family", &[BEN, CHEN]);    p[1].sync();    p[2].sync();    let id = p[0].say(&g, "photos tonight");    p[1].sync();    p[2].sync();    let bens = p[1].call("chat.thread", json!({ "thread": p[1].thread(&g) }));    let message = bens["bubbles"].as_array().or_else(|| bens["items"].as_array()).and_then(|b| b.iter().find(|b| b.to_string().contains("photos tonight")).cloned()).map(|b| b["message"].as_str().unwrap_or_default().to_string());    let message = message.unwrap_or_else(|| panic!("no bubble in {bens}"));    p[1].call("chat.act", json!({ "act": "react", "thread": p[1].thread(&g), "message": message, "emoji": "❤️" }));    p[1].call("chat.flush", json!({}));    p[0].sync();    p[2].sync();    let count = |phone: &Phone| phone.handle.client().with_writer(|r| Ok(r.driver.all("SELECT 1 FROM cotton_msg_reactions", &[]).map_err(|e| e.to_string())?.len())).unwrap();    assert_eq!(count(&p[0]), 1);    assert_eq!(count(&p[2]), 1);    let _ = id;}// RULE: Pictures in a group go up once each and open on every member's phone.#[test]fn pictures_in_a_group() {    let (relay, p) = world(&[ASHA, BEN, CHEN], &[(ASHA, BEN), (ASHA, CHEN)]);    let g = create(&p[0], "Family", &[BEN, CHEN]);    p[1].sync();    p[2].sync();    let dir = tempfile::tempdir().unwrap();    let paths: Vec<String> = (0..3).map(|i| {        let path = dir.path().join(format!("p{i}.jpg"));        std::fs::write(&path, format!("picture {i}")).unwrap();        path.to_string_lossy().to_string()    }).collect();    let attachments: Vec<Value> = paths.iter().map(|p| json!({ "path": p, "mime": "image/jpeg" })).collect();    p[0].call("chat.act", json!({ "act": "send", "thread": p[0].thread(&g), "attachments": attachments }));    p[0].call("chat.flush", json!({}));    assert_eq!(relay.0.lock().unwrap().files.len(), 3, "each picture put up once, whatever the members");    let got = p[2].sync();    let message = got["landed"][0]["message"].as_str().unwrap().to_string();    for index in 0..3 {        let opened = p[2].call("chat.picture", json!({ "message": message, "index": index, "dir": dir.path().join("in").to_string_lossy() }));        assert_eq!(std::fs::read(opened["path"].as_str().unwrap()).unwrap(), format!("picture {index}").as_bytes());    }    // The sender's own conversation (owner, Comms iPhone build 19, 22 Nov 2026: "Picture not available" on a picture just sent in a new group).    let mine = p[0].handle.client().with_writer(|r| r.driver.get("SELECT id FROM cotton_msg_messages WHERE meta LIKE '%\"pictures\"%'", &[]).map_err(|e| e.to_string())).unwrap().and_then(|row| row.text("id").map(str::to_string)).expect("the sender's own message");    for index in 0..3 {        let opened = p[0].call("chat.picture", json!({ "message": mine, "index": index, "dir": dir.path().join("mine").to_string_lossy() }));        assert_eq!(std::fs::read(opened["path"].as_str().expect("the sender's own picture opens")).unwrap(), format!("picture {index}").as_bytes());    }}// RULE (owner, Comms build 19 on iPhone, 22 Nov 2026: a picture he had just sent said "Picture not available"): a// picture the person has just sent opens at once from the phone's own file while it is still going up, over a slow// line, and is never said gone. chat.act send answers before the network, with no state to draw until// QUIET_SENDING_MS; chat.picture answers the outbox's copy, the bubble is not gone, and another send stands at once// while the upload waits. Once up it opens as before. On the other phone, a new message's file the store does not// hold yet is not_yet, kept as absent by nothing, and opens once it is there; only past GONE_NOT_BEFORE_MS is a 404// gone, said once and then refused with no request.#[test]fn a_picture_being_sent_shows_at_once_and_is_never_gone() {    use std::sync::atomic::Ordering;    use std::time::{Duration, Instant};    let (relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    let thread = p[0].start(BEN);    let dir = tempfile::tempdir().unwrap();    // A grid of five, then a single one, as the owner sent them.    let photos: Vec<std::path::PathBuf> = (0..6).map(|i| {        let photo = dir.path().join(format!("sent-{i}.jpg"));        std::fs::write(&photo, format!("an invented picture {i}")).unwrap();        photo    }).collect();    let attach = |range: std::ops::Range<usize>| json!(photos[range].iter().map(|p| json!({ "path": p.to_string_lossy(), "mime": "image/jpeg", "width": 4, "height": 3 })).collect::<Vec<_>>());    let ask_at = |message: &str, index: usize| json!({ "message": message, "index": index, "dir": dir.path().join("in").to_string_lossy() });    let ask = |message: &str| ask_at(message, 0);    let bubble = |phone: &Phone, thread: &str, message: &str| {        let page = phone.call("chat.thread", json!({ "thread": thread }));        page["items"].as_array().unwrap().iter().find(|i| i["message"] == message).cloned().unwrap_or_else(|| panic!("{message} in {page}"))    };    relay.1.hold(true);    let before = chrono::Utc::now().timestamp_millis();    let grid = p[0].call("chat.act", json!({ "act": "send", "thread": thread, "attachments": attach(0..5) }))["message"].as_str().unwrap().to_string();    let sent = p[0].call("chat.act", json!({ "act": "send", "thread": thread, "attachments": attach(5..6) }));    let message = sent["message"].as_str().unwrap().to_string();    assert_eq!((sent["bubble"]["tick"].as_str(), sent["flush"].as_bool()), (Some("sending"), Some(true)), "{sent}");    let quiet = sent["bubble"]["quietUntil"].as_i64().unwrap_or_else(|| panic!("no quietUntil: {sent}"));    assert!(quiet >= before + cotton_core::messages::app::bubble::QUIET_SENDING_MS, "a fast send draws no Sending: {quiet}");    std::thread::scope(|scope| {        let flushing = scope.spawn(|| p[0].call("chat.flush", json!({})));        let deadline = Instant::now() + Duration::from_secs(10);        while relay.1.waiting.load(Ordering::SeqCst) == 0 {            assert!(Instant::now() < deadline, "the upload never started");            std::thread::sleep(Duration::from_millis(5));        }        // Let go after ten seconds whatever happens, so a call that waits on the upload fails rather than hangs.        scope.spawn(|| {            std::thread::sleep(Duration::from_secs(10));            relay.1.hold(false);        });        let started = Instant::now();        let opened = p[0].call("chat.picture", ask(&message));        assert_eq!(std::fs::read(opened["path"].as_str().unwrap()).unwrap(), b"an invented picture 5", "the phone's own copy: {opened}");        for index in 0..5 {            let opened = p[0].call("chat.picture", ask_at(&grid, index));            assert_eq!(std::fs::read(opened["path"].as_str().unwrap()).unwrap(), format!("an invented picture {index}").as_bytes(), "the grid's tile {index}: {opened}");        }        let drawn = bubble(&p[0], &thread, &message);        assert!(drawn["media"][0].get("gone").is_none(), "never gone while it goes: {drawn}");        assert_eq!(drawn["tick"], "sending");        let tiles = bubble(&p[0], &thread, &grid);        assert_eq!(tiles["media"].as_array().unwrap().len(), 5, "{tiles}");        assert!(tiles["media"].as_array().unwrap().iter().all(|m| m.get("gone").is_none()), "no tile of the grid gone: {tiles}");        let next = p[0].call("chat.act", json!({ "act": "send", "thread": thread, "text": "and the view" }));        assert_eq!(next["bubble"]["tick"], "sending");        assert!(started.elapsed() < Duration::from_secs(2), "the phone's answers waited on the upload: {:?}", started.elapsed());        assert!(relay.1.waiting.load(Ordering::SeqCst) > 0, "the upload was still waiting");        relay.1.hold(false);        flushing.join().unwrap();    });    assert_eq!((p[0].message(&grid)["send_state"].as_str(), p[0].message(&message)["send_state"].as_str()), (Some("sent"), Some("sent")));    let opened = p[0].call("chat.picture", ask(&message));    assert_eq!(std::fs::read(opened["path"].as_str().unwrap()).unwrap(), b"an invented picture 5", "once up: {opened}");    let opened = p[0].call("chat.picture", ask_at(&grid, 4));    assert_eq!(std::fs::read(opened["path"].as_str().unwrap()).unwrap(), b"an invented picture 4", "once up: {opened}");    let drawn = bubble(&p[0], &thread, &message);    assert!(drawn.get("quietUntil").is_none() && drawn["media"][0].get("gone").is_none(), "{drawn}");    // Ben's phone: the message is new, and its file is not in the store yet (still on its way).    let got = p[1].sync();    let pictures_of = |id: &str| serde_json::from_str::<Value>(p[1].message(id)["meta"].as_str().unwrap_or("{}")).unwrap_or_default()["cotton"]["pictures"].as_array().map_or(0, Vec::len);    let landed: Vec<String> = got["landed"].as_array().unwrap().iter().map(|l| l["message"].as_str().unwrap().to_string()).collect();    let theirs = landed.iter().find(|id| pictures_of(id) == 1).cloned().unwrap_or_else(|| panic!("{got}"));    let their_grid = landed.iter().find(|id| pictures_of(id) == 5).cloned().unwrap_or_else(|| panic!("{got}"));    let bens = p[1].message(&theirs)["thread_id"].as_str().unwrap().to_string();    let held: Vec<(String, Vec<u8>)> = relay.0.lock().unwrap().files.drain().collect();    assert_eq!(p[1].refused("chat.picture", ask(&theirs)), "not_yet");    assert_eq!(p[1].refused("chat.picture", ask(&theirs)), "not_yet", "asked again: still not gone");    assert_eq!(p[1].refused("chat.picture", ask(&their_grid)), "not_yet");    assert!(p[1].handle.client().absent_media().is_empty(), "nothing kept as absent while it is new");    assert!(bubble(&p[1], &bens, &theirs)["media"][0].get("gone").is_none());    relay.0.lock().unwrap().files.extend(held);    let opened = p[1].call("chat.picture", ask(&their_grid));    assert_eq!(std::fs::read(opened["path"].as_str().unwrap()).unwrap(), b"an invented picture 0", "landed: {opened}");    // Long after, a file never seen here that the store does not hold is gone: said once, then refused with no request until its wait is over.    let old = (chrono::Utc::now() - chrono::Duration::minutes(30)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true);    p[1].handle.client().with_writer(|r| r.driver.run("UPDATE cotton_msg_messages SET sent_at = ?1, created_at = ?1, meta = json_set(meta, '$.cotton.written_at', ?1) WHERE id = ?2", &[rusqlite::types::Value::Text(old.clone()), rusqlite::types::Value::Text(theirs.clone())]).map(|_| ()).map_err(|e| e.to_string())).unwrap();    relay.0.lock().unwrap().files.clear();    assert_eq!(p[1].refused("chat.picture", ask(&theirs)), "not_found");    let asked = relay.0.lock().unwrap().file_gets;    assert_eq!(p[1].refused("chat.picture", ask(&theirs)), "not_found");    assert_eq!(relay.0.lock().unwrap().file_gets, asked, "refused at once, no request");    assert_eq!(bubble(&p[1], &bens, &theirs)["media"][0]["gone"], true);}// RULE: A failed message offers Retry, and retrying puts it back in the outbox.#[test]fn a_failed_message_offers_retry() {    let (_relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    let g = create(&p[0], "Family", &[BEN]);    let id = p[0].say(&g, "to fail");    p[0].handle.client().with_writer(|r| r.driver.run("UPDATE cotton_msg_messages SET send_state = 'failed' WHERE id = ?", &[rusqlite::types::Value::Text(id.clone())]).map(|_| ()).map_err(|e| e.to_string())).unwrap();    let thread = p[0].call("chat.thread", json!({ "thread": p[0].thread(&g) }));    assert!(thread.to_string().contains("\"retry\""), "{thread}");    let answer = p[0].call("chat.act", json!({ "act": "retry", "thread": p[0].thread(&g), "message": id }));    assert_eq!(answer["flush"], true);    p[0].call("chat.flush", json!({}));    assert_eq!(p[0].message(&id)["send_state"], "sent");}#[allow(dead_code)]fn opened(p: &Phone, b: &str) -> Payload {    serde_json::from_slice(&seal::open(&seal::key_from_text(&p.secret).unwrap(), b).unwrap().payload).unwrap()}// ── the c2 box between phones (SEALING.md) ───────────impl Phone {    /// `chat.register`, as a shell that opens c2 boxes (`ratchet: true`) or one that does not.    fn register(&self, ratchet: bool) -> Value {        self.call("chat.register", json!({ "ratchet": ratchet }))    }    fn start(&self, number: &str) -> String {        self.call("chat.start", json!({ "number": number }))["thread"].as_str().unwrap().to_string()    }    fn write(&self, number: &str, words: &str) -> Value {        let thread = self.start(number);        self.call("chat.send", json!({ "thread": thread, "body": words }))    }    /// The words of the one-to-one conversation with `number`, sorted (the relay's clocks for sent and received words differ).    fn said_with(&self, number: &str) -> Vec<String> {        let thread = cotton_core::chat::ids::thread_id(&super::super::cotton_chat::namespace(&self.handle.client()).unwrap(), number);        self.handle            .client()            .with_writer(|replica| {                Ok(replica                    .driver                    .all("SELECT body FROM cotton_msg_messages WHERE thread_id = ? AND json_extract(meta, '$.system') IS NULL ORDER BY sent_at, id", &[rusqlite::types::Value::Text(thread.clone())])                    .map_err(|e| e.to_string())?                    .iter()                    .map(|r| crate::phone::passwords::json_row(r)["body"].as_str().unwrap_or_default().to_string())                    .collect::<Vec<String>>())            })            .map(|mut words: Vec<String>| {                words.sort();                words            })            .unwrap()    }    fn ratchet_file(&self) -> std::path::PathBuf {        let secret = seal::key_from_text(&self.secret).unwrap();        self.handle.client().layout().client_dir().join(cotton_core::chat::ratchet::store_name(&public_of(&secret)))    }}/// The boxes a credential holds, by kind.fn held_boxes(relay: &Relay, credential: &str, kind: &str) -> Vec<String> {    relay.0.lock().unwrap().held.get(credential).into_iter().flatten().filter(|i| i["kind"] == json!(kind)).map(|i| i["box"].as_str().unwrap_or_default().to_string()).collect()}// RULE: Two phones whose shells open c2 speak it both ways: every box between them is a c2 one, each message lands, and the one-time keys claimed are one per pair.#[test]fn c2_both_ways() {    let (relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    assert_eq!(p[0].register(true)["ratchet"], true);    assert_eq!(p[1].register(true)["ratchet"], true);    p[0].write(BEN, "hello Ben");    let boxes = held_boxes(&relay, &p[1].credential, "message");    assert_eq!(boxes.len(), 1);    assert!(boxes[0].starts_with("c2:"), "{}", boxes[0]);    p[1].sync();    assert_eq!(p[1].said_with(ASHA), ["hello Ben"]);    p[1].write(ASHA, "hello Asha");    assert!(held_boxes(&relay, &p[0].credential, "message").iter().all(|b| b.starts_with("c2:")));    p[0].sync();    assert_eq!(p[0].said_with(BEN), ["hello Asha", "hello Ben"]);    for n in 0..3 {        p[0].write(BEN, &format!("more {n}"));        p[1].write(ASHA, &format!("back {n}"));    }    p[0].sync();    p[1].sync();    assert_eq!(p[1].said_with(ASHA).len(), 8);    assert_eq!(p[0].said_with(BEN).len(), 8);    // Ben answered on the session Asha's first message made: one key was claimed between them in all.    assert_eq!(relay.0.lock().unwrap().claims, 1);    // Nothing kept on either side once taken; the ratchet files are sealed (no words in them).    for phone in &p {        let file = std::fs::read(phone.ratchet_file()).unwrap();        assert!(file.starts_with(b"c2s:"));        assert!(!String::from_utf8_lossy(&file).contains("hello"));    }}// RULE: A phone offline while several messages are sealed for it opens them all, in order, when it comes back: the ratchet keeps the keys it skipped.#[test]fn c2_offline_catch_up() {    let (relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    p[0].register(true);    p[1].register(true);    for n in 0..5 {        p[0].write(BEN, &format!("while you were away {n}"));    }    // Held out of order (the object's order is its clock; a resend can come late): all open.    relay.0.lock().unwrap().held.get_mut(&p[1].credential).unwrap().reverse();    p[1].sync();    assert_eq!(p[1].said_with(ASHA), (0..5).map(|n| format!("while you were away {n}")).collect::<Vec<_>>());    assert!(held_boxes(&relay, &p[1].credential, "message").is_empty(), "every one taken");}// RULE: Two devices on each side: each pair of devices has its own session, every device reads every message, and a person's own other phone gets their own words in c2 too.#[test]fn c2_two_devices_each_side() {    let (relay, p) = world(&[ASHA, ASHA, BEN, BEN], &[(ASHA, BEN)]);    for phone in &p {        phone.register(true);    }    p[0].write(BEN, "to both of Ben's phones");    for phone in &p[1..] {        assert!(held_boxes(&relay, &phone.credential, "message").iter().all(|b| b.starts_with("c2:")));    }    for phone in &p {        phone.sync();    }    assert_eq!(p[2].said_with(ASHA), ["to both of Ben's phones"]);    assert_eq!(p[3].said_with(ASHA), ["to both of Ben's phones"]);    assert_eq!(p[1].said_with(BEN), ["to both of Ben's phones"], "Asha's other phone has her own words");    p[3].write(ASHA, "from Ben's second phone");    for phone in &p {        phone.sync();    }    assert_eq!(p[0].said_with(BEN), ["from Ben's second phone", "to both of Ben's phones"]);    assert_eq!(p[1].said_with(BEN), ["from Ben's second phone", "to both of Ben's phones"]);    assert_eq!(p[2].said_with(ASHA), ["from Ben's second phone", "to both of Ben's phones"]);}// RULE: A phone that joins later (a new device of Ben's) is sealed for at once, on a session from its first key, and reads what is sent from then on; what came before stays in Ben's own database, never re-sent.#[test]fn c2_a_new_device_joins() {    let (relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    p[0].register(true);    p[1].register(true);    p[0].write(BEN, "before the tablet");    p[1].sync();    let (dir, handle) = phone();    let credential = "ctd_88888888-1111-4111-8111-111111111111_test-credential".to_string();    relay.0.lock().unwrap().devices.push((credential.clone(), BEN.to_string(), format!("{:0>22}", "bentablet"), seal::key_text(&public_of(&scalar(88)))));    let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: relay.clone(), credential: credential.clone() };    handle.client().set_object_door(Some(Arc::new(door)));    let thread: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/thread.json")).unwrap();    handle.client().with_writer(|replica| cotton_client::transport::object::hold_defined_columns(&replica.driver, [&thread]).map(|_| ())).unwrap();    let tablet = Phone { _dir: dir, handle, number: BEN, secret: seal::key_text(&scalar(88)), credential };    tablet.register(true);    // Asha's phone asks Ben's keys again (the Worker refuses a message sealed for his devices of before: stale_devices).    super::super::cotton_chat::forget_keys(&p[0].handle.client());    p[0].write(BEN, "after the tablet");    let boxes = held_boxes(&relay, &tablet.credential, "message");    assert_eq!(boxes.len(), 1);    assert!(boxes[0].starts_with("c2:"));    tablet.sync();    assert_eq!(tablet.said_with(ASHA), ["after the tablet"]);}// RULE: A group between c2 phones ratchets each pair: every member's box is c2, and each member reads the group's words.#[test]fn c2_in_a_group() {    let (relay, p) = world(&[ASHA, BEN, CHEN], &[(ASHA, BEN), (ASHA, CHEN)]);    for phone in &p {        phone.register(true);    }    let g = create(&p[0], "Family", &[BEN, CHEN]);    assert!(held_boxes(&relay, &p[1].credential, "group").iter().all(|b| b.starts_with("c2:")));    p[1].sync();    p[2].sync();    p[1].say(&g, "dinner at eight?");    assert!(held_boxes(&relay, &p[2].credential, "message").iter().all(|b| b.starts_with("c2:")));    p[2].sync();    p[0].sync();    assert_eq!(p[2].bodies(&g), ["dinner at eight?"]);    assert_eq!(p[0].bodies(&g), ["dinner at eight?"]);}// RULE: c2 only to a device that advertises it: a phone whose shell does not open c2 is written to in c1 and reads it, and old messages stay readable.#[test]fn c1_for_a_phone_that_does_not_speak_c2() {    let (relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    p[0].register(true);    p[1].register(false);    p[0].write(BEN, "in c1");    assert!(held_boxes(&relay, &p[1].credential, "message")[0].starts_with("c1:"));    p[1].sync();    assert_eq!(p[1].said_with(ASHA), ["in c1"]);    p[1].write(ASHA, "back in c1");    p[0].sync();    assert_eq!(p[0].said_with(BEN), ["back in c1", "in c1"]);}// RULE: Once a pair spoke c2 it never falls back: a record that disappears fails the next message loudly ("downgrade"), and a c1 box from that device is dropped.#[test]fn c2_never_downgrades_silently() {    let (relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    p[0].register(true);    p[1].register(true);    p[0].write(BEN, "in c2");    p[1].sync();    p[0].sync();    // The keys answer stops carrying Ben's record (an object that strips it, or an older app).    {        let mut w = relay.0.lock().unwrap();        let ben = p[1].credential.clone();        w.c2.remove(&ben);    }    super::super::cotton_chat::forget_keys(&p[0].handle.client());    let sent = p[0].write(BEN, "would be c1");    assert_eq!(sent["state"], "failed", "{sent}");    let failed = p[0].message(sent["message"].as_str().unwrap());    assert!(failed["send_error"].as_str().unwrap().contains("stronger lock"), "{failed:?}");    // Ben's phone, as an older app with no ratchet, writes in c1: Asha's phone drops it.    std::fs::remove_file(p[1].ratchet_file()).unwrap();    super::super::chat_ratchet::forget_cached();    p[1].register(false);    p[1].write(ASHA, "a c1 word");    assert!(held_boxes(&relay, &p[0].credential, "message").iter().any(|b| b.starts_with("c1:")));    let got = p[0].sync();    assert_eq!(got["dropped"], 1, "{got}");    assert_eq!(p[0].said_with(BEN), ["in c2", "would be c1"], "the failed one stays, Ben's c1 word does not land");}// RULE: A session lost on one side (its ratchet file put back from before) is reset: the box that opens nothing is answered on a fresh session, and the next words land.#[test]fn c2_a_lost_session_resets() {    let (relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    p[0].register(true);    p[1].register(true);    let before = std::fs::read(p[1].ratchet_file()).unwrap();    p[0].write(BEN, "first");    p[1].sync();    p[1].write(ASHA, "reply");    p[0].sync();    std::fs::write(p[1].ratchet_file(), &before).unwrap();    super::super::chat_ratchet::forget_cached();    p[0].write(BEN, "lost");    let got = p[1].sync();    // The lost words, and Asha's delivered tick for "reply" on the same lost session.    assert_eq!(got["dropped"], 2, "{got}");    // Ben's phone told Asha's on a fresh session; her next words go on it, after the lost ones sent again.    assert!(held_boxes(&relay, &p[0].credential, "receipt").iter().any(|b| b.starts_with("c2:")));    p[0].sync();    p[0].write(BEN, "after the reset");    p[1].sync();    assert_eq!(p[1].said_with(ASHA), ["after the reset", "first", "lost", "reply"]);}// RULE: A reset device gets what it lost again (SEALING.md, decided 21 Nov 2026): the sender's phone seals each of its// messages the notice names again for that one device alone, once. The person's other device gets nothing more, the// words land once, and a second notice for the same message sends nothing.#[test]fn c2_a_lost_message_is_sent_again_once_to_that_device() {    let (relay, p) = world(&[ASHA, BEN, BEN], &[(ASHA, BEN)]);    for phone in &p {        phone.register(true);    }    let before = std::fs::read(p[1].ratchet_file()).unwrap();    p[0].write(BEN, "first");    p[1].sync();    p[2].sync();    p[1].write(ASHA, "reply");    p[0].sync();    p[2].sync();    std::fs::write(p[1].ratchet_file(), &before).unwrap();    super::super::chat_ratchet::forget_cached();    let lost = p[0].write(BEN, "lost");    let lost_id = lost["message"].as_str().unwrap().to_string();    p[2].sync();    assert_eq!(p[1].sync()["dropped"], 2);    let got = p[0].sync();    assert_eq!(got["resent"], json!([lost_id]), "{got}");    assert!(p[0].message(&lost_id)["meta"].to_string().contains("resent"));    // Only Ben's phone that lost it holds it again; his tablet, which read it, holds nothing more.    assert_eq!(held_boxes(&relay, &p[1].credential, "message").len(), 1);    assert!(held_boxes(&relay, &p[2].credential, "message").is_empty());    assert_eq!(relay.0.lock().unwrap().resent.len(), 1);    // The phone's session is lost again before it opens the re-sent box: a second notice names the same message.    std::fs::write(p[1].ratchet_file(), &before).unwrap();    super::super::chat_ratchet::forget_cached();    assert_eq!(p[1].sync()["dropped"], 1);    assert!(held_boxes(&relay, &p[0].credential, "receipt").iter().any(|b| b.starts_with("c2:")));    let again = p[0].sync();    assert_eq!(again["resent"], json!([]), "sent again once, never twice: {again}");    assert!(held_boxes(&relay, &p[1].credential, "message").is_empty());    assert_eq!(relay.0.lock().unwrap().resent.len(), 1);    // The pair goes on, on the fresh session.    p[0].write(BEN, "after");    p[1].sync();    assert_eq!(p[1].said_with(ASHA), ["after", "first", "reply"]);    assert_eq!(p[2].said_with(ASHA), ["first", "lost", "reply"]);}// RULE: Re-sent words land once, in their place, and a message deleted before the notice comes back is never sent again.#[test]fn c2_a_re_sent_message_lands_once_and_a_deleted_one_never_goes_again() {    let (relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    p[0].register(true);    p[1].register(true);    let before = std::fs::read(p[1].ratchet_file()).unwrap();    p[0].write(BEN, "first");    p[1].sync();    p[1].write(ASHA, "reply");    p[0].sync();    std::fs::write(p[1].ratchet_file(), &before).unwrap();    super::super::chat_ratchet::forget_cached();    let kept = p[0].write(BEN, "lost, then found");    let gone = p[0].write(BEN, "taken back");    let thread = p[0].start(BEN);    p[0].call("chat.act", json!({ "act": "delete", "thread": thread, "message": gone["message"] }));    p[1].sync();    let got = p[0].sync();    assert_eq!(got["resent"], json!([kept["message"]]), "{got}");    p[1].sync();    p[1].sync();    assert_eq!(p[1].said_with(ASHA), ["first", "lost, then found", "reply"]);    assert!(held_boxes(&relay, &p[1].credential, "message").is_empty());}// RULE: A phone tops its one-time keys up when its object holds fewer than 25.#[test]fn c2_one_time_keys_are_topped_up() {    let (relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    p[1].register(true);    let ben = p[1].credential.clone();    assert_eq!(relay.0.lock().unwrap().prekeys[&ben].len(), cotton_core::chat::ratchet::PREKEYS_TARGET);    relay.0.lock().unwrap().prekeys.get_mut(&ben).unwrap().truncate(5);    p[1].sync();    assert_eq!(relay.0.lock().unwrap().prekeys[&ben].len(), cotton_core::chat::ratchet::PREKEYS_TARGET);}/// `chat.peek` through the C ABI with no core open, as an iPhone's notification extension calls it.fn peek_through_the_abi(request: &Value) -> Value {    let method = std::ffi::CString::new("chat.peek").unwrap();    let body = std::ffi::CString::new(request.to_string()).unwrap();    // SAFETY: a null handle (the one method that takes none), NUL-terminated strings, the answer freed once.    let answer = unsafe { crate::ffi::cotton_call(std::ptr::null_mut(), method.as_ptr(), body.as_ptr()) };    let text = unsafe { std::ffi::CStr::from_ptr(answer) }.to_string_lossy().into_owned();    unsafe { crate::ffi::cotton_string_free(answer) };    serde_json::from_str(&text).unwrap()}// RULE: An iPhone's notification extension opens a c2 box read-only with no core open (chat.peek through cotton_call with a null handle): on a session the ratchet holds it says who and what, changes nothing, and the app then opens the same box for real; a first message of a new session, a stranger's box or a c1 box is not peeked.#[test]fn c2_a_box_is_peeked_without_the_core_and_still_opens() {    let (relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    p[0].register(true);    p[1].register(true);    let dir = p[1].handle.client().layout().client_dir().to_string_lossy().into_owned();    let item = |n: usize| relay.0.lock().unwrap().held.get(&p[1].credential).unwrap().iter().filter(|i| i["kind"] == json!("message")).nth(n).cloned().unwrap();    p[0].write(BEN, "first");    // The first message makes the session: the extension has no record to check it against.    let first = peek_through_the_abi(&json!({ "privateKey": p[1].secret, "dir": dir, "item": item(0), "me": BEN }));    assert_eq!(first, json!({ "ok": true, "data": { "opened": false } }));    p[1].sync();    p[0].write(BEN, "on the lock screen");    let held = item(0);    let request = json!({ "privateKey": p[1].secret, "dir": dir, "item": held, "me": BEN });    let peeked = peek_through_the_abi(&request);    assert_eq!(peeked["data"], json!({ "opened": true, "from": ASHA, "kind": "message", "out": false, "pictures": 0, "body": "on the lock screen" }));    assert_eq!(peek_through_the_abi(&request)["data"]["opened"], true, "peeked twice: nothing used up");    p[1].sync();    assert_eq!(p[1].said_with(ASHA), ["first", "on the lock screen"]);    // Another chat key, a box that says another sender, a c1 box: not opened.    let wrong_key = json!({ "privateKey": seal::key_text(&scalar(99)), "dir": dir, "item": held, "me": BEN });    assert_eq!(peek_through_the_abi(&wrong_key)["data"]["opened"], false);    let mut moved = held.clone();    moved["peer"] = json!(CHEN);    assert_eq!(peek_through_the_abi(&json!({ "privateKey": p[1].secret, "dir": dir, "item": moved }))["data"]["opened"], false);    let mut c1 = held.clone();    c1["box"] = json!("c1:abc");    assert_eq!(peek_through_the_abi(&json!({ "privateKey": p[1].secret, "dir": dir, "item": c1 }))["data"]["opened"], false);    // Any other method with no core is still refused.    let method = std::ffi::CString::new("chat.list").unwrap();    let answer = unsafe { crate::ffi::cotton_call(std::ptr::null_mut(), method.as_ptr(), std::ptr::null()) };    let text = unsafe { std::ffi::CStr::from_ptr(answer) }.to_string_lossy().into_owned();    unsafe { crate::ffi::cotton_string_free(answer) };    assert!(text.contains("no_core"), "{text}");}// Disappearing and starred messages between phones (chat-search): `chat_timer_tests.rs`.#[path = "chat_timer_tests.rs"]mod timer;// Safety numbers between phones: `chat_safety_tests.rs`.#[path = "chat_safety_tests.rs"]pub(crate) mod safety;// A reply's quote between phones: `chat_reply_tests.rs`.#[path = "chat_reply_tests.rs"]mod reply;// A voice message between phones (the voice player): `chat_voice_relay_tests.rs`.#[path = "chat_voice_relay_tests.rs"]mod voice;// ── an agent in a chat (23 Nov 2026; CONTRACT "An agent in a chat") ──/// The agent's own member key in these tests: its connection's, which only it opens on the Worker.fn agent_secret() -> [u8; 32] {    scalar(55)}const AGENT: &str = "mem-claude-1";/// The phone's person has connected Claude (a live account grant naming its member).fn connect_claude(phone: &Phone) {    let client = phone.handle.client();    let file = rusqlite::Connection::open(client.layout().replica(&client.current_database().unwrap())).expect("the copy");    let member_pub = seal::key_text(&public_of(&agent_secret()));    file.execute_batch(&format!(        "CREATE TABLE IF NOT EXISTS cotton_unlock_grant (id TEXT PRIMARY KEY, workspace_id TEXT, request_id TEXT, token_id TEXT, tables TEXT, minutes REAL, standing INTEGER, granted_at TEXT, ends_at TEXT, ended_at TEXT, client TEXT, account INTEGER, member_id TEXT, member_pub TEXT, withheld TEXT, ask TEXT, off TEXT);         INSERT INTO cotton_unlock_grant VALUES ('g-a', 'w', 'req-a', '{AGENT}', '[\"message\"]', 0, 1, '2026-11-23T09:00:00.000Z', '9999-12-31T23:59:59.999Z', NULL, 'Claude', 1, '{AGENT}', '{member_pub}', '[]', '[]', '[]');"    ))    .expect("the grant row");}/// What the agent reads: a feed item's box opened with its member key.fn fed_box(item: &Value) -> Value {    let plain = cotton_core::vault::wrap::unwrap(&agent_secret(), item["box"].as_str().unwrap()).expect("the agent's key opens it");    serde_json::from_slice(&plain).unwrap()}fn bubble_of(phone: &Phone, group: &str, message: &str) -> Value {    let thread = phone.call("chat.thread", json!({ "thread": phone.thread(group) }));    let found = thread["items"].as_array().cloned().unwrap_or_default();    found.into_iter().find(|b| b["message"] == json!(message)).unwrap_or_else(|| panic!("no bubble {message} in {thread}"))}fn message_by_external(phone: &Phone, group: &str, words: &str) -> String {    let thread = phone.thread(group);    phone.handle.client().with_writer(|replica| Ok(replica.driver.get("SELECT id FROM cotton_msg_messages WHERE thread_id = ? AND body = ?", &[rusqlite::types::Value::Text(thread.clone()), rusqlite::types::Value::Text(words.to_string())]).map_err(|e| e.to_string())?.map(|r| crate::phone::passwords::json_row(&r)["id"].as_str().unwrap().to_string()).unwrap())).unwrap()}// RULE (an agent in a chat): the person adds their own connected Claude to a group; every member sees it in the// member list and a line; the agent reads what is said there from then on (sealed to its own key), posts a reply// and reacts, each marked as the agent's on every phone and never as the person; taken out, it reads and says// nothing more there.#[test]fn an_agent_joins_reads_posts_reacts_and_leaves() {    let (relay, p) = world(&[ASHA, BEN, CHEN], &[(ASHA, BEN), (ASHA, CHEN)]);    let g = create(&p[0], "Feedback", &[BEN, CHEN]);    p[1].sync();    p[2].sync();    p[1].say(&g, "said before the agent came");    p[0].sync();    // No agent is offered until one is connected, and nothing is on by default.    let choices = p[0].call("chat.agent.choices", json!({ "thread": p[0].thread(&g) }));    assert_eq!(choices["connect"], true, "{choices}");    assert_eq!(p[0].refused("chat.agent.add", json!({ "thread": p[0].thread(&g), "agent": AGENT })), "no_agent");    connect_claude(&p[0]);    let choices = p[0].call("chat.agent.choices", json!({ "thread": p[0].thread(&g) }));    assert_eq!(choices["agents"], json!([{ "agent": AGENT, "name": "Claude", "in": false }]));    p[0].call("chat.agent.add", json!({ "thread": p[0].thread(&g), "agent": AGENT }));    p[0].sync();    {        let w = relay.0.lock().unwrap();        let told = w.agent_chats.iter().find(|c| c.0 == ASHA && c.1 == AGENT && c.3).expect("the Worker is told the agent is in");        assert_eq!(told.2, p[0].thread(&g));        let about: Value = serde_json::from_slice(&cotton_core::vault::wrap::unwrap(&agent_secret(), told.4.as_deref().unwrap()).unwrap()).unwrap();        assert_eq!(about["title"], "Feedback");    }    assert_eq!(p[0].lines(&g).last().map(String::as_str), Some("You added Claude, your agent"));    let info = p[0].info(&g);    assert_eq!(info["agents"][0]["line"], "Your agent");    assert_eq!(info["agents"][0]["can"]["remove"], true);    // Ben sees the agent among the members, named as Asha's, and a line in the chat.    p[1].sync();    let info = p[1].info(&g);    assert_eq!(info["agents"].as_array().unwrap().len(), 1, "{info}");    assert_eq!(info["agents"][0]["name"], "Claude");    assert_eq!(info["agents"][0]["of"], ASHA);    assert_eq!(info["agents"][0]["yours"], false);    assert_eq!(info["agents"][0]["can"]["remove"], false, "Ben is neither its person nor an admin");    assert!(p[1].lines(&g).last().unwrap().ends_with("added Claude, an agent"), "{:?}", p[1].lines(&g));    assert_eq!(members(&info), [ASHA, BEN, CHEN], "an agent is no member");    // Ben writes; Asha's phone hands it to the agent, sealed to its key alone, and nothing from before it came.    p[1].say(&g, "the share button does nothing");    p[0].sync();    let item = {        let w = relay.0.lock().unwrap();        let fed: Vec<Value> = w.feed.iter().filter(|(o, i)| o == ASHA && i["agent"] == json!(AGENT)).map(|(_, i)| i.clone()).collect();        assert!(fed.iter().all(|i| fed_box(i)["body"] != json!("said before the agent came")), "nothing from before it joined");        fed.into_iter().find(|i| fed_box(i)["body"] == json!("the share button does nothing")).expect("Ben's words reached the agent")    };    let said = fed_box(&item);    assert_eq!((said["from"].as_str(), said["mine"].as_bool()), (Some(BEN), Some(false)));    let bens = said["id"].as_str().unwrap().to_string();    assert_eq!(item["thread"], json!(p[0].thread(&g)));    let fed_before = relay.0.lock().unwrap().feed.len();    p[0].sync();    assert_eq!(relay.0.lock().unwrap().feed.len(), fed_before, "each message is handed over once");    // The agent answers, quoting Ben: Asha's phone sends it as her envelope, marked as the agent's.    relay.0.lock().unwrap().act(ASHA, json!({ "id": "act-1", "agent": AGENT, "thread": p[0].thread(&g), "kind": "post", "body": "Thanks, it's fixed in the next build.", "replyTo": bens }));    p[0].sync();    assert!(relay.0.lock().unwrap().done.iter().any(|d| d.1 == "act-1" && d.2 == "sent"), "the act is reported sent");    let mine = message_by_external(&p[0], &g, "Thanks, it's fixed in the next build.");    let on_asha = bubble_of(&p[0], &g, &mine);    assert_eq!(on_asha["mine"], false, "never drawn as Asha's own: {on_asha}");    assert_eq!(on_asha["agent"]["name"], "Claude");    assert_eq!(on_asha["agent"]["line"], "Your agent");    assert!(on_asha["reply"].is_object(), "it quotes Ben: {on_asha}");    p[1].sync();    let theirs = message_by_external(&p[1], &g, "Thanks, it's fixed in the next build.");    let on_ben = bubble_of(&p[1], &g, &theirs);    assert_eq!(on_ben["mine"], false);    assert_eq!(on_ben["agent"]["name"], "Claude", "Ben sees the mark: {on_ben}");    assert_eq!(on_ben["sender"]["name"], "Claude");    assert!(on_ben["agent"]["line"].as_str().unwrap().ends_with("'s agent"), "{on_ben}");    assert!(on_ben["reply"].is_object(), "{on_ben}");    // Its own words reach it too, marked as its own.    p[0].sync();    assert!(relay.0.lock().unwrap().feed.iter().any(|(_, i)| fed_box(i)["agent"]["self"] == json!(true)));    // A reaction is the agent's, under its own name, never Asha's.    relay.0.lock().unwrap().act(ASHA, json!({ "id": "act-2", "agent": AGENT, "thread": p[0].thread(&g), "kind": "react", "message": bens, "emoji": "👍" }));    p[0].sync();    assert!(relay.0.lock().unwrap().done.iter().any(|d| d.1 == "act-2" && d.2 == "sent"));    p[1].sync();    let on_ben = bubble_of(&p[1], &g, &message_by_external(&p[1], &g, "the share button does nothing"));    assert_eq!(on_ben["reactions"][0]["emoji"], "👍", "{on_ben}");    let actors: Vec<String> = p[1].handle.client().with_writer(|replica| Ok(replica.driver.all("SELECT actor FROM cotton_msg_reactions", &[]).map_err(|e| e.to_string())?.iter().map(|r| crate::phone::passwords::json_row(r)["actor"].as_str().unwrap_or_default().to_string()).collect())).unwrap();    assert_eq!(actors, [super::super::chat_agent::actor(AGENT)], "kept as the agent's, not as Asha's");    // Taken out: a line, the Worker told, and an act after it refused.    p[0].call("chat.agent.remove", json!({ "thread": p[0].thread(&g), "agent": AGENT }));    p[0].sync();    assert!(relay.0.lock().unwrap().agent_chats.iter().any(|c| c.0 == ASHA && c.1 == AGENT && !c.3), "the Worker is told it left");    p[1].sync();    assert_eq!(p[1].info(&g)["agents"], json!([]));    assert_eq!(p[1].lines(&g).last().map(String::as_str), Some("Claude left"));    relay.0.lock().unwrap().act(ASHA, json!({ "id": "act-3", "agent": AGENT, "thread": p[0].thread(&g), "kind": "post", "body": "still here?" }));    p[0].sync();    assert!(relay.0.lock().unwrap().done.iter().any(|d| d.1 == "act-3" && d.2 == "failed" && d.3.as_deref() == Some("This agent is not in that chat.")));    p[1].sync();    assert!(!p[1].bodies(&g).iter().any(|b| b == "still here?"));    let fed = relay.0.lock().unwrap().feed.len();    p[1].say(&g, "after it left");    p[0].sync();    assert_eq!(relay.0.lock().unwrap().feed.len(), fed, "nothing said after it left reaches it");}// RULE: an agent acts only in a chat it was added to; nobody adds another person's agent; a member who is neither// its person nor an admin cannot take it out; and an admin can.#[test]fn an_agent_is_only_where_it_was_added() {    let (relay, p) = world(&[ASHA, BEN, CHEN], &[(ASHA, BEN), (ASHA, CHEN)]);    let g = create(&p[0], "Feedback", &[BEN, CHEN]);    let other = create(&p[0], "Family", &[BEN]);    p[1].sync();    p[2].sync();    connect_claude(&p[0]);    p[0].call("chat.agent.add", json!({ "thread": p[0].thread(&g), "agent": AGENT }));    p[0].sync();    p[1].sync();    relay.0.lock().unwrap().act(ASHA, json!({ "id": "act-x", "agent": AGENT, "thread": p[0].thread(&other), "kind": "post", "body": "hello family" }));    p[0].sync();    assert!(relay.0.lock().unwrap().done.iter().any(|d| d.1 == "act-x" && d.2 == "failed"), "a chat it was not added to refuses");    p[1].sync();    assert!(!p[1].bodies(&other).iter().any(|b| b == "hello family"));    // Ben has no agent of Asha's to add, and cannot take hers out.    assert_eq!(p[1].refused("chat.agent.add", json!({ "thread": p[1].thread(&g), "agent": AGENT })), "no_agent");    assert_eq!(p[1].refused("chat.agent.remove", json!({ "thread": p[1].thread(&g), "agent": AGENT })), "not_yours");    // In Family, where Ben is no admin and Asha is, Asha could; here Asha removes it as its person.    assert_eq!(p[0].info(&g)["agents"][0]["can"]["remove"], true);}// RULE (owner's bug, 28 Nov 2026): a group whose log a phone's copy lost (filled from the object before the log went// with the row) says so on send, asks its members for the whole log, and is whole again once one answers: the member// answers to that phone alone, and the log merges as a welcome does. Nobody is put in the group from the seats.#[test]fn a_group_whose_log_was_lost_is_asked_back_from_its_members() {    let (relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    let g = create(&p[0], "Family", &[BEN]);    p[1].sync();    p[1].say(&g, "before");    p[0].sync();    let thread = p[1].thread(&g);    p[1].handle        .client()        .with_writer(|replica| replica.driver.run("UPDATE cotton_msg_threads SET group_log = NULL WHERE id = ?", &[rusqlite::types::Value::Text(thread.clone())]).map_err(|e| e.to_string()))        .unwrap();    assert_eq!(p[1].refused("chat.act", json!({ "act": "send", "thread": thread, "text": "lost" })), "group_restoring");    let before = relay.0.lock().unwrap().sent.len();    p[1].sync(); // asks    p[0].sync(); // answers, to Ben alone    p[1].sync(); // the whole log lands    let sent = relay.0.lock().unwrap().sent[before..].to_vec();    assert!(sent.iter().all(|(_, to, kind, _)| kind != "group" || to == ASHA || to == BEN), "{sent:?}");    let info = p[1].info(&g);    assert_eq!(members(&info), [ASHA, BEN]);    assert_eq!(info["title"], "Family");    p[1].say(&g, "after");    p[0].sync();    assert_eq!(p[0].bodies(&g), ["before", "after"]);}// RULE: an ask for the log is answered only to a member, by a member: someone not in the group asks for nothing.#[test]fn a_stranger_asking_for_a_groups_log_is_told_nothing() {    let (_relay, p) = world(&[ASHA, BEN, CHEN], &[(ASHA, BEN), (ASHA, CHEN)]);    let g = create(&p[0], "Family", &[BEN]);    p[1].sync();    let client = p[0].handle.client();    let ns = crate::phone::cotton_chat::namespace(&client).unwrap();    let item = cotton_core::chat::payload::Item { id: "ask-1".into(), kind: cotton_core::chat::payload::Kind::Group, peer: CHEN.to_string(), out: false, request: false, sealed: String::new(), at: 1, group: Some(g.clone()) };    let ask = cotton_core::chat::payload::Payload::group_ask("ask-1", CHEN, ASHA, 1, &g);    super::arrive(&client, &ns, ASHA, &item, &ask, 2).unwrap();    let kept = super::kept_for(&client, &p[0].thread(&g)).unwrap();    assert!(kept.told.iter().all(|t| !t.to.contains(&CHEN.to_string())), "{:?}", kept.told.iter().map(|t| &t.to).collect::<Vec<_>>());}