Cotton code
742 lines · 52.1 KB · RustRaw
//! `chat.*` on a phone over a scripted object: what each method asks, what//! it seals and for whom, and the rows it leaves. Every number, key and//! person is invented; the other person's phone is a scalar here.use std::sync::Arc;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange, Seen};use cotton_core::chat::payload::{Kind, Payload, Receipt};use cotton_core::chat::seal;use cotton_core::vault::wrap::public_of;use serde_json::{json, Value};use super::over;use crate::handle::CottonHandle;use crate::phone::passwords::tests::phone;use crate::phone::personal_object::ObjectDoor;const CREDENTIAL: &str = "ctd_11111111-1111-4111-8111-111111111111_test-credential";const ME: &str = "+15550100002";const THEM: &str = "+15550100001";fn scalar(seed: u8) -> [u8; 32] {    let mut bytes = [seed; 32];    bytes[0] = seed.wrapping_mul(7).wrapping_add(1);    bytes}/// This phone's chat key, their phone's, and this person's tablet's.const MINE: u8 = 2;const THEIRS: u8 = 1;const TABLET: u8 = 4;fn key(seed: u8) -> String {    seal::key_text(&public_of(&scalar(seed)))}fn private(seed: u8) -> String {    seal::key_text(&scalar(seed))}fn with_door(handle: &CottonHandle, replies: impl IntoIterator<Item = Reply>) -> Arc<ScriptedExchange> {    let exchange = ScriptedExchange::new(replies);    let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: exchange.clone(), credential: CREDENTIAL.to_string() };    handle.client().set_object_door(Some(Arc::new(door)));    exchange}fn answer(handle: &CottonHandle, method: &str, request: Value) -> Value {    over(&handle.client(), method, &request).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message))}fn refused(handle: &CottonHandle, method: &str, request: Value) -> String {    over(&handle.client(), method, &request).err().map(|error| error.code).unwrap_or_else(|| panic!("{method} answered"))}fn keys_reply() -> Reply {    Reply::ok(&json!({ "me": ME, "devices": [{ "device": "theirhandle00000000000", "key": key(THEIRS) }], "own": [{ "device": "tablethandle0000000000", "key": key(TABLET) }] }).to_string())}fn body(seen: &Seen) -> Value {    serde_json::from_slice(&seen.body).expect("a JSON body")}fn row(handle: &CottonHandle, sql: &str, id: &str) -> Option<serde_json::Map<String, Value>> {    handle        .client()        .with_writer(|replica| Ok(replica.driver.get(sql, &[rusqlite::types::Value::Text(id.to_string())]).map_err(|e| e.to_string())?.map(|row| crate::phone::passwords::json_row(&row))))        .unwrap()}fn message(handle: &CottonHandle, id: &str) -> serde_json::Map<String, Value> {    row(handle, "SELECT * FROM cotton_msg_messages WHERE id = ?", id).unwrap_or_else(|| panic!("no message {id}"))}/// The chat with them, known on Cotton here (chat.start asks the server nothing), the test's own door kept.fn thread_with(handle: &CottonHandle) -> String {    let held = handle.client().object_door();    crate::phone::chat_people::hold_on_cotton(&handle.client(), THEM);    let found = cotton_client::transport::scripted::ScriptedExchange::new([]);    let door = crate::phone::personal_object::ObjectDoor { address: cotton_client::transport::object::ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: found, credential: "ctd_11111111-1111-4111-8111-111111111111_test-credential".to_string() };    handle.client().set_object_door(Some(std::sync::Arc::new(door)));    let thread = answer(handle, "chat.start", json!({ "number": THEM }))["thread"].as_str().unwrap().to_string();    handle.client().set_object_door(held);    thread}/// The thread table as the object's definition lays it (the request column).fn hold_definitions(handle: &CottonHandle) {    let thread: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/thread.json")).expect("the thread definition");    handle.client().with_writer(|replica| cotton_client::transport::object::hold_defined_columns(&replica.driver, [&thread]).map(|_| ())).unwrap();}/// An item their phone sealed for this one.fn from_them(payload: &Payload, request: bool, at: i64) -> Value {    json!({ "id": payload.id, "kind": payload.kind.as_str(), "peer": THEM, "out": false, "request": request, "box": seal::seal(&scalar(THEIRS), &public_of(&scalar(MINE)), &payload.bytes()).unwrap(), "at": at })}// RULE: a message to a number is a Cotton thread and a queued row at once, then sealed once for each of their devices and each of this person's other devices, and sent under its own id; the row says sent at the object's clock.#[test]fn sending_seals_for_every_device_and_marks_the_row_sent() {    let (_dir, handle) = phone();    let exchange = with_door(&handle, [keys_reply(), Reply::ok(r#"{"ok":true,"id":"x","at":1763000000000}"#)]);    let thread = thread_with(&handle);    let sent = answer(&handle, "chat.send", json!({ "thread": thread, "body": "the kettle is on", "privateKey": private(MINE) }));    assert_eq!(sent["state"], "sent");    let seen = exchange.seen();    assert_eq!(seen[0].path, "/v1/chat/keys?number=%2B15550100001");    assert_eq!((seen[1].method.as_str(), seen[1].path.as_str()), ("POST", "/v1/chat/send"));    let envelope = body(&seen[1]);    assert_eq!((envelope["to"].as_str(), envelope["kind"].as_str()), (Some(THEM), Some("message")));    let boxes = envelope["boxes"].as_object().unwrap();    assert_eq!(boxes.len(), 2, "their phone and this person's tablet");    let theirs = seal::open(&scalar(THEIRS), boxes["theirhandle00000000000"].as_str().unwrap()).expect("their box opens with their key");    assert_eq!(theirs.sender, public_of(&scalar(MINE)), "sealed by this phone");    let said: Payload = serde_json::from_slice(&theirs.payload).unwrap();    assert_eq!((said.from.as_str(), said.to.as_str(), said.body.as_deref()), (ME, THEM, Some("the kettle is on")));    assert_eq!(said.id, envelope["id"].as_str().unwrap());    assert!(seal::open(&scalar(TABLET), boxes["tablethandle0000000000"].as_str().unwrap()).is_some());    assert!(!envelope.to_string().contains("kettle"), "no words outside the boxes");    let stored = message(&handle, sent["message"].as_str().unwrap());    assert_eq!((stored["channel"].as_str(), stored["direction"].as_str(), stored["send_state"].as_str()), (Some("cotton"), Some("out"), Some("sent")));    assert_eq!(stored["sent_at"], "2025-11-13T02:13:20.000Z");    assert_eq!(stored["thread_id"], json!(thread));    let thread_row = row(&handle, "SELECT * FROM cotton_msg_threads WHERE id = ?", &thread).unwrap();    assert_eq!(thread_row["external_key"], json!(format!("cotton:{THEM}")));    assert_eq!(thread_row["last_message_preview"], "the kettle is on");}// RULE: a message refused as sealed for devices that have changed (one signed in since the keys were kept) is sealed again once for the keys asked afresh, under the same id, and goes.#[test]fn a_message_sealed_for_old_devices_is_sealed_again_for_the_new() {    let (_dir, handle) = phone();    let fresh = Reply::ok(&json!({ "me": ME, "devices": [{ "device": "theirhandle00000000000", "key": key(THEIRS) }, { "device": "theirnewphone000000000", "key": key(5) }], "own": [{ "device": "tablethandle0000000000", "key": key(TABLET) }] }).to_string());    let exchange = with_door(&handle, [keys_reply(), Reply::json(409, r#"{"code":"stale_devices","message":"The devices to seal for have changed; ask their keys again."}"#), fresh, Reply::ok(r#"{"ok":true,"id":"x","at":1763000000000}"#)]);    let thread = thread_with(&handle);    let sent = answer(&handle, "chat.send", json!({ "thread": thread, "body": "welcome, new phone", "privateKey": private(MINE) }));    assert_eq!(sent["state"], "sent");    let seen = exchange.seen();    let paths: Vec<&str> = seen.iter().map(|s| s.path.as_str()).collect();    assert_eq!(paths, vec!["/v1/chat/keys?number=%2B15550100001", "/v1/chat/send", "/v1/chat/keys?number=%2B15550100001", "/v1/chat/send"]);    let (first, second) = (body(&seen[1]), body(&seen[3]));    assert_eq!(first["id"], second["id"], "the same message, not a second one");    assert_eq!((first["check"].as_bool(), second["check"].as_bool()), (Some(true), Some(true)), "it says it seals again");    let boxes = second["boxes"].as_object().unwrap();    assert_eq!(boxes.len(), 3);    let opened = seal::open(&scalar(5), boxes["theirnewphone000000000"].as_str().unwrap()).expect("their new phone's box opens");    let said: Payload = serde_json::from_slice(&opened.payload).unwrap();    assert_eq!(said.body.as_deref(), Some("welcome, new phone"));}// RULE: offline, a message waits queued; the outbox sends the oldest first and the next only after it, so the other side reads them in order.#[test]fn offline_messages_wait_and_go_in_order() {    let (_dir, handle) = phone();    with_door(&handle, []);    // No door answers at all: the thread is made here, the message waits.    let thread = thread_with(&handle);    let first = answer(&handle, "chat.send", json!({ "thread": thread, "body": "one", "privateKey": private(MINE) }));    assert_eq!(first["state"], "queued");    assert!(first["nextAt"].as_i64().is_some(), "the shell's timer");    // Waited out, the door back: one goes, then two.    let exchange = with_door(&handle, [keys_reply(), Reply::ok(r#"{"ok":true,"at":1}"#), Reply::ok(r#"{"ok":true,"at":2}"#)]);    let second = over(&handle.client(), "chat.send", &json!({ "thread": thread, "body": "two", "privateKey": private(MINE) }));    // The first still waits out its backoff: nothing is sent, nothing overtakes it.    assert_eq!(second.unwrap()["state"], "queued");    assert_eq!(exchange.calls(), 0);    handle.client().with_writer(|replica| replica.driver.run("UPDATE cotton_msg_messages SET meta = json_set(meta, '$.cotton.tried_at', 0)", &[]).map(|_| ()).map_err(|e| e.to_string())).unwrap();    let pass = answer(&handle, "chat.flush", json!({ "privateKey": private(MINE) }));    assert_eq!(pass["sent"].as_array().unwrap().len(), 2);    let said: Vec<String> = exchange.seen().iter().filter(|s| s.path == "/v1/chat/send").map(|s| {        let boxes = body(s)["boxes"].clone();        let opened = seal::open(&scalar(THEIRS), boxes["theirhandle00000000000"].as_str().unwrap()).unwrap();        serde_json::from_slice::<Payload>(&opened.payload).unwrap().body.unwrap()    }).collect();    assert_eq!(said, ["one", "two"]);}// RULE: a refusal the object meant fails the message, in its words; it does not retry forever.#[test]fn a_meant_refusal_fails_the_message() {    let (_dir, handle) = phone();    with_door(&handle, [keys_reply(), Reply::json(400, r#"{"code":"bad_boxes","message":"boxes: each a device handle and its c1: box"}"#)]);    let thread = thread_with(&handle);    let sent = answer(&handle, "chat.send", json!({ "thread": thread, "body": "hi", "privateKey": private(MINE) }));    assert_eq!(sent["state"], "failed");}// RULE: a failed message is tried again only when the person asks, counted afresh, and goes once the object takes it.#[test]fn a_failed_message_is_sent_again_on_asking() {    let (_dir, handle) = phone();    with_door(&handle, [keys_reply(), Reply::json(400, r#"{"code":"bad_boxes","message":"boxes"}"#), Reply::ok(r#"{"ok":true,"id":"x","at":1800000000000}"#)]);    let thread = thread_with(&handle);    let sent = answer(&handle, "chat.send", json!({ "thread": thread, "body": "hi", "privateKey": private(MINE) }));    assert_eq!(sent["state"], "failed");    let id = sent["message"].as_str().expect("an id").to_string();    let again = answer(&handle, "chat.retry", json!({ "message": id, "privateKey": private(MINE) }));    assert_eq!(again["state"], "sent");    assert_eq!(message(&handle, &id)["send_error"], Value::Null);    assert_eq!(refused(&handle, "chat.retry", json!({ "message": id, "privateKey": private(MINE) })), "not_failed");}/// The app's kit says its chats signal (`"signals": true`): read receipts and typing are sent and drawn, behind the person's switches.fn signalling(handle: &CottonHandle) {    let kit = cotton_core::kit::AppKit { signals: true, ..cotton_core::kit::AppKit::named("messages").expect("the messages kit") };    cotton_core::kit::AppKit::keep(Some(&kit), handle.client().layout().root()).expect("the kit kept");}/// Chat as it ships: its kit, which offers the two switches.fn messages(handle: &CottonHandle) {    let kit = cotton_core::kit::AppKit::named("messages").expect("the messages kit");    assert!(kit.signals, "Chat's kit offers read receipts and typing");    cotton_core::kit::AppKit::keep(Some(&kit), handle.client().layout().root()).expect("the kit kept");}/// A payload of theirs carrying their two switches.fn saying(mut payload: Payload, read: bool, typing: bool) -> Payload {    payload.signals = Some(cotton_core::chat::payload::Signals { read, typing });    payload}/// The switches a box this phone sealed for their phone carries.fn carried(seen: &Seen) -> Option<cotton_core::chat::payload::Signals> {    let boxes = body(seen)["boxes"].clone();    let opened = seal::open(&scalar(THEIRS), boxes["theirhandle00000000000"].as_str().expect("a box for their phone")).expect("their box opens");    serde_json::from_slice::<Payload>(&opened.payload).expect("a payload").signals}// RULE (DECISIONS.md, 20 Nov 2026): read receipts and typing are each a switch the person controls, off by default. Chat as it ships offers both, off; an app whose kit does not signal offers neither. While off, even with theirs on: reading a chat marks it read here and tells them nothing (this person's own other phones learn it at the flush), a key pressed tells them nothing, their typing is not answered to the shell, and their read receipt moves a message no further than delivered.#[test]fn the_switches_are_off_until_turned_on_and_tell_nothing() {    for kept in [true, false] {        let (_dir, handle) = phone();        hold_definitions(&handle);        if kept {            messages(&handle);        }        assert_eq!(answer(&handle, "chat.settings", json!({})), json!({ "readReceipts": false, "typing": false, "offered": kept, "voiceSpeed": 1.0, "linkPreviews": true }), "both switches off; offered only where the kit signals");        // Their message lands, their switches on, and is ticked delivered, as every message is.        let hello = saying(Payload::message("ffffffffffffffff", THEM, ME, 10, Some("hello".into()), None, vec![]), true, true);        with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [from_them(&hello, false, 100)] }).to_string()), keys_reply(), Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#)]);        let thread = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }))["landed"][0]["thread"].as_str().unwrap().to_string();        // Read here: marked read on this phone, nothing asked of the object; the flush tells this person's other phones.        let exchange = with_door(&handle, []);        let read = answer(&handle, "chat.receipt", json!({ "thread": thread, "privateKey": private(MINE) }));        assert_eq!((read["read"].as_u64(), read["told"].as_bool(), read["flush"].as_bool()), (Some(1), Some(false), Some(true)));        assert_eq!(answer(&handle, "chat.typing", json!({ "thread": thread, "on": true, "privateKey": private(MINE) }))["told"], false);        assert_eq!(exchange.calls(), 0, "no read receipt and no typing leaves the phone");        // Theirs: typing is not answered, and a read receipt says no more than delivered.        // The send's flush first tells this person's own other phones of the read, then the message goes.        let exchange = with_door(&handle, [keys_reply(), Reply::ok(r#"{"ok":true,"at":1}"#), keys_reply(), Reply::ok(r#"{"ok":true,"at":1}"#)]);        let sent = answer(&handle, "chat.send", json!({ "thread": thread, "body": "hi", "privateKey": private(MINE) }));        let own = exchange.seen().into_iter().find(|s| s.path == "/v1/chat/send" && body(s)["kind"] == "receipt").expect("the read told to this person's own phones");        assert_eq!(body(&own)["boxes"].as_object().map(|b| b.keys().cloned().collect::<Vec<_>>()), Some(vec!["tablethandle0000000000".to_string()]), "their own tablet alone, never them");        let going = exchange.seen().into_iter().find(|s| s.path == "/v1/chat/send" && body(s)["kind"] == "message").expect("the message");        let expected = kept.then_some(cotton_core::chat::payload::Signals { read: false, typing: false });        assert_eq!(carried(&going), expected, "the message says this person's switches where the app signals");        let id = message(&handle, sent["message"].as_str().unwrap())["external_id"].as_str().unwrap().to_string();        let typing = saying(Payload::typing("iiiiiiiiiiiiiiii", THEM, ME, 15, true), true, true);        let seen = saying(Payload::receipt("dddddddddddddddd", THEM, ME, 20, Receipt::Read, vec![id]), true, true);        with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [from_them(&typing, false, 150), from_them(&seen, false, 200)] }).to_string()), Reply::ok(r#"{"ok":true}"#)]);        let got = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }));        assert_eq!(got["typing"], json!([]), "their typing is not drawn");        assert_eq!(got["receipts"][0]["state"], "delivered");        assert_eq!(message(&handle, sent["message"].as_str().unwrap())["send_state"], "delivered", "their read receipt draws no Read");    }}// RULE: a stranger's first message lands as a request in its own Cotton thread, taken from the object, and tells them nothing: no delivered receipt.#[test]fn a_strangers_message_lands_as_a_request_and_sends_no_receipt() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let first = Payload::message("aaaaaaaaaaaaaaaa", THEM, ME, 10, Some("we met at the station".into()), None, vec![]);    let exchange = with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [from_them(&first, true, 100)] }).to_string()), keys_reply(), Reply::ok(r#"{"ok":true}"#)]);    let got = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }));    assert_eq!(got["landed"].as_array().unwrap().len(), 1);    let thread = got["requests"][0].as_str().expect("a request").to_string();    let landed = message(&handle, got["landed"][0]["message"].as_str().unwrap());    assert_eq!((landed["direction"].as_str(), landed["body"].as_str(), landed["channel"].as_str()), (Some("in"), Some("we met at the station"), Some("cotton")));    assert_eq!(landed["sent_at"], "1970-01-01T00:00:00.100Z", "the order is the sender's object's clock");    assert_eq!(row(&handle, "SELECT request FROM cotton_msg_threads WHERE id = ?", &thread).unwrap()["request"], "pending");    let paths: Vec<String> = exchange.seen().iter().map(|s| s.path.clone()).collect();    assert_eq!(paths, ["/v1/chat/inbox", "/v1/chat/keys?number=%2B15550100001", "/v1/chat/ack"]);    assert_eq!(body(&exchange.nth(2))["items"], json!([{ "id": "aaaaaaaaaaaaaaaa", "kind": "message" }]));    // Typing to a request tells nothing either.    assert_eq!(answer(&handle, "chat.typing", json!({ "thread": thread, "on": true, "privateKey": private(MINE) }))["told"], false);}// RULE: from an accepted person, a message lands and they get the delivered tick, sealed for their devices alone; landing it twice writes one row.#[test]fn an_accepted_persons_message_is_ticked_delivered_once() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let hello = Payload::message("bbbbbbbbbbbbbbbb", THEM, ME, 10, Some("hello".into()), None, vec![]);    let item = from_them(&hello, false, 100);    let exchange = with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [item.clone()] }).to_string()), keys_reply(), Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#)]);    let got = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }));    assert_eq!(got["requests"], json!([]));    // Who it is with rides on what landed, for the lock screen's alerts.    assert_eq!(got["landed"][0]["peer"], THEM);    assert!(got["landed"][0].get("name").is_some());    let receipt = exchange.seen().into_iter().find(|s| s.path == "/v1/chat/send").expect("the tick");    let envelope = body(&receipt);    assert_eq!(envelope["kind"], "receipt");    assert_eq!(envelope["boxes"].as_object().unwrap().len(), 1, "their devices only");    let opened: Payload = serde_json::from_slice(&seal::open(&scalar(THEIRS), envelope["boxes"]["theirhandle00000000000"].as_str().unwrap()).unwrap().payload).unwrap();    assert_eq!((opened.kind, opened.state, opened.ids.clone()), (Kind::Receipt, Some(Receipt::Delivered), vec!["bbbbbbbbbbbbbbbb".to_string()]));    // The same item again (a socket frame after the inbox): one row, no second tick.    let again = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE), "items": [item] }));    assert_eq!(again["landed"], json!([]));}// RULE: a box sealed by a device their keys never named, or one claiming another sender, is dropped and still taken from the object.#[test]fn a_box_from_an_unknown_device_is_dropped() {    let (_dir, handle) = phone();    let forged = Payload::message("cccccccccccccccc", THEM, ME, 10, Some("trust me".into()), None, vec![]);    let sealed = seal::seal(&scalar(9), &public_of(&scalar(MINE)), &forged.bytes()).unwrap();    let item = json!({ "id": forged.id, "kind": "message", "peer": THEM, "out": false, "request": false, "box": sealed, "at": 5 });    // Keys asked, then asked again once (a new device of theirs?), then the ack.    let exchange = with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [item] }).to_string()), keys_reply(), keys_reply(), Reply::ok(r#"{"ok":true}"#)]);    let got = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }));    assert_eq!((got["dropped"].as_u64(), got["landed"].as_array().unwrap().len()), (Some(1), 0));    assert_eq!(exchange.seen().last().unwrap().path, "/v1/chat/ack");}// RULE: their receipts move this person's message forward (delivered, then read) and never back.#[test]fn receipts_move_a_message_forward() {    let (_dir, handle) = phone();    signalling(&handle);    answer(&handle, "chat.settings", json!({ "readReceipts": true }));    let exchange = with_door(&handle, [keys_reply(), Reply::ok(r#"{"ok":true,"at":1}"#)]);    let thread = thread_with(&handle);    let sent = answer(&handle, "chat.send", json!({ "thread": thread, "body": "hi", "privateKey": private(MINE) }));    let id = body(&exchange.nth(1))["id"].as_str().unwrap().to_string();    let read = Payload::receipt("dddddddddddddddd", THEM, ME, 20, Receipt::Read, vec![id.clone()]);    let delivered = Payload::receipt("eeeeeeeeeeeeeeee", THEM, ME, 30, Receipt::Delivered, vec![id]);    with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [from_them(&read, false, 200), from_them(&delivered, false, 300)] }).to_string()), Reply::ok(r#"{"ok":true}"#)]);    let got = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }));    assert_eq!(got["receipts"].as_array().unwrap().len(), 2);    assert_eq!(message(&handle, sent["message"].as_str().unwrap())["send_state"], "read", "a later delivered does not undo read");}// RULE: reading a conversation marks its messages read here; their read receipt goes only while both switches are on, the person's own and theirs as their last word said it (an older app's word says nothing: off).#[test]fn a_read_receipt_goes_only_when_both_switches_are_on() {    let (_dir, handle) = phone();    signalling(&handle);    hold_definitions(&handle);    let land = |payload: &Payload, at: i64| {        with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [from_them(payload, false, at)] }).to_string()), keys_reply(), Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#)]);        answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }))    };    let receipt = |thread: &str| {        let exchange = with_door(&handle, [keys_reply(), Reply::ok(r#"{"ok":true}"#)]);        let told = answer(&handle, "chat.receipt", json!({ "thread": thread, "privateKey": private(MINE) }))["told"].as_bool();        (told, exchange.seen().iter().filter(|s| s.path == "/v1/chat/send").count())    };    // Theirs on, this person's off: nothing goes.    let thread = land(&saying(Payload::message("ffffffffffffffff", THEM, ME, 10, Some("hello".into()), None, vec![]), true, false), 100)["landed"][0]["thread"].as_str().unwrap().to_string();    assert_eq!(answer(&handle, "chat.settings", json!({ "readReceipts": false })), json!({ "readReceipts": false, "typing": false, "offered": true, "voiceSpeed": 1.0, "linkPreviews": true }));    assert_eq!(receipt(&thread), (Some(false), 0), "off means they learn nothing");    // Both on: told, to them and to this person's own other devices.    answer(&handle, "chat.settings", json!({ "readReceipts": true }));    land(&saying(Payload::message("gggggggggggggggg", THEM, ME, 11, Some("still there?".into()), None, vec![]), true, false), 101);    let exchange = with_door(&handle, [keys_reply(), Reply::ok(r#"{"ok":true}"#)]);    assert_eq!(answer(&handle, "chat.receipt", json!({ "thread": thread, "privateKey": private(MINE) }))["told"], true);    let told = exchange.seen().into_iter().find(|s| s.path == "/v1/chat/send").expect("their read receipt");    assert_eq!(body(&told)["boxes"].as_object().unwrap().len(), 2);    assert_eq!(carried(&told), Some(cotton_core::chat::payload::Signals { read: true, typing: false }), "the receipt says this person's switches");    // Theirs turned off (their next word says so): nothing goes, though this person's is on.    land(&saying(Payload::message("jjjjjjjjjjjjjjjj", THEM, ME, 12, Some("going quiet".into()), None, vec![]), false, false), 102);    assert_eq!(receipt(&thread), (Some(false), 0));    // A word from an older app carries no switches: off.    land(&saying(Payload::message("kkkkkkkkkkkkkkkk", THEM, ME, 13, Some("on".into()), None, vec![]), true, false), 103);    land(&Payload::message("llllllllllllllll", THEM, ME, 14, Some("old app".into()), None, vec![]), 104);    assert_eq!(receipt(&thread), (Some(false), 0));}// RULE: "typing…" goes only while both typing switches are on, and theirs is drawn only while this person's own is on.#[test]fn typing_goes_and_draws_only_when_both_switches_are_on() {    let (_dir, handle) = phone();    signalling(&handle);    hold_definitions(&handle);    let hello = saying(Payload::message("ffffffffffffffff", THEM, ME, 10, Some("hello".into()), None, vec![]), false, true);    with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [from_them(&hello, false, 100)] }).to_string()), keys_reply(), Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#)]);    let thread = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }))["landed"][0]["thread"].as_str().unwrap().to_string();    let theirs = |id: &str, at: i64| {        let typing = saying(Payload::typing(id, THEM, ME, at, true), false, true);        with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [from_them(&typing, false, at * 10)] }).to_string())]);        answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }))["typing"].clone()    };    // This person's off: nothing goes, theirs is not drawn.    let exchange = with_door(&handle, []);    assert_eq!(answer(&handle, "chat.typing", json!({ "thread": thread, "on": true, "privateKey": private(MINE) }))["told"], false);    assert_eq!(exchange.calls(), 0);    assert_eq!(theirs("iiiiiiiiiiiiiiii", 20), json!([]));    // Both on: it goes, saying this person's switches, and theirs is drawn.    answer(&handle, "chat.settings", json!({ "typing": true }));    let exchange = with_door(&handle, [keys_reply(), Reply::ok(r#"{"ok":true}"#)]);    assert_eq!(answer(&handle, "chat.typing", json!({ "thread": thread, "on": true, "privateKey": private(MINE) }))["told"], true);    let said = exchange.seen().into_iter().find(|s| s.path == "/v1/chat/send").expect("typing");    assert_eq!((body(&said)["kind"].as_str(), body(&said)["boxes"].as_object().map(|b| b.len())), (Some("typing"), Some(1)), "their devices alone");    assert_eq!(carried(&said), Some(cotton_core::chat::payload::Signals { read: false, typing: true }));    assert_eq!(theirs("mmmmmmmmmmmmmmmm", 30), json!([{ "thread": thread, "on": true }]));    // Theirs off (their next word): nothing goes.    let quiet = saying(Payload::message("nnnnnnnnnnnnnnnn", THEM, ME, 40, Some("bye".into()), None, vec![]), false, false);    with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [from_them(&quiet, false, 400)] }).to_string()), keys_reply(), Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#)]);    answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }));    let exchange = with_door(&handle, []);    assert_eq!(answer(&handle, "chat.typing", json!({ "thread": thread, "on": true, "privateKey": private(MINE) }))["told"], false);    assert_eq!(exchange.calls(), 0);}// RULE: blocking a request's sender tells the object, and what the request brought leaves the conversation list.#[test]fn blocking_a_request_puts_it_away() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let spam = Payload::message("hhhhhhhhhhhhhhhh", THEM, ME, 10, Some("buy my course".into()), None, vec![]);    with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [from_them(&spam, true, 100)] }).to_string()), keys_reply(), Reply::ok(r#"{"ok":true}"#)]);    let got = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }));    let thread = got["requests"][0].as_str().unwrap().to_string();    let exchange = with_door(&handle, [Reply::ok(r#"{"ok":true}"#)]);    answer(&handle, "chat.block", json!({ "thread": thread }));    let seen = exchange.only();    assert_eq!((seen.path.as_str(), body(&seen)), ("/v1/chat/block", json!({ "number": THEM })));    assert!(message(&handle, got["landed"][0]["message"].as_str().unwrap())["trashed_at"].is_string());    assert!(row(&handle, "SELECT trashed_at FROM cotton_msg_threads WHERE id = ?", &thread).unwrap()["trashed_at"].is_string());}// RULE: a copy of this person's own message from their other phone lands as theirs, sent, checked against their own keys.#[test]fn my_message_from_another_phone_lands_as_mine() {    let (_dir, handle) = phone();    let mine = Payload::message("iiiiiiiiiiiiiiii", ME, THEM, 10, Some("from my tablet".into()), None, vec![]);    let item = json!({ "id": mine.id, "kind": "message", "peer": THEM, "out": true, "request": false, "box": seal::seal(&scalar(TABLET), &public_of(&scalar(MINE)), &mine.bytes()).unwrap(), "at": 100 });    with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [item] }).to_string()), keys_reply(), Reply::ok(r#"{"ok":true}"#)]);    let got = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }));    let landed = message(&handle, got["landed"][0]["message"].as_str().unwrap());    assert_eq!((landed["direction"].as_str(), landed["send_state"].as_str()), (Some("out"), Some("sent")));}// RULE: a key minted here registers its public half alone, with the alert token; a send needs a body or a picture, and a private key.#[test]fn keys_register_and_sends_are_checked() {    let (_dir, handle) = phone();    let minted = answer(&handle, "chat.key", json!({}));    let exchange = with_door(&handle, [Reply::ok(r#"{"ok":true}"#)]);    let done = answer(&handle, "chat.register", json!({ "privateKey": minted["privateKey"], "platform": "ios", "token": "ab".repeat(32), "topic": "com.cottondb.messages.dev", "sandbox": true }));    assert_eq!(done["fingerprint"], minted["fingerprint"]);    let sent = body(&exchange.only());    assert_eq!(sent["publicKey"], minted["publicKey"]);    assert!(!sent.to_string().contains(minted["privateKey"].as_str().unwrap()), "the private half never leaves");    with_door(&handle, []);    let thread = thread_with(&handle);    assert_eq!(refused(&handle, "chat.send", json!({ "thread": thread, "body": "  ", "privateKey": private(MINE) })), "empty");    assert_eq!(refused(&handle, "chat.send", json!({ "thread": thread, "body": "hi" })), "invalid_request");    assert_eq!(refused(&handle, "chat.start", json!({ "number": "12345" })), "bad_number");}// RULE: chat.socket hands the shell the socket's address and a ticket the object minted for it, never the device's credential.#[test]fn the_socket_is_opened_with_a_ticket_the_object_minted() {    let (_dir, handle) = phone();    let exchange = with_door(&handle, [Reply::ok(r#"{"ticket":"cts_00000000-0000-4000-8000-000000000000_ticketticketticketticketticketticketticket0"}"#)]);    let socket = answer(&handle, "chat.socket", json!({}));    assert_eq!(socket["url"], "wss://cottondb.example.test/v1/chat/socket");    assert_eq!(socket["ticket"], "cts_00000000-0000-4000-8000-000000000000_ticketticketticketticketticketticketticket0");    // The device's credential went only to the object, on this door; the shell is handed the ticket alone.    let seen = exchange.seen();    assert_eq!((seen[0].method.as_str(), seen[0].path.as_str()), ("POST", "/v1/chat/socket"));    assert!(!socket.to_string().contains(CREDENTIAL));}// RULE (23 Nov 2026: his Mac's writes reached an open phone at its next minute): the socket's// `{ t: "rows" }` asks the sync loop for a pass now and asks the object nothing itself; with no loop running it says so.#[test]fn rows_moved_elsewhere_ask_the_loop_for_a_pass() {    let (_dir, handle) = phone();    let exchange = with_door(&handle, []);    assert_eq!(answer(&handle, "chat.rows", json!({})), json!({ "pull": "no schedule" }));    assert!(exchange.seen().is_empty(), "the pass asks, not chat.rows");}// RULE: chat.forget asks the object, on this door, to forget this phone's chat device; it is the shell's sign-out step, before the door goes.#[test]fn forgetting_the_device_is_asked_of_the_object_on_the_door() {    let (_dir, handle) = phone();    let exchange = with_door(&handle, [Reply::ok(r#"{"ok":true}"#)]);    assert_eq!(answer(&handle, "chat.forget", json!({})), json!({ "ok": true }));    let seen = exchange.seen();    assert_eq!((seen[0].method.as_str(), seen[0].path.as_str()), ("DELETE", "/v1/chat/device"));    handle.client().set_object_door(None);    assert_eq!(refused(&handle, "chat.forget", json!({})), "not_connected");}// RULE: a request's messages stay unread, and their sender untold, until the person accepts; read then, the receipt goes.#[test]fn a_request_is_read_only_once_accepted() {    let (_dir, handle) = phone();    signalling(&handle);    hold_definitions(&handle);    answer(&handle, "chat.settings", json!({ "readReceipts": true }));    let hello = saying(Payload::message("hhhhhhhhhhhhhhhh", THEM, ME, 10, Some("we met at the station".into()), None, vec![]), true, false);    with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [from_them(&hello, true, 100)] }).to_string()), keys_reply(), Reply::ok(r#"{"ok":true}"#)]);    let thread = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }))["requests"][0].as_str().unwrap().to_string();    let exchange = with_door(&handle, []);    let read = answer(&handle, "chat.receipt", json!({ "thread": thread, "privateKey": private(MINE) }));    assert_eq!((read["read"].as_u64(), read["told"].as_bool()), (Some(0), Some(false)));    assert_eq!(exchange.calls(), 0, "a request's sender learns nothing");    with_door(&handle, [Reply::ok(r#"{"ok":true}"#)]);    answer(&handle, "chat.accept", json!({ "thread": thread }));    let exchange = with_door(&handle, [keys_reply(), Reply::ok(r#"{"ok":true}"#)]);    let read = answer(&handle, "chat.receipt", json!({ "thread": thread, "privateKey": private(MINE) }));    assert_eq!((read["read"].as_u64(), read["told"].as_bool()), (Some(1), Some(true)));    assert!(exchange.seen().iter().any(|s| s.path == "/v1/chat/send"));}// RULE: a request's messages get their delivered tick once the person accepts (the tick waited for that, so a stranger learns nothing before), whatever the read receipts say (walk, 21 Nov 2026: a findable person's first words stood "Sent" on the writer's phone for ever after they were accepted).#[test]fn accepting_a_request_ticks_its_messages_delivered() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let first = Payload::message("aaaaaaaaaaaaaaaa", THEM, ME, 10, Some("we met at the station".into()), None, vec![]);    let second = Payload::message("cccccccccccccccc", THEM, ME, 20, Some("at the pottery class".into()), None, vec![]);    with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [from_them(&first, true, 100), from_them(&second, true, 110)] }).to_string()), keys_reply(), Reply::ok(r#"{"ok":true}"#)]);    let thread = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }))["requests"][0].as_str().expect("a request").to_string();    let exchange = with_door(&handle, [Reply::ok(r#"{"ok":true}"#), keys_reply(), Reply::ok(r#"{"ok":true}"#)]);    answer(&handle, "chat.accept", json!({ "thread": thread, "privateKey": private(MINE) }));    let seen = exchange.seen();    assert_eq!(seen[0].path, "/v1/chat/accept");    let tick = seen.iter().find(|s| s.path == "/v1/chat/send").expect("the delivered tick, once accepted");    let envelope = body(tick);    assert_eq!(envelope["kind"], "receipt");    let opened: Payload = serde_json::from_slice(&seal::open(&scalar(THEIRS), envelope["boxes"]["theirhandle00000000000"].as_str().unwrap()).unwrap().payload).unwrap();    let mut ids = opened.ids.clone();    ids.sort();    assert_eq!((opened.kind, opened.state, ids), (Kind::Receipt, Some(Receipt::Delivered), vec!["aaaaaaaaaaaaaaaa".to_string(), "cccccccccccccccc".to_string()]));}// RULE: someone who wrote to this person while they keep "can be found" off (or added them from Your people) asks; the ask lands as an ordinary request with one line in the chat set's words and none of what they wrote, nothing is asked of their phone or told them, and landing it again writes nothing new (21 Nov 2026).#[test]fn an_ask_lands_as_a_request_and_tells_them_nothing() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let inbox = || Reply::ok(&json!({ "me": ME, "items": [], "asks": [{ "number": THEM, "name": "Pat Walker", "at": "2026-11-21T01:00:00.000Z" }] }).to_string());    let exchange = with_door(&handle, [inbox()]);    let got = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }));    let thread = got["requests"][0].as_str().unwrap_or_else(|| panic!("a request: {got}")).to_string();    assert_eq!((got["landed"][0]["request"].as_bool(), got["landed"][0]["out"].as_bool()), (Some(true), Some(false)));    let line = message(&handle, got["landed"][0]["message"].as_str().unwrap());    assert_eq!((line["direction"].as_str(), line["body"].as_str()), (Some("in"), Some("Wants to chat with you on Cotton. Accept to see their messages.")));    assert_eq!(row(&handle, "SELECT request FROM cotton_msg_threads WHERE id = ?", &thread).unwrap()["request"], "pending");    // Only the inbox was asked: no keys, no ack, no receipt.    assert_eq!(exchange.seen().iter().map(|s| s.path.clone()).collect::<Vec<_>>(), ["/v1/chat/inbox"]);    // The list draws it as any request; the conversation offers Accept, Block and Delete.    let page = answer(&handle, "chat.thread", json!({ "thread": thread }));    assert_eq!(page["request"]["accept"], "Accept", "{page}");    // The notice is a request's: "New message", no words of theirs.    let notices = answer(&handle, "chat.notices", json!({}));    let notice = notices["notices"].as_array().unwrap().iter().find(|n| n["thread"] == json!(thread)).cloned().expect("a notice");    assert_eq!((notice["request"].as_bool(), notice["lines"].as_array().map(Vec::len)), (Some(true), Some(0)), "{notice}");    // Landed again (the next pass, or another of the person's phones): nothing new.    with_door(&handle, [inbox()]);    let again = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }));    assert_eq!((again["landed"].as_array().map(Vec::len), again["requests"].as_array().map(Vec::len)), (Some(0), Some(0)));    // Accepted: the object is told (it hands the ask back, and their waiting messages come); the line goes.    let exchange = with_door(&handle, [Reply::ok(r#"{"ok":true}"#)]);    answer(&handle, "chat.accept", json!({ "thread": thread }));    assert_eq!((exchange.only().path.as_str(), body(&exchange.only())), ("/v1/chat/accept", json!({ "number": THEM })));    assert_eq!(row(&handle, "SELECT request FROM cotton_msg_threads WHERE id = ?", &thread).unwrap()["request"], "accepted");    assert!(message(&handle, got["landed"][0]["message"].as_str().unwrap())["trashed_at"].is_string());}// RULE: an ask no longer listed (refused or blocked on another phone, or taken back) leaves a conversation that is only a request; an inbox from an older Worker, with no `asks`, changes nothing.#[test]fn an_ask_taken_back_goes_from_the_list() {    let (_dir, handle) = phone();    hold_definitions(&handle);    with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [], "asks": [{ "number": THEM, "name": null, "at": "2026-11-21T01:00:00.000Z" }] }).to_string())]);    let got = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }));    let thread = got["requests"][0].as_str().unwrap().to_string();    with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [] }).to_string())]);    answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }));    assert!(row(&handle, "SELECT trashed_at FROM cotton_msg_threads WHERE id = ?", &thread).unwrap()["trashed_at"].is_null());    with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [], "asks": [] }).to_string())]);    answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }));    assert!(message(&handle, got["landed"][0]["message"].as_str().unwrap())["trashed_at"].is_string());    assert!(row(&handle, "SELECT trashed_at FROM cotton_msg_threads WHERE id = ?", &thread).unwrap()["trashed_at"].is_string());    assert_eq!(answer(&handle, "chat.list", json!({}))["rows"].as_array().map(Vec::len), Some(0));}/// The change a send carried, opened from their box.fn their_change(seen: &Seen) -> Payload {    let envelope = body(seen);    let theirs = seal::open(&scalar(THEIRS), envelope["boxes"]["theirhandle00000000000"].as_str().unwrap()).expect("their box opens");    serde_json::from_slice(&theirs.payload).unwrap()}// RULE (FEEDBACK1 items 2 and 5, 22 Nov 2026): a voice message goes the moment it is released, never waiting for// its words; the transcript its phone heard follows as a change to the same message, sealed like it, never outside// the box, and both sides draw it under the player.#[test]fn a_voice_message_goes_at_once_and_its_transcript_follows_sealed() {    use cotton_core::chat::payload::What;    let (dir, handle) = phone();    let thread = thread_with(&handle);    let voice = dir.path().join("note.m4a");    std::fs::write(&voice, b"invented voice bytes").unwrap();    let exchange = with_door(&handle, [Reply::ok(r#"{"file":"0123456789abcdef0123456789abcdef"}"#), keys_reply(), Reply::ok(r#"{"ok":true,"id":"x","at":1763000000000}"#), Reply::ok(r#"{"ok":true,"id":"y","at":1763000001000}"#)]);    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": thread, "attachments": [{ "path": voice.to_string_lossy(), "mime": "audio/mp4", "kind": "voice", "durationMs": 2400 }] }));    let id = sent["message"].as_str().unwrap().to_string();    let pass = answer(&handle, "chat.flush", json!({ "privateKey": private(MINE) }));    assert_eq!(pass["sent"], json!([id]), "it goes at once, waiting for no words: {pass}");    let told = answer(&handle, "chat.act", json!({ "act": "transcript", "thread": thread, "message": id, "text": "  See you at ten, by the bookshop  " }));    assert_eq!(told["flush"], true);    assert_eq!(told["bubble"]["media"][0]["transcript"], "See you at ten, by the bookshop", "{told}");    answer(&handle, "chat.flush", json!({ "privateKey": private(MINE) }));    let sends: Vec<Seen> = exchange.seen().into_iter().filter(|s| s.path == "/v1/chat/send").collect();    assert_eq!(sends.len(), 2, "the message, then its words");    assert!(!body(&sends[0]).to_string().contains("bookshop") && !body(&sends[1]).to_string().contains("bookshop"), "the words never outside the box");    assert_eq!(body(&sends[1])["kind"], "change");    let change = their_change(&sends[1]);    let external = message(&handle, &id)["external_id"].as_str().unwrap().to_string();    assert_eq!((change.change.as_ref().map(|c| (c.what, c.message.clone())), change.body.as_deref()), (Some((What::Transcript, external)), Some("See you at ten, by the bookshop")));    let page = answer(&handle, "chat.thread", json!({ "thread": thread }));    let bubble = page["items"].as_array().unwrap().iter().find(|i| i["message"] == json!(id)).cloned().expect("the bubble");    assert_eq!(bubble["media"][0]["transcript"], "See you at ten, by the bookshop", "{bubble}");    // Told once: a second transcript changes nothing and tells no one.    let again = answer(&handle, "chat.act", json!({ "act": "transcript", "thread": thread, "message": id, "text": "something else" }));    assert_ne!(again["flush"], true);    assert!(!message(&handle, &id)["meta"].to_string().contains("something else"));}// RULE: words heard while the voice message still waits (offline) never go before it: the message goes first, then// its transcript in the same pass. No words heard, nothing follows.#[test]fn a_transcript_never_goes_before_its_voice_message() {    use cotton_core::chat::payload::What;    let (dir, handle) = phone();    let thread = thread_with(&handle);    let voice = dir.path().join("note.m4a");    std::fs::write(&voice, b"invented voice bytes").unwrap();    with_door(&handle, []);    let sent = answer(&handle, "chat.act", json!({ "act": "send", "thread": thread, "attachments": [{ "path": voice.to_string_lossy(), "mime": "audio/mp4", "kind": "voice", "durationMs": 900 }] }));    let id = sent["message"].as_str().unwrap().to_string();    assert_eq!(answer(&handle, "chat.flush", json!({ "privateKey": private(MINE) }))["sent"], json!([]), "offline");    answer(&handle, "chat.act", json!({ "act": "transcript", "thread": thread, "message": id, "text": "On the train" }));    let exchange = with_door(&handle, [Reply::ok(r#"{"file":"0123456789abcdef0123456789abcdef"}"#), keys_reply(), Reply::ok(r#"{"ok":true,"id":"x","at":1763000000000}"#), Reply::ok(r#"{"ok":true,"id":"y","at":1763000001000}"#)]);    let pass = answer(&handle, "chat.flush", json!({ "privateKey": private(MINE), "online": true }));    assert_eq!(pass["sent"], json!([id]), "{pass}");    let sends: Vec<Seen> = exchange.seen().into_iter().filter(|s| s.path == "/v1/chat/send").collect();    assert_eq!(sends.iter().map(|s| body(s)["kind"].as_str().unwrap_or_default().to_string()).collect::<Vec<_>>(), ["message", "change"]);    assert_eq!(their_change(&sends[1]).change.map(|c| c.what), Some(What::Transcript));    assert!(message(&handle, &id)["meta"].to_string().contains("pictures"), "the row keeps its sent file and its words: {:?}", message(&handle, &id)["meta"]);    assert!(message(&handle, &id)["meta"].to_string().contains("On the train"));    // No words: nothing to tell.    let quiet = answer(&handle, "chat.act", json!({ "act": "send", "thread": thread, "text": "and a line" }));    let none = answer(&handle, "chat.act", json!({ "act": "transcript", "thread": thread, "message": quiet["message"], "text": "   " }));    assert_ne!(none["flush"], true);}// RULE (FEEDBACK1 item 2, 22 Nov 2026): a message written offline waits out its tries' backoff; when the phone is// back (`chat.flush { online: true }`) it goes at once, not up to five minutes later.#[test]fn back_online_what_waited_goes_at_once() {    let (_dir, handle) = phone();    let thread = thread_with(&handle);    // Offline: the try gets no answer at all.    with_door(&handle, []);    let sent = answer(&handle, "chat.send", json!({ "thread": thread, "body": "written on the train", "privateKey": private(MINE) }));    let id = sent["message"].as_str().unwrap().to_string();    assert_eq!(sent["state"], "queued");    // Tried a few times while offline: its next try is a minute away.    let now = chrono::Utc::now().timestamp_millis();    handle.client().with_writer(|replica| replica.driver.run("UPDATE cotton_msg_messages SET send_attempts = 6, meta = json_set(meta, '$.cotton.tried_at', ?)", &[rusqlite::types::Value::Integer(now)]).map(|_| ()).map_err(|e| e.to_string())).unwrap();    // Back: an ordinary pass still waits out the backoff; the pass told the phone is online sends it.    let exchange = with_door(&handle, [keys_reply(), Reply::ok(r#"{"ok":true,"id":"x","at":1763000000000}"#)]);    assert_eq!(answer(&handle, "chat.flush", json!({ "privateKey": private(MINE) }))["sent"], json!([]));    assert_eq!(exchange.calls(), 0);    assert_eq!(answer(&handle, "chat.flush", json!({ "privateKey": private(MINE), "online": true }))["sent"], json!([id]));}// RULE (DISCOVERY OFF 3): a box no session opened is answered ("unreadable", on a fresh session) only to a sender this// person accepted: never to a number with no chat here, nor to one whose request is still unanswered, so a crafted box// never tells its maker whether this person accepted them.#[test]fn unreadable_is_answered_only_to_someone_accepted() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let client = handle.client();    assert!(!super::answers_to(&client, THEM).unwrap(), "a number with no chat here");    let inbox = Reply::ok(&json!({ "me": ME, "items": [], "asks": [{ "number": THEM, "name": "Pat Walker", "at": "2026-11-21T01:00:00.000Z" }] }).to_string());    with_door(&handle, [inbox]);    let got = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }));    let thread = got["requests"][0].as_str().unwrap().to_string();    assert!(!super::answers_to(&client, THEM).unwrap(), "an unanswered request");    with_door(&handle, [Reply::ok(r#"{"ok":true}"#)]);    answer(&handle, "chat.accept", json!({ "thread": thread }));    assert!(super::answers_to(&client, THEM).unwrap(), "accepted");    let (_dir2, mine) = phone();    hold_definitions(&mine);    thread_with(&mine);    assert!(super::answers_to(&mine.client(), THEM).unwrap(), "a chat this person started");}// RULE (PEOPLE BUILD 1): a Cotton chat's contact carries its phone handle, as WhatsApp's does, and its person is// derived by who(handle): someone who gains that number in his contacts later names the chat already there, in the// list and in every matcher, with nothing rewritten.#[test]fn a_cotton_chat_writes_its_handle_and_names_a_person_who_gains_the_number_later() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let thread = thread_with(&handle);    let digits = THEM.trim_start_matches('+');    let held = row(&handle, "SELECT contact_id, kind FROM cotton_msg_contact_handles WHERE value = ?", digits).expect("the chat's contact carries its number");    assert_eq!(held["kind"], "phone");    assert_eq!(crate::phone::cotton_chat::person_of(&handle.client(), THEM), (None, None));    handle        .client()        .with_writer(|replica| {            let ws: String = replica.driver.get("SELECT workspace_id FROM _meta", &[]).map_err(|e| e.to_string())?.and_then(|r| r.text("workspace_id").map(str::to_string)).unwrap();            let at = "2026-11-27T10:00:00.000Z";            replica.driver.run("INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES ('p-them', ?, 'Them Example', ?, ?)", &[ws.clone().into(), at.to_string().into(), at.to_string().into()]).map_err(|e| e.to_string())?;            replica                .driver                .run("INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, created_at, updated_at) VALUES ('h-them', ?, 'p-them', 'phone', '+1 555 010 0001', ?, 'manual', ?, ?)", &[ws.into(), digits.to_string().into(), at.to_string().into(), at.to_string().into()])                .map_err(|e| e.to_string())?;            Ok(())        })        .unwrap();    assert_eq!(crate::phone::cotton_chat::person_of(&handle.client(), THEM), (Some("p-them".into()), Some("Them Example".into())));    let list = answer(&handle, "chat.list", json!({}));    let named = list["rows"].as_array().unwrap().iter().find(|r| r["thread"] == json!(thread) || r["id"] == json!(thread)).cloned().unwrap_or_else(|| panic!("the chat is listed: {list}"));    assert_eq!(named["name"], "Them Example", "{named}");}