//! `calls.*` on a phone over a scripted object: the routes each method asks, //! the effects the shell is handed, the call's phases, and the history row it //! leaves. Every number and person is invented. use std::sync::Arc; use cotton_client::transport::object::ObjectAddress; use cotton_client::transport::scripted::{Reply, ScriptedExchange}; use serde_json::{json, Value}; use super::over; use crate::handle::CottonHandle; use crate::phone::passwords::tests::{exec, phone}; use crate::phone::personal_object::ObjectDoor; const CREDENTIAL: &str = "ctd_11111111-1111-4111-8111-111111111111_test-credential"; const ROOM: &str = "0123456789abcdef0123456789abcdef"; const FRIEND: &str = "+919000000301"; const NOW: &str = "2026-11-12T09:00:00.000Z"; fn with_door(handle: &CottonHandle, replies: impl IntoIterator) -> Arc { 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, false).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message)) } fn refused(handle: &CottonHandle, method: &str, request: Value) -> String { over(&handle.client(), method, &request, false).err().map(|error| error.code).unwrap_or_else(|| panic!("{method} answered")) } fn workspace(handle: &CottonHandle) -> String { handle.client().with_writer(|replica| Ok(replica.workspace_id.to_string())).unwrap() } fn friend(handle: &CottonHandle) { let ws = workspace(handle); exec(handle, "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES ('p-friend', ?, 'An Invented Friend', ?, ?)", &[&ws, NOW, NOW]); exec( handle, "INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, created_at, updated_at) VALUES ('h-1', ?, 'p-friend', 'phone', '+91 90000 00301', '919000000301', 'manual', ?, ?)", &[&ws, NOW, NOW], ); } fn started() -> Reply { Reply::ok(&json!({"room": ROOM, "credential": format!("ccr_{ROOM}_secret"), "iceServers": [{"urls": ["stun:stun.invented.test:3478"]}], "ttl": 3600, "ringFor": 45}).to_string()) } fn does(effects: &Value) -> Vec { effects.as_array().expect("effects").iter().map(|e| e["do"].as_str().unwrap().to_string()).collect() } fn body(seen: &cotton_client::transport::scripted::Seen) -> Value { serde_json::from_slice(&seen.body).expect("a JSON body") } fn calls_row(handle: &CottonHandle, id: &str) -> Option> { handle .client() .with_writer(|replica| { Ok(replica .driver .get("SELECT * FROM cotton_call_log WHERE id = ?", &[rusqlite::types::Value::Text(id.to_string())]) .map_err(|e| e.to_string())? .map(|row| crate::phone::passwords::json_row(&row))) }) .unwrap() } // RULE: calling a person asks the object to start a call to their number with this phone's credential, and hands the shell CallKit's start, the audio, the socket with the room credential and the offerer's peer — never the core's own asks. #[test] fn calling_a_person_starts_a_room_and_hands_the_shell_its_effects() { let (_dir, handle) = phone(); friend(&handle); let exchange = with_door(&handle, [started()]); let answered = answer(&handle, "calls.start", json!({"person": "p-friend", "video": false})); let sent = exchange.only(); assert_eq!((sent.method.as_str(), sent.path.as_str()), ("POST", "/v1/calls")); assert_eq!(sent.header("authorization"), Some(format!("Bearer {CREDENTIAL}").as_str())); assert_eq!(body(&sent), json!({"to": FRIEND, "video": false})); assert_eq!(answered["call"]["phase"], "ringing_out"); assert_eq!(answered["call"]["name"], "An Invented Friend"); assert!(answered["call"].get("credential").is_none()); assert_eq!(does(&answered["effects"]), ["system_call_outgoing", "start_audio", "timer", "open_socket", "create_peer", "play_tone", "timer"]); assert_eq!(answered["effects"][3]["credential"], format!("ccr_{ROOM}_secret")); assert_eq!(answered["effects"][3]["url"], "wss://cottondb.example.test/v1/calls/socket", "the socket's whole address: the shell holds no origin"); assert_eq!(refused(&handle, "calls.start", json!({"number": "+919000000302"})), "in_a_call"); let state = answer(&handle, "calls.state", json!({})); assert_eq!(state["active"], true); } // RULE: a number nobody is named for is called as typed (E.164), a bad one or a person with no phone is refused by name before anything is asked. #[test] fn numbers_and_people_are_checked_first() { let (_dir, handle) = phone(); let exchange = with_door(&handle, []); assert_eq!(refused(&handle, "calls.start", json!({"number": "not a number"})), "bad_number"); assert_eq!(refused(&handle, "calls.start", json!({"person": "nobody"})), "person_not_found"); exec(&handle, "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES ('p-quiet', ?, 'No Phone', ?, ?)", &[&workspace(&handle), NOW, NOW]); assert_eq!(refused(&handle, "calls.start", json!({"person": "p-quiet"})), "no_number"); assert_eq!(exchange.calls(), 0); } // RULE: the object refusing the start ends the call at once: too_many_calls by name, CallKit told it failed, nothing left active. #[test] fn a_refused_start_ends_the_call() { let (_dir, handle) = phone(); with_door(&handle, [Reply::json(429, r#"{"code":"too_many_calls","message":"Too many calls this hour."}"#)]); let answered = answer(&handle, "calls.start", json!({"number": FRIEND})); assert_eq!(answered["call"]["phase"], "ended"); assert_eq!(answered["call"]["reason"], "too_many_calls"); let ended = answered["effects"].as_array().unwrap().iter().find(|e| e["do"] == "system_call_ended").expect("the system call UI told"); assert_eq!((ended["cause"].clone(), ended["ios"].clone(), ended["android"].clone()), (json!("failed"), json!(1), json!(1))); assert_eq!(answer(&handle, "calls.state", json!({}))["active"], false); } // RULE: a frame and the shell's own signals go through the machine: the shell's offer is handed back to send, the room's answer to apply, the media connecting makes it live. #[test] fn signals_and_media_through_the_machine() { let (_dir, handle) = phone(); with_door(&handle, [started()]); answer(&handle, "calls.start", json!({"number": FRIEND, "video": true})); let offer = answer(&handle, "calls.signal", json!({"out": {"kind": "offer", "sdp": "v=0"}})); assert_eq!(offer["effects"], json!([{"do": "send", "frame": {"t": "signal", "kind": "offer", "sdp": "v=0"}}])); assert_eq!(refused(&handle, "calls.signal", json!({"out": {"kind": "ice"}})), "bad_request"); let applied = answer(&handle, "calls.signal", json!({"in": {"t": "signal", "from": "callee:d1", "kind": "answer", "sdp": "v=1"}})); assert_eq!(applied["effects"], json!([{"do": "apply_remote", "kind": "answer", "sdp": "v=1"}])); answer(&handle, "calls.signal", json!({"in": {"t": "state", "state": "connecting"}})); let live = answer(&handle, "calls.media", json!({"state": "connected"})); assert_eq!(live["call"]["phase"], "live"); } // RULE: hanging up a live call sends end on the socket and writes the call's row into this copy: source and provider cotton, the room as its external id, answered, out, the other number. #[test] fn hanging_up_writes_the_history_row() { let (_dir, handle) = phone(); friend(&handle); with_door(&handle, [started()]); answer(&handle, "calls.start", json!({"person": "p-friend"})); answer(&handle, "calls.signal", json!({"in": {"t": "state", "state": "connecting"}})); answer(&handle, "calls.media", json!({"state": "connected"})); let ended = answer(&handle, "calls.end", json!({})); assert_eq!(ended["call"]["reason"], "hung_up"); assert_eq!(ended["effects"][0], json!({"do": "send", "frame": {"t": "end"}})); let id = ended["history"].as_str().unwrap_or_else(|| panic!("the row written: {}", ended["historyRefused"])); let database = handle.client().current_database().unwrap(); assert_eq!(id, cotton_core::calling::history::call_id(&database, ROOM)); let row = calls_row(&handle, id).expect("the row is in the copy"); assert_eq!(row["source"], "cotton"); assert_eq!(row["provider"], "cotton"); assert_eq!(row["external_id"], ROOM); assert_eq!(row["direction"], "out"); assert_eq!(row["outcome"], "answered"); assert_eq!(row["handle"], FRIEND); assert_eq!(row["person_id"], "p-friend"); assert_eq!(answer(&handle, "calls.history", json!({}))["id"], id, "writing again lands the same row"); } // RULE: a push rings: CallKit is told "Cotton" first, the join is asked, and the caller is named from this copy; answering sends accept and makes the answering peer. #[test] fn a_push_rings_joins_and_answers() { let (_dir, handle) = phone(); friend(&handle); let joined = json!({"room": ROOM, "from": FRIEND, "video": false, "credential": format!("ccr_{ROOM}_callee"), "iceServers": [], "ttl": 3600}); let exchange = with_door(&handle, [Reply::ok(&joined.to_string())]); let rung = answer(&handle, "calls.incoming", json!({"room": ROOM})); assert_eq!(rung["effects"][0], json!({"do": "system_call_incoming", "uuid": "01234567-89AB-CDEF-0123-456789ABCDEF", "title": "Cotton", "video": false})); assert_eq!(does(&rung["effects"]), ["system_call_incoming", "timer", "system_call_update", "open_socket"]); assert_eq!(rung["effects"][2]["name"], "An Invented Friend"); assert_eq!(rung["call"]["person"], "p-friend"); assert_eq!(exchange.only().path, format!("/v1/calls/{ROOM}/join")); let answered = answer(&handle, "calls.answer", json!({})); assert_eq!(answered["call"]["phase"], "connecting"); assert_eq!(answered["effects"][0], json!({"do": "send", "frame": {"t": "accept"}})); } // RULE: a copy whose call table holds the columns the object's definition lays (kind, ended_reason, missed) gets them on the row: a missed ring is in Missed, said by the one clear flag, with how it ended. #[test] fn a_missed_ring_lands_in_missed_on_a_copy_holding_the_served_columns() { let (_dir, handle) = phone(); let call: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/call.json")).expect("the call definition"); handle.client().with_writer(|replica| cotton_client::transport::object::hold_defined_columns(&replica.driver, [&call]).map(|_| ())).unwrap(); with_door(&handle, [Reply::json(404, r#"{"code":"not_ringing","message":"no"}"#)]); let missed = answer(&handle, "calls.incoming", json!({"room": ROOM, "video": true})); let id = missed["history"].as_str().unwrap_or_else(|| panic!("the row written: {missed}")); let row = calls_row(&handle, id).expect("the row is in the copy"); assert_eq!((row["direction"].as_str(), row["outcome"].as_str()), (Some("in"), Some("missed"))); assert_eq!(row["missed"], json!(1), "the clear flag Missed reads"); assert_eq!(row["ended_reason"], "missed"); assert_eq!(row["kind"], "video"); } // RULE: a ring that ended before the join answered is missed; a stop push ends a ring and leaves its row to the device that answered; a stop for no call here is reported and ended. #[test] fn rings_that_end_without_an_answer() { let (_dir, handle) = phone(); let exchange = with_door(&handle, [Reply::json(404, r#"{"code":"not_ringing","message":"no"}"#)]); let missed = answer(&handle, "calls.incoming", json!({"room": ROOM})); assert_eq!(missed["call"]["reason"], "missed"); assert_eq!(exchange.calls(), 1); let (_dir2, other) = phone(); let other_exchange = with_door(&other, [Reply::ok(&json!({"room": ROOM, "from": FRIEND, "credential": "ccr_x", "iceServers": [], "ttl": 1}).to_string())]); answer(&other, "calls.incoming", json!({"room": ROOM})); let stopped = answer(&other, "calls.stop", json!({"room": ROOM, "reason": "answered_elsewhere"})); assert_eq!(stopped["call"]["reason"], "answered_elsewhere"); assert!(stopped.get("history").is_none(), "the device that answered writes the call"); assert_eq!(other_exchange.calls(), 1, "nothing more is asked"); // A stop pushed for a call this phone does not hold: CallKit was told of the push, so it is reported and ended at // once; the same stop over the chat socket rings nothing (CALLS FIX 2). let stray = answer(&other, "calls.stop", json!({"room": "fedcba9876543210fedcba9876543210", "reason": "cancelled", "pushed": true})); assert_eq!(does(&stray["effects"]), ["system_call_incoming", "system_call_ended"]); let framed = answer(&other, "calls.stop", json!({"room": "fedcba9876543210fedcba9876543211", "reason": "cancelled"})); assert_eq!(does(&framed["effects"]), Vec::::new()); } // RULE: a ring of another room during a call is reported, answered busy over HTTP and ended, and the call under way is untouched. #[test] fn a_ring_during_a_call_is_busy() { let (_dir, handle) = phone(); let exchange = with_door(&handle, [started(), Reply::ok(r#"{"ok":true}"#)]); answer(&handle, "calls.start", json!({"number": FRIEND})); let other = "fedcba9876543210fedcba9876543210"; let rung = answer(&handle, "calls.incoming", json!({"room": other})); assert_eq!(does(&rung["effects"]), ["system_call_incoming", "system_call_ended"]); assert_eq!(rung["call"]["phase"], "ringing_out"); let decline = exchange.nth(1); assert_eq!(decline.path, format!("/v1/calls/{other}/decline")); assert_eq!(body(&decline), json!({"busy": true})); } // RULE: the VoIP token is filed with the object under Cotton Calling's topic only, as hex; the ICE servers are the object's answer as it came. #[test] fn push_token_and_ice_servers() { let (_dir, handle) = phone(); let ice = json!({"iceServers": [{"urls": ["stun:stun.invented.test:3478"]}], "ttl": 3600}); let exchange = with_door(&handle, [Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#), Reply::ok(&ice.to_string())]); assert_eq!(refused(&handle, "calls.pushToken", json!({"platform": "ios", "token": "zz", "topic": "com.cottondb.calling"})), "bad_request"); assert_eq!(refused(&handle, "calls.pushToken", json!({"platform": "ios", "token": "ab".repeat(32), "topic": "com.invented.app"})), "bad_request"); assert_eq!(refused(&handle, "calls.pushToken", json!({"platform": "windows", "token": "ab".repeat(32)})), "bad_request"); assert_eq!(refused(&handle, "calls.pushToken", json!({"platform": "android", "token": "has a space in it, which FCM never makes"})), "bad_request"); answer(&handle, "calls.pushToken", json!({"platform": "ios", "token": "AB".repeat(32), "topic": "com.cottondb.calling.dev", "sandbox": true})); let sent = exchange.nth(0); assert_eq!((sent.method.as_str(), sent.path.as_str()), ("POST", "/v1/calls/device")); assert_eq!(body(&sent), json!({"platform": "ios", "token": "ab".repeat(32), "topic": "com.cottondb.calling.dev", "sandbox": true})); let fcm = "fInvEnTeD0123:APA91b-invented_registration_token_0123456789"; answer(&handle, "calls.pushToken", json!({"platform": "android", "token": fcm})); assert_eq!(body(&exchange.nth(1)), json!({"platform": "android", "token": fcm}), "no topic or sandbox for Android"); assert_eq!(answer(&handle, "calls.iceServers", json!({})), ice); assert_eq!(exchange.nth(2).path, "/v1/calls/ice"); } // RULE (CALLS FIX 2): a shell that speaks the new way says so with its token (`can`), and acks a ring or a stop that // came by push (`calls.ack`); one that says nothing files its token as before. #[test] fn a_token_says_what_the_phone_speaks_and_a_push_is_acked() { let (_dir, handle) = phone(); let exchange = with_door(&handle, [Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#)]); answer(&handle, "calls.pushToken", json!({"platform": "ios", "token": "ab".repeat(32), "topic": "com.cottondb.messages.dev", "sandbox": true, "can": ["ring_ack"]})); assert_eq!(body(&exchange.nth(0))["can"], json!(["ring_ack"])); answer(&handle, "calls.ack", json!({"room": ROOM})); let acked = exchange.nth(1); assert_eq!((acked.method.as_str(), acked.path.as_str()), ("POST", "/v1/calls/ack")); assert_eq!(body(&acked), json!({"room": ROOM})); } // RULE: the link another app opens to call a person is the core's, built and read here; the Dev app's names its own scheme. #[test] fn the_call_link() { let (_dir, handle) = phone(); assert_eq!(answer(&handle, "calls.link", json!({"person": "p-friend", "video": true}))["url"], "cottoncalling://call?person=p-friend&video=1"); let dev = over(&handle.client(), "calls.link", &json!({"person": "p-friend"}), true).unwrap(); assert_eq!(dev["url"], "cottoncallingdev://call?person=p-friend&video=0"); assert_eq!(answer(&handle, "calls.openLink", json!({"url": "cottoncalling://call?person=p-friend&video=1"})), json!({"people": ["p-friend"], "video": true})); assert_eq!(answer(&handle, "calls.link", json!({"people": ["p-1", "p-2"], "video": true}))["url"], "cottoncalling://call?person=p-1&person=p-2&video=1"); assert_eq!(answer(&handle, "calls.openLink", json!({"url": "https://invented.test/"})), Value::Null); } // RULE: without the door a call cannot start: it ends unreachable, and the ICE servers are refused not_connected. #[test] fn no_door_no_call() { let (_dir, handle) = phone(); let answered = answer(&handle, "calls.start", json!({"number": FRIEND})); assert_eq!(answered["call"]["reason"], "unreachable_network"); assert_eq!(refused(&handle, "calls.iceServers", json!({})), "not_connected"); } fn second(handle: &CottonHandle) { let ws = workspace(handle); exec(handle, "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES ('p-second', ?, 'A Second Friend', ?, ?)", &[&ws, NOW, NOW]); exec( handle, "INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, created_at, updated_at) VALUES ('h-2', ?, 'p-second', 'phone', '+919000000303', '919000000303', 'manual', ?, ?)", &[&ws, NOW, NOW], ); } // RULE: calling several people asks one start with every number, on the SFU: the SFU connection and the push are the shell's, the invitees shown by the names this copy holds. #[test] fn a_group_call_from_the_phone() { let (_dir, handle) = phone(); friend(&handle); second(&handle); let exchange = with_door(&handle, [Reply::ok(&json!({"room": ROOM, "credential": format!("ccr_{ROOM}_secret"), "iceServers": [], "ttl": 3600, "ringFor": 45, "mode": "sfu", "me": "caller"}).to_string())]); let answered = answer(&handle, "calls.start", json!({"people": ["p-friend", "p-second"], "video": true})); assert_eq!(body(&exchange.only()), json!({"to": [FRIEND, "+919000000303"], "video": true})); assert_eq!(answered["call"]["mode"], "sfu"); assert_eq!(does(&answered["effects"]), ["system_call_outgoing", "start_audio", "start_camera", "timer", "open_socket", "switch_to_sfu", "push_tracks", "show_roster", "play_tone", "timer"]); let names: Vec<&str> = answered["call"]["members"].as_array().unwrap().iter().map(|m| m["name"].as_str().unwrap()).collect(); assert_eq!(names, ["An Invented Friend", "A Second Friend"]); let nine: Vec = (0..9).map(|n| format!("+9190000004{n:02}")).collect(); let (_dir2, other) = phone(); with_door(&other, []); assert_eq!(refused(&other, "calls.start", json!({"numbers": nine})), "too_many"); } // RULE: in a call: inviting asks the object's invite route, the roster names members from this copy, muting and speaking go to the room, and leaving a group sends leave. #[test] fn inviting_muting_and_leaving() { let (_dir, handle) = phone(); second(&handle); let exchange = with_door(&handle, [started(), Reply::ok(r#"{"ok":true}"#)]); answer(&handle, "calls.start", json!({"number": FRIEND})); answer(&handle, "calls.signal", json!({"in": {"t": "state", "state": "connecting"}})); answer(&handle, "calls.media", json!({"state": "connected"})); let invited = answer(&handle, "calls.invite", json!({"person": "p-second"})); let sent = exchange.nth(1); assert_eq!(sent.path, format!("/v1/calls/{ROOM}/invite")); assert_eq!(body(&sent), json!({"to": "+919000000303"})); assert_eq!(does(&invited["effects"]), ["show_roster"]); let moved = answer(&handle, "calls.signal", json!({"in": {"t": "mode", "mode": "sfu"}})); assert_eq!(does(&moved["effects"]), ["close_peer", "switch_to_sfu", "push_tracks"]); let roster = answer(&handle, "calls.signal", json!({"in": {"t": "roster", "members": [{"id": "caller", "number": "+919000000300", "state": "joined"}, {"id": "callee:x", "number": FRIEND, "state": "joined"}, {"id": "callee:y", "number": "+919000000303", "state": "joined"}]}})); let second_member = roster["call"]["members"].as_array().unwrap().iter().find(|m| m["id"] == "callee:y").unwrap().clone(); assert_eq!(second_member["name"], "A Second Friend"); let muted = answer(&handle, "calls.mute", json!({"audio": false, "video": false})); assert_eq!(muted["effects"], json!([{"do": "set_sending", "audio": false, "video": false}, {"do": "send", "frame": {"t": "mute", "audio": false, "video": false}}])); let speaking = answer(&handle, "calls.speaking", json!({"on": true})); assert_eq!(speaking["effects"], json!([{"do": "send", "frame": {"t": "speaking", "on": true}}])); let left = answer(&handle, "calls.leave", json!({})); assert_eq!(left["effects"][0], json!({"do": "send", "frame": {"t": "leave"}})); assert_eq!(left["call"]["phase"], "ended"); } // RULE (owner, 23 Nov 2026; chat CONTRACT "Take notes"): a phone that draws the mark says so (`can: ["notes"]`) on its // start; a tap only asks the room; the recording begins when the room names this phone as taking notes (everyone // has been told), with a track for this phone and one for each other person; someone who comes in later is a new // track; when the room no longer names this phone the notes stop, the files are kept as one recording of the call, // each person's voice named as the call named them. #[test] fn notes_begin_when_the_room_says_so_with_a_track_per_person() { let dir = tempfile::tempdir().unwrap(); let handle = crate::phone::chat_app::mail::tests::comms(&dir, cotton_core::flavor::Flavor::Real); friend(&handle); second(&handle); let exchange = with_door(&handle, [started()]); answer(&handle, "calls.start", json!({"number": FRIEND, "can": ["notes"]})); assert_eq!(body(&exchange.nth(0))["can"], json!(["notes"]), "the start says this phone can show the mark"); answer(&handle, "calls.signal", json!({"in": {"t": "state", "state": "connecting"}})); answer(&handle, "calls.media", json!({"state": "connected"})); let me = answer(&handle, "calls.state", json!({}))["call"]["me"].as_str().map(str::to_string).unwrap_or_else(|| "caller".into()); let member = |id: &str, number: &str, notes: bool| json!({"id": id, "number": number, "state": "joined", "notes": notes, "can": ["notes"]}); let asked = answer(&handle, "calls.notes", json!({"on": true})); assert_eq!(asked["effects"], json!([{"do": "send", "frame": {"t": "notes", "on": true}}]), "a tap only asks the room"); let roster = answer(&handle, "calls.signal", json!({"in": {"t": "roster", "members": [member(&me, "+919000000300", true), member("callee:x", FRIEND, false)]}})); let start = roster["effects"].as_array().unwrap().iter().find(|e| e["do"] == "notes_start").unwrap_or_else(|| panic!("no notes_start: {roster}")).clone(); let meeting = start["meeting"].as_str().unwrap().to_string(); let tracks: Vec<(&str, Option<&str>)> = start["tracks"].as_array().unwrap().iter().map(|t| (t["track"].as_str().unwrap(), t["person"].as_str())).collect(); assert_eq!(tracks, [("me", None), ("callee:x", Some("p-friend"))]); let again = answer(&handle, "calls.signal", json!({"in": {"t": "speaking", "member": "callee:x", "on": true}})); assert!(!does(&again["effects"]).iter().any(|d| d.starts_with("notes_")), "once begun, never again: {again}"); let joined = answer(&handle, "calls.signal", json!({"in": {"t": "member", "member": member("callee:y", "+919000000303", false)}})); let track = joined["effects"].as_array().unwrap().iter().find(|e| e["do"] == "notes_track").unwrap_or_else(|| panic!("no notes_track: {joined}")).clone(); assert_eq!((track["track"].as_str(), track["name"].as_str()), (Some("callee:y"), Some("A Second Friend"))); let stopped = answer(&handle, "calls.signal", json!({"in": {"t": "member", "member": member(&me, "+919000000300", false)}})); let stop = stopped["effects"].as_array().unwrap().iter().find(|e| e["do"] == "notes_stop").unwrap_or_else(|| panic!("no notes_stop: {stopped}")).clone(); assert_eq!(stop["tracks"].as_array().unwrap().len(), 3); // The shell's files, handed to the core as one recording of the call. let mut files = Vec::new(); for t in stop["tracks"].as_array().unwrap() { let path = std::path::PathBuf::from(t["path"].as_str().unwrap()); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); let mut bytes = Vec::new(); for _ in 0..40 { bytes.extend_from_slice(&[0xFF, 0xF1, 0x60, 0x40, 0x01, 0x7F, 0xFC, 0, 0, 0, 0]); } std::fs::write(&path, bytes).unwrap(); files.push(json!({ "track": t["track"], "path": path.to_string_lossy() })); } let kept = crate::methods::dispatch(&handle, "meetings.record.stop", &json!({ "id": meeting, "tracks": files, "duration_ms": 90_000 })).unwrap(); assert_eq!(kept["status"], "waiting", "{kept}"); let next = crate::methods::dispatch(&handle, "meetings.next", &json!({ "on": "phone", "charging": true })).unwrap(); assert_eq!(next["meeting"], json!(meeting)); let heard: Vec<&str> = next["tracks"].as_array().unwrap().iter().map(|t| t["track"].as_str().unwrap()).collect(); assert_eq!(heard, ["me", "callee:x", "callee:y"], "each person's file, to be heard alone"); let window = |start: i64, text: &str| json!([{ "index": 0, "start_ms": 0, "end_ms": 90_000, "lines": [{ "speaker": "S1", "start_ms": start, "end_ms": start + 2_000, "text": text, "language": "en" }] }]); crate::methods::dispatch(&handle, "meetings.transcribed", &json!({ "id": meeting, "by": "phone:test", "tracks": [ { "track": "me", "windows": window(1_000, "Shall we book the boat house?") }, { "track": "callee:x", "windows": window(4_000, "Yes, by Wednesday.") }, { "track": "callee:y", "windows": window(8_000, "I will print the maps.") }, ] })).unwrap(); let page = crate::methods::dispatch(&handle, "chat.recording", &json!({ "id": meeting })).unwrap(); let said: Vec<(&str, &str)> = page["lines"].as_array().unwrap().iter().map(|l| (l["name"].as_str().unwrap_or_default(), l["text"].as_str().unwrap())).collect(); assert_eq!(said[0], ("You", "Shall we book the boat house?"), "his own voice is You, never \"Speaker me\": {page}"); assert_eq!(said[1..], [("An Invented Friend", "Yes, by Wednesday."), ("A Second Friend", "I will print the maps.")], "{page}"); assert_eq!(page["title"], "Notes on a call with An Invented Friend, A Second Friend", "{page}"); // Hung up: Calls shows the call with its notes on its row, never the notes as a row of their own (seen on // emulator-5620: the notes stood apart as "Meeting", the call's row matched by its id, the notes by its room). answer(&handle, "calls.end", json!({})); let calls = crate::methods::dispatch(&handle, "chat.calls", &json!({})).unwrap(); let rows = calls["rows"].as_array().unwrap(); assert!(rows.iter().any(|r| r["kind"] == "call" && r["recording"] == json!(meeting)), "{calls}"); assert!(!rows.iter().any(|r| r["kind"] == "recording"), "{calls}"); drop(dir); } // RULE (owner, 23 Nov 2026; DECISIONS "Recordings": a recording is never lost): a call's notes cut off by a killed app // are kept at the next start with every person's file so far, as one recording of the call. #[test] fn notes_a_killed_app_left_are_kept_at_the_next_start() { let dir = tempfile::tempdir().unwrap(); let handle = crate::phone::chat_app::mail::tests::comms(&dir, cotton_core::flavor::Flavor::Real); friend(&handle); with_door(&handle, [started()]); answer(&handle, "calls.start", json!({"number": FRIEND, "can": ["notes"]})); answer(&handle, "calls.signal", json!({"in": {"t": "state", "state": "connecting"}})); answer(&handle, "calls.media", json!({"state": "connected"})); let member = |id: &str, number: &str, notes: bool| json!({"id": id, "number": number, "state": "joined", "notes": notes, "can": ["notes"]}); let roster = answer(&handle, "calls.signal", json!({"in": {"t": "roster", "members": [member("caller", "+919000000300", true), member("callee:x", FRIEND, false)]}})); let start = roster["effects"].as_array().unwrap().iter().find(|e| e["do"] == "notes_start").unwrap().clone(); for t in start["tracks"].as_array().unwrap() { let path = std::path::PathBuf::from(t["path"].as_str().unwrap()); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(&path, [0xFF, 0xF1, 0x60, 0x40, 0x01, 0x7F, 0xFC, 0, 0, 0, 0].repeat(30)).unwrap(); } // The app is killed here: no stop. At the next start only a call's notes are looked for. let kept = crate::methods::dispatch(&handle, "meetings.record.recover", &json!({ "source": "call" })).unwrap(); let one = kept["recovered"].as_array().unwrap(); assert_eq!(one.len(), 1, "{kept}"); assert_eq!(one[0]["status"], "waiting"); let row = answer(&handle, "calls.state", json!({})); drop(row); let read = crate::methods::dispatch(&handle, "records.get", &json!({ "table": "meetings_meeting", "id": start["meeting"] })).unwrap(); let data = if read["data"].is_object() { read["data"].clone() } else { read["record"]["data"].clone() }; assert_eq!((data["status_why"].as_str(), data["source"].as_str()), (Some("recovered"), Some("call"))); let tracks: Vec = serde_json::from_str(data["tracks"].as_str().unwrap()).unwrap(); assert_eq!(tracks.iter().map(|t| t["track"].as_str().unwrap()).collect::>(), ["me", "callee:x"]); assert!(tracks.iter().all(|t| t["key"].is_string()), "each file kept in the store: {tracks:?}"); }