Cotton code
848 lines · 45.6 KB · RustRaw
//! Calls in Cotton Chat on this phone (owner, 19 Nov 2026): the call is//! Calling's engine (`phone::calls`, the `calls.*` methods the shell already//! performs), placed from a conversation, said in it, listed in the Calls//! tile and drawn on the call screen. Every word is the kit's (`chat` set,//! `app.call.*`); the rules are `cotton_core::messages::app::calls`.//!//! ```text//! chat.call        { thread, video? } | { call, video? }   → calls.start's { call, effects }  (refused not_cotton, request, no_one, in_a_call)//! chat.calls       { after? }                              → CallsAnswer { rows, next?, words }//! chat.callScreen  { speaker?, routes?: [{ id, kind, name? }], route? } → CallScreen (`routes` and an `audio` control when a headset is there; a group's `tiles`, `grid`, `privacy`, `notes`)//! chat.call        { thread, join: true }                  → calls.enter's { call, effects }  (a group's call going on: come in late, or again)//! chat.groupCall   { thread }                              → GroupCall { live, room?, video?, here?, banner?, people?, join? }//! chat.thread      (Chat's) gains `header.calls` and, on a call's line, `call`//! ```//!//! A call that ends leaves its `call` row (Calling's, one per room and side,//! `meta.chat` holding what Chat needs to say it and ring again) and, where it//! has a conversation on this phone, one centred line in it: a local message//! row (`meta.system`, `meta.call`), never sent, never counted unread, its id//! made from the room so every phone of the person writes the same one.use std::collections::HashMap;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use cotton_core::calling::history::call_id;use cotton_core::calling::machine::Call;use cotton_core::chat::{ids, CHANNEL};use cotton_core::messages::app::calls::{self as rules, CallFacts, CallRow, CallsAnswer, CallsWords, ThreadCall};use cotton_core::messages::app::lay;use cotton_core::messages::app::list::{self, say};use cotton_core::messages::app::shapes::Picture;use cotton_core::messages::display::{direct_name, group_name};use cotton_core::records::page::{stamp_parts, DateWords};use cotton_core::rules::shell_lines::LineSet;use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::insert_row;use super::cotton_chat::{self, holds, iso, namespace, now_ms, one, read, rows, write, ws, MESSAGES, THREADS};use crate::methods::MethodError;use crate::shell::client::ClientController;const CONTACTS: &str = "cotton_msg_contacts";const SEATS: &str = "cotton_msg_thread_participants";pub(crate) const CALLS: &str = "cotton_call_log";/// The methods this module answers (each also in `cotton_chat::METHODS`).pub const METHODS: [&str; 4] = ["chat.call", "chat.callScreen", "chat.calls", "chat.groupCall"];pub fn over(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "chat.call" => place(client, request),        "chat.calls" => serde_json::to_value(calls(client, request)?).map_err(unreadable),        "chat.callScreen" => serde_json::to_value(screen(client, request)?).map_err(unreadable),        "chat.groupCall" => group_call(client, request),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a chat call method"))),    }}fn unreadable(e: serde_json::Error) -> MethodError {    MethodError::new("unreadable", e.to_string())}fn refuse(lines: &LineSet, code: &str, line: &str) -> MethodError {    MethodError::new(code, say(lines, line, &[]))}fn s(row: &Map<String, Value>, key: &str) -> Option<String> {    row.get(key).and_then(Value::as_str).map(str::to_string).filter(|v| !v.is_empty())}fn t(text: &str) -> SqlValue {    SqlValue::Text(text.to_string())}fn meta(row: &Map<String, Value>) -> Value {    cotton_chat::meta_value(row.get("meta").unwrap_or(&Value::Null))}fn plus(number: &str) -> String {    if number.starts_with('+') { number.to_string() } else { format!("+{number}") }}// ── who a number is ─────────────────────────────────────────────────────/// A number's name and picture as Chat says them: the person it is, else the contact's name, else the number.#[derive(Debug, Clone)]pub(crate) struct Who {    pub(crate) name: String,    pub(crate) photo: Option<String>,}pub(crate) fn who(ctx: &mut Ctx<'_>, numbers: &[String]) -> Result<HashMap<String, Who>, String> {    let mut out = HashMap::new();    if numbers.is_empty() || !holds(ctx, CONTACTS, "phone_e164")? {        for n in numbers {            out.insert(n.clone(), Who { name: n.clone(), photo: None });        }        return Ok(out);    }    let avatar = if holds(ctx, CONTACTS, "avatar_key")? { "avatar_key" } else { "NULL AS avatar_key" };    for number in numbers {        let digits = number.trim_start_matches('+').to_string();        // The contact's person is who(handle)'s, derived as it is read; a number several of his contacts share (a        // household landline) is called by all their names, never one of them (PEOPLE BUILD 1b).        let contact = one(            ctx,            &format!(                "SELECT c.display_name AS display_name, {person} AS person_id, {shared} AS shared_names, c.{avatar} FROM {CONTACTS} c WHERE c.workspace_id = ? AND c.phone_e164 = ?",                person = cotton_store::protocol::who::contact_person_sql(cotton_store::protocol::who::shared_held(ctx.db()), "c"),                shared = cotton_store::protocol::who::contact_shared_names_sql(cotton_store::protocol::who::shared_held(ctx.db()), "c"),            ),            &[ws(ctx), t(&digits)],        )?;        let person = match contact.as_ref().and_then(|c| s(c, "person_id")) {            Some(id) => one(ctx, "SELECT full_name, avatar_key FROM cotton_people WHERE workspace_id = ? AND id = ?", &[ws(ctx), t(&id)])?,            None => None,        };        let shared = contact.as_ref().and_then(|c| s(c, "shared_names"));        let name = direct_name(            person.as_ref().and_then(|p| s(p, "full_name")).as_deref().or(shared.as_deref()),            contact.as_ref().and_then(|c| s(c, "display_name")).as_deref(),            None,            Some(number.as_str()),            None,        );        let photo = person.as_ref().and_then(|p| s(p, "avatar_key")).or_else(|| contact.as_ref().and_then(|c| s(c, "avatar_key")));        out.insert(number.clone(), Who { name, photo });    }    Ok(out)}/// The names of a group call's people, as a group with no title is named.fn names_of(found: &HashMap<String, Who>, numbers: &[String]) -> String {    let names: Vec<String> = numbers.iter().map(|n| found.get(n).map_or_else(|| n.clone(), |w| w.name.clone())).collect();    group_name(None, &names)}// ── a conversation's callable people ────────────────────────────────────/// A conversation as calls need it.#[derive(Debug, Clone, Default)]struct Callable {    cotton: bool,    group: bool,    pending: bool,    /// Everyone a call from here rings, E.164.    numbers: Vec<String>,    /// A Cotton group's id: its call is the group's (anyone of it may come in late).    group_id: Option<String>,}fn callable(ctx: &mut Ctx<'_>, thread: &str) -> Result<Option<Callable>, String> {    let request = if holds(ctx, THREADS, "request")? { "request" } else { "NULL AS request" };    let Some(row) = one(ctx, &format!("SELECT id, kind, external_key, {request} FROM {THREADS} WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL"), &[ws(ctx), t(thread)])? else {        return Ok(None);    };    let key = s(&row, "external_key").unwrap_or_default();    let group = s(&row, "kind").as_deref() == Some("group");    let pending = s(&row, "request").as_deref() == Some("pending");    let blocked_col = holds(ctx, CONTACTS, "blocked")?;    let blocked = |ctx: &mut Ctx<'_>, number: &str| -> Result<bool, String> {        if !blocked_col {            return Ok(false);        }        let digits = number.trim_start_matches('+').to_string();        Ok(one(ctx, &format!("SELECT blocked FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), t(&digits)])?            .is_some_and(|c| matches!(c.get("blocked"), Some(Value::Bool(true))) || c.get("blocked").and_then(Value::as_i64) == Some(1)))    };    let mut numbers = Vec::new();    let cotton = if group {        // A Cotton group: every member still in it but you, by their contact's number.        let cotton = key.starts_with("cotton:");        if cotton {            let seats = rows(ctx, &format!("SELECT c.phone_e164 AS phone FROM {SEATS} p JOIN {CONTACTS} c ON c.id = p.contact_id WHERE p.workspace_id = ? AND p.thread_id = ? AND p.left_at IS NULL AND coalesce(p.is_self, 0) = 0"), &[ws(ctx), t(thread)])?;            for seat in seats {                if let Some(phone) = s(&seat, "phone") {                    numbers.push(plus(&phone));                }            }        }        cotton    } else {        match ids::number_of_key(&key) {            Some(number) => {                numbers.push(number.to_string());                true            }            None => false,        }    };    let mut kept = Vec::new();    for number in numbers {        if !blocked(ctx, &number)? && !kept.contains(&number) {            kept.push(number);        }    }    let group_id = if group { super::chat_group::group_of_key(&key).map(str::to_string) } else { None };    Ok(Some(Callable { cotton, group, pending, numbers: kept, group_id }))}// ── chat.call ───────────────────────────────────────────────────────────fn place(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let lines = list::lines();    let asked_video = request.get("video").and_then(Value::as_bool);    if request.get("join").and_then(Value::as_bool) == Some(true) {        return join_group_call(client, request);    }    let mut group: Option<String> = None;    let (thread, numbers, video) = if let Some(thread) = request.get("thread").and_then(Value::as_str).filter(|v| !v.is_empty()) {        let thread = thread.to_string();        let found = read(client, "chat.call", |ctx| Ok(callable(ctx, &thread)?.map(|c| json!({ "cotton": c.cotton, "pending": c.pending, "numbers": c.numbers, "group": c.group_id })).unwrap_or(Value::Null)))?;        if found.is_null() {            return Err(refuse(&lines, "not_found", "refused.not_found"));        }        if found["cotton"] != json!(true) {            return Err(refuse(&lines, "not_cotton", "app.call.refused.not_cotton"));        }        if found["pending"] == json!(true) {            return Err(refuse(&lines, "request", "app.call.refused.request"));        }        let numbers: Vec<String> = found["numbers"].as_array().into_iter().flatten().filter_map(|n| n.as_str().map(str::to_string)).collect();        group = found["group"].as_str().map(str::to_string);        (Some(thread), numbers, asked_video.unwrap_or(false))    } else if let Some(id) = request.get("call").and_then(Value::as_str).filter(|v| !v.is_empty()) {        let id = id.to_string();        let found = read(client, "chat.call", |ctx| Ok(one(ctx, &format!("SELECT handle, meta FROM {CALLS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), t(&id)])?.map(Value::Object).unwrap_or(Value::Null)))?;        let Some(row) = found.as_object() else { return Err(refuse(&lines, "not_found", "refused.not_found")) };        let chat = meta(row)["chat"].clone();        let mut numbers: Vec<String> = chat["numbers"].as_array().into_iter().flatten().filter_map(|n| n.as_str().map(str::to_string)).collect();        if numbers.is_empty() {            numbers.extend(s(row, "handle"));        }        let thread = chat["thread"].as_str().map(str::to_string);        (thread, numbers, asked_video.unwrap_or(chat["video"] == json!(true)))    } else {        return Err(cotton_chat::bad("thread or call", "required"));    };    if numbers.is_empty() {        return Err(refuse(&lines, "no_one", "app.call.refused.no_one"));    }    let mut asked = json!({ "numbers": numbers, "video": video });    if let Some(group) = &group {        asked["group"] = json!(group);    }    // Take notes: what the shell says it can draw goes with the call (phone::call_notes).    if let Some(can) = request.get("can") {        asked["can"] = can.clone();    }    let mut answer = super::calls::over(client, "calls.start", &asked, false).map_err(|error| match error.code.as_str() {        "in_a_call" => refuse(&lines, "in_a_call", "app.call.refused.in_a_call"),        _ => error,    })?;    // The call knows its conversation from here on: its line goes there, its screen says whose it is.    if let Some(thread) = &thread {        // A group's call is named by the group on the caller's screen too, as on the phones it rings.        let group_name = group.as_deref().and_then(|g| super::calls::group_place(client, g)).and_then(|(_, name)| name);        let room = {            let mut slot = client.call_slot().lock().unwrap_or_else(|p| p.into_inner());            slot.thread = Some(thread.clone());            if group_name.is_some() {                slot.name = group_name.clone();            }            slot.room.clone()        };        if let Some(name) = &group_name {            answer["call"]["name"] = json!(name);        }        answer["call"]["thread"] = json!(thread);        // A group's call is told to every member, sealed as any group word is: its line, with Join while it goes on.        if let (Some(_), Some(room)) = (&group, room) {            if tell_group_call(client, thread, &room, video)? {                answer["flush"] = json!(true);            }        }    }    Ok(answer)}/// The group's call line, here and (at the next `chat.flush`) on every member's phone and this person's others.fn tell_group_call(client: &ClientController, thread: &str, room: &str, video: bool) -> Result<bool, MethodError> {    let ns = namespace(client)?;    let (thread, room) = (thread.to_string(), room.to_string());    let at = now_ms(client);    let told = write(client, "chat.groupCall.tell", move |ctx| {        write_group_line(ctx, &ns, &thread, &room, video, None, at)?;        cotton_chat::wait_change(ctx, &thread, cotton_core::chat::payload::What::Call, &room, None, Some(if video { "video" } else { "voice" }), at)?;        Ok(json!(true))    })?;    Ok(told == json!(true))}/// A group's call line: the call's own line id (the one its ended line takes over), written once./// `by`: the member who started it (none: this person).fn write_group_line(ctx: &mut Ctx<'_>, ns: &str, thread: &str, room: &str, video: bool, by: Option<(&str, &str)>, at: i64) -> Result<Option<String>, String> {    let id = ids::message_id(ns, "call", room);    if !holds(ctx, MESSAGES, "meta")? || !cotton_chat::exists(ctx, THREADS, thread)? || cotton_chat::exists(ctx, MESSAGES, &id)? {        return Ok(None);    }    let text = rules::group_started(&list::lines(), by.map(|(_, name)| name), video);    let when = iso(at);    let mut columns = Map::new();    columns.insert("thread_id".into(), json!(thread));    columns.insert("direction".into(), json!(if by.is_some() { "in" } else { "out" }));    columns.insert("channel".into(), json!(CHANNEL));    columns.insert("origin".into(), json!("live"));    columns.insert("body".into(), json!(text));    columns.insert("external_id".into(), json!(format!("call:{room}")));    columns.insert("sent_at".into(), json!(when));    let mut call = json!({ "room": room, "video": video, "at": at });    if let Some((number, _)) = by {        call["from"] = json!(number);    }    columns.insert("meta".into(), json!({ "system": true, "groupCall": call }));    insert_row(ctx, MESSAGES, &id, columns).map_err(|f| f.to_string())?;    // A newer call in the group: an older call's line gives up its Join (only the newest is asked of the room, so an    // older one kept offering Join to a call long over: launch-ios on dev, 23 Nov 2026).    for row in rows(ctx, &format!("SELECT id, meta FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND external_id LIKE 'call:%' AND id <> ?"), &[ws(ctx), t(thread), t(&id)])? {        let mut kept = meta(&row);        if kept["groupCall"].is_object() && kept["groupCall"]["over"] != json!(true) {            kept["groupCall"]["over"] = json!(true);            let mut patch = Map::new();            patch.insert("meta".into(), kept);            if let Some(older) = s(&row, "id") {                cotton_tools::mcp::handlers::common::update_row(ctx, MESSAGES, &older, patch).map_err(|f| f.to_string())?;            }        }    }    cotton_chat::touch_thread(ctx, thread, &when, Some(&text), false)?;    Ok(Some(id))}/// A group's call told by a member (`What::Call`): its line lands in the group, once.pub(crate) fn land_group_call(ctx: &mut Ctx<'_>, ns: &str, thread: &str, out: bool, payload: &cotton_core::chat::payload::Payload, sender: &str) -> Result<Value, String> {    let Some(change) = &payload.change else { return Ok(Value::Null) };    let video = payload.body.as_deref() == Some("video");    let by = if out {        None    } else {        let named = who(ctx, &[sender.to_string()])?;        Some((sender.to_string(), named.get(sender).map_or_else(|| sender.to_string(), |w| w.name.clone())))    };    let written = write_group_line(ctx, ns, thread, &change.message, video, by.as_ref().map(|(n, w)| (n.as_str(), w.as_str())), payload.at)?;    Ok(written.map_or(Value::Null, |message| json!({ "thread": thread, "message": message, "groupCall": change.message })))}/// The newest group call line of `thread` still said to go on: (its message id, room, video).fn live_line(ctx: &mut Ctx<'_>, thread: &str) -> Result<Option<(String, String, bool)>, String> {    let found = rows(ctx, &format!("SELECT id, meta FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND external_id LIKE 'call:%' ORDER BY sent_at DESC LIMIT 5"), &[ws(ctx), t(thread)])?;    for row in found {        let meta = meta(&row);        let call = &meta["groupCall"];        if call.is_object() && call["over"] != json!(true) {            if let (Some(id), Some(room)) = (s(&row, "id"), call["room"].as_str()) {                return Ok(Some((id, room.to_string(), call["video"] == json!(true))));            }        }    }    Ok(None)}/// A group's call line said to be over: it stops offering Join.fn mark_over(client: &ClientController, message: &str) -> Result<(), MethodError> {    let message = message.to_string();    write(client, "chat.groupCall.over", move |ctx| {        if let Some(row) = one(ctx, &format!("SELECT meta FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), t(&message)])? {            let mut meta = meta(&row);            meta["groupCall"]["over"] = json!(true);            let mut patch = Map::new();            patch.insert("meta".into(), meta);            cotton_tools::mcp::handlers::common::update_row(ctx, MESSAGES, &message, patch).map_err(|f| f.to_string())?;        }        Ok(Value::Null)    })?;    Ok(())}/// `chat.groupCall { thread }`: whether the group has a call going on now, asked of the room (members only).fn group_call(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let lines = list::lines();    let thread = request.get("thread").and_then(Value::as_str).filter(|v| !v.is_empty()).ok_or_else(|| cotton_chat::bad("thread", "required"))?.to_string();    let th = thread.clone();    let line = read(client, "chat.groupCall", move |ctx| Ok(live_line(ctx, &th)?.map(|(id, room, video)| json!({ "id": id, "room": room, "video": video })).unwrap_or(Value::Null)))?;    let Some(line) = line.as_object() else { return Ok(json!({ "live": false })) };    let (id, room, video) = (line["id"].as_str().unwrap_or_default().to_string(), line["room"].as_str().unwrap_or_default().to_string(), line["video"] == json!(true));    let here = {        let slot = client.call_slot().lock().unwrap_or_else(|p| p.into_inner());        slot.is_active() && slot.room.as_deref() == Some(room.as_str())    };    let status: cotton_core::calling::wire::CallStatus = match client.object_door() {        Some(door) => match door.send("GET", &super::calls::routes::status(&room), None) {            Ok(answer) => serde_json::from_value(answer).unwrap_or_default(),            // Offline: said as not known, never as over.            Err(_) => return Ok(json!({ "live": false, "room": room, "unknown": true })),        },        None => return Ok(json!({ "live": false, "room": room, "unknown": true })),    };    if !status.live && !here {        mark_over(client, &id)?;        return Ok(json!({ "live": false, "room": room }));    }    let numbers = status.joined.clone();    let named = read(client, "chat.groupCall.who", move |ctx| {        let found = who(ctx, &numbers)?;        Ok(json!(numbers.iter().map(|n| found.get(n).map_or_else(|| n.clone(), |w| w.name.clone())).collect::<Vec<_>>()))    })?;    let me = cotton_chat::me(client);    let people: Vec<String> = named.as_array().into_iter().flatten().zip(status.joined.iter()).filter(|(_, n)| me.as_deref() != Some(n.as_str())).filter_map(|(w, _)| w.as_str().map(str::to_string)).collect();    let video = status.video || video;    let banner = say(&lines, if video { "app.call.group.live.video" } else { "app.call.group.live.voice" }, &[]);    let mut answer = json!({ "live": true, "room": room, "video": video, "here": here, "banner": banner, "people": people, "count": status.joined.len() });    if !people.is_empty() {        answer["in"] = json!(say(&lines, "app.call.group.in", &[("names", &people.join(", "))]));    }    if here {        answer["hereText"] = json!(say(&lines, "app.call.group.here", &[]));    } else {        answer["join"] = json!(say(&lines, "app.call.group.join", &[]));    }    Ok(answer)}/// `chat.call { thread, join: true }`: into the group's call going on, late or again.fn join_group_call(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let lines = list::lines();    let thread = request.get("thread").and_then(Value::as_str).filter(|v| !v.is_empty()).ok_or_else(|| cotton_chat::bad("thread", "required"))?.to_string();    let th = thread.clone();    let found = read(client, "chat.call.join", move |ctx| {        let callable = callable(ctx, &th)?.unwrap_or_default();        let title = one(ctx, &format!("SELECT title FROM {THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), t(&th)])?.and_then(|r| s(&r, "title"));        Ok(json!({ "line": live_line(ctx, &th)?.map(|(_, room, video)| json!({ "room": room, "video": video })), "group": callable.group_id, "title": title }))    })?;    let Some(line) = found["line"].as_object() else { return Err(refuse(&lines, "no_call", "app.call.group.refused.over")) };    let mut asked = json!({ "room": line["room"], "video": request.get("video").and_then(Value::as_bool).unwrap_or(line["video"] == json!(true)), "group": found["group"], "name": found["title"] });    if asked["name"].is_null() {        asked.as_object_mut().map(|o| o.remove("name"));    }    if let Some(can) = request.get("can") {        asked["can"] = can.clone();    }    let mut answer = super::calls::over(client, "calls.enter", &asked, false).map_err(|error| match error.code.as_str() {        "in_a_call" => refuse(&lines, "in_a_call", "app.call.refused.in_a_call"),        _ => error,    })?;    {        let mut slot = client.call_slot().lock().unwrap_or_else(|p| p.into_inner());        if slot.room.as_ref().and_then(|r| line["room"].as_str().map(|l| l == r)) == Some(true) {            slot.thread = Some(thread.clone());            answer["call"]["thread"] = json!(thread);        }    }    // Not let in: said in the person's words.    if answer["call"]["phase"] == "ended" && answer["call"]["entered"] == json!(true) {        answer["refused"] = json!(say(&lines, "app.call.group.refused.over", &[]));    }    Ok(answer)}// ── chat.calls ──────────────────────────────────────────────────────────/// A call row's facts: Chat's own (`meta.chat`), else what the row's columns say (a call Calling wrote).pub(crate) fn facts_of(row: &Map<String, Value>) -> CallFacts {    let chat = meta(row)["chat"].clone();    if let Ok(facts) = serde_json::from_value::<CallFacts>(chat.clone()) {        return facts;    }    let direction = s(row, "direction").unwrap_or_else(|| "out".into());    let outcome = s(row, "outcome").unwrap_or_else(|| "failed".into());    CallFacts {        room: s(row, "external_id").unwrap_or_default(),        missed: direction == "in" && outcome == "missed",        reason: if outcome == "answered" { "hung_up".into() } else { outcome.clone() },        direction,        video: s(row, "kind").as_deref() == Some("video"),        outcome,        duration_s: row.get("duration_s").and_then(Value::as_i64).unwrap_or(0),        group: false,    }}fn parse_cursor(cursor: &str) -> Option<(String, String)> {    let (at, id) = cursor.split_once('\u{1f}')?;    Some((at.to_string(), id.to_string()))}fn calls(client: &ClientController, request: &Value) -> Result<CallsAnswer, MethodError> {    let lines = list::lines();    let after = request.get("after").and_then(Value::as_str).and_then(parse_cursor);    if after.is_none() {        // The Calls list opened: its missed calls are no longer noticed (`chat.notices`).        super::chat_app::notices::seen_calls(client);    }    let zone = client.time_zone().unwrap_or("Etc/UTC").to_string();    let now = client.clock().now();    let ns = namespace(client)?;    let found = read(client, "chat.calls", |ctx| {        let mut sql = format!("SELECT * FROM {CALLS} WHERE workspace_id = ? AND source = 'cotton'");        let mut params = vec![ws(ctx)];        if let Some((at, id)) = &after {            sql.push_str(" AND (started_at < ? OR (started_at = ? AND id < ?))");            params.extend([t(at), t(at), t(id)]);        }        sql.push_str(&format!(" ORDER BY started_at DESC, id DESC LIMIT {}", rules::PAGE + 1));        let found = rows(ctx, &sql, &params)?;        let mut numbers: Vec<String> = Vec::new();        for row in &found {            let chat = meta(row)["chat"].clone();            numbers.extend(chat["numbers"].as_array().into_iter().flatten().filter_map(|n| n.as_str().map(str::to_string)));            numbers.extend(s(row, "handle"));        }        numbers.sort();        numbers.dedup();        let named = who(ctx, &numbers)?;        let mut threads: HashMap<String, bool> = HashMap::new();        // Each entry: (started_at, id, row), calls and recordings together, newest first.        let mut out: Vec<(String, String, Value)> = Vec::new();        // The recordings, older than the cursor: notes taken on a call stand on its row, the rest as rows of their own.        let recordings = super::chat_recordings::listed(ctx, after.as_ref())?;        for row in found.iter() {            let facts = facts_of(row);            let chat = meta(row)["chat"].clone();            let people: Vec<String> = chat["numbers"].as_array().into_iter().flatten().filter_map(|n| n.as_str().map(str::to_string)).collect();            let handle = s(row, "handle");            let group = facts.group || people.len() > 1;            let (name, photo) = if group {                (names_of(&named, &people), None)            } else {                let number = handle.clone().or_else(|| people.first().cloned()).unwrap_or_default();                named.get(&number).map_or((number.clone(), None), |w| (w.name.clone(), w.photo.clone()))            };            let thread = match chat["thread"].as_str() {                Some(thread) => Some(thread.to_string()),                None => match handle.as_ref() { Some(n) => Some(super::cotton_chat::chat_with(ctx, &ns, n)?), None => None },            };            let thread = match thread {                Some(id) => {                    let here = match threads.get(&id) {                        Some(here) => *here,                        None => {                            let here = cotton_chat::exists(ctx, THREADS, &id)?;                            threads.insert(id.clone(), here);                            here                        }                    };                    here.then_some(id)                }                None => None,            };            let at = s(row, "started_at").unwrap_or_default();            let parts = stamp_parts(&at, &zone, now, DateWords::shipped());            let when = parts.as_ref().map(|p| p.recent.clone()).unwrap_or_default();            let day = parts.map(|p| p.heading).unwrap_or_default();            let key = thread.clone().or_else(|| handle.clone()).unwrap_or_else(|| s(row, "id").unwrap_or_default());            let id = s(row, "id").unwrap_or_default();            // A call's notes name its room, which is the call row's external id.            let room = s(row, "external_id").unwrap_or_default();            let notes = recordings.iter().find(|r| r.on_call.as_deref().is_some_and(|c| c == id || (!room.is_empty() && c == room))).map(|r| r.id.clone());            out.push((at.clone(), id.clone(), json!(CallRow {                call: id.clone(),                picture: Picture { photo, initials: lay::initials(&name), tint: lay::tint(&key) },                name,                thread,                incoming: facts.incoming(),                video: facts.video,                missed: facts.missed,                group,                line: rules::line(&lines, &facts),                when,                kind: "call".into(),                day,                mark: notes.as_ref().map(|_| "notes".to_string()),                recording: notes,            })));        }        // A recording stands as a row of its own unless a call's row holds it (its notes).        let held: Vec<String> = out.iter().filter_map(|(_, _, row)| row["recording"].as_str().map(str::to_string)).collect();        for r in recordings.iter().filter(|r| !held.contains(&r.id)) {            let parts = stamp_parts(&r.started_at, &zone, now, DateWords::shipped());            let row = CallRow {                call: r.id.clone(),                name: r.title.clone(),                picture: Picture { photo: None, initials: String::new(), tint: lay::tint(&r.id) },                thread: None,                incoming: false,                video: false,                missed: false,                group: false,                line: r.line.clone(),                when: parts.as_ref().map(|p| p.recent.clone()).unwrap_or_default(),                kind: "recording".into(),                day: parts.map(|p| p.heading).unwrap_or_default(),                recording: Some(r.id.clone()),                mark: Some(r.mark.clone()),            };            out.push((r.started_at.clone(), r.id.clone(), json!(row)));        }        out.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));        // A page is the newest PAGE of both together; a call row past the calls' own page is left for the next.        let calls_more = found.len() > rules::PAGE;        if calls_more {            let last = &found[rules::PAGE - 1];            let floor = (s(last, "started_at").unwrap_or_default(), s(last, "id").unwrap_or_default());            out.retain(|(at, id, _)| (at.as_str(), id.as_str()) >= (floor.0.as_str(), floor.1.as_str()));        }        let more = calls_more || out.len() > rules::PAGE;        out.truncate(rules::PAGE);        let next = more.then(|| out.last().map(|(at, id, _)| format!("{at}\u{1f}{id}"))).flatten();        let rows: Vec<Value> = out.into_iter().map(|(_, _, row)| row).collect();        Ok(json!({ "rows": rows, "next": next }))    })?;    let rows: Vec<CallRow> = serde_json::from_value(found["rows"].clone()).map_err(unreadable)?;    Ok(CallsAnswer {        rows,        next: found["next"].as_str().map(str::to_string),        words: CallsWords {            title: say(&lines, "app.calls.title", &[]),            empty: say(&lines, "app.calls.empty", &[]),            back: say(&lines, "app.call.back", &[]),            record: say(&lines, "app.calls.record", &[]),            import: say(&lines, "app.calls.import", &[]),        },    })}// ── chat.callScreen ─────────────────────────────────────────────────────fn screen(client: &ClientController, request: &Value) -> Result<rules::CallScreen, MethodError> {    let lines = list::lines();    let speaker = request.get("speaker").and_then(Value::as_bool).unwrap_or(false);    // The phone's audio routes and the one in use (`routes: [{id, kind, name?}]`, `route`): a headset makes the speaker a choice.    let routes: Vec<rules::AudioRoute> = request.get("routes").cloned().and_then(|r| serde_json::from_value(r).ok()).unwrap_or_default();    let route = request.get("route").and_then(Value::as_str);    let call = client.call_slot().lock().unwrap_or_else(|p| p.into_inner()).clone();    let (name, photo, key) = screen_who(client, &call)?;    let picture = Picture { photo, initials: lay::initials(&name), tint: lay::tint(&key) };    if call.mode != cotton_core::calling::wire::Mode::Sfu {        return Ok(rules::routed(&lines, &call, &name, picture, speaker, &routes, route, now_ms(client)));    }    // A group call's tiles, each named and pictured as Chat knows them.    let numbers: Vec<String> = call.members.iter().filter_map(|m| m.number.clone()).collect();    let found = read(client, "chat.callScreen.tiles", move |ctx| {        let named = who(ctx, &numbers)?;        Ok(json!(named.into_iter().map(|(n, w)| (n, json!({ "name": w.name, "photo": w.photo }))).collect::<Map<String, Value>>()))    })    .unwrap_or_else(|_| json!({}));    // This phone's own tile is pictured by its own profile (name and picture), never by its number's digits    // (launch-ios on dev, 23 Nov 2026: the iPhone's own tile read "15").    let own = super::chat_people::own_profile(client);    let own_name = own.as_ref().and_then(|p| p.name.clone());    let own_photo = own.as_ref().and_then(|p| p.picture.as_ref()).map(|_| client.layout().client_dir().join(super::chat_people::OWN_PICTURE)).filter(|p| p.exists()).map(|p| p.to_string_lossy().to_string());    let me = call.me.clone();    let named = |m: &cotton_core::calling::wire::Member| -> (String, Picture) {        let number = m.number.clone().unwrap_or_default();        if me.as_deref() == Some(m.id.as_str()) {            let name = own_name.clone().unwrap_or_else(|| number.clone());            return (name.clone(), Picture { photo: own_photo.clone(), initials: lay::initials(&name), tint: lay::tint(&number) });        }        let held = &found[number.as_str()];        let name = held["name"].as_str().map(str::to_string).filter(|n| n != &number).or_else(|| m.name.clone()).unwrap_or_else(|| number.clone());        let photo = held["photo"].as_str().map(str::to_string);        (name.clone(), Picture { photo, initials: lay::initials(&name), tint: lay::tint(&number) })    };    Ok(rules::group_screen(&lines, &call, &name, picture, speaker, &routes, route, now_ms(client), &named))}/// The names Chat knows `numbers` by, as the call screen names a group's tiles: a number Chat has no name for is left/// out. Take notes names each person's track so (chat CONTRACT.md "Take notes").pub(crate) fn names_of_numbers(client: &ClientController, numbers: &[String]) -> HashMap<String, String> {    let asked = numbers.to_vec();    read(client, "calls.notes.names", move |ctx| {        let named = who(ctx, &asked)?;        Ok(json!(named.into_iter().filter(|(n, w)| w.name != *n).map(|(n, w)| (n, json!(w.name))).collect::<Map<String, Value>>()))    })    .ok()    .and_then(|v| v.as_object().cloned())    .map(|m| m.into_iter().filter_map(|(n, w)| Some((n, w.as_str()?.to_string()))).collect())    .unwrap_or_default()}/// Who the call screen names: a group's people, else the other side as Chat names them.fn screen_who(client: &ClientController, call: &Call) -> Result<(String, Option<String>, String), MethodError> {    // A group's call is the group's: its name heads the screen (the tiles say who is in it).    if let (Some(_), Some(name)) = (&call.group, call.name.as_ref().filter(|n| !n.is_empty())) {        return Ok((name.clone(), None, call.thread.clone().unwrap_or_else(|| name.clone())));    }    let others: Vec<String> = if call.mode == cotton_core::calling::wire::Mode::Sfu {        call.members.iter().filter(|m| Some(&m.id) != call.me.as_ref()).filter_map(|m| m.number.clone()).collect()    } else {        call.number.iter().cloned().collect()    };    if others.is_empty() {        let name = call.name.clone().unwrap_or_default();        return Ok((name.clone(), None, call.thread.clone().unwrap_or(name)));    }    let numbers = others.clone();    let found = read(client, "chat.callScreen", move |ctx| {        let named = who(ctx, &numbers)?;        Ok(json!(numbers.iter().map(|n| { let w = named.get(n); json!({ "number": n, "name": w.map(|w| w.name.clone()), "photo": w.and_then(|w| w.photo.clone()) }) }).collect::<Vec<_>>()))    })    .unwrap_or_else(|_| json!([]));    let named: HashMap<String, Who> = found        .as_array()        .into_iter()        .flatten()        .filter_map(|w| Some((w["number"].as_str()?.to_string(), Who { name: w["name"].as_str()?.to_string(), photo: w["photo"].as_str().map(str::to_string) })))        .collect();    if others.len() > 1 {        return Ok((names_of(&named, &others), None, call.thread.clone().unwrap_or_else(|| others.join(","))));    }    let number = &others[0];    // The contact's name where Chat knows them, else who the core named them as, else the number.    let w = named.get(number).filter(|w| w.name != *number);    let name = w.map(|w| w.name.clone()).or_else(|| call.name.clone()).unwrap_or_else(|| number.clone());    let key = call.thread.clone().unwrap_or_else(|| number.clone());    Ok((name, w.and_then(|w| w.photo.clone()), key))}// ── chat.thread ─────────────────────────────────────────────────────────/// Chat's thread answer, with what calls add: the header's buttons and, on/// each call's line, its facts and words (said in this reader's words, not/// the writer's), tappable to call back.pub(crate) fn decorate_thread(client: &ClientController, thread: &str, answer: &mut Value) -> Result<(), MethodError> {    let lines = list::lines();    let events: Vec<String> = answer["items"].as_array().into_iter().flatten().filter(|i| i["item"] == "event").filter_map(|i| i["message"].as_str().map(str::to_string)).collect();    let thread = thread.to_string();    let zone = client.time_zone().unwrap_or("Etc/UTC").to_string();    let now = client.clock().now();    let found = read(client, "chat.thread.calls", move |ctx| {        let callable = callable(ctx, &thread)?.unwrap_or_default();        let mut lines_of = Map::new();        let mut group_lines = Map::new();        for id in &events {            if let Some(m) = one(ctx, &format!("SELECT id, meta, sent_at, channel FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), t(id)])? {                let meta = meta(&m);                let call = meta["call"].clone();                if call.is_object() {                    // A call his Mac read from WhatsApp (Mac 10) has no Cotton call to ring again.                    let cotton = matches!(s(&m, "channel").as_deref(), None | Some("") | Some(CHANNEL));                    lines_of.insert(id.clone(), json!({ "facts": call, "at": s(&m, "sent_at"), "cotton": cotton }));                }                // A group's call goes on after this phone leaves it: its line offers Join until the room says it is over.                if meta["groupCall"].is_object() && meta["groupCall"]["over"] != json!(true) {                    group_lines.insert(id.clone(), meta["groupCall"].clone());                }            }        }        Ok(json!({ "cotton": callable.cotton, "pending": callable.pending, "group": callable.group, "count": callable.numbers.len(), "lines": lines_of, "groupLines": group_lines }))    })?;    if let Some(buttons) = rules::buttons(&lines, found["cotton"] == json!(true), found["pending"] == json!(true), found["group"] == json!(true), found["count"].as_u64().unwrap_or(0) as usize) {        answer["header"]["calls"] = json!(buttons);    }    let ns = namespace(client)?;    for item in answer["items"].as_array_mut().into_iter().flatten() {        let Some(id) = item["message"].as_str().map(str::to_string) else { continue };        if let Some(live) = found["groupLines"].get(&id) {            // A group's call still said to go on: its line, and Join (the screen asks `chat.groupCall` whether it does).            item["groupCall"] = json!({ "room": live["room"], "video": live["video"], "join": say(&lines, "app.call.group.join", &[]) });            continue;        }        let Some(line) = found["lines"].get(&id) else { continue };        let Ok(facts) = serde_json::from_value::<CallFacts>(line["facts"].clone()) else { continue };        let at = line["at"].as_str().unwrap_or_default();        let time = stamp_parts(at, &zone, now, DateWords::shipped()).and_then(|p| p.clock).unwrap_or_default();        item["text"] = json!(rules::line(&lines, &facts));        // A WhatsApp call's line (Mac 10, CONTRACT "WhatsApp calls from the link") is its words alone: no `call` and no        // Call back, since no Cotton call row stands behind it; the phones draw it untappable.        let cotton = line["cotton"].as_bool().unwrap_or(true);        let (call, back) = if cotton { (call_id(&ns, &facts.room), say(&lines, "app.call.back", &[])) } else { (String::new(), String::new()) };        item["call"] = json!(ThreadCall { call, video: facts.video, missed: facts.missed, incoming: facts.incoming(), time, back });    }    Ok(())}// ── an ended call's traces ──────────────────────────────────────────────/// What Chat keeps on the ended call's `call` row (`meta.chat`): its facts,/// its conversation and everyone it rang, so the Calls tile can say it and ring again.pub(crate) fn row_meta(call: &Call) -> Option<Value> {    let facts = CallFacts::of(call)?;    let mut chat = serde_json::to_value(&facts).ok()?;    let numbers: Vec<String> = if facts.group {        call.members.iter().filter(|m| Some(&m.id) != call.me.as_ref()).filter_map(|m| m.number.clone()).collect()    } else {        call.number.iter().cloned().collect()    };    chat["numbers"] = json!(numbers);    if let Some(thread) = &call.thread {        chat["thread"] = json!(thread);    }    Some(json!({ "chat": chat }))}/// The ended call's line in its conversation, where this copy holds Chat and/// the conversation is here: the one Chat placed it from, else (a one-to-one/// call) the other person's. None when there is none, or it is written already.pub(crate) fn leave_line(client: &ClientController, call: &Call) -> Result<Option<String>, MethodError> {    let Some(facts) = CallFacts::of(call) else { return Ok(None) };    let ns = namespace(client)?;    let thread = match (&call.thread, facts.group, &call.number) {        (Some(thread), _, _) => thread.clone(),        (None, false, Some(number)) => super::cotton_chat::chat_with_number(client, &ns, number),        _ => return Ok(None),    };    let id = ids::message_id(&ns, "call", &facts.room);    let text = rules::line(&list::lines(), &facts);    let at = iso(call.started_at);    let room = facts.room.clone();    let facts = json!(facts);    let written = write(client, "chat.callLine", move |ctx| {        if !holds(ctx, MESSAGES, "meta")? || !cotton_chat::exists(ctx, THREADS, &thread)? {            return Ok(Value::Null);        }        if let Some(held) = one(ctx, &format!("SELECT meta FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), t(&id)])? {            // A group's call line becomes this call's own line once it is over here. The call itself may go on            // without this phone, so the line is not said over: the room says that (chat.groupCall's mark_over).            let mut kept = meta(&held);            if !kept["groupCall"].is_object() || kept["call"].is_object() {                return Ok(Value::Null);            }            kept["call"] = facts.clone();            let mut patch = Map::new();            patch.insert("body".into(), json!(text));            patch.insert("meta".into(), kept);            cotton_tools::mcp::handlers::common::update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?;            return Ok(json!(id));        }        let mut columns = Map::new();        columns.insert("thread_id".into(), json!(thread));        columns.insert("direction".into(), json!(if facts["direction"] == "in" { "in" } else { "out" }));        columns.insert("channel".into(), json!(CHANNEL));        columns.insert("origin".into(), json!("live"));        columns.insert("body".into(), json!(text));        columns.insert("external_id".into(), json!(format!("call:{room}")));        columns.insert("sent_at".into(), json!(at));        columns.insert("meta".into(), json!({ "system": true, "call": facts }));        insert_row(ctx, MESSAGES, &id, columns).map_err(|f| f.to_string())?;        cotton_chat::touch_thread(ctx, &thread, &at, Some(&text), false)?;        Ok(json!(id))    })?;    Ok(written.as_str().map(str::to_string))}#[cfg(test)]#[path = "chat_calls_tests.rs"]mod tests;