Cotton code
532 lines · 34.7 KB · RustRaw
//! Calls in Cotton Chat over a phone's own copy and a scripted object: the//! header's buttons, a call placed from a conversation, the line and row it//! leaves, the Calls tile, calling back and the call screen. Every name,//! number and room is invented.use std::sync::Arc;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange};use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use crate::handle::CottonHandle;use crate::phone::cotton_chat::over;use crate::phone::passwords::tests::phone;use crate::phone::personal_object::ObjectDoor;const CREDENTIAL: &str = "ctd_11111111-1111-4111-8111-111111111111_test-credential";const ROOM: &str = "0123456789abcdef0123456789abcdef";const ROOM_2: &str = "fedcba9876543210fedcba9876543210";const ASHA: &str = "+15550100001";const SMS: &str = "11111111-1111-4111-8111-0000000000c1";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 calls(handle: &CottonHandle, method: &str, request: Value) -> Value {    crate::phone::calls::over(&handle.client(), method, &request, false).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message))}fn refused(handle: &CottonHandle, method: &str, request: Value) -> (String, String) {    over(&handle.client(), method, &request).err().map(|e| (e.code, e.message)).unwrap_or_else(|| panic!("{method} answered"))}fn sql(handle: &CottonHandle, statement: &str, params: &[SqlValue]) {    handle.client().with_writer(|replica| replica.driver.run(statement, params).map(|_| ()).map_err(|e| e.to_string())).expect(statement);}fn t(s: &str) -> SqlValue {    SqlValue::Text(s.to_string())}fn workspace(handle: &CottonHandle) -> String {    crate::phone::cotton_chat::read(&handle.client(), "test.ws", |ctx| Ok(json!(ctx.workspace_id))).unwrap().as_str().unwrap().to_string()}fn ns(handle: &CottonHandle) -> String {    handle.client().current_database().expect("a database")}fn iso(minutes_ago: i64) -> String {    (chrono::Utc::now() - chrono::Duration::minutes(minutes_ago)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true)}/// Asha on Cotton (one message), and an imported SMS thread.fn chats(handle: &CottonHandle) -> String {    let ws = workspace(handle);    let thread = cotton_core::chat::ids::thread_id(&ns(handle), ASHA);    sql(handle, "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, created_at, updated_at) VALUES ('c-asha', ?, '15550100001', 'Asha Example', '2026-01-01', '2026-01-01')", &[t(&ws)]);    sql(        handle,        "INSERT INTO cotton_msg_threads (id, workspace_id, kind, external_key, contact_id, last_message_at, read_seq, created_at, updated_at) VALUES (?, ?, 'dm', ?, 'c-asha', ?, 1, ?, ?)",        &[t(&thread), t(&ws), t(&format!("cotton:{ASHA}")), t(&iso(30)), t(&iso(30)), t(&iso(30))],    );    sql(        handle,        "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, seq, created_at, external_id) VALUES ('m-1', ?, ?, 'in', 'cotton', 'live', 'Call me?', ?, 1, ?, 'x-1')",        &[t(&thread), t(&ws), t(&iso(30)), t(&iso(30))],    );    sql(        handle,        "INSERT INTO cotton_msg_threads (id, workspace_id, kind, external_key, title, last_message_at, read_seq, created_at, updated_at) VALUES (?, ?, 'dm', '+15550100009', 'Old number', ?, 0, ?, ?)",        &[t(SMS), t(&ws), t(&iso(900)), t(&iso(900)), t(&iso(900))],    );    sql(        handle,        "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, seq, created_at, external_id) VALUES ('m-s', ?, ?, 'in', 'sms', 'imported', 'Your parcel', ?, 0, ?, 'x-s')",        &[t(SMS), t(&ws), t(&iso(900)), t(&iso(900))],    );    thread}fn started(room: &str) -> Reply {    Reply::ok(&json!({"room": room, "credential": format!("ccr_{room}_secret"), "iceServers": [], "ttl": 3600, "ringFor": 45}).to_string())}fn body(seen: &cotton_client::transport::scripted::Seen) -> Value {    serde_json::from_slice(&seen.body).expect("a JSON body")}fn events(thread: &Value) -> Vec<Value> {    thread["items"].as_array().unwrap().iter().filter(|i| i["item"] == "event").cloned().collect()}// RULE: a Cotton conversation's header offers Call and Video call; an imported SMS thread offers none, nor does a// stranger's request until it is answered.#[test]fn only_a_cotton_conversation_offers_calls() {    let (_dir, handle) = phone();    let asha = chats(&handle);    let thread = answer(&handle, "chat.thread", json!({"thread": asha}));    assert_eq!(thread["header"]["calls"], json!([{"video": false, "label": "Call"}, {"video": true, "label": "Video call"}]));    assert!(answer(&handle, "chat.thread", json!({"thread": SMS}))["header"].get("calls").is_none(), "an imported thread offers no call");    sql(&handle, "ALTER TABLE cotton_msg_threads ADD COLUMN request TEXT", &[]);    sql(&handle, "UPDATE cotton_msg_threads SET request = 'pending' WHERE id = ?", &[t(&asha)]);    assert!(answer(&handle, "chat.thread", json!({"thread": asha}))["header"].get("calls").is_none(), "a request is answered first");    assert_eq!(refused(&handle, "chat.call", json!({"thread": asha})).0, "request");    assert_eq!(refused(&handle, "chat.call", json!({"thread": SMS})), ("not_cotton".into(), "Calls are for Cotton chats.".into()));}// RULE: Call in a conversation asks the object to ring its number, the call knows its conversation, and the call// screen names the person as Chat does and says the ring in Chat's words; a second call is refused in Chat's words.#[test]fn a_call_from_a_conversation_rings_its_number() {    let (_dir, handle) = phone();    let asha = chats(&handle);    let exchange = with_door(&handle, [started(ROOM)]);    let placed = answer(&handle, "chat.call", json!({"thread": asha, "video": true}));    let sent = exchange.only();    assert_eq!((sent.method.as_str(), sent.path.as_str()), ("POST", "/v1/calls"));    assert_eq!(body(&sent), json!({"to": ASHA, "video": true}));    assert_eq!(placed["call"]["phase"], "ringing_out");    assert_eq!(placed["call"]["thread"], json!(asha));    assert!(placed["effects"].as_array().unwrap().iter().any(|e| e["do"] == "open_socket"), "the shell is handed calls.start's effects");    let screen = answer(&handle, "chat.callScreen", json!({"speaker": true}));    assert_eq!((screen["shown"].clone(), screen["name"].clone(), screen["status"].clone()), (json!(true), json!("Asha Example"), json!("Ringing…")));    assert_eq!(screen["picture"]["initials"], "AE");    assert_eq!(screen["thread"], json!(asha));    assert_eq!(screen["bar"], "Asha Example · tap to return");    let ids: Vec<&str> = screen["controls"].as_array().unwrap().iter().map(|c| c["id"].as_str().unwrap()).collect();    assert_eq!(ids, ["mute", "speaker", "video", "flip", "end"]);    assert_eq!(refused(&handle, "chat.call", json!({"thread": asha})), ("in_a_call".into(), "You're already in a call.".into()));}// RULE: an answered call leaves one centred line in its conversation (its kind and length, in the reader's words,// tappable to call back), moves the conversation up and is never counted unread; its row is in the Calls tile, newest// first; tapping it rings the same number the same kind of call.#[test]fn an_ended_call_is_said_in_its_conversation_and_the_calls_tile() {    let (_dir, handle) = phone();    let asha = chats(&handle);    with_door(&handle, [started(ROOM), Reply::ok(r#"{"ok":true}"#)]);    answer(&handle, "chat.call", json!({"thread": asha}));    calls(&handle, "calls.signal", json!({"in": {"t": "state", "state": "connecting"}}));    calls(&handle, "calls.media", json!({"state": "connected"}));    let ended = calls(&handle, "calls.end", json!({}));    assert_eq!(ended["call"]["phase"], "ended");    assert!(ended.get("history").is_some(), "the call row is written: {ended}");    let thread = answer(&handle, "chat.thread", json!({"thread": asha}));    let lines = events(&thread);    assert_eq!(lines.len(), 1, "one line: {thread}");    assert!(lines[0]["text"].as_str().unwrap().starts_with("Voice call · 0:0"), "{}", lines[0]);    assert_eq!(lines[0]["call"]["call"], ended["history"]);    assert_eq!((lines[0]["call"]["video"].clone(), lines[0]["call"]["missed"].clone(), lines[0]["call"]["back"].clone()), (json!(false), json!(false), json!("Call back")));    assert_eq!(thread["unread"], 0, "a call's line is never unread");    let list = answer(&handle, "chat.list", json!({}));    let row = list["rows"].as_array().unwrap().iter().find(|r| r["thread"] == json!(asha)).unwrap().clone();    assert!(row["lastLine"]["text"].as_str().unwrap().starts_with("Voice call"), "{row}");    assert_eq!(list["rows"][0]["thread"], json!(asha), "the call moved the conversation up");    let tile = answer(&handle, "chat.calls", json!({}));    assert_eq!(tile["words"]["title"], "Calls");    let rows = tile["rows"].as_array().unwrap();    assert_eq!(rows.len(), 1);    assert_eq!((rows[0]["name"].clone(), rows[0]["thread"].clone(), rows[0]["incoming"].clone(), rows[0]["missed"].clone()), (json!("Asha Example"), json!(asha), json!(false), json!(false)));    assert_eq!(rows[0]["call"], ended["history"]);    // A second phone of the same person writing the same call does not write a second line.    let again = crate::phone::chat_calls::leave_line(&handle.client(), &handle.client().call_slot().lock().unwrap().clone()).unwrap();    assert!(again.is_none());    let exchange = with_door(&handle, [started(ROOM_2)]);    let back = answer(&handle, "chat.call", json!({"call": rows[0]["call"]}));    assert_eq!(body(&exchange.only()), json!({"to": ASHA, "video": false}));    assert_eq!(back["call"]["thread"], json!(asha));}// RULE: a ring here that nobody answers leaves "Missed voice call" in the caller's conversation, marked missed in// the Calls tile; a ring from a number with no conversation here is in the Calls tile alone, named by its number.#[test]fn a_missed_ring_is_marked() {    let (_dir, handle) = phone();    let asha = chats(&handle);    with_door(&handle, [Reply::ok(&json!({"room": ROOM, "from": ASHA, "credential": "ccr_x", "iceServers": [], "ttl": 60}).to_string())]);    let ring = calls(&handle, "calls.incoming", json!({"room": ROOM}));    assert_eq!(ring["call"]["phase"], "ringing_in");    let screen = answer(&handle, "chat.callScreen", json!({}));    assert_eq!((screen["ring"]["answer"].clone(), screen["ring"]["decline"].clone(), screen["name"].clone()), (json!("Answer"), json!("Decline"), json!("Asha Example")));    calls(&handle, "calls.stop", json!({"room": ROOM, "reason": "cancelled"}));    let lines = events(&answer(&handle, "chat.thread", json!({"thread": asha})));    assert_eq!(lines.len(), 1);    assert_eq!((lines[0]["text"].clone(), lines[0]["call"]["missed"].clone(), lines[0]["call"]["incoming"].clone()), (json!("Missed voice call"), json!(true), json!(true)));    with_door(&handle, [Reply::ok(&json!({"room": ROOM_2, "from": "+15550100077", "credential": "ccr_y", "iceServers": [], "ttl": 60, "video": true}).to_string())]);    calls(&handle, "calls.incoming", json!({"room": ROOM_2, "video": true}));    calls(&handle, "calls.stop", json!({"room": ROOM_2, "reason": "cancelled"}));    let tile = answer(&handle, "chat.calls", json!({}));    let rows = tile["rows"].as_array().unwrap();    assert_eq!(rows.len(), 2);    let stranger = rows.iter().find(|r| r.get("thread").is_none()).unwrap_or_else(|| panic!("{tile}"));    assert!(stranger["name"].as_str().unwrap().contains("555"), "named by the number: {stranger}");    assert_eq!((stranger["missed"].clone(), stranger["video"].clone(), stranger["line"].clone()), (json!(true), json!(true), json!("Missed video call")));    let mine = rows.iter().find(|r| r["thread"] == json!(asha)).unwrap();    assert_eq!(mine["line"], "Missed voice call");}// RULE: a missed ring is noticed (its name and Call back) until the Calls list is opened, or the chat with them is read, after it.#[test]fn a_missed_ring_is_noticed_until_seen() {    let (_dir, handle) = phone();    let asha = chats(&handle);    with_door(&handle, [Reply::ok(&json!({"room": ROOM, "from": ASHA, "credential": "ccr_x", "iceServers": [], "ttl": 60}).to_string())]);    calls(&handle, "calls.incoming", json!({"room": ROOM}));    calls(&handle, "calls.stop", json!({"room": ROOM, "reason": "cancelled"}));    let got = answer(&handle, "chat.notices", json!({}));    let missed = got["missed"].as_array().unwrap();    assert_eq!(missed.len(), 1, "{got}");    assert_eq!((missed[0]["title"].as_str(), missed[0]["text"].as_str(), missed[0]["back"].as_str(), missed[0]["thread"].as_str()), (Some("Missed voice call"), Some("Asha Example"), Some("Call back"), Some(asha.as_str())));    assert!(!got["notices"].to_string().contains("Missed"), "the call's own line in the chat is no message of theirs");    answer(&handle, "chat.act", json!({"act": "read", "thread": asha}));    assert_eq!(answer(&handle, "chat.notices", json!({}))["missed"], json!([]));    with_door(&handle, [Reply::ok(&json!({"room": ROOM_2, "from": "+15550100077", "credential": "ccr_y", "iceServers": [], "ttl": 60, "video": true}).to_string())]);    calls(&handle, "calls.incoming", json!({"room": ROOM_2, "video": true}));    calls(&handle, "calls.stop", json!({"room": ROOM_2, "reason": "cancelled"}));    assert_eq!(answer(&handle, "chat.notices", json!({}))["missed"][0]["title"], "Missed video call");    answer(&handle, "chat.calls", json!({}));    assert_eq!(answer(&handle, "chat.notices", json!({}))["missed"], json!([]));}// RULE: a ring's sealed box (made by the person's own object for this phone's chat key) names the caller at once, without the network: the system call UI's title, `caller`, and the call screen say who it is before any join; with `later` the join waits for `calls.join`, which then joins. A box for another room, or one that does not open, is ignored.#[test]fn a_rings_sealed_box_names_the_caller_before_the_join() {    let (_dir, handle) = phone();    chats(&handle);    let mine = [7u8; 32];    let hint = |room: &str| {        let said = json!({ "v": 1, "ring": room, "from": ASHA, "video": false }).to_string();        cotton_core::chat::seal::seal(&[9u8; 32], &cotton_core::vault::wrap::public_of(&mine), said.as_bytes()).unwrap()    };    let key = cotton_core::chat::seal::key_text(&mine);    let exchange = with_door(&handle, [Reply::ok(&json!({"room": ROOM, "from": ASHA, "credential": "ccr_x", "iceServers": [], "ttl": 60}).to_string())]);    let ring = calls(&handle, "calls.incoming", json!({"room": ROOM, "ring": hint(ROOM), "privateKey": key, "later": true}));    assert_eq!(exchange.calls(), 0, "nothing asked before the report");    assert_eq!(ring["join"], ROOM);    assert_eq!((ring["caller"]["name"].as_str(), ring["caller"]["number"].as_str()), (Some("Asha Example"), Some(ASHA)));    let report = ring["effects"].as_array().unwrap().iter().find(|e| e["do"] == "system_call_incoming").expect("the report");    assert_eq!(report["title"], "Asha Example");    assert_eq!(answer(&handle, "chat.callScreen", json!({}))["name"], "Asha Example");    let joined = calls(&handle, "calls.join", json!({"room": ROOM}));    assert_eq!(exchange.calls(), 1, "joined now");    assert!(joined["effects"].as_array().unwrap().iter().any(|e| e["do"] == "open_socket"), "{joined}");    calls(&handle, "calls.stop", json!({"room": ROOM, "reason": "cancelled"}));    // Another room's box, or a key it was not sealed for: the ring says "Cotton" as before, and joins at once.    with_door(&handle, [Reply::ok(&json!({"room": ROOM_2, "from": ASHA, "credential": "ccr_y", "iceServers": [], "ttl": 60}).to_string())]);    let ring = calls(&handle, "calls.incoming", json!({"room": ROOM_2, "ring": hint(ROOM), "privateKey": key}));    assert!(ring.get("caller").is_none() && ring.get("join").is_none());}// RULE (CALLS FIX 1): a ring that ended unanswered leaves a missed call on a phone that never heard it: the stop names// who called, sealed as the ring was, and the row is written as if it had rung. A stop answered or declined on// another phone writes none (that phone writes the call). A ring arriving again after it ended here rings no more.#[test]fn a_missed_stop_for_a_ring_never_heard_leaves_the_missed_call() {    let (_dir, handle) = phone();    chats(&handle);    let mine = [7u8; 32];    let hint = |room: &str| {        let said = json!({ "v": 1, "ring": room, "from": ASHA, "video": false }).to_string();        cotton_core::chat::seal::seal(&[9u8; 32], &cotton_core::vault::wrap::public_of(&mine), said.as_bytes()).unwrap()    };    let key = cotton_core::chat::seal::key_text(&mine);    let exchange = with_door(&handle, []);    calls(&handle, "calls.stop", json!({"room": ROOM_2, "reason": "answered_elsewhere", "ring": hint(ROOM_2), "privateKey": key}));    assert_eq!(answer(&handle, "chat.notices", json!({}))["missed"], json!([]), "answered elsewhere: no row here");    // Over the socket (or as a stored missed call): the row is written with the ring's own times, and nothing rings.    let at = chrono::Utc::now().timestamp_millis() - 120_000;    let ended = at + 45_000;    let stopped = calls(&handle, "calls.stop", json!({"room": ROOM, "reason": "missed", "ring": hint(ROOM), "privateKey": key, "at": at, "ended": ended}));    assert_eq!(exchange.calls(), 0, "nothing asked of the network");    assert_eq!(effects_of(&stopped["effects"]), Vec::<String>::new(), "a stop not pushed rings nothing: {stopped}");    let missed = answer(&handle, "chat.notices", json!({}))["missed"].clone();    assert_eq!(missed.as_array().map(Vec::len), Some(1), "{missed}");    assert_eq!(missed[0]["title"], "Missed voice call");    assert_eq!(times(&handle, ROOM), (cotton_core::calling::history::iso(at), 0), "rang 45 s, never live: started at the ring");    // The same stop again, later (a push after the frame, a second telling): the row is not written again.    let pushed = calls(&handle, "calls.stop", json!({"room": ROOM, "reason": "missed", "ring": hint(ROOM), "privateKey": key, "at": at + 9_000, "ended": ended + 9_000, "pushed": true}));    assert_eq!(answer(&handle, "chat.notices", json!({}))["missed"].as_array().map(Vec::len), Some(1));    assert_eq!(times(&handle, ROOM).0, cotton_core::calling::history::iso(at), "a second delivery never changes the row");    // A VoIP push must be reported to CallKit whatever it carries: a pushed stop for a call not here is reported and ended at once.    assert_eq!(effects_of(&pushed["effects"]), ["system_call_incoming", "system_call_ended"]);}/// The row a room left: when it started and how long it rang, as written.fn times(handle: &CottonHandle, room: &str) -> (String, i64) {    let room = room.to_string();    let row = crate::phone::cotton_chat::read(&handle.client(), "test.times", move |ctx| {        Ok(crate::phone::cotton_chat::one(ctx, "SELECT started_at, duration_s FROM cotton_call_log WHERE external_id = ?", &[rusqlite::types::Value::Text(room.clone())])?.map(Value::Object).unwrap_or(Value::Null))    })    .unwrap();    (row["started_at"].as_str().unwrap_or_default().to_string(), row["duration_s"].as_i64().unwrap_or(-1))}fn effects_of(effects: &Value) -> Vec<String> {    effects.as_array().into_iter().flatten().filter_map(|e| e["do"].as_str().map(str::to_string)).collect()}// RULE (CALLS FIX 1): a ring that comes again (its frame and its push, or a socket that opened late) after the ring// ended here does not ring a second time.#[test]fn a_ring_that_comes_again_after_it_ended_rings_no_more() {    let (_dir, handle) = phone();    chats(&handle);    let exchange = with_door(&handle, []);    calls(&handle, "calls.incoming", json!({"room": ROOM, "later": true}));    calls(&handle, "calls.stop", json!({"room": ROOM, "reason": "missed"}));    let again = calls(&handle, "calls.incoming", json!({"room": ROOM, "later": true}));    assert_eq!(again["call"]["phase"], "ended", "{again}");    assert_eq!(effects_of(&again["effects"]), Vec::<String>::new(), "a frame again rings nothing: {again}");    assert_eq!(exchange.calls(), 0);}// RULE (CALLS FIX 3): a phone rung late takes the ring's own start from the object (`at` on the ring, or on its stop),// so its Missed row says when the call came, not when the phone heard it.#[test]fn a_phone_rung_late_writes_the_rings_own_start() {    let (_dir, handle) = phone();    chats(&handle);    let _exchange = with_door(&handle, []);    let at = chrono::Utc::now().timestamp_millis() - 38_000;    let rung = calls(&handle, "calls.incoming", json!({"room": ROOM, "later": true, "at": at}));    assert_eq!(rung["call"]["startedAt"].as_i64().or_else(|| rung["call"]["started_at"].as_i64()), Some(at), "{rung}");    calls(&handle, "calls.stop", json!({"room": ROOM, "reason": "missed"}));    assert_eq!(times(&handle, ROOM).0, cotton_core::calling::history::iso(at));    // Heard late with no start on the ring: the stop's `at` sets it.    let at2 = chrono::Utc::now().timestamp_millis() - 20_000;    calls(&handle, "calls.incoming", json!({"room": ROOM_2, "later": true}));    calls(&handle, "calls.stop", json!({"room": ROOM_2, "reason": "missed", "at": at2, "ended": at2 + 45_000}));    assert_eq!(times(&handle, ROOM_2).0, cotton_core::calling::history::iso(at2));}// RULE (CALLS FIX 2, M1): a late duplicate VoIP push for a call this phone knows has ended is reported and ended at// once (CallKit was told of it before the core was asked), never left ringing with nothing behind it; and the phone// remembers ended calls for the push's lifetime, past the next call.#[test]fn a_late_push_for_an_ended_call_is_reported_and_ended_at_once() {    let (_dir, handle) = phone();    chats(&handle);    let exchange = with_door(&handle, []);    calls(&handle, "calls.incoming", json!({"room": ROOM, "later": true, "pushed": true}));    calls(&handle, "calls.stop", json!({"room": ROOM, "reason": "missed"}));    let late = calls(&handle, "calls.incoming", json!({"room": ROOM, "later": true, "pushed": true}));    assert_eq!(effects_of(&late["effects"]), ["system_call_incoming", "system_call_ended"], "{late}");    assert!(late.get("join").is_none(), "no join for a call that ended: {late}");    // Another call came and went: the first room is still known as ended.    calls(&handle, "calls.incoming", json!({"room": ROOM_2, "later": true, "pushed": true}));    calls(&handle, "calls.stop", json!({"room": ROOM_2, "reason": "cancelled"}));    let later = calls(&handle, "calls.incoming", json!({"room": ROOM, "later": true, "pushed": true}));    assert_eq!(effects_of(&later["effects"]), ["system_call_incoming", "system_call_ended"], "{later}");    assert!(later.get("join").is_none());    let framed = calls(&handle, "calls.incoming", json!({"room": ROOM, "later": true}));    assert_eq!(effects_of(&framed["effects"]), Vec::<String>::new(), "over the socket: nothing");    assert_eq!(exchange.calls(), 0);}// ── a group's call (23 Nov 2026) ─────────────────────const GROUP: &str = "aaaabbbbccccdddd0000111122223333";const RAVI: &str = "+15550100002";/// A Cotton group, "Invented Family", with Asha and Ravi.fn family(handle: &CottonHandle) -> String {    let ws = workspace(handle);    let thread = crate::phone::chat_group::thread_id(&ns(handle), GROUP);    sql(handle, "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, created_at, updated_at) VALUES ('c-asha', ?, '15550100001', 'Asha Example', '2026-01-01', '2026-01-01')", &[t(&ws)]);    sql(handle, "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, created_at, updated_at) VALUES ('c-ravi', ?, '15550100002', 'Ravi Example', '2026-01-01', '2026-01-01')", &[t(&ws)]);    sql(        handle,        "INSERT INTO cotton_msg_threads (id, workspace_id, kind, external_key, title, last_message_at, read_seq, created_at, updated_at) VALUES (?, ?, 'group', ?, 'Invented Family', ?, 0, ?, ?)",        &[t(&thread), t(&ws), t(&format!("cotton:group:{GROUP}")), t(&iso(30)), t(&iso(30)), t(&iso(30))],    );    for (id, contact) in [("p-asha", "c-asha"), ("p-ravi", "c-ravi")] {        sql(handle, "INSERT INTO cotton_msg_thread_participants (id, thread_id, workspace_id, contact_id, is_self, created_at) VALUES (?, ?, ?, ?, 0, '2026-01-01')", &[t(id), t(&thread), t(&ws), t(contact)]);    }    thread}fn waiting(handle: &CottonHandle, thread: &str) -> Vec<Value> {    let th = thread.to_string();    let row = crate::phone::cotton_chat::read(&handle.client(), "test.waiting", move |ctx| Ok(crate::phone::cotton_chat::one(ctx, "SELECT changes_waiting FROM cotton_msg_threads WHERE id = ?", &[t(&th)])?.map(serde_json::Value::Object).unwrap_or(Value::Null))).unwrap();    row["changes_waiting"].as_str().and_then(|s| serde_json::from_str(s).ok()).unwrap_or_default()}// RULE: a group's call rings everyone still in it as the group's (the SFU's from the start), and is told to every// member sealed as a group word: its line here says you started it, with Join while it goes on.#[test]fn a_groups_call_rings_everyone_and_is_told_to_the_group() {    let (_dir, handle) = phone();    let group = family(&handle);    let header = answer(&handle, "chat.thread", json!({"thread": group}));    assert_eq!(header["header"]["calls"][0]["label"], "Group call");    let exchange = with_door(&handle, [Reply::ok(&json!({"room": ROOM, "credential": format!("ccr_{ROOM}_secret"), "mode": "sfu", "group": GROUP, "iceServers": [], "ttl": 3600, "ringFor": 45}).to_string())]);    let placed = answer(&handle, "chat.call", json!({"thread": group, "video": false}));    let sent = body(&exchange.only());    assert_eq!(sent["group"], GROUP);    let mut to: Vec<String> = sent["to"].as_array().unwrap().iter().map(|n| n.as_str().unwrap().to_string()).collect();    to.sort();    assert_eq!(to, [ASHA, RAVI]);    assert_eq!(placed["call"]["mode"], "sfu");    assert_eq!(placed["flush"], json!(true));    assert!(placed["effects"].as_array().unwrap().iter().any(|e| e["do"] == "switch_to_sfu"));    let told = waiting(&handle, &group);    assert_eq!((told[0]["what"].clone(), told[0]["message"].clone(), told[0]["body"].clone()), (json!("call"), json!(ROOM), json!("voice")));    let thread = answer(&handle, "chat.thread", json!({"thread": group}));    let line = events(&thread).into_iter().find(|e| e.get("groupCall").is_some()).expect("the call's line");    assert_eq!(line["text"], "You started a voice call");    assert_eq!((line["groupCall"]["room"].clone(), line["groupCall"]["join"].clone()), (json!(ROOM), json!("Join")));    // The call screen draws the group's people as tiles, and says it is protected in transit.    let standing = || Reply::ok(&json!({ "me": "+15550100000" }).to_string());    let contact: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/message_contact.json")).unwrap();    handle.client().with_writer(|replica| cotton_client::transport::object::hold_defined_columns(&replica.driver, [&contact]).map(|_| ())).unwrap();    let _ = with_door(&handle, [standing(), standing()]);    let _ = answer(&handle, "chat.profile.set", json!({ "name": "Invented Me" }));    let screen = answer(&handle, "chat.callScreen", json!({}));    let own = screen["tiles"].as_array().unwrap().iter().find(|t| t["you"] == json!(true)).unwrap().clone();    assert_eq!((own["name"].clone(), own["picture"]["initials"].clone()), (json!("You"), json!("IM")), "the own tile is pictured by the own profile: {own}");    assert_eq!(screen["group"], json!(true));    assert_eq!(screen["privacy"], "Protected in transit");    // Headed by the group's name on the caller's phone too, not by its people's numbers (walk on dev, 23 Nov 2026).    assert_eq!(screen["name"], "Invented Family");    let names: Vec<&str> = screen["tiles"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap()).collect();    assert!(names.contains(&"Asha Example") && names.contains(&"Ravi Example") && names.last() == Some(&"You"), "{names:?}");}// RULE: a member's word that the group's call started lands its line; while the room says it goes on the group offers// Join, which comes in without a ring; once the room says it is over the line stops offering it.#[test]fn a_member_comes_in_late_while_the_call_goes_on() {    let (_dir, handle) = phone();    let group = family(&handle);    let ns_ = ns(&handle);    let change = cotton_core::chat::payload::Payload::change("c-1", ASHA, "+15550100000", 1_000, cotton_core::chat::payload::Change { what: cotton_core::chat::payload::What::Call, message: ROOM.into(), emoji: None }, Some("video".into()));    let (g, p) = (group.clone(), change.clone());    let landed = crate::phone::cotton_chat::write(&handle.client(), "test.land", move |ctx| crate::phone::chat_calls::land_group_call(ctx, &ns_, &g, false, &p, ASHA)).unwrap();    assert_eq!(landed["groupCall"], ROOM);    let line = events(&answer(&handle, "chat.thread", json!({"thread": group}))).into_iter().find(|e| e.get("groupCall").is_some()).unwrap();    assert_eq!(line["text"], "Asha Example started a video call");    let status = Reply::ok(&json!({"live": true, "video": true, "group": GROUP, "joined": [ASHA, RAVI], "you": "invited"}).to_string());    let exchange = with_door(&handle, [status]);    let going = answer(&handle, "chat.groupCall", json!({"thread": group}));    assert_eq!(exchange.only().path, format!("/v1/calls/{ROOM}/status"));    assert_eq!((going["live"].clone(), going["join"].clone(), going["banner"].clone()), (json!(true), json!("Join"), json!("Video call going on")));    assert_eq!(going["in"], "Asha Example, Ravi Example in the call");    let entered = Reply::ok(&json!({"room": ROOM, "member": "m2", "me": "m2", "from": ASHA, "video": true, "group": GROUP, "mode": "sfu", "credential": format!("ccr_{ROOM}_late"), "iceServers": [], "ttl": 3600}).to_string());    let exchange = with_door(&handle, [entered]);    let joined = answer(&handle, "chat.call", json!({"thread": group, "join": true}));    assert_eq!(exchange.only().path, format!("/v1/calls/{ROOM}/enter"));    assert_eq!(joined["call"]["phase"], "connecting");    assert_eq!(joined["call"]["thread"], json!(group));    assert_eq!(joined["call"]["name"], "Invented Family");    let did: Vec<&str> = joined["effects"].as_array().unwrap().iter().filter_map(|e| e["do"].as_str()).collect();    assert!(did.contains(&"switch_to_sfu") && did.contains(&"open_socket") && !did.contains(&"system_call_incoming"), "{did:?}");    // In the call here: the group says so.    let exchange = with_door(&handle, [Reply::ok(&json!({"live": true, "video": true, "joined": [ASHA, RAVI, "+15550100000"]}).to_string())]);    let here = answer(&handle, "chat.groupCall", json!({"thread": group}));    let _ = exchange.only();    assert_eq!(here["here"], json!(true));    assert!(here.get("join").is_none());    // Leaving: the line becomes this phone's own call line, and the call goes on without it, so the group still    // offers Join (walk on dev, 23 Nov 2026: who left saw the call as over while the others talked on).    let _ = with_door(&handle, [Reply::ok("{}"), Reply::ok("{}")]);    let _ = calls(&handle, "calls.end", json!({}));    let line = events(&answer(&handle, "chat.thread", json!({"thread": group}))).into_iter().find(|e| e.get("groupCall").is_some()).expect("Join stays on the line while the call goes on");    assert_ne!(line["text"], "Asha Example started a video call", "the line is this phone's call now: {line}");    assert_eq!(line["groupCall"]["join"], "Join");    let exchange = with_door(&handle, [Reply::ok(&json!({"live": true, "video": true, "joined": [ASHA, RAVI]}).to_string())]);    let after = answer(&handle, "chat.groupCall", json!({"thread": group}));    let _ = exchange.only();    assert_eq!((after["live"].clone(), after["join"].clone()), (json!(true), json!("Join")));}// RULE: a group's call the room says is over offers no Join; one asked offline is said as not known, never as over.#[test]fn an_over_call_stops_offering_join() {    let (_dir, handle) = phone();    let group = family(&handle);    let ns_ = ns(&handle);    let change = cotton_core::chat::payload::Payload::change("c-1", ASHA, "+15550100000", 1_000, cotton_core::chat::payload::Change { what: cotton_core::chat::payload::What::Call, message: ROOM.into(), emoji: None }, Some("voice".into()));    let g = group.clone();    crate::phone::cotton_chat::write(&handle.client(), "test.land", move |ctx| crate::phone::chat_calls::land_group_call(ctx, &ns_, &g, false, &change, ASHA)).unwrap();    with_door(&handle, [Reply::json(503, r#"{"code":"offline","message":"offline"}"#)]);    assert_eq!(answer(&handle, "chat.groupCall", json!({"thread": group}))["unknown"], json!(true));    with_door(&handle, [Reply::ok(r#"{"live":false}"#)]);    assert_eq!(answer(&handle, "chat.groupCall", json!({"thread": group}))["live"], json!(false));    let line = events(&answer(&handle, "chat.thread", json!({"thread": group}))).into_iter().find(|e| e["text"] == "Asha Example started a voice call").unwrap();    assert!(line.get("groupCall").is_none(), "no Join once it is over: {line}");    assert_eq!(answer(&handle, "chat.groupCall", json!({"thread": group}))["live"], json!(false));    assert_eq!(refused(&handle, "chat.call", json!({"thread": group, "join": true})), ("no_call".into(), "This call has ended.".into()));}// RULE: a newer call in a group takes Join from the older calls' lines: only the newest is asked of the room, so an// older line kept offering Join to a call long over (launch-ios on dev, 23 Nov 2026).#[test]fn a_newer_call_takes_join_from_the_older_lines() {    let (_dir, handle) = phone();    let group = family(&handle);    for (n, room) in [(1, ROOM), (2, ROOM_2)] {        let ns_ = ns(&handle);        let change = cotton_core::chat::payload::Payload::change(&format!("c-{n}"), ASHA, "+15550100000", 1_000 * n, cotton_core::chat::payload::Change { what: cotton_core::chat::payload::What::Call, message: room.into(), emoji: None }, Some("voice".into()));        let g = group.clone();        crate::phone::cotton_chat::write(&handle.client(), "test.land", move |ctx| crate::phone::chat_calls::land_group_call(ctx, &ns_, &g, false, &change, ASHA)).unwrap();    }    let joins: Vec<Value> = events(&answer(&handle, "chat.thread", json!({"thread": group}))).into_iter().filter_map(|e| e.get("groupCall").map(|c| c["room"].clone())).collect();    assert_eq!(joins, vec![json!(ROOM_2)], "only the newer call offers Join");}#[path = "chat_group_notes_tests.rs"]mod group_notes;