Cotton code
1044 lines · 58.0 KB · RustRaw
//! `chat.group.*` — Cotton groups on this phone (20 Nov//! 2026). Every decision is the core's ([`cotton_core::chat::group`]): this//! keeps a group's op log on its thread row, folds it, writes the seats and//! the event lines the chat screens already draw, seals each message and each//! change once for every member device, and tells this person's own object//! who is in each group so their envelopes are no stranger's.//!//! ```text//! chat.group.create   { title, members: [number | { number } | { person }], privateKey? } → { thread, group }//! chat.group.add      { thread, members: [...], privateKey? }                          → { ok }//! chat.group.remove   { thread, member, privateKey? }                                  → { ok }//! chat.group.leave    { thread, privateKey? }                                          → { ok }//! chat.group.admin    { thread, member, admin: bool, privateKey? }                     → { ok }//! chat.group.rename   { thread, title, privateKey? }                                   → { ok }//! chat.group.picture  { thread, path?, mime?, width?, height?, privateKey? }           → { ok }   (no path: taken away)//! chat.group.info     { thread }                                                       → the group as drawn (CONTRACT.md)//! chat.group.receipts { message }                                                      → { members: [{ number, name, state }] }//! chat.group.photo    { thread, dir }                                                  → { path, mime } | { path: null }//! ```//!//! **Changes wait on the row until told.** A change is written into the log//! here at once (the screens redraw from it), with whom it is still to be//! told; `chat.flush` (or the method itself, given the key) tells them. A//! change that cannot go yet stays and goes on the next pass, so a change made//! offline is never lost.//!//! **What the Worker learns.** It routes each member's boxes as it routes a//! one-to-one message, so it sees, as it already does one to one, which//! numbers this person writes to and when; it also sees that the envelope//! names a group (a random id) and how many members it went to. This person's//! own object keeps the group's members' numbers keyed under its own key (so//! it can take their envelopes as a friend's): never a name, a picture or a//! word. Nobody learns a number is on Cotton by being added: an added number//! that is not on Cotton is sealed for with the same made-up key a one-to-one//! message gets, and no member sees a delivered tick from someone until that//! person has joined.use std::collections::{BTreeMap, BTreeSet, HashMap};use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use cotton_client::transport::object::ObjectRefusal;use cotton_core::chat::group::{self, Accept, Op, State, What as Change};use cotton_core::chat::payload::{Item, Kind, Payload, Picture, Receipt};use cotton_core::chat::{files, ids, outbox, seal, CHANNEL};use cotton_core::constants::GroupEventKind;use cotton_core::messages::{GroupEvent, MessageSystem};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{insert_row, update_row};use super::cotton_chat::{    ask, bad, e164, exists, fresh_id, iso, keys_many, meta_value, namespace, not_connected, now_ms, one, person_of, private_key_of, read, refused, rows, seal_for, text, touch_thread, words, write, ws, CONTACTS, MESSAGES, THREADS,};use crate::methods::MethodError;use crate::shell::client::ClientController;pub const METHODS: [&str; 10] = ["chat.group.add", "chat.group.admin", "chat.group.create", "chat.group.info", "chat.group.leave", "chat.group.photo", "chat.group.picture", "chat.group.receipts", "chat.group.remove", "chat.group.rename"];pub(crate) const SEATS: &str = "cotton_msg_thread_participants";/// A group thread's external key: never a number's (`cotton:+…`), still a Cotton conversation's (`cotton:`).const KEY_PREFIX: &str = "cotton:group:";/// Keys asked again for a group's members after this long: a member's new phone gets boxes within it.pub const GROUP_KEYS_FRESH_MS: i64 = 30 * 60_000;/// A group envelope from someone this phone cannot yet place (a group it has no head for, a sender not/// yet known to be in it) stays held this long, tried again at each pass, then is let go.pub const WAIT_MS: i64 = 24 * 3_600_000;pub fn over(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "chat.group.create" => create(client, request),        "chat.group.add" => change(client, request, |r| Ok(Change::Add { members: members_of(client, r)? })),        "chat.group.remove" => change(client, request, |r| Ok(Change::Remove { members: vec![member_of(r)?] })),        "chat.group.leave" => change(client, request, |_| Ok(Change::Leave)),        "chat.group.admin" => change(client, request, |r| {            let member = member_of(r)?;            Ok(if r.get("admin").and_then(Value::as_bool).ok_or_else(|| bad("admin", "true or false"))? { Change::Admin { members: vec![member] } } else { Change::Unadmin { members: vec![member] } })        }),        "chat.group.rename" => change(client, request, |r| Ok(Change::Rename { title: text(r, "title")?.trim().to_string() })),        "chat.group.picture" => change(client, request, |r| Ok(Change::Picture { picture: picture_up(client, r)? })),        "chat.group.info" => info(client, request),        "chat.group.receipts" => receipts(client, request),        "chat.group.photo" => photo(client, request),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a group method"))),    }}// ── the log on the row ──────────────────────────────────────────────────/// What a group thread keeps (`thread.group_log`, sealed with the row).#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]pub(crate) struct Kept {    pub group: String,    #[serde(default)]    pub ops: Vec<Op>,    /// Changes still to be told: whose, and to whom.    #[serde(default)]    pub told: Vec<Telling>,    /// The members this person's object was last told of (`None`: never told; empty: told they left).    #[serde(default)]    pub registered: Option<Vec<String>>,    /// The person refused this group's invitation: whatever it sends goes, unsaid, and nobody learns this phone is on Cotton.    #[serde(default, skip_serializing_if = "std::ops::Not::not")]    pub refused: bool,    /// This person's agents the Worker was last told are in this group (`None`: never told), as    /// `/v1/agents/chat` holds them (an agent in a chat, `chat_agent`).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub agents_told: Option<Vec<String>>,}#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]pub(crate) struct Telling {    /// The envelope's id.    pub id: String,    /// The ops it carries, by id; empty with `whole`: the log as it stands when it goes.    #[serde(default)]    pub ops: Vec<String>,    #[serde(default)]    pub whole: bool,    pub to: Vec<String>,    /// This person's own other devices get it too.    #[serde(default)]    pub own: bool,}pub fn thread_id(ns: &str, group: &str) -> String {    cotton_core::cotton_rules::ids::derived_id("cotton_msg_threads", &[ns, CHANNEL, &format!("group:{group}")])}pub(crate) fn seat_id(ns: &str, group: &str, number: &str) -> String {    cotton_core::cotton_rules::ids::derived_id(SEATS, &[ns, CHANNEL, group, number])}pub fn group_of_key(key: &str) -> Option<&str> {    key.strip_prefix(KEY_PREFIX).filter(|g| group::is_group_id(g))}fn kept_of(ctx: &mut Ctx<'_>, thread: &str) -> Result<Option<Kept>, String> {    let row = one(ctx, &format!("SELECT group_log FROM {THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(thread.to_string())])?;    Ok(row.and_then(|r| r.get("group_log").and_then(Value::as_str).and_then(|t| serde_json::from_str(t).ok())))}/// The group a thread is, by its id: its log, or a refusal when the thread is no Cotton group.pub(crate) fn kept_for(client: &ClientController, thread: &str) -> Result<Kept, MethodError> {    let id = thread.to_string();    let found = read(client, "chat.group", move |ctx| Ok(kept_of(ctx, &id)?.map(|k| serde_json::to_value(k).unwrap_or(Value::Null)).unwrap_or(Value::Null)))?;    serde_json::from_value(found).map_err(|_| {        // A Cotton group whose log this copy lost: its members are being asked for it (`ask_lost`).        if is_group_thread(client, thread) {            words("group_restoring", "Getting this group back from its members. Try again in a moment.")        } else {            words("not_group", "This chat isn't a Cotton group.")        }    })}/// This phone's own number, known once its object has answered.fn me(client: &ClientController) -> Result<String, MethodError> {    super::cotton_chat::my_number(client).ok_or_else(not_connected)}// ── making changes ──────────────────────────────────────────────────────fn create(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let me = me(client)?;    let title = text(request, "title")?.trim().to_string();    let members = members_of(client, request)?;    let op = group::create(&me, &fresh_id(), now_ms(client), &title, &members).map_err(refusal)?;    let gid = fresh_id();    let ns = namespace(client)?;    let state = group::fold(std::slice::from_ref(&op));    let kept = Kept { group: gid.clone(), ops: vec![op.clone()], told: vec![Telling { id: fresh_id(), ops: vec![], whole: true, to: state.audience(&me), own: true }], registered: None, refused: false, agents_told: None };    let names = names_for(client, &state);    let (g, m, k) = (gid.clone(), me.clone(), kept.clone());    let thread = write(client, "chat.group.create", move |ctx| {        let thread = ensure_group_thread(ctx, &ns, &g, &title, Some("accepted"))?;        store(ctx, &ns, &thread, &k, &m, &names, &[op.id.clone()], Some(op.at))?;        Ok(Value::from(thread))    })?;    let thread = thread.as_str().unwrap_or_default().to_string();    flush_now(client, request);    Ok(json!({ "thread": thread, "group": gid }))}/// A change by this person: checked by the core, written into the log at once, told now or at the next pass.pub(crate) fn change(client: &ClientController, request: &Value, what: impl FnOnce(&Value) -> Result<Change, MethodError>) -> Result<Value, MethodError> {    let me = me(client)?;    let thread = text(request, "thread")?.to_string();    let mut kept = kept_for(client, &thread)?;    let before = group::fold(&kept.ops);    let op = group::make(&before, &me, &fresh_id(), now_ms(client), what(request)?).map_err(refusal)?;    kept.ops.push(op.clone());    let after = group::fold(&kept.ops);    let told = group::told(&before, &after, &op, &me);    // This person's own other phones are told too, whoever else is.    kept.told.push(Telling { id: fresh_id(), ops: vec![op.id.clone()], whole: false, to: told, own: true });    let welcomed = group::welcomed(&before, &after);    if !welcomed.is_empty() {        kept.told.push(Telling { id: fresh_id(), ops: vec![], whole: true, to: welcomed, own: false });    }    let ns = namespace(client)?;    let names = names_for(client, &after);    let (t, m) = (thread.clone(), me.clone());    write(client, "chat.group.change", move |ctx| store(ctx, &ns, &t, &kept, &m, &names, &[op.id.clone()], Some(op.at)).map(|_| Value::Null))?;    flush_now(client, request);    Ok(json!({ "ok": true }))}/// Told now when the call carries the key; else the shell's next `chat.flush` tells it.fn flush_now(client: &ClientController, request: &Value) {    if let Ok(secret) = private_key_of(request) {        let _ = flush(client, &secret);    }}pub(crate) fn refusal(why: group::Refusal) -> MethodError {    words(why.code(), why.words())}/// Numbers from `members`: each a number, `{ number }` or `{ person }` (their first phone).fn members_of(client: &ClientController, request: &Value) -> Result<Vec<String>, MethodError> {    let list = request.get("members").and_then(Value::as_array).ok_or_else(|| bad("members", "numbers, or { number } or { person }"))?;    let mut out = Vec::new();    for entry in list {        let number = match entry {            Value::String(n) => e164(n),            Value::Object(o) => match (o.get("number").and_then(Value::as_str), o.get("person").and_then(Value::as_str)) {                (Some(n), _) => e164(n),                (None, Some(p)) => super::cotton_chat::first_number(client, p)?,                _ => None,            },            _ => None,        };        out.push(number.ok_or_else(|| words("bad_number", "That isn't a phone number Cotton can use. Start it with + and the country code."))?);    }    out.sort();    out.dedup();    Ok(out)}fn member_of(request: &Value) -> Result<String, MethodError> {    e164(text(request, "member")?).ok_or_else(|| words("bad_number", "That isn't a phone number Cotton can use."))}/// A new group picture put up sealed (its key travels in the op); no `path` takes the picture away.fn picture_up(client: &ClientController, request: &Value) -> Result<Option<Picture>, MethodError> {    let Some(path) = request.get("path").and_then(Value::as_str) else { return Ok(None) };    let plain = std::fs::read(path).map_err(|e| MethodError::new("unreadable", format!("the picture could not be read ({e})")))?;    let sealed = files::seal_file(&plain).ok_or_else(|| words("picture_too_large", "That picture is too large to send."))?;    let answer = super::cotton_chat::put_sealed(client, &sealed.bytes).map_err(refused)?;    Ok(Some(Picture {        file: answer["file"].as_str().unwrap_or_default().to_string(),        key: seal::key_text(&sealed.key),        sha256: sealed.sha256,        mime: request.get("mime").and_then(Value::as_str).unwrap_or("image/jpeg").to_string(),        width: request.get("width").and_then(Value::as_u64).map(|w| w as u32),        height: request.get("height").and_then(Value::as_u64).map(|h| h as u32),        bytes: plain.len() as u64,        ..Default::default()    }))}// ── the rows ────────────────────────────────────────────────────────────/// The thread for a group, made when new; `request` sets a new one's request state.fn ensure_group_thread(ctx: &mut Ctx<'_>, ns: &str, group: &str, title: &str, request: Option<&str>) -> Result<String, String> {    let thread = thread_id(ns, group);    if !exists(ctx, THREADS, &thread)? {        let mut columns = Map::new();        columns.insert("kind".into(), json!("group"));        // A group's thread always has a name (the table's check): its own, as the log says.        columns.insert("title".into(), json!(if title.trim().is_empty() { "Group" } else { title }));        columns.insert("external_key".into(), json!(format!("{KEY_PREFIX}{group}")));        columns.insert("archived".into(), json!(false));        columns.insert("group_log".into(), json!(serde_json::to_string(&Kept { group: group.to_string(), ..Kept::default() }).unwrap_or_default()));        if let Some(request) = request {            if super::cotton_chat::holds(ctx, THREADS, "request")? {                columns.insert("request".into(), json!(request));            }        }        insert_row(ctx, THREADS, &thread, columns).map_err(|f| f.to_string())?;    }    Ok(thread)}/// Names this phone knows the group's people by, by number: Your people first, else the name its chats know them/// by (the address book's, from "Find people I know", or the one they gave themselves), never a bare number.fn names_for(client: &ClientController, state: &State) -> HashMap<String, (Option<String>, Option<String>)> {    let known = chat_names(client);    state        .seats        .keys()        .map(|n| {            let (person, name) = person_of(client, n);            (n.clone(), (person, name.or_else(|| known.get(n.trim_start_matches('+')).cloned())))        })        .collect()}/// The names this phone's chat contacts carry, by their number's digits, where one is more than the number.fn chat_names(client: &ClientController) -> HashMap<String, String> {    let found = super::cotton_chat::read(client, "chat.group.names", |ctx| {        let rows = super::cotton_chat::rows(ctx, "SELECT phone_e164, display_name FROM cotton_msg_contacts WHERE workspace_id = ? AND phone_e164 IS NOT NULL AND display_name IS NOT NULL", &[super::cotton_chat::ws(ctx)])?;        Ok(Value::Object(            rows.iter()                .filter_map(|r| {                    let digits = r.get("phone_e164")?.as_str()?.trim_start_matches('+').to_string();                    let name = r.get("display_name")?.as_str()?.trim().to_string();                    (!name.is_empty() && name.trim_start_matches('+') != digits).then(|| (digits, json!(name)))                })                .collect(),        ))    });    found.ok().and_then(|v| v.as_object().cloned()).map(|m| m.into_iter().filter_map(|(k, v)| Some((k, v.as_str()?.to_string()))).collect()).unwrap_or_default()}/// The log written back, and from it: the title, whether this person may send, each seat, and a line for each op that counted and is new here.#[allow(clippy::too_many_arguments)]fn store(ctx: &mut Ctx<'_>, ns: &str, thread: &str, kept: &Kept, me: &str, names: &HashMap<String, (Option<String>, Option<String>)>, new: &[String], at: Option<i64>) -> Result<State, String> {    let state = group::fold(&kept.ops);    let mut patch = Map::new();    patch.insert("group_log".into(), json!(serde_json::to_string(kept).unwrap_or_default()));    if state.made {        patch.insert("title".into(), json!(state.title));    }    if let Some(creator) = &state.creator {        patch.insert("created_by_phone".into(), json!(creator.trim_start_matches('+')));    }    let member = state.is_member(me);    if super::cotton_chat::holds(ctx, THREADS, "sendable")? {        patch.insert("sendable".into(), json!(i64::from(member)));        patch.insert("send_blocked_reason".into(), if member || !state.made { Value::Null } else { json!(group::Refusal::NotMember.words()) });    }    update_row(ctx, THREADS, thread, patch).map_err(|f| f.to_string())?;    for (number, seat) in &state.seats {        let id = seat_id(ns, &kept.group, number);        let you = number == me;        let (person, name) = names.get(number).cloned().unwrap_or((None, None));        let mut columns = Map::new();        columns.insert("role".into(), json!(if seat.admin { "admin" } else { "member" }));        columns.insert("left_at".into(), if seat.member { Value::Null } else { json!(iso(at.unwrap_or(0))) });        columns.insert("is_self".into(), json!(you));        columns.insert("display_name".into(), json!(name.clone().unwrap_or_else(|| number.clone())));        if exists(ctx, SEATS, &id)? {            update_row(ctx, SEATS, &id, columns).map_err(|f| f.to_string())?;        } else {            columns.insert("thread_id".into(), json!(thread));            if !you {                columns.insert("contact_id".into(), json!(ensure_contact(ctx, ns, number, name.as_deref(), person.as_deref())?));            }            if let Some(person) = &person {                columns.insert("person_id".into(), json!(person));            }            insert_row(ctx, SEATS, &id, columns).map_err(|f| f.to_string())?;        }    }    let applied: BTreeSet<&str> = state.applied.iter().map(String::as_str).collect();    for op in kept.ops.iter().filter(|op| new.contains(&op.id) && applied.contains(op.id.as_str())) {        event_line(ctx, ns, thread, op, me, names, at.unwrap_or(op.at))?;    }    Ok(state)}/// The contact a member's number is, made when new.fn ensure_contact(ctx: &mut Ctx<'_>, ns: &str, number: &str, name: Option<&str>, person: Option<&str>) -> Result<String, String> {    let digits = number.trim_start_matches('+').to_string();    if let Some(row) = one(ctx, &format!("SELECT id FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), SqlValue::Text(digits.clone())])? {        let id = row.get("id").and_then(Value::as_str).unwrap_or_default().to_string();        crate::phone::cotton_chat::contact_handle_here(ctx, ns, &id, &digits)?;        return Ok(id);    }    let id = ids::contact_id(ns, number);    let mut columns = Map::new();    columns.insert("phone_e164".into(), json!(digits));    columns.insert("display_name".into(), json!(name.unwrap_or(number)));    if let Some(person) = person {        columns.insert("person_id".into(), json!(person));    }    insert_row(ctx, CONTACTS, &id, columns).map_err(|f| f.to_string())?;    crate::phone::cotton_chat::contact_handle_here(ctx, ns, &id, &digits)?;    Ok(id)}/// The centred line an op that counted leaves in the conversation: created, added, removed, left, renamed, a new picture. Admin changes leave none (the members list says who is one).fn event_line(ctx: &mut Ctx<'_>, ns: &str, thread: &str, op: &Op, me: &str, names: &HashMap<String, (Option<String>, Option<String>)>, at: i64) -> Result<(), String> {    let (kind, subjects, title) = match &op.what {        Change::Create { title, .. } => (GroupEventKind::Created, None, Some(title.clone())),        Change::Add { members } => (GroupEventKind::Added, Some(members.clone()), None),        Change::Remove { members } => (GroupEventKind::Removed, Some(members.clone()), None),        Change::Leave => (GroupEventKind::Left, None, None),        Change::Rename { title } => (GroupEventKind::Renamed, None, Some(title.trim().to_string())),        Change::Picture { .. } => (GroupEventKind::Photo, None, None),        Change::Admin { .. } | Change::Unadmin { .. } => return Ok(()),        Change::Agent { agent, on } => return agent_line(ctx, ns, thread, op, agent, *on, me, names, at),    };    let digits = |n: &str| n.trim_start_matches('+').to_string();    let event = GroupEvent { kind, actor: (op.by != me).then(|| digits(&op.by)), subjects: subjects.map(|s| s.iter().map(|n| digits(n)).collect()), title };    let name_for = |phone: Option<&str>| -> Option<String> {        match phone {            None => Some("You".to_string()),            Some(d) if format!("+{d}") == me => Some("you".to_string()),            // Nobody this phone knows: the number as a number is written, with its "+", never bare digits.            Some(d) => names.get(&format!("+{d}")).and_then(|(_, n)| n.clone()).or_else(|| Some(format!("+{d}"))),        }    };    let body = cotton_core::messages::group_event::group_event_sentence(&event, &name_for);    let id = ids::message_id(ns, &format!("op:{}", op.by), &op.id);    if exists(ctx, MESSAGES, &id)? {        return Ok(());    }    let sent_at = iso(at);    let mut columns = Map::new();    columns.insert("thread_id".into(), json!(thread));    columns.insert("direction".into(), json!(if op.by == me { "out" } else { "in" }));    columns.insert("channel".into(), json!(CHANNEL));    columns.insert("origin".into(), json!("live"));    columns.insert("body".into(), json!(body));    columns.insert("external_id".into(), json!(format!("op:{}", op.id)));    columns.insert("sent_at".into(), json!(sent_at));    columns.insert("read_at".into(), json!(sent_at));    columns.insert("meta".into(), json!({ "system": serde_json::to_value(MessageSystem::Event(event)).unwrap_or(Value::Null), "cotton": { "op": op.id } }));    insert_row(ctx, MESSAGES, &id, columns).map_err(|f| f.to_string())?;    touch_thread(ctx, thread, &sent_at, Some(&body), false)}/// The line an agent's coming or going leaves (an agent in a chat): "Asha added Claude, an agent", "You added/// Claude, your agent", "Claude left" (its person took it out, or left), "Asha removed Claude" (an admin).#[allow(clippy::too_many_arguments)]fn agent_line(ctx: &mut Ctx<'_>, ns: &str, thread: &str, op: &Op, agent: &group::AgentId, on: bool, me: &str, names: &HashMap<String, (Option<String>, Option<String>)>, at: i64) -> Result<(), String> {    let actor = names.get(&op.by).and_then(|(_, n)| n.clone()).unwrap_or_else(|| op.by.clone());    let id = ids::message_id(ns, &format!("op:{}", op.by), &op.id);    if exists(ctx, MESSAGES, &id)? {        return Ok(());    }    let kept = kept_of(ctx, thread)?.unwrap_or_default();    // Whose it is: its person taking it out says it left; anyone else removed it.    let person = group::fold(&kept.ops).agents.get(&agent.id).map(|a| a.of.clone());    let lines = super::chat_agent::lines();    let name = agent.name.trim();    let fill = [("actor", actor.as_str()), ("agent", name)];    let line_id = match (on, op.by == me, person.as_deref() == Some(op.by.as_str())) {        (true, true, _) => "app.group.agent_added_you",        (true, false, _) => "app.group.agent_added",        (false, _, true) => "app.group.agent_left",        (false, true, false) => "app.group.agent_removed_you",        (false, false, false) => "app.group.agent_removed",    };    let body = lines.as_ref().and_then(|l| l.say(line_id, &fill)).unwrap_or_else(|| name.to_string());    let sent_at = iso(at);    let mut columns = Map::new();    columns.insert("thread_id".into(), json!(thread));    columns.insert("direction".into(), json!(if op.by == me { "out" } else { "in" }));    columns.insert("channel".into(), json!(CHANNEL));    columns.insert("origin".into(), json!("live"));    columns.insert("body".into(), json!(body));    columns.insert("external_id".into(), json!(format!("op:{}", op.id)));    columns.insert("sent_at".into(), json!(sent_at));    columns.insert("read_at".into(), json!(sent_at));    columns.insert("meta".into(), json!({ "system": true, "cotton": { "op": op.id, "agent_event": on } }));    insert_row(ctx, MESSAGES, &id, columns).map_err(|f| f.to_string())?;    touch_thread(ctx, thread, &sent_at, Some(&body), false)}// ── telling ─────────────────────────────────────────────────────────────/// Every group's changes still to be told, and every object registration out of date: the outbox's part for groups.pub(crate) fn flush(client: &ClientController, secret: &[u8; 32]) -> Result<usize, MethodError> {    let asked = ask_lost(client, secret);    let groups = read(client, "chat.groups", |ctx| {        if !super::cotton_chat::holds(ctx, THREADS, "group_log")? {            return Ok(json!([]));        }        // A copy before the object's definitions holds no request column: nothing there is a request.        let request = if super::cotton_chat::holds(ctx, THREADS, "request")? { "request" } else { "NULL AS request" };        Ok(Value::Array(rows(ctx, &format!("SELECT id, group_log, {request} FROM {THREADS} WHERE workspace_id = ? AND group_log IS NOT NULL"), &[ws(ctx)])?.into_iter().map(Value::Object).collect()))    })?;    if groups.as_array().is_none_or(Vec::is_empty) {        return Ok(asked);    }    let Some(me) = super::cotton_chat::my_number(client) else { return Ok(asked) };    let mut told = asked;    for row in groups.as_array().into_iter().flatten() {        let Some(mut kept) = row["group_log"].as_str().and_then(|t| serde_json::from_str::<Kept>(t).ok()) else { continue };        let thread = row["id"].as_str().unwrap_or_default().to_string();        let accepted = row["request"].as_str() != Some("pending");        let before = kept.clone();        let mut left = Vec::new();        for telling in std::mem::take(&mut kept.told) {            if !accepted {                left.push(telling);                continue;            }            if tell_ops(client, secret, &me, &kept, &telling).is_ok() {                told += 1;            } else {                left.push(telling);            }        }        kept.told = left;        let state = group::fold(&kept.ops);        if accepted {            let want = if state.is_member(&me) { state.audience(&me) } else { vec![] };            if kept.registered.as_ref() != Some(&want) && state.made {                if ask(client, "POST", "/v1/chat/group", Some(&json!({ "group": kept.group, "members": want }))).is_ok() {                    kept.registered = Some(want);                }            }        }        if accepted && state.made {            // This person's own agents here, as the Worker should hold them: told when they differ (chat_agent).            let want: Vec<String> = if state.is_member(&me) { state.agents_on().into_iter().filter(|(_, a)| a.of == me).map(|(id, _)| id.clone()).collect() } else { vec![] };            if kept.agents_told.as_ref() != Some(&want) && (kept.agents_told.is_some() || !want.is_empty()) {                let was = kept.agents_told.clone().unwrap_or_default();                if super::chat_agent::tell_worker(client, &thread, &state, &was, &want).is_ok() {                    kept.agents_told = Some(want);                }            }        }        if kept.told.len() != before.told.len() || kept.registered != before.registered || kept.agents_told != before.agents_told {            let k = kept.clone();            write(client, "chat.group.told", move |ctx| {                let mut patch = Map::new();                patch.insert("group_log".into(), json!(serde_json::to_string(&k).unwrap_or_default()));                update_row(ctx, THREADS, &thread, patch).map_err(|f| f.to_string())?;                Ok(Value::Null)            })?;        }    }    Ok(told)}/// One telling: the ops it names (or the whole log) sealed for each of its people's devices and, when it says so, this person's own.fn tell_ops(client: &ClientController, secret: &[u8; 32], me: &str, kept: &Kept, telling: &Telling) -> Result<(), ObjectRefusal> {    let ops: Vec<Op> = if telling.whole { kept.ops.clone() } else { kept.ops.iter().filter(|op| telling.ops.contains(&op.id)).cloned().collect() };    if ops.is_empty() {        return Ok(());    }    let at = ops.iter().map(|o| o.at).max().unwrap_or(0);    let make = |to: &str| Payload::group_ops(&telling.id, me, to, at, &kept.group, ops.clone());    send_group(client, secret, me, &kept.group, &telling.to, telling.own, Kind::Group, &telling.id, &make).map(|_| ())}/// One envelope said in a group: a payload for each member (and this person's own devices), each sealed for that member's devices.#[allow(clippy::too_many_arguments)]pub(crate) fn send_group(client: &ClientController, secret: &[u8; 32], me: &str, group: &str, to: &[String], own: bool, kind: Kind, id: &str, make: &dyn Fn(&str) -> Payload) -> Result<i64, ObjectRefusal> {    match seal_and_send(client, secret, me, group, to, own, kind, id, make, GROUP_KEYS_FRESH_MS) {        // A member's devices (or this person's own) changed since the keys were kept: asked again, sealed again, once.        Err(refusal) if refusal.code == super::cotton_chat::STALE_DEVICES => seal_and_send(client, secret, me, group, to, own, kind, id, make, 0),        other => other,    }}#[allow(clippy::too_many_arguments)]fn seal_and_send(client: &ClientController, secret: &[u8; 32], me: &str, group: &str, to: &[String], own: bool, kind: Kind, id: &str, make: &dyn Fn(&str) -> Payload, fresh_ms: i64) -> Result<i64, ObjectRefusal> {    let (peers, own_keys) = if to.is_empty() { (HashMap::new(), super::cotton_chat::own_keys(client)?) } else { keys_many(client, to, fresh_ms)? };    let mut boxes = Map::new();    for number in to {        let Some(devices) = peers.get(number) else { continue };        let sealed = seal_for(client, secret, number, devices, &make(number))?;        if !sealed.is_empty() {            boxes.insert(number.clone(), Value::Object(sealed));        }    }    // `check`: the Worker may refuse a message sealed for devices of before (stale_devices); `send_group` seals again.    let mut body = json!({ "id": id, "kind": kind.as_str(), "group": group, "to": boxes, "check": true });    if own && !own_keys.is_empty() {        body["own"] = Value::Object(seal_for(client, secret, me, &own_keys, &make(me))?);    }    if boxes_empty(&body) {        // Nobody to tell (a group of one, with no other device): told.        return Ok(now_ms(client));    }    let answer = ask(client, "POST", "/v1/chat/group/send", Some(&body))?;    Ok(answer["at"].as_i64().unwrap_or_else(|| now_ms(client)))}fn boxes_empty(body: &Value) -> bool {    body["to"].as_object().is_none_or(Map::is_empty) && body["own"].as_object().is_none_or(Map::is_empty)}// ── a message's try ─────────────────────────────────────────────────────/// A message in a group: sealed for every current member's devices and this person's own; the members it went to kept on the row, each at "sent".pub(crate) fn attempt(client: &ClientController, secret: &[u8; 32], row: &Value, message: &dyn Fn(&str) -> Payload) -> Result<(i64, Value), ObjectRefusal> {    let thread = row["thread_id"].as_str().unwrap_or_default().to_string();    let local = |m: String| ObjectRefusal { status: 400, code: "refused".into(), message: m };    let kept = kept_for(client, &thread).map_err(|e| local(e.message))?;    let me = super::cotton_chat::my_number(client).ok_or_else(|| local("this phone's number is not known yet".into()))?;    let state = group::fold(&kept.ops);    if !state.is_member(&me) {        return Err(ObjectRefusal { status: 403, code: "not_member".into(), message: group::Refusal::NotMember.words().into() });    }    let audience = state.audience(&me);    let id = row["external_id"].as_str().unwrap_or_default().to_string();    let make = |to: &str| message(to).in_group(&kept.group);    let at = send_group(client, secret, &me, &kept.group, &audience, true, Kind::Message, &id, &make)?;    let receipts: Map<String, Value> = audience.iter().map(|n| (n.clone(), json!("sent"))).collect();    Ok((at, Value::Object(receipts)))}// ── arrivals ────────────────────────────────────────────────────────────/// What one group envelope came to.#[derive(Debug, Default)]pub(crate) struct Arrival {    /// Keep it held: tried again at the next pass.    pub wait: bool,    pub landed: Option<Value>,    pub receipt: Option<Value>,    pub changed: Option<Value>,    /// A delivered tick owed to its author: (their number, the message's id).    pub tick: Option<(String, String)>,    /// A new group to tell the shell of (a request, or one joined).    pub request: Option<String>,}/// One opened envelope said in a group, `item.group` its group.pub(crate) fn arrive(client: &ClientController, ns: &str, me: &str, item: &Item, payload: &Payload, now: i64) -> Result<Arrival, MethodError> {    let gid = item.group.clone().unwrap_or_default();    let thread = thread_id(ns, &gid);    let sender = if item.out { me.to_string() } else { item.peer.clone() };    let t = thread.clone();    let kept = read(client, "chat.group.arrive", move |ctx| Ok(kept_of(ctx, &t)?.map(|k| serde_json::to_value(k).unwrap_or(Value::Null)).unwrap_or(Value::Null)))?;    let kept: Kept = serde_json::from_value(kept).unwrap_or_else(|_| Kept { group: gid.clone(), ..Kept::default() });    if kept.refused {        return Ok(Arrival::default());    }    let late = now.saturating_sub(item.at) > WAIT_MS;    let wait = |a: Arrival| if late { Ok(Arrival::default()) } else { Ok(Arrival { wait: true, ..a }) };    if payload.kind == Kind::Group && payload.ask {        // A member whose copy lost the log asks for it ([`ask_lost`]): answered with the whole log, to them alone        // (to this person's own devices when it is this person), only while both are in the group by this log.        let state = group::fold(&kept.ops);        if kept.ops.is_empty() || !state.is_member(me) || !state.is_member(&sender) {            return Ok(Arrival::default());        }        let own = sender == me;        let mut next = kept.clone();        next.told.push(Telling { id: fresh_id(), ops: vec![], whole: true, to: if own { vec![] } else { vec![sender.clone()] }, own });        let t = thread.clone();        write(client, "chat.group.asked", move |ctx| {            let mut patch = Map::new();            patch.insert("group_log".into(), json!(serde_json::to_string(&next).unwrap_or_default()));            update_row(ctx, THREADS, &t, patch).map_err(|f| f.to_string())?;            Ok(Value::Null)        })?;        return Ok(Arrival::default());    }    if payload.kind == Kind::Group {        let accept = group::merge(&kept.ops, &payload.ops, &sender, me);        let (log, new) = match accept {            Accept::Merged { log, new } => (log, new),            Accept::Wait => return wait(Arrival::default()),            Accept::Refuse => return Ok(Arrival::default()),        };        if new.is_empty() {            return Ok(Arrival::default());        }        let before = group::fold(&kept.ops);        let fresh_thread = kept.ops.is_empty();        let mut next = Kept { group: gid.clone(), ops: log, told: kept.told.clone(), registered: kept.registered.clone(), refused: false, agents_told: kept.agents_told.clone() };        let after = group::fold(&next.ops);        // Someone else brought people in: what this person changed themselves goes to them too, so their log is whole.        let mine: Vec<String> = next.ops.iter().filter(|op| op.by == me).map(|op| op.id.clone()).collect();        let welcomed: Vec<String> = group::welcomed(&before, &after).into_iter().filter(|n| n != me && *n != sender).collect();        if !mine.is_empty() && !welcomed.is_empty() && before.is_member(me) {            next.told.push(Telling { id: fresh_id(), ops: mine, whole: false, to: welcomed, own: false });        }        let names = names_for(client, &after);        let title = after.title.clone();        let (n, m, nw) = (ns.to_string(), me.to_string(), new.clone());        let request = if item.request && fresh_thread { Some("pending") } else if fresh_thread { Some("accepted") } else { None };        let at = item.at;        write(client, "chat.group.land", move |ctx| {            let thread = ensure_group_thread(ctx, &n, &next.group, &title, request)?;            store(ctx, &n, &thread, &next, &m, &names, &nw, Some(at)).map(|_| Value::Null)        })?;        return Ok(Arrival { changed: Some(json!({ "thread": thread, "group": gid })), request: fresh_thread.then(|| thread.clone()), ..Arrival::default() });    }    let state = group::fold(&kept.ops);    // Said by someone this phone does not (yet) hold in the group: kept waiting for the change that puts them there.    if !state.is_member(&sender) || !state.is_member(me) {        return if state.made && !state.is_member(me) { Ok(Arrival::default()) } else { wait(Arrival::default()) };    }    // Marked as an agent's: it must be one of its sender's agents in this group now, or it claims what is not there.    if let Some(agent) = &payload.agent {        if !state.is_agent_of(&agent.id, &sender) {            return Ok(Arrival::default());        }    }    match payload.kind {        Kind::Message => {            let (person, name) = person_of(client, &sender);            let (n, it, p, g, s) = (ns.to_string(), item.clone(), payload.clone(), gid.clone(), sender.clone());            let answer = write(client, "chat.group.message", move |ctx| land(ctx, &n, &g, &it, &p, &s, person.as_deref(), name.as_deref()))?;            if answer["new"] != json!(true) {                return Ok(Arrival::default());            }            let pending = answer["request"] == json!(true);            let group_name = state.title.clone();            let said = person_of(client, &sender).1;            Ok(Arrival {                landed: Some(json!({ "thread": thread, "message": answer["message"], "out": item.out, "request": pending, "peer": sender, "name": group_name, "group": true, "sender": said })),                tick: (!item.out && !pending).then(|| (sender.clone(), payload.id.clone())),                ..Arrival::default()            })        }        Kind::Receipt => {            let (n, it, p) = (ns.to_string(), item.clone(), payload.clone());            let audience = state.members();            let moved = write(client, "chat.group.receipt", move |ctx| receipt(ctx, &n, &it, &p, &audience))?;            Ok(Arrival { receipt: Some(json!({ "thread": thread, "state": payload.state, "messages": moved, "from": sender })), ..Arrival::default() })        }        Kind::Change => {            let (it, p, s, n) = (item.clone(), payload.clone(), sender.clone(), ns.to_string());            let t = thread.clone();            let answer = write(client, "chat.group.change", move |ctx| super::cotton_chat::apply_change_in(ctx, &n, &t, &it, &p, &s))?;            Ok(Arrival { changed: (!answer.is_null()).then_some(answer), ..Arrival::default() })        }        Kind::Typing | Kind::Group | Kind::Agent => Ok(Arrival::default()),    }}/// One group message into its conversation; one already here is not written again.#[allow(clippy::too_many_arguments)]fn land(ctx: &mut Ctx<'_>, ns: &str, group: &str, item: &Item, payload: &Payload, sender: &str, person: Option<&str>, name: Option<&str>) -> Result<Value, String> {    let thread = thread_id(ns, group);    let request = super::cotton_chat::request_state(ctx, &thread)?.as_deref() == Some("pending");    let author = if item.out { ids::ME } else { sender };    let id = ids::message_id(ns, author, &payload.id);    if exists(ctx, MESSAGES, &id)? {        return Ok(json!({ "message": id, "new": false, "request": request }));    }    let sent_at = iso(item.at);    let mut columns = Map::new();    columns.insert("thread_id".into(), json!(thread));    columns.insert("direction".into(), json!(if item.out { "out" } else { "in" }));    columns.insert("channel".into(), json!(CHANNEL));    columns.insert("origin".into(), json!("live"));    // An agent's words are its own body; the labelled `body` is for phones that know no agents.    let words = payload.agent.as_ref().and_then(|a| a.body.clone()).or_else(|| payload.body.clone());    columns.insert("body".into(), json!(words.clone().unwrap_or_default()));    columns.insert("external_id".into(), json!(payload.id));    columns.insert("sent_at".into(), json!(sent_at));    if item.out {        columns.insert("send_state".into(), json!("sent"));    } else {        columns.insert("sender_participant_id".into(), json!(seat_id(ns, group, sender)));        // The sender is its seat (the participant), whose row carries the contact; the contact is made here when the seat is new.        ensure_contact(ctx, ns, sender, name, person)?;    }    if let Some(reply) = &payload.reply_to {        columns.insert("reply_to_external_id".into(), json!(reply));        let replied = one(ctx, &format!("SELECT id FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND external_id = ?"), &[ws(ctx), SqlValue::Text(thread.clone()), SqlValue::Text(reply.clone())])?;        if let Some(replied) = replied.and_then(|row| row.get("id").and_then(Value::as_str).map(str::to_string)) {            columns.insert("reply_to_id".into(), json!(replied));        }    }    let mut meta = json!({ "cotton": { "pictures": payload.pictures, "written_at": iso(payload.at), "from": sender } });    if let Some(agent) = &payload.agent {        meta["cotton"]["agent"] = json!({ "id": agent.id, "name": agent.name });    }    if let Some(seconds) = payload.timer {        super::chat_timer::stamp(&mut meta, payload.at, seconds);    }    columns.insert("meta".into(), meta);    insert_row(ctx, MESSAGES, &id, columns).map_err(|f| f.to_string())?;    super::cotton_chat::link_waiting_replies(ctx, &thread, &payload.id, &id)?;    touch_thread(ctx, &thread, &sent_at, words.as_deref(), !payload.pictures.is_empty())?;    Ok(json!({ "message": id, "new": true, "request": request }))}/// A member's receipt about this person's message: their own state on it moves forward, and the message's when every member it went to is there.fn receipt(ctx: &mut Ctx<'_>, ns: &str, item: &Item, payload: &Payload, members: &[String]) -> Result<Value, String> {    let state = match payload.state {        Some(Receipt::Read) => "read",        _ => "delivered",    };    let mut moved = Vec::new();    for external in &payload.ids {        if item.out {            // This person read it on another phone.            let Some(row) = one(ctx, &format!("SELECT id FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND external_id = ? AND direction = 'in'"), &[ws(ctx), SqlValue::Text(thread_id(ns, item.group.as_deref().unwrap_or_default())), SqlValue::Text(external.clone())])? else { continue };            if state == "read" {                let id = row.get("id").and_then(Value::as_str).unwrap_or_default().to_string();                let mut patch = Map::new();                patch.insert("read_at".into(), json!(iso(payload.at)));                update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?;                moved.push(json!(id));            }            continue;        }        let id = ids::message_id(ns, ids::ME, external);        let Some(row) = one(ctx, &format!("SELECT send_state, meta FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.clone())])? else { continue };        let mut meta = meta_value(row.get("meta").unwrap_or(&Value::Null));        let Some(each) = meta["cotton"]["receipts"].as_object_mut() else { continue };        let Some(current) = each.get(&item.peer).and_then(Value::as_str).map(str::to_string) else { continue };        let next = outbox::advanced(&current, state).to_string();        if next == current {            continue;        }        each.insert(item.peer.clone(), json!(next));        let whole = whole_state(each, members);        let mut patch = Map::new();        patch.insert("meta".into(), meta.clone());        let now = row.get("send_state").and_then(Value::as_str).unwrap_or("sent").to_string();        let advanced = outbox::advanced(&now, &whole).to_string();        if advanced != now {            patch.insert("send_state".into(), json!(advanced));        }        update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?;        moved.push(json!(id));    }    Ok(Value::Array(moved))}/// A group message's own tick: the least any member it went to (and is still in the group) has reached.pub(crate) fn whole_state(each: &Map<String, Value>, members: &[String]) -> String {    let counted: Vec<&str> = each.iter().filter(|(n, _)| members.is_empty() || members.contains(n)).filter_map(|(_, s)| s.as_str()).collect();    counted.into_iter().min_by_key(|s| outbox::rank(s)).unwrap_or("sent").to_string()}// ── what the screens read ───────────────────────────────────────────────fn info(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let thread = text(request, "thread")?.to_string();    let kept = kept_for(client, &thread)?;    let me = me(client)?;    let state = group::fold(&kept.ops);    let can = group::can(&state, &me);    let t = thread.clone();    let request_state = read(client, "chat.group.info", move |ctx| Ok(super::cotton_chat::request_state(ctx, &t)?.map(Value::from).unwrap_or(Value::Null)))?;    let mut members: Vec<Value> = Vec::new();    let mut past: Vec<Value> = Vec::new();    for (number, seat) in &state.seats {        let (person, name) = person_of(client, number);        let you = number == &me;        let entry = json!({            "number": number,            "name": if you { "You".to_string() } else { name.clone().unwrap_or_else(|| number.clone()) },            "known": name.is_some(),            "person": person,            "you": you,            "admin": seat.admin,            "addedBy": seat.added_by,            "out": match &seat.out { Some(group::Out::Left) => json!("left"), Some(group::Out::Removed { .. }) => json!("removed"), None => Value::Null },        });        if seat.member { members.push(entry) } else { past.push(entry) }    }    // You first, then admins, then by name.    members.sort_by(|a, b| (!a["you"].as_bool().unwrap_or(false), !a["admin"].as_bool().unwrap_or(false), a["name"].as_str().unwrap_or("").to_lowercase()).cmp(&(!b["you"].as_bool().unwrap_or(false), !b["admin"].as_bool().unwrap_or(false), b["name"].as_str().unwrap_or("").to_lowercase())));    let state_word = if !state.made { "arriving" } else if request_state.as_str() == Some("pending") { "invited" } else if state.is_member(&me) { "member" } else if matches!(state.seats.get(&me).and_then(|s| s.out.clone()), Some(group::Out::Removed { .. })) { "removed" } else { "left" };    Ok(json!({        "thread": thread,        "group": kept.group,        "title": state.title,        "picture": state.picture.is_some(),        "members": members,        "past": past,        "count": state.members().len(),        "max": group::MEMBERS_MAX,        "you": state_word,        "can": can,        "waiting": kept.told.len(),        "createdBy": state.creator,        "agents": super::chat_agent::info_agents(client, &state, &me),        "canAgents": state.is_member(&me) && state_word == "member",    }))}fn receipts(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let message = text(request, "message")?.to_string();    let m = message.clone();    let row = read(client, "chat.group.receipts", move |ctx| Ok(one(ctx, &format!("SELECT meta, send_state, direction FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(m.clone())])?.map(Value::Object).unwrap_or(Value::Null)))?;    if row.is_null() {        return Err(words("not_found", "This message isn't here any more."));    }    let meta = meta_value(&row["meta"]);    let each: BTreeMap<String, String> = meta["cotton"]["receipts"].as_object().map(|o| o.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))).collect()).unwrap_or_default();    let members: Vec<Value> = each        .iter()        .map(|(number, state)| {            let (_, name) = person_of(client, number);            json!({ "number": number, "name": name.unwrap_or_else(|| number.clone()), "state": state })        })        .collect();    Ok(json!({ "message": message, "state": row["send_state"], "members": members }))}/// The group's picture, fetched, opened and checked, written into `dir`; none when it has none.fn photo(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let thread = text(request, "thread")?.to_string();    let dir = std::path::PathBuf::from(text(request, "dir")?);    let kept = kept_for(client, &thread)?;    let Some(picture) = group::fold(&kept.ops).picture else { return Ok(json!({ "path": null })) };    super::cotton_chat::open_picture(client, &picture, &dir, true)}/// How often a lost group's members are asked again for its log.const ASK_AGAIN_MS: i64 = 10 * 60_000;/// When each lost group was last asked for, by thread: once per ten minutes, whatever the pass rate.static ASKED: std::sync::LazyLock<std::sync::Mutex<HashMap<String, i64>>> = std::sync::LazyLock::new(Default::default);/// Group threads whose log this copy lost (a copy filled from the object before the log went with the row, owner's/// bug 28 Nov 2026): the members its seats name and this person's own other devices are asked for the whole log; a/// member answers with it ([`arrive`], `ask`) and it merges as a welcome does, checked op by op. Nobody is put in a/// group from here: the seats only say whom to ask.fn ask_lost(client: &ClientController, secret: &[u8; 32]) -> usize {    let lost = read(client, "chat.group.lost", |ctx| {        if !super::cotton_chat::holds(ctx, THREADS, "group_log")? {            return Ok(json!([]));        }        let sql = format!(            "SELECT t.id, t.external_key, (SELECT json_group_array(c.phone_e164) FROM {SEATS} s JOIN {CONTACTS} c ON c.id = s.contact_id \               WHERE s.thread_id = t.id AND s.left_at IS NULL AND COALESCE(s.is_self, 0) = 0) AS numbers \             FROM {THREADS} t WHERE t.workspace_id = ? AND t.group_log IS NULL AND t.external_key LIKE 'cotton:group:%'"        );        Ok(Value::Array(rows(ctx, &sql, &[ws(ctx)])?.into_iter().map(Value::Object).collect()))    });    let Ok(Value::Array(lost)) = lost else { return 0 };    if lost.is_empty() {        return 0;    }    let Some(me) = super::cotton_chat::my_number(client) else { return 0 };    let me = me.as_str();    let now = now_ms(client);    let mut asked = 0;    for row in lost {        let (Some(thread), Some(group)) = (row["id"].as_str(), row["external_key"].as_str().and_then(group_of_key)) else { continue };        {            let mut held = ASKED.lock().unwrap_or_else(std::sync::PoisonError::into_inner);            if held.get(thread).is_some_and(|at| now - at < ASK_AGAIN_MS) {                continue;            }            held.insert(thread.to_string(), now);        }        let numbers: Vec<String> = row["numbers"]            .as_str()            .and_then(|list| serde_json::from_str::<Vec<Value>>(list).ok())            .unwrap_or_default()            .iter()            .filter_map(|n| n.as_str().map(|d| format!("+{}", d.trim_start_matches('+'))))            .filter(|n| n != me)            .collect();        let id = fresh_id();        match send_group(client, secret, me, group, &numbers, true, Kind::Group, &id, &|to| Payload::group_ask(&id, me, to, now, group)) {            Ok(_) => {                asked += 1;                tracing::info!("chat.group: asked {} members and this person's devices for a lost group's log", numbers.len());            }            Err(refusal) => tracing::warn!("chat.group: a lost group's log could not be asked for ({})", refusal.code),        }    }    asked}/// A refusal, in the person's words, when this person may not write in the group now.pub(crate) fn can_send(client: &ClientController, thread: &str) -> Result<(), MethodError> {    let kept = kept_for(client, thread)?;    let me = me(client)?;    if group::fold(&kept.ops).is_member(&me) { Ok(()) } else { Err(refusal(group::Refusal::NotMember)) }}/// The group a thread is.pub(crate) fn group_of_thread(client: &ClientController, thread: &str) -> Result<String, MethodError> {    Ok(kept_for(client, thread)?.group)}/// A reaction, edit or delete in a group: to every current member and this person's own other devices.pub(crate) fn tell_change(client: &ClientController, secret: &[u8; 32], thread: &str, me: &str, make: &dyn Fn(&str) -> Payload) -> Result<(), ObjectRefusal> {    let local = |m: String| ObjectRefusal { status: 400, code: "refused".into(), message: m };    let kept = kept_for(client, thread).map_err(|e| local(e.message))?;    let state = group::fold(&kept.ops);    if !state.is_member(me) {        // Out of the group: a change has nobody to go to, and is let go.        return Ok(());    }    let id = make(me).id;    let group_id = kept.group.clone();    send_group(client, secret, me, &kept.group, &state.audience(me), true, Kind::Change, &id, &|to| make(to).in_group(&group_id)).map(|_| ())}/// Whether a thread is a Cotton group's, by its external key.pub(crate) fn is_group_thread(client: &ClientController, thread: &str) -> bool {    let id = thread.to_string();    read(client, "chat.group.is", move |ctx| Ok(one(ctx, &format!("SELECT external_key FROM {THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.clone())])?.and_then(|r| r.get("external_key").and_then(Value::as_str).map(|k| Value::Bool(group_of_key(k).is_some()))).unwrap_or(Value::Bool(false))))        .map(|v| v == Value::Bool(true))        .unwrap_or(false)}/// The person's answer to a group they were invited to: joined (their object told who is in it, the group's request gone), or refused (the thread and what it brought go; the object told they are not in it).pub(crate) fn decide(client: &ClientController, thread: &str, verb: &str) -> Result<Value, MethodError> {    let mut kept = kept_for(client, thread)?;    let me = me(client)?;    let state = group::fold(&kept.ops);    let now = now_iso_of(client);    match verb {        "accept" => {            let want = state.audience(&me);            ask(client, "POST", "/v1/chat/group", Some(&json!({ "group": kept.group, "members": want }))).map_err(refused)?;            kept.registered = Some(want);        }        "refuse" | "block" => {            let _ = ask(client, "POST", "/v1/chat/group", Some(&json!({ "group": kept.group, "members": [] })));            kept.registered = Some(vec![]);            kept.refused = true;            kept.told.clear();            // A block is of whoever added this person: they are blocked as one to one.            if verb == "block" {                if let Some(adder) = state.seats.get(&me).map(|s| s.added_by.clone()).filter(|a| a != &me) {                    super::cotton_chat::over(client, "chat.block", &json!({ "number": adder }))?;                }            }        }        _ => {}    }    let (t, v) = (thread.to_string(), verb.to_string());    write(client, "chat.group.decide", move |ctx| {        let mut patch = Map::new();        patch.insert("group_log".into(), json!(serde_json::to_string(&kept).unwrap_or_default()));        if super::cotton_chat::holds(ctx, THREADS, "request")? {            patch.insert("request".into(), json!(if v == "accept" { "accepted" } else { "pending" }));        }        if v != "accept" {            patch.insert("trashed_at".into(), json!(now));            for row in rows(ctx, &format!("SELECT id FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND trashed_at IS NULL"), &[ws(ctx), SqlValue::Text(t.clone())])? {                let mut gone = Map::new();                gone.insert("trashed_at".into(), json!(now));                update_row(ctx, MESSAGES, row.get("id").and_then(Value::as_str).unwrap_or_default(), gone).map_err(|f| f.to_string())?;            }        }        update_row(ctx, THREADS, &t, patch).map_err(|f| f.to_string())?;        Ok(Value::Null)    })?;    Ok(json!({ "ok": true }))}fn now_iso_of(client: &ClientController) -> String {    iso(now_ms(client))}#[cfg(test)]#[path = "chat_group_tests.rs"]pub(crate) mod tests;