Cotton code
2784 lines ยท 156.7 KB ยท RustRaw
//! Cotton Chat on this phone: `chat.list`, `chat.thread`, `chat.compose`//! and `chat.act`, answered from the phone's own copy (the shapes are//! `cotton_core::messages::app::shapes`; `shapes.md` in the lane folder).//!//! Speed is designed in (owner, 19 Nov 2026): the list reads every//! conversation's few cheap columns once, by index, and names and last//! lines only for the page it answers; a thread reads one page through//! `idx_cotton_msg_messages_thread_sent` by a (sent_at, id) cursor, plus the//! one message on each side of the page so runs and dividers meet without a//! seam. A send writes the copy and answers its bubble before any network//! (`chat.flush` sends it). Every word is the kit's (`chat` set, `app.*`).use std::collections::{HashMap, HashSet};use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use cotton_core::chat::payload::What;use cotton_core::messages::app::bubble::{self, Row};use cotton_core::messages::app::can::Can;use cotton_core::messages::app::compose::{self, Quoted};use cotton_core::messages::app::lay::{self, Laid, Slot};use cotton_core::messages::app::list::{self, say, Listed};use cotton_core::messages::app::shapes::*;use cotton_core::messages::display::{direct_name, group_name};use cotton_core::messages::unread::is_muted;use cotton_core::messages::{MessageMedia, MessageMeta};use cotton_core::records::page::{stamp_parts, DateWords, Moment};use cotton_core::rules::shell_lines::LineSet;use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{insert_row, update_row};use super::cotton_chat::{self, bad, one, rows, 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";const REACTIONS: &str = "cotton_msg_reactions";/// Unread and jump counts stop here and say "999+": a badge, never a walk through the thread.const COUNT_CEILING: i64 = cotton_core::messages::app::shapes::COUNT_CEILING as i64;const SELF_ACTOR: &str = cotton_core::constants::REACTION_ACTOR_SELF;/// Emoji a react row offers first.const QUICK: [&str; 6] = ["๐Ÿ‘", "โค๏ธ", "๐Ÿ˜‚", "๐Ÿ˜ฎ", "๐Ÿ˜ข", "๐Ÿ™"];/// Every method this module answers.pub const METHODS: [&str; 36] = ["chat.act", "chat.compose", "chat.downloads", "chat.downloads.act", "chat.downloads.send", "chat.export", "chat.ground", "chat.link", "chat.list", "chat.mail", "chat.mail.act", "chat.mail.compose", "chat.mail.countSender", "chat.mail.discard", "chat.mail.file", "chat.mail.free", "chat.mail.page", "chat.mail.hold", "chat.mail.save", "chat.mail.send", "chat.mail.sender", "chat.mail.thread", "chat.mail.trashSender", "chat.notices", "chat.search", "chat.sender.act", "chat.sender.ask", "chat.sender.page", "chat.senders", "chat.senders.blocked", "chat.starred", "chat.text", "chat.theme", "chat.theme.set", "chat.themes", "chat.thread"];#[path = "chat_notices.rs"]pub(crate) mod notices;#[path = "chat_search.rs"]mod search;#[path = "chat_whatsapp.rs"]pub(crate) mod whatsapp_send;#[path = "chat_mail.rs"]pub(crate) mod mail;#[path = "chat_downloads.rs"]pub(crate) mod downloads;#[path = "chat_senders.rs"]pub(crate) mod senders;#[path = "chat_export.rs"]mod export;/// Answer a `chat.*` method. WHILE THE COPY HAS NOT COME WHOLE (its first/// pull under way, or failing: `phone::copy_standing`) an empty list says/// so in place of "No chats yet", and a chat or message not found is/// `not_here_yet`, never "no longer here" (incident, 21 Nov 2026).pub fn call(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    use crate::phone::copy_standing;    match answer(client, method, request) {        Ok(mut answer) if method == "chat.list" => {            // Cotton's own Downloads chat stands in every list (3e20835c64): it is not the person's chats            // having come, so a list holding only it still says the copy is coming or unreached.            let has_rows = answer["rows"].as_array().is_some_and(|rows| rows.iter().any(|row| row["thread"] != downloads::THREAD));            copy_standing::said_on_list(copy_standing::of(client), &mut answer, &["words", "empty"], has_rows);            answer["places"] = places(client);            Ok(answer)        }        Err(refused) if refused.code == "not_found" => Err(copy_standing::not_here(copy_standing::of(client), refused)),        answered => answered,    }}/// The places Comms' floating switch holds, in order, each `{ id, label }`: Chats, Calls, You. The core decides; the/// phones draw these and no other (they drew four of their own until 22 Nov 2026). Mail is Cotton Post's now/// (COMMS WITHOUT MAIL, mail CONTRACT row 21): his mail stays in his database, and Post reads it there.fn places(_client: &ClientController) -> Value {    let lines = list::lines();    Value::Array(["chats", "calls", "you"].into_iter().map(|id| json!({ "id": id, "label": say(&lines, &format!("app.place.{id}"), &[]) })).collect())}/// `chat.link { url }` โ†’ `{ url, sites: { ios: { live, dev }, android: { package, dev_package, extra } } }`: where a/// web link tapped in Comms goes (COMMS WITHOUT MAIL; sites CONTRACT row 8, "links handed to Sites"). The phone hands/// it to Cotton Sites, saying it came from Comms, when Sites is on the phone, and else reads it in its own in-app/// browser (a Custom Tab, Safari's sheet). Comms keeps no sites of its own. A link that is not a web address is/// refused, in Sites' words.fn link(request: &Value) -> Result<Value, MethodError> {    let url = request.get("url").and_then(Value::as_str).unwrap_or_default().trim().to_string();    let scheme = url.split_once(':').map(|(s, _)| s.to_lowercase()).unwrap_or_default();    if !matches!(scheme.as_str(), "http" | "https") {        return Err(MethodError::new("not_web", say(&list::lines(), "app.sites.refused.address", &[])));    }    let encoded: String = url::form_urlencoded::byte_serialize(url.as_bytes()).collect();    Ok(json!({        "url": url,        "sites": {            "ios": { "live": format!("cottonsites://open?url={encoded}&from=comms"), "dev": format!("cottonsitesdev://open?url={encoded}&from=comms") },            "android": { "package": "com.cottondb.sites", "dev_package": "com.cottondb.sites.dev", "action": "android.intent.action.VIEW", "extra": { "from": "comms" } },        },    }))}fn answer(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    let answer = match method {        "chat.notices" => {            let mut answer = serde_json::to_value(notices::answer(client)?).map_err(|e| MethodError::new("unanswerable", e.to_string()))?;            answer["downloads"] = Value::Array(downloads::notices(client)?);            return Ok(answer);        }        "chat.list" => return list_with_downloads(client, request),        "chat.downloads" => return downloads::page(client, request),        "chat.downloads.send" => return downloads::send(client, request),        "chat.downloads.act" => return downloads::act(client, request, &downloads::object_of(client)),        "chat.act" if request.get("thread").and_then(Value::as_str) == Some(downloads::THREAD) => return downloads::act(client, request, &downloads::object_of(client)),        "chat.export" => return export::export(client, request),        "chat.search" => return search::answer(client, request),        "chat.senders" => return senders::page(client, request),        "chat.sender.ask" => return senders::ask(client, request),        "chat.sender.act" => return senders::act(client, request),        "chat.senders.blocked" => return senders::blocked_place(client),        "chat.starred" => return search::starred(client, request),        "chat.link" => return link(request),        "chat.mail" | "chat.mail.thread" | "chat.mail.file" | "chat.mail.free" | "chat.mail.page" | "chat.mail.compose" | "chat.mail.save" | "chat.mail.send" | "chat.mail.discard" | "chat.mail.sender" | "chat.mail.countSender" | "chat.mail.trashSender" | "chat.mail.hold" | "chat.mail.act" | "chat.sender.page" => return mail::answer(client, method, request),        "chat.thread" => serde_json::to_value(thread_answer(client, request)?),        "chat.compose" => serde_json::to_value(compose_answer(client, request)?),        "chat.act" => serde_json::to_value(act(client, request)?),        "chat.themes" => serde_json::to_value(themes_answer(client)?),        "chat.theme.set" | "chat.theme" => serde_json::to_value(set_theme(client, request)?),        "chat.text" => serde_json::to_value(set_choice(client, request, "text", "value")?),        "chat.ground" => serde_json::to_value(set_choice(client, request, "ground", "ground")?),        other => return Err(MethodError::new("unknown_method", format!("`{other}` is not a chat method"))),    };    answer.map_err(|e| MethodError::new("unanswerable", e.to_string()))}// โ”€โ”€ reading the copy โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€fn read<T>(client: &ClientController, label: &str, mut work: impl FnMut(&mut Ctx<'_>) -> Result<T, String>) -> Result<T, MethodError> {    let mut out: Option<T> = None;    cotton_chat::read(client, label, |ctx| {        out = Some(work(ctx)?);        Ok(Value::Null)    })?;    out.ok_or_else(|| MethodError::new("unreadable", "the copy answered nothing"))}fn write<T>(client: &ClientController, label: &str, mut work: impl FnMut(&mut Ctx<'_>) -> Result<T, String>) -> Result<T, MethodError> {    let mut out: Option<T> = None;    cotton_chat::write(client, label, |ctx| {        out = Some(work(ctx)?);        Ok(Value::Null)    })?;    out.ok_or_else(|| MethodError::new("write_refused", "the copy wrote nothing"))}fn s(row: &Map<String, Value>, key: &str) -> Option<String> {    row.get(key).and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()).map(str::to_string)}fn n(row: &Map<String, Value>, key: &str) -> i64 {    match row.get(key) {        Some(Value::Number(n)) => n.as_i64().or_else(|| n.as_f64().map(|f| f as i64)).unwrap_or(0),        Some(Value::String(t)) => t.parse().unwrap_or(0),        _ => 0,    }}fn truthy(row: &Map<String, Value>, key: &str) -> bool {    match row.get(key) {        Some(Value::Bool(b)) => *b,        Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0,        Some(Value::String(t)) => t == "1" || t == "true",        _ => false,    }}fn text(value: String) -> SqlValue {    SqlValue::Text(value)}fn holes(count: usize) -> String {    vec!["?"; count].join(", ")}/// Rows whose `column` is one of `ids`, in chunks SQLite takes.fn rows_in(ctx: &mut Ctx<'_>, select: &str, column: &str, ids: &[String]) -> Result<Vec<Map<String, Value>>, String> {    let mut out = Vec::new();    for batch in ids.chunks(400) {        let sql = format!("{select} AND {column} IN ({})", holes(batch.len()));        let mut params = vec![ws(ctx)];        params.extend(batch.iter().cloned().map(text));        out.extend(rows(ctx, &sql, &params)?);    }    Ok(out)}/// Columns this copy's table holds, asked once per read.fn columns_of(ctx: &mut Ctx<'_>, table: &str) -> Result<HashSet<String>, String> {    Ok(rows(ctx, &format!("SELECT name FROM pragma_table_info('{table}')"), &[])?.iter().filter_map(|r| s(r, "name")).collect())}/// A message's attachments: an import's `media` entries, then a Cotton/// message's files (`meta.cotton.pictures`, sealed in the chat file store,/// opened by `chat.picture`), then those still waiting to go up/// (`meta.cotton.pending_pictures`, on this phone).fn media_of(row: &Map<String, Value>) -> Vec<MessageMedia> {    let parsed = match row.get("media") {        Some(Value::String(t)) => serde_json::from_str::<Value>(t).unwrap_or(Value::Null),        Some(v) => v.clone(),        None => Value::Null,    };    // A Cotton file kept in the person's own media is named in `media` too (`chat_files::keep`): drawn once, from its picture.    let mut media: Vec<MessageMedia> = parsed.as_array().into_iter().flatten().filter(|entry| entry["cottonKept"] != json!(true)).filter_map(|entry| serde_json::from_value(entry.clone()).ok()).collect();    let meta = cotton_chat::meta_value(row.get("meta").unwrap_or(&Value::Null));    for (list, key) in [("pictures", "file"), ("pending_pictures", "path")] {        for p in meta["cotton"][list].as_array().into_iter().flatten() {            let Some(at) = p[key].as_str() else { continue };            let wave: Vec<f64> = p["waveform"].as_array().into_iter().flatten().filter_map(Value::as_f64).map(|v| if list == "pictures" { v / 255.0 } else { v }).collect();            media.push(MessageMedia {                key: at.to_string(),                content_type: p["mime"].as_str().unwrap_or("image/jpeg").to_string(),                name: p["name"].as_str().map(str::to_string),                width: p["width"].as_f64(),                height: p["height"].as_f64(),                size_bytes: p["bytes"].as_f64(),                kind: p["kind"].as_str().and_then(|k| serde_json::from_value(json!(k)).ok()),                duration_ms: p["duration_ms"].as_f64().or_else(|| p["durationMs"].as_f64()),                waveform: (!wave.is_empty()).then_some(wave),                // Sealed in the message with the words: drawn at once, the picture's own size, until its file is here.                preview: p["preview"].as_str().map(str::to_string),                ..MessageMedia::default()            });        }    }    media}fn meta_value_of(row: &Map<String, Value>) -> Value {    cotton_chat::meta_value(row.get("meta").unwrap_or(&Value::Null))}fn meta_of(row: &Map<String, Value>) -> Option<MessageMeta> {    match row.get("meta") {        Some(Value::String(t)) => serde_json::from_str(t).ok(),        Some(v @ Value::Object(_)) => serde_json::from_value(v.clone()).ok(),        _ => None,    }}/// The reader's clock and zone, read once per answer.struct Clock {    zone: String,    now: chrono::DateTime<chrono::Utc>,    dates: &'static DateWords,}impl Clock {    fn of(client: &ClientController) -> Self {        Self { zone: client.time_zone().unwrap_or("Etc/UTC").to_string(), now: client.clock().now(), dates: DateWords::shipped() }    }    fn now_iso(&self) -> String {        self.now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)    }    /// The list's "time today, Yesterday, else the day", and only the month and year ("Nov 2025") for a day    /// outside the reader's year, so a list row keeps its room for the name and the line at any text size.    fn recent(&self, at: &str) -> Option<String> {        let parts = stamp_parts(at, &self.zone, self.now, self.dates)?;        let this_year = Moment::now(self.now, &self.zone).map(|m| self.dates.numeral_parts(m.day).3);        let (year, month) = (parts.day.get(..4)?.parse::<i64>().ok()?, parts.day.get(5..7)?.parse::<i64>().ok()?);        Some(if this_year.is_some_and(|this| this != year) { self.dates.month_year(year, month) } else { parts.recent })    }    /// A bubble's clock, its day's heading, and the day as a number.    fn slip(&self, at: &str) -> (String, String, i64) {        let parts = stamp_parts(at, &self.zone, self.now, self.dates);        let day = Moment::parse(at, &self.zone).map_or(0, |m| m.day);        parts.map(|p| (p.clock.unwrap_or(p.under_day), p.heading, day)).unwrap_or((String::new(), String::new(), day))    }}impl Clock {    /// A day as the thread draws it, a large numeral and its words:    /// ("20", "Friday ยท November"), the year said outside the reader's own.    fn numeral(&self, lines: &LineSet, day: i64) -> (String, String) {        let (date, weekday, month, year) = self.dates.numeral_parts(day);        let this_year = Moment::now(self.now, &self.zone).map(|m| self.dates.numeral_parts(m.day).3).unwrap_or(year);        let fills = [("weekday", weekday.as_str()), ("month", month.as_str()), ("year", &year.to_string())];        let line = if year == this_year { "app.thread.day_words.this_year" } else { "app.thread.day_words.other_year" };        (date, say(lines, line, &fills))    }}pub(crate) fn ms(at: &str) -> i64 {    chrono::DateTime::parse_from_rfc3339(at).map(|t| t.timestamp_millis()).unwrap_or(0)}// โ”€โ”€ conversations โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€/// One conversation's cheap columns: everything the counts, filters and/// order need, read for every conversation in one indexed pass.#[derive(Debug, Clone)]struct Summary {    id: String,    group: bool,    archived: bool,    pinned_at: Option<String>,    muted_until: Option<String>,    marked: bool,    last_at: Option<String>,    source: String,    unread: u32,    title: Option<String>,    contact: Option<String>,    photo: Option<String>,    draft: Option<String>,    draft_reply: Option<String>,    read_seq: i64,    cleared_before: Option<String>,    pinned_messages: Vec<String>,    request: Option<String>,    /// The last message's direction (`in`, `out`), its own row's.    last_direction: Option<String>,    /// A Cotton group this person is no longer in (the thread's `sendable` is false): nothing can be said in it.    out_of_group: bool,    /// A WhatsApp chat a text written here goes out from, through the Mac (`whatsapp_send`): read only where a    /// page offers writing (the thread, its acts), false elsewhere.    whatsapp_sends: bool,    /// Such a chat's files go too: the outbox its object serves takes a file row (`whatsapp_send::takes_files`).    whatsapp_files: bool,    /// Such a chat's replies and reactions go too: the served outbox takes them (`whatsapp_send::takes_answers`).    whatsapp_answers: bool,    /// Such a chat's documents go too (`whatsapp_send::takes_documents`).    whatsapp_documents: bool,    /// He can vote on such a chat's polls (`whatsapp_send::takes_votes`).    whatsapp_votes: bool,    /// He can edit his own messages there, and delete them for everyone (`whatsapp_send::takes_changes`).    whatsapp_changes: bool,    /// He can make a poll there (`whatsapp_send::takes_polls`).    whatsapp_polls: bool,    /// A text's link card goes to WhatsApp where the served outbox carries one (FEEDBACK-4 B4).    whatsapp_links: bool,    /// A person's WhatsApp chat he can block there, and delete there for him: the served outbox takes the source    /// acts (`whatsapp_send::takes_source_acts`).    whatsapp_source_acts: bool,    /// This copy is linked to WhatsApp through the Mac (`whatsapp_send::link`): the pages that offer writing mark    /// where a message goes (FEEDBACK-2 A). False elsewhere.    linked: bool,    /// The chat holds both Cotton's messages and WhatsApp's, on a linked copy: each bubble says which.    mixed: bool,    /// The chat holds a message that came from WhatsApp: Delete takes it from Cotton only, and says so.    whatsapp: bool,    /// An SMS chat's number (or short code) texts can go to; `None` for a sender with a name, and for every other chat.    sms_to: Option<String>,    /// An SMS chat landed by Comms on Android (`sms:` key) whose sender has a name: it takes no reply.    sms_named: bool,    /// An SMS chat with someone this phone asked on Cotton who has not accepted yet (DISCOVERY OFF 3): each text he    /// sends there says it is not private, as a text chosen in a Cotton chat does. Read where the thread is drawn.    sms_asked: bool,    /// An SMS chat written from this phone: it holds Android's SMS role (`chat_sms::held`) and the chat has a number.    sms_sends: bool,}impl Summary {    /// Deleted from the list (`deleteChat`): cleared up to its newest message. A later message brings it back.    fn deleted(&self) -> bool {        match (&self.cleared_before, &self.last_at) {            (Some(cut), Some(last)) => ms(last) <= ms(cut),            (Some(_), None) => true,            _ => false,        }    }    fn listed(&self) -> Listed {        Listed {            group: self.group,            source: self.source.clone(),            archived: self.archived,            unread: self.unread > 0 || self.marked,            waiting: self.last_direction.as_deref() == Some("in"),        }    }    fn can(&self) -> Can {        if self.out_of_group {            return Can::of("", false);        }        if self.whatsapp_sends {            // Through the Mac's link: words, pictures, videos and voice notes, replies and reactions (FEEDBACK-3), and            // his own message edited or deleted for everyone. Each only where the server's outbox takes it (files:            // `whatsapp_files`, replies and reactions: `whatsapp_answers`, edits and deletes: `whatsapp_changes`);            // words always. Which message offers which, and for how long, the bubble says (`whatsapp_acts`).            let (files, answers, changes) = (self.whatsapp_files, self.whatsapp_answers, self.whatsapp_changes);            return Can { send: true, attach: files, voice: files, reply: answers, react: answers, edit: changes, delete: changes, ..Can::of("", false) };        }        if self.sms_sends {            // Texts from the phone holding the SMS role: words only (DECISIONS "SMS on Android").            return Can { send: true, ..Can::of("", false) };        }        Can::of(&self.source, false)    }    /// Where a message written here goes, said before it is sent: only on a linked copy, only where it can be written.    /// An SMS chat always says it is one, the quiet mark under its name.    fn place(&self, lines: &LineSet) -> Option<PlaceMark> {        if self.source == super::chat_sms::CHANNEL && !self.group {            return Some(compose::place_mark(lines, "sms"));        }        (self.linked && self.can().send).then(|| compose::place_mark(lines, if self.whatsapp_sends { "whatsapp" } else { "cotton" }))    }    /// Pinned first (newest pin first), then the newest; ties by id.    fn order(&self) -> (u8, std::cmp::Reverse<String>, std::cmp::Reverse<String>, String) {        match &self.pinned_at {            Some(p) => (0, std::cmp::Reverse(p.clone()), std::cmp::Reverse(self.last_at.clone().unwrap_or_default()), self.id.clone()),            None => (1, std::cmp::Reverse(String::new()), std::cmp::Reverse(self.last_at.clone().unwrap_or_default()), self.id.clone()),        }    }    fn cursor(&self) -> String {        let (g, p, l, id) = self.order();        format!("{g}\u{1f}{}\u{1f}{}\u{1f}{id}", p.0, l.0)    }}fn parse_list_cursor(cursor: &str) -> Option<(u8, std::cmp::Reverse<String>, std::cmp::Reverse<String>, String)> {    let mut parts = cursor.split('\u{1f}');    let g = parts.next()?.parse().ok()?;    let p = parts.next()?.to_string();    let l = parts.next()?.to_string();    let id = parts.next()?.to_string();    Some((g, std::cmp::Reverse(p), std::cmp::Reverse(l), id))}fn ids_json(raw: Option<String>) -> Vec<String> {    raw.and_then(|r| serde_json::from_str::<Vec<String>>(&r).ok()).unwrap_or_default()}/// Every conversation's summary; `only` narrows to one./// A thread's unread messages, counted to the badge's ceiling.fn count_unread(ctx: &mut Ctx<'_>, t: &mut Summary) -> Result<(), String> {    if t.unread == 0 {        return Ok(());    }    let counted = one(        ctx,        &format!(            "SELECT COUNT(*) AS n FROM (SELECT 1 FROM {MESSAGES} WHERE thread_id = ? AND (seq > ? OR (seq IS NULL AND read_at IS NULL)) AND direction = 'in' AND origin = 'live'               AND hidden_at IS NULL AND trashed_at IS NULL AND (? IS NULL OR sent_at > ?) AND json_extract(meta, '$.cotton.safety') IS NULL LIMIT {COUNT_CEILING})"        ),        &[text(t.id.clone()), SqlValue::Integer(t.read_seq), t.cleared_before.clone().map_or(SqlValue::Null, text), t.cleared_before.clone().map_or(SqlValue::Null, text)],    )?;    t.unread = counted.map_or(1, |r| n(&r, "n").clamp(1, COUNT_CEILING) as u32);    Ok(())}/// Every conversation, `unread` 0 or 1 (whether anything is unread); one asked by id is counted whole.fn summaries(ctx: &mut Ctx<'_>, only: Option<&str>) -> Result<Vec<Summary>, String> {    let held = columns_of(ctx, THREADS)?;    let col = |name: &str| if held.contains(name) { format!("t.{name}") } else { "NULL".to_string() };    let sql = format!(        "SELECT t.id, t.kind, t.archived, t.pinned_at, t.muted_until, t.unread_marked_at, t.last_message_at, t.external_key,                t.title, t.contact_id, t.photo_key, t.draft, t.draft_reply_to_id, t.read_seq, t.cleared_before,                {pins} AS pinned_messages, {request} AS request, {sendable} AS sendable,                -- whether anything is unread: one seek on idx_cotton_msg_messages_unread_cursor. The badge's                -- figure is counted only for the rows a page shows (`count_unread`).                -- A message that just landed has no sequence until the copy syncs: unread until it is read.                EXISTS (SELECT 1 FROM {MESSAGES} m WHERE m.thread_id = t.id AND (m.seq > coalesce(t.read_seq, 0) OR (m.seq IS NULL AND m.read_at IS NULL))                   AND m.direction = 'in' AND m.origin = 'live' AND m.hidden_at IS NULL AND m.trashed_at IS NULL                   AND (t.cleared_before IS NULL OR m.sent_at > t.cleared_before) AND json_extract(m.meta, '$.cotton.safety') IS NULL) AS unread,                (SELECT m.channel FROM {MESSAGES} m WHERE m.thread_id = t.id ORDER BY m.sent_at DESC LIMIT 1) AS channel,                -- one seek on idx_cotton_msg_messages_thread_channel.                EXISTS (SELECT 1 FROM {MESSAGES} m WHERE m.thread_id = t.id AND m.channel = 'whatsapp') AS whatsapp,                -- whose the last word is, for Waiting on you: the newest live message shown.                (SELECT m.direction FROM {MESSAGES} m WHERE m.thread_id = t.id AND m.hidden_at IS NULL AND m.trashed_at IS NULL                   AND m.deleted_at IS NULL AND (t.cleared_before IS NULL OR m.sent_at > t.cleared_before) AND json_extract(m.meta, '$.cotton.safety') IS NULL                 ORDER BY m.sent_at DESC LIMIT 1) AS last_direction           FROM {THREADS} t WHERE t.workspace_id = ? AND t.trashed_at IS NULL{one}",        pins = col("pinned_messages"),        request = col("request"),        sendable = col("sendable"),        one = if only.is_some() { " AND t.id = ?" } else { "" },    );    let mut params = vec![ws(ctx)];    if let Some(id) = only {        params.push(text(id.to_string()));    }    let mut all: Vec<Summary> = rows(ctx, &sql, &params)?        .into_iter()        .filter_map(|r| {            let id = s(&r, "id")?;            let key = s(&r, "external_key").unwrap_or_default();            let source = if key.starts_with("cotton:") { "cotton".to_string() } else { s(&r, "channel").unwrap_or_else(|| "cotton".into()) };            let sms = source == super::chat_sms::CHANNEL;            Some(Summary {                sms_to: if sms { super::chat_sms::to_of(&key) } else { None },                sms_named: sms && key.starts_with(super::chat_sms::SMS_PREFIX) && super::chat_sms::to_of(&key).is_none(),                group: s(&r, "kind").as_deref() == Some("group"),                archived: truthy(&r, "archived"),                pinned_at: s(&r, "pinned_at"),                muted_until: s(&r, "muted_until"),                marked: s(&r, "unread_marked_at").is_some(),                last_at: s(&r, "last_message_at"),                source,                unread: n(&r, "unread").clamp(0, 1) as u32,                title: s(&r, "title"),                contact: s(&r, "contact_id"),                photo: s(&r, "photo_key"),                draft: s(&r, "draft"),                draft_reply: s(&r, "draft_reply_to_id"),                read_seq: n(&r, "read_seq"),                cleared_before: s(&r, "cleared_before"),                pinned_messages: ids_json(s(&r, "pinned_messages")),                request: s(&r, "request"),                last_direction: s(&r, "last_direction"),                out_of_group: key.starts_with("cotton:group:") && r.get("sendable").is_some_and(|v| v == &json!(false) || v == &json!(0)),                whatsapp_sends: false,                whatsapp_files: false,                whatsapp_answers: false,                whatsapp_documents: false,                whatsapp_votes: false,                whatsapp_changes: false,                whatsapp_polls: false,                whatsapp_links: false,                whatsapp_source_acts: false,                linked: false,                mixed: false,                whatsapp: truthy(&r, "whatsapp"),                sms_sends: false,                sms_asked: false,                id,            })        })        .collect();    if only.is_some() {        for t in &mut all {            count_unread(ctx, t)?;        }    }    Ok(all)}/// Who a conversation is: its name and picture, and in a group each seat's name.#[derive(Debug, Clone, Default)]struct Named {    name: String,    photo: Option<String>,    /// Current members other than you.    members: usize,    /// Seat id โ†’ (name, photo).    seats: HashMap<String, (String, Option<String>)>,}fn names(ctx: &mut Ctx<'_>, threads: &[&Summary], you: &str) -> Result<HashMap<String, Named>, String> {    let groups: Vec<String> = threads.iter().filter(|t| t.group).map(|t| t.id.clone()).collect();    let seats = if groups.is_empty() {        Vec::new()    } else {        rows_in(ctx, &format!("SELECT id, thread_id, contact_id, display_name, left_at, is_self FROM {SEATS} WHERE workspace_id = ?"), "thread_id", &groups)?    };    let mut contact_ids: Vec<String> = threads.iter().filter_map(|t| t.contact.clone()).collect();    contact_ids.extend(seats.iter().filter_map(|r| s(r, "contact_id")));    contact_ids.sort();    contact_ids.dedup();    let contact_cols = columns_of(ctx, CONTACTS)?;    let avatar = if contact_cols.contains("avatar_key") { "avatar_key" } else { "NULL AS avatar_key" };    let contacts = if contact_ids.is_empty() {        Vec::new()    } else {        rows_in(            ctx,            &format!(                "SELECT c.id AS id, c.display_name AS display_name, c.phone_e164 AS phone_e164, {person} AS person_id, {shared} AS shared_names, c.{avatar} FROM {CONTACTS} c WHERE c.workspace_id = ?",                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"),            ),            "c.id",            &contact_ids,        )?    };    let person_ids: Vec<String> = contacts.iter().filter_map(|r| s(r, "person_id")).collect();    let people = if person_ids.is_empty() {        Vec::new()    } else {        rows_in(ctx, "SELECT id, full_name, avatar_key FROM cotton_people WHERE workspace_id = ?", "id", &person_ids)?    };    let people: HashMap<String, (Option<String>, Option<String>)> = people.iter().filter_map(|r| Some((s(r, "id")?, (s(r, "full_name"), s(r, "avatar_key"))))).collect();    let contacts: HashMap<String, &Map<String, Value>> = contacts.iter().filter_map(|r| Some((s(r, "id")?, r))).collect();    let contact_name = |id: &str, title: Option<&str>| -> (String, Option<String>) {        let row = contacts.get(id);        let person = row.and_then(|r| s(r, "person_id")).and_then(|p| people.get(&p).cloned());        // A number several of his contacts share (a household landline) is called by all their names, never one of        // them as if certain (PEOPLE BUILD 1b).        let shared = row.and_then(|r| s(r, "shared_names"));        let name = direct_name(            person.as_ref().and_then(|p| p.0.as_deref()).or(shared.as_deref()),            row.and_then(|r| s(r, "display_name")).as_deref(),            title,            row.and_then(|r| s(r, "phone_e164")).as_deref(),            None,        );        let photo = person.and_then(|p| p.1).or_else(|| row.and_then(|r| s(r, "avatar_key")));        (name, photo)    };    let mut out: HashMap<String, Named> = HashMap::new();    let mut members: HashMap<String, Vec<String>> = HashMap::new();    let mut still_in: std::collections::HashSet<String> = std::collections::HashSet::new();    for seat in &seats {        let (Some(id), Some(thread)) = (s(seat, "id"), s(seat, "thread_id")) else { continue };        let is_self = truthy(seat, "is_self");        let (name, photo) = if is_self {            (you.to_string(), None)        } else {            match s(seat, "contact_id") {                Some(contact) => contact_name(&contact, s(seat, "display_name").as_deref()),                None => (s(seat, "display_name").unwrap_or_else(|| cotton_core::messages::display::UNKNOWN_NAME.to_string()), None),            }        };        if s(seat, "left_at").is_none() {            if is_self {                still_in.insert(thread.clone());            } else {                members.entry(thread.clone()).or_default().push(name.clone());            }        }        out.entry(thread).or_default().seats.insert(id, (name, photo));    }    for t in threads {        let named = out.entry(t.id.clone()).or_default();        if t.group {            let others = members.get(&t.id).cloned().unwrap_or_default();            named.name = group_name(t.title.as_deref(), &others);            // Counted as the group's page counts them (`chat.group.info`): you too, while you are in it.            named.members = others.len() + usize::from(still_in.contains(&t.id));            named.photo = t.photo.clone();        } else {            let (name, photo) = match &t.contact {                Some(contact) => contact_name(contact, t.title.as_deref()),                None => (direct_name(None, None, t.title.as_deref(), None, None), None),            };            named.name = name;            named.photo = photo.or_else(|| t.photo.clone());        }    }    Ok(out)}fn picture(key: &str, name: &str, photo: Option<String>) -> Picture {    Picture { photo, initials: lay::initials(name), tint: lay::tint(key) }}const MESSAGE_COLUMNS: &str = "rowid AS _row, id, thread_id, direction, channel, origin, body, media, meta, sent_at, seq, send_state, deleted_at, edited_at, reply_to_id, forward_of_id, sender_participant_id, reactions, starred_at, created_at, external_id, send_error";/// The newest message a conversation shows (a safety number's line is quiet: never the list's last line, never unread).fn last_message(ctx: &mut Ctx<'_>, t: &Summary) -> Result<Option<Map<String, Value>>, String> {    let mut params = vec![ws(ctx), text(t.id.clone())];    let cleared = match &t.cleared_before {        Some(c) => {            params.push(text(c.clone()));            " AND sent_at > ?"        }        None => "",    };    one(        ctx,        &format!("SELECT {MESSAGE_COLUMNS} FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND trashed_at IS NULL AND hidden_at IS NULL AND json_extract(meta, '$.cotton.safety') IS NULL{cleared} ORDER BY sent_at DESC LIMIT 1"),        &params,    )}fn row_of(lines: &LineSet, clock: &Clock, t: &Summary, named: &Named, last: Option<&Map<String, Value>>) -> ListRow {    row_with(lines, clock, t, named, last, None)}/// [`row_of`], with the newest text or file still on its way to WhatsApp (FEEDBACK-2 A): when it is newer than the/// last message it is the row's last line, the person's own, with its tick and where it stands, as its bubble says.fn row_with(lines: &LineSet, clock: &Clock, t: &Summary, named: &Named, last: Option<&Map<String, Value>>, going: Option<&whatsapp_send::Pending>) -> ListRow {    let you = say(lines, "app.list.you", &[]);    let going = going.filter(|p| last.and_then(|m| s(m, "sent_at")).is_none_or(|at| p.written_at >= at));    if let Some(p) = going {        let media: Vec<MessageMedia> = p.media.iter().cloned().collect();        let r = Row { body: Some(&p.body), media: &media, meta: None, deleted_at: None };        let mut row = row_with(lines, clock, t, named, None, None);        row.last_line = Some(LastLine {            text: bubble::line_of(&r),            sender: t.group.then(|| you.clone()),            mark: bubble::mark_of(&r),            mine: true,            tick: Some(match p.status.as_str() {                "failed" => Tick::Failed,                "sent" => Tick::Sent,                _ => Tick::Sending,            }),            state: (p.status != "sent").then(|| whatsapp_send::state_words(lines, p)),        });        if t.last_at.as_deref().is_none_or(|at| at < p.written_at.as_str()) {            row.when = clock.recent(&p.written_at);        }        return row;    }    let last_line = last.map(|m| {        let media = media_of(m);        let meta = meta_of(m);        let deleted = s(m, "deleted_at");        let r = Row { body: m.get("body").and_then(Value::as_str), media: &media, meta: meta.as_ref(), deleted_at: deleted.as_deref() };        let mine = s(m, "direction").as_deref() == Some("out");        let sender = if !t.group || r.event() {            None        } else if mine {            Some(you.clone())        } else {            s(m, "sender_participant_id").and_then(|seat| named.seats.get(&seat).map(|(name, _)| lay::first_name(name)))        };        // A WhatsApp call is the call's own line, as its thread draws it, never the caller's words.        if let Some(call) = imported_call(lines, m) {            return LastLine { text: call, sender: None, mark: None, mine, tick: None, state: None };        }        LastLine {            text: bubble::line_of(&r),            sender,            mark: bubble::mark_of(&r),            mine,            tick: bubble::tick_of(s(m, "send_state").as_deref(), s(m, "channel").as_deref() == Some("cotton"), mine),            state: None,        }    });    let muted = is_muted(t.muted_until.as_deref(), &clock.now_iso());    let unread = t.unread > 0 || t.marked;    let (leading, mut trailing) = list::swipes(lines, unread, t.pinned_at.is_some(), muted, t.archived, &named.name);    let mut hold = list::hold(lines, unread, t.pinned_at.is_some(), muted, t.archived, &named.name);    // A WhatsApp chat's Delete says what it is: it leaves Cotton only, WhatsApp keeps it (FEEDBACK-4 B2). So does a    // chat holding WhatsApp's messages whose newest is Cotton's (a person on both, FEEDBACK-2 A).    if t.whatsapp || t.source == "whatsapp" {        let asked = list::say(lines, "app.confirm.delete_chat_whatsapp", &[("name", &named.name)]);        for act in trailing.iter_mut().chain(hold.iter_mut()).filter(|a| a.act == "deleteChat") {            act.confirm = Some(asked.clone());        }    }    ListRow {        thread: t.id.clone(),        name: named.name.clone(),        group: t.group,        source: t.source.clone(),        picture: picture(&t.id, &named.name, named.photo.clone()),        last_line,        when: t.last_at.as_deref().and_then(|at| clock.recent(at)),        unread: t.unread,        badge: (t.unread > 0).then(|| badge(t.unread)),        sendable: t.can().send,        marked_unread: t.marked && t.unread == 0,        pinned: t.pinned_at.is_some(),        muted,        archived: t.archived,        typing: None,        draft: t.draft.as_ref().map(|d| say(lines, "app.list.draft", &[("text", d)])),        leading,        trailing,        hold,    }}/// The search: conversations whose name holds every word, then those/// holding a message that does (the device's own search index).fn search_hits(ctx: &mut Ctx<'_>, all: &[Summary], words: &[String], you: &str) -> Result<HashSet<String>, String> {    let every: Vec<&Summary> = all.iter().collect();    let named = names(ctx, &every, you)?;    let mut hits: HashSet<String> = named        .iter()        .filter(|(_, n)| {            let name = n.name.to_lowercase();            words.iter().all(|w| name.contains(w.as_str()))        })        .map(|(id, _)| id.clone())        .collect();    let query: String = words.iter().map(|w| format!("\"{}\"*", w.replace('"', ""))).collect::<Vec<_>>().join(" ");    let found = rows(        ctx,        &format!("SELECT DISTINCT m.thread_id AS thread_id FROM fts_messages f JOIN {MESSAGES} m ON m.rowid = f.rowid WHERE fts_messages MATCH ? AND m.workspace_id = ? AND m.trashed_at IS NULL AND m.deleted_at IS NULL"),        &[text(query), ws(ctx)],    )    .unwrap_or_default();    hits.extend(found.iter().filter_map(|r| s(r, "thread_id")));    Ok(hits)}/// Each row of a list page as the Downloads chat's place needs it: its last moment and its pin.type Moments = Vec<(Option<String>, bool)>;/// `chat.list`, with the Downloads chat in its place on the page its newest/// download falls on (`downloads::place`): under All, with no search, never/// in Forward's picker, while the phone holds it (`downloads::shows`).fn list_with_downloads(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let (answer, moments) = list_answer(client, request)?;    let mut answer = serde_json::to_value(answer).map_err(|e| MethodError::new("unanswerable", e.to_string()))?;    let plain = matches!(Filter::parse(request.get("filter").and_then(Value::as_str)), Filter::All)        && request.get("search").and_then(Value::as_str).is_none_or(|q| q.trim().is_empty())        && !request.get("sendable").and_then(Value::as_bool).unwrap_or(false);    if !plain || !downloads::shows(client) {        return Ok(answer);    }    let newest = downloads::newest(client)?;    let after = request.get("after").and_then(Value::as_str).and_then(parse_list_cursor).map(|(group, _, last, _)| (group == 0, Some(last.0).filter(|at| !at.is_empty())));    let more = answer.get("next").is_some_and(|next| !next.is_null());    if let Some(at) = downloads::place(&moments, after, more, newest.as_ref().map(|(at, _)| at.as_str())) {        if let Some(rows) = answer["rows"].as_array_mut() {            rows.insert(at, downloads::row(client, newest.as_ref()));        }    }    Ok(answer)}fn list_answer(client: &ClientController, request: &Value) -> Result<(ListAnswer, Moments), MethodError> {    let filter = Filter::parse(request.get("filter").and_then(Value::as_str));    let search = request.get("search").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()).map(str::to_string);    let after = request.get("after").and_then(Value::as_str).and_then(parse_list_cursor);    // Forward's picker: only the conversations a message can go to, archived ones too.    let sendable_only = request.get("sendable").and_then(Value::as_bool).unwrap_or(false);    let lines = list::lines();    let clock = Clock::of(client);    let you = say(&lines, "app.list.you", &[]);    read(client, "chat.list", |ctx| {        // A chat deleted from the list (`deleteChat`) stands nowhere until a later message brings it back.        // A blocked sender's chat stands only in Blocked (SENDERS.md).        let hidden = senders::hidden_threads(ctx)?;        let all: Vec<Summary> = summaries(ctx, None)?.into_iter().filter(|t| !t.deleted() && !hidden.contains(&t.id)).collect();        let listed: Vec<Listed> = all.iter().map(Summary::listed).collect();        let counts = list::counts(&listed);        let words: Vec<String> = search.as_deref().map(|q| q.to_lowercase().split_whitespace().map(str::to_string).collect()).unwrap_or_default();        let hits = if words.is_empty() { None } else { Some(search_hits(ctx, &all, &words, &you)?) };        let mut kept: Vec<&Summary> = all            .iter()            .filter(|t| match &hits {                Some(hits) => hits.contains(&t.id),                None if sendable_only => true,                None => list::keeps(&filter, &t.listed()),            })            .filter(|t| !sendable_only || t.can().send)            .collect();        kept.sort_by_key(|t| t.order());        if let Some(after) = &after {            kept.retain(|t| t.order() > *after);        }        let more = kept.len() > LIST_PAGE;        kept.truncate(LIST_PAGE);        let mut kept: Vec<Summary> = kept.into_iter().cloned().collect();        for t in &mut kept {            count_unread(ctx, t)?;        }        let kept: Vec<&Summary> = kept.iter().collect();        let named = names(ctx, &kept, &you)?;        let outbox = whatsapp_send::keeps_outbox(ctx)?;        let mut out = Vec::with_capacity(kept.len());        for t in &kept {            let last = last_message(ctx, t)?;            let going = if outbox { whatsapp_send::newest_pending(ctx, &t.id)? } else { None };            out.push(row_with(&lines, &clock, t, named.get(&t.id).unwrap_or(&Named::default()), last.as_ref(), going.as_ref()));        }        let moments: Moments = kept.iter().map(|t| (t.last_at.clone(), t.pinned_at.is_some())).collect();        Ok((ListAnswer {            filter: filter.id().to_string(),            search: search.clone(),            next: if more { kept.last().map(|t| t.cursor()) } else { None },            fan: list::fan(&lines, &counts, &filter),            filters: list::filters(&lines, &counts, &filter),            counts,            words: ListWords { title: say(&lines, "app.list.title", &[]), search: say(&lines, "app.list.search", &[]), empty: list::empty(&lines, &filter, search.is_some()) },            rows: out,        }, moments))    })}/// Where his own text in an SMS chat stands, in words under it: "Sendingโ€ฆ" until the radio answers, "Not sent: <why>"/// after a failure (with Retry), nothing once sent.fn sms_state(lines: &LineSet, m: &Map<String, Value>, mine: bool) -> Option<String> {    if !mine || s(m, "channel").as_deref() != Some(super::chat_sms::CHANNEL) {        return None;    }    match s(m, "send_state").as_deref()? {        "queued" | "sending" => Some(say(lines, "state.sending", &[])),        "failed" => {            let code = s(m, "send_error").unwrap_or_else(|| "generic".into());            let why = say(lines, &format!("app.sms.why.{code}"), &[]);            let why = if why.is_empty() { say(lines, "app.sms.why.generic", &[]) } else { why };            Some(say(lines, "state.failed_why", &[("why", &why)]))        }        _ => None,    }}/// The chats muted now, in the list's order (You โ€บ Notifications' Muted): each by its list row's name and picture,/// and until when ("Until you turn it back on", "Until 18:00").pub(crate) fn muted(client: &ClientController) -> Result<Vec<Value>, MethodError> {    let lines = list::lines();    let clock = Clock::of(client);    let you = say(&lines, "app.list.you", &[]);    let now = clock.now_iso();    read(client, "chat.you", |ctx| {        let mut all: Vec<Summary> = summaries(ctx, None)?.into_iter().filter(|t| !t.deleted() && is_muted(t.muted_until.as_deref(), &now)).collect();        all.sort_by_key(|t| t.order());        let kept: Vec<&Summary> = all.iter().collect();        let named = names(ctx, &kept, &you)?;        Ok(kept            .iter()            .map(|t| {                let row = row_of(&lines, &clock, t, named.get(&t.id).unwrap_or(&Named::default()), None);                let until = if cotton_core::messages::unread::is_muted_forever(t.muted_until.as_deref()) {                    say(&lines, "app.you.muted_always", &[])                } else {                    let when = t.muted_until.as_deref().and_then(|at| clock.recent(at)).unwrap_or_default();                    say(&lines, "app.you.muted_until", &[("when", &when)])                };                json!({ "thread": row.thread, "name": row.name, "picture": row.picture, "until": until })            })            .collect())    })}/// Every chat's name and picture as the list draws them, by thread (Storage by chat).pub(crate) fn named(client: &ClientController) -> Result<HashMap<String, (String, Value)>, MethodError> {    let lines = list::lines();    let clock = Clock::of(client);    let you = say(&lines, "app.list.you", &[]);    read(client, "chat.storage", |ctx| {        let all: Vec<Summary> = summaries(ctx, None)?.into_iter().filter(|t| !t.deleted()).collect();        let kept: Vec<&Summary> = all.iter().collect();        let named = names(ctx, &kept, &you)?;        Ok(kept            .iter()            .map(|t| {                let row = row_of(&lines, &clock, t, named.get(&t.id).unwrap_or(&Named::default()), None);                (row.thread.clone(), (row.name.clone(), json!(row.picture)))            })            .collect())    })}/// One conversation's list row, as a list act leaves it.fn one_row(client: &ClientController, thread: &str) -> Result<Option<ListRow>, MethodError> {    let lines = list::lines();    let clock = Clock::of(client);    let you = say(&lines, "app.list.you", &[]);    read(client, "chat.row", |ctx| {        let Some(t) = summaries(ctx, Some(thread))?.into_iter().next() else { return Ok(None) };        let named = names(ctx, &[&t], &you)?;        let last = last_message(ctx, &t)?;        let going = if whatsapp_send::keeps_outbox(ctx)? { whatsapp_send::newest_pending(ctx, &t.id)? } else { None };        Ok(Some(row_with(&lines, &clock, &t, named.get(&t.id).unwrap_or(&Named::default()), last.as_ref(), going.as_ref())))    })}// โ”€โ”€ a thread โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€/// A thread page's edge: the message's moment and its row, the order/// `idx_cotton_msg_messages_thread_sent` keeps them in (a tie on the moment/// falls to the row, so no page is ever sorted apart from the index).fn parse_thread_cursor(cursor: &str) -> Option<(String, i64)> {    let mut parts = cursor.split('\u{1f}');    let (at, row) = (parts.next()?, parts.next()?);    Some((at.to_string(), row.parse().ok()?))}fn thread_cursor(m: &Map<String, Value>) -> String {    format!("{}\u{1f}{}", s(m, "sent_at").unwrap_or_default(), n(m, "_row"))}/// Messages on one side of a point, nearest first.fn side(ctx: &mut Ctx<'_>, t: &Summary, from: Option<&(String, i64)>, older: bool, inclusive: bool, count: usize) -> Result<Vec<Map<String, Value>>, String> {    let mut params = vec![ws(ctx), text(t.id.clone())];    let mut sql = format!("SELECT {MESSAGE_COLUMNS} FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND trashed_at IS NULL AND hidden_at IS NULL");    if let Some(c) = &t.cleared_before {        sql.push_str(" AND sent_at > ?");        params.push(text(c.clone()));    }    // The index runs newest first and, within one moment, by row: older is    // (sent_at DESC, rowid ASC), newer (sent_at ASC, rowid DESC). A range on    // the moment seeks; the row settles a tie at the edge.    if let Some((at, row)) = from {        let (range, cmp, tie) = match (older, inclusive) {            (true, false) => ("<=", "<", ">"),            (true, true) => ("<=", "<", ">="),            (false, false) => (">=", ">", "<"),            (false, true) => (">=", ">", "<="),        };        sql.push_str(&format!(" AND sent_at {range} ? AND (sent_at {cmp} ? OR rowid {tie} ?)"));        params.extend([text(at.clone()), text(at.clone()), SqlValue::Integer(*row)]);    }    let order = if older { "sent_at DESC, rowid ASC" } else { "sent_at ASC, rowid DESC" };    sql.push_str(&format!(" ORDER BY {order} LIMIT ?"));    params.push(SqlValue::Integer(count as i64));    rows(ctx, &sql, &params)}/// The first unread message: the oldest live inbound one past what was read.fn first_unread(ctx: &mut Ctx<'_>, t: &Summary) -> Result<Option<Map<String, Value>>, String> {    if t.unread == 0 {        return Ok(None);    }    one(        ctx,        &format!("SELECT id, sent_at FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND seq > ? AND direction = 'in' AND origin = 'live' AND hidden_at IS NULL AND trashed_at IS NULL ORDER BY seq ASC LIMIT 1"),        &[ws(ctx), text(t.id.clone()), SqlValue::Integer(t.read_seq)],    )}fn sender_key(m: &Map<String, Value>) -> String {    // An agent's words are a run of their own, whichever phone sent them.    if let Some((id, _)) = super::chat_agent::agent_of(&meta_value_of(m)) {        return format!("agent:{id}");    }    if s(m, "direction").as_deref() == Some("out") {        return "me".into();    }    s(m, "sender_participant_id").unwrap_or_else(|| "them".into())}/// A WhatsApp call as its line, drawn centred as a call's and the list's last line, never as their words: one an/// export wrote under the caller's name ("Voice call, 41 sec"), or one the Mac's link wrote with the call's facts/// (`meta.call`, [`cotton_core::messages::app::calls::CallFacts`]; CONTRACT "WhatsApp calls in a chat").fn imported_call(lines: &LineSet, m: &Map<String, Value>) -> Option<String> {    if s(m, "channel").as_deref() != Some("whatsapp") {        return None;    }    let facts = meta_value_of(m).get("call").cloned().and_then(|c| serde_json::from_value::<cotton_core::messages::app::calls::CallFacts>(c).ok());    if let Some(facts) = facts {        return Some(cotton_core::messages::app::calls::line(lines, &facts));    }    if s(m, "origin").as_deref() != Some("imported") {        return None;    }    cotton_core::messages::app::calls::imported_line(lines, m.get("body").and_then(Value::as_str)?)}/// A voice message's transcript (`meta.cotton.transcript`: set by the phone/// that recorded it, or landed after the message as its writer's change), on/// its voice part.////// And whether it has been played: a voice message of theirs that came live/// is not played until one of the person's phones played it a second/// (`chat.act played`, `meta.cotton.played_at` on their own copy, never told/// to the sender). The person's own, and an imported note, are played.fn transcripts(m: &Map<String, Value>, bubble: &mut Bubble) {    let meta = meta_value_of(m);    let unplayed = s(m, "direction").as_deref() != Some("out") && s(m, "origin").as_deref() == Some("live") && !meta["cotton"]["played_at"].is_string();    let words = meta["cotton"]["transcript"].as_str();    if let Some(part) = bubble.media.iter_mut().find(|p| p.kind == Mark::Voice) {        part.transcript = words.map(str::to_string);        part.played = !unplayed;    }}/// Each of a bubble's files the store said it does not hold (`cotton_client::media::absent`,/// kept by `media.ensure` and `chat.picture`) is said so, until its wait is over.fn mark_gone(client: &ClientController, m: &Map<String, Value>, bubble: &mut Bubble) {    transcripts(m, bubble);    let absent = client.absent_media();    // A message still sending, or written or landed here within minutes, has nothing gone (`files::may_be_gone`).    if absent.is_empty() || !super::chat_files::may_be_gone(client, &Value::Object(m.clone())) {        return;    }    let files = media_of(m);    let now = client.now().timestamp_millis();    for part in &mut bubble.media {        part.gone = files.get(part.index as usize).is_some_and(|file| absent.waits(&file.key, now).is_some());    }}fn laid(clock: &Clock, lines: &LineSet, m: &Map<String, Value>) -> Laid {    let at = s(m, "sent_at").unwrap_or_default();    let meta = meta_of(m);    let event = meta.as_ref().and_then(|m| m.system.as_ref()).is_some_and(|s| s.is_truthy()) || imported_call(lines, m).is_some();    Laid { id: s(m, "id").unwrap_or_default(), sender: sender_key(m), at_ms: ms(&at), day: clock.slip(&at).2, event }}/// The long press's words. In a WhatsApp chat that sends, Delete is "Delete for everyone", beside "Delete for me".fn action_words(lines: &LineSet, whatsapp: bool) -> ActionWords {    ActionWords {        reply: say(lines, "app.actions.reply", &[]),        react: say(lines, "app.actions.react", &[]),        copy: say(lines, "app.actions.copy", &[]),        forward: say(lines, "app.actions.forward", &[]),        edit: say(lines, "app.actions.edit", &[]),        delete: say(lines, if whatsapp { "app.actions.delete_everyone" } else { "app.actions.delete" }, &[]),        delete_mine: if whatsapp { say(lines, "app.actions.delete_mine", &[]) } else { String::new() },        pin: say(lines, "app.actions.pin", &[]),        unpin: say(lines, "app.actions.unpin", &[]),        select: say(lines, "app.actions.select", &[]),        info: say(lines, "app.group.info", &[]),        star: say(lines, "app.actions.star", &[]),        unstar: say(lines, "app.actions.unstar", &[]),        copied: say(lines, "app.actions.copied", &[]),        emoji: QUICK.iter().map(|e| e.to_string()).collect(),    }}/// Everything a page's bubbles need beyond their own rows.struct Around {    reactions: HashMap<String, Vec<(String, bool)>>,    quoted: HashMap<String, Map<String, Value>>,    /// The page's poll voters, by their number's digits: the name the chat knows them by (CONTRACT "Polls shown").    voters: HashMap<String, String>,    /// His reaction on its way to WhatsApp, by the reacted message's id (CONTRACT "Replies and reactions").    reacting: HashMap<String, whatsapp_send::Reacting>,    /// His vote on its way to WhatsApp, by the poll message's id (CONTRACT "Documents and votes").    voting: HashMap<String, whatsapp_send::Voting>,    /// His edit on its way, by the message's id; his delete for everyone, by the marker's (CONTRACT "Editing and    /// deleting his own message").    changing: HashMap<String, whatsapp_send::Changing>,}fn around(ctx: &mut Ctx<'_>, page: &[Map<String, Value>]) -> Result<Around, String> {    let ids: Vec<String> = page.iter().filter_map(|m| s(m, "id")).collect();    let mut reactions: HashMap<String, Vec<(String, bool)>> = HashMap::new();    for m in page {        let stored = bubble::stored_reactions(m.get("reactions").and_then(Value::as_str));        if !stored.is_empty() {            reactions.insert(s(m, "id").unwrap_or_default(), stored);        }    }    if !ids.is_empty() {        for r in rows_in(ctx, &format!("SELECT message_id, actor, emoji FROM {REACTIONS} WHERE workspace_id = ?"), "message_id", &ids)? {            if let (Some(message), Some(emoji)) = (s(&r, "message_id"), s(&r, "emoji")) {                reactions.entry(message).or_default().push((emoji, s(&r, "actor").as_deref() == Some(SELF_ACTOR)));            }        }    }    let replies: Vec<String> = page.iter().filter_map(|m| s(m, "reply_to_id")).collect();    let quoted = if replies.is_empty() {        HashMap::new()    } else {        rows_in(ctx, &format!("SELECT {MESSAGE_COLUMNS} FROM {MESSAGES} WHERE workspace_id = ?"), "id", &replies)?.into_iter().filter_map(|r| Some((s(&r, "id")?, r))).collect()    };    let digits: Vec<String> = page        .iter()        .filter_map(meta_of)        .filter_map(|m| m.poll)        .flat_map(|p| p.voters.into_iter().map(|v| v.who))        .filter(|who| who != cotton_core::messages::app::poll::ME)        .collect::<HashSet<_>>()        .into_iter()        .collect();    let voters = if digits.is_empty() {        HashMap::new()    } else {        rows_in(ctx, &format!("SELECT phone_e164, display_name FROM {CONTACTS} WHERE workspace_id = ?"), "phone_e164", &digits)?            .into_iter()            .filter_map(|r| Some((s(&r, "phone_e164")?, s(&r, "display_name").filter(|n| !n.trim().is_empty())?)))            .collect()    };    // A reaction on its way to WhatsApp stands on its message: asked only of a page holding WhatsApp's messages.    let mut reacting = HashMap::new();    let mut voting = HashMap::new();    let mut changing = HashMap::new();    if let Some(thread) = page.iter().find(|m| s(m, "channel").as_deref() == Some("whatsapp")).and_then(|m| s(m, "thread_id")) {        let mut waiting = whatsapp_send::reactions_waiting(ctx, &thread)?;        let mut votes = whatsapp_send::votes_waiting(ctx, &thread)?;        let mut changes = whatsapp_send::changes_waiting(ctx, &thread)?;        if !waiting.is_empty() || !votes.is_empty() || !changes.is_empty() {            for m in page {                if let (Some(id), Some(external)) = (s(m, "id"), s(m, "external_id")) {                    if let Some(r) = waiting.remove(&external) {                        reacting.insert(id.clone(), r);                    }                    if let Some(c) = changes.remove(&external) {                        changing.insert(id.clone(), c);                    }                    if let Some(v) = votes.remove(&external) {                        voting.insert(id, v);                    }                }            }        }    }    Ok(Around { reactions, quoted, voters, reacting, voting, changing })}/// Where a bubble stands in its run (`lay::Slot::Message`).#[derive(Clone, Copy)]struct Place {    head: bool,    tail: bool,    face: bool,}struct Speaker<'a> {    lines: &'a LineSet,    t: &'a Summary,    named: &'a Named,    can: Can,    clock: &'a Clock,    /// The person's own number, whose country reads a number written in words without a code.    me: Option<String>,}impl Speaker<'_> {    /// Who wrote a message in a group, by the seat it came from, never an agent's name: whose agent it is.    fn who_seat(&self, m: &Map<String, Value>) -> String {        s(m, "sender_participant_id").and_then(|seat| self.named.seats.get(&seat).map(|(n, _)| n.clone())).unwrap_or_else(|| cotton_core::messages::display::UNKNOWN_NAME.to_string())    }    fn who(&self, m: &Map<String, Value>) -> String {        if let Some((_, name)) = super::chat_agent::agent_of(&meta_value_of(m)) {            return name;        }        if s(m, "direction").as_deref() == Some("out") {            return say(self.lines, "app.thread.you", &[]);        }        if !self.t.group {            return self.named.name.clone();        }        s(m, "sender_participant_id").and_then(|seat| self.named.seats.get(&seat).map(|(n, _)| n.clone())).unwrap_or_else(|| cotton_core::messages::display::UNKNOWN_NAME.to_string())    }    fn quote(&self, m: &Map<String, Value>) -> Quote {        let media = media_of(m);        let meta = meta_of(m);        let deleted = s(m, "deleted_at");        let r = Row { body: m.get("body").and_then(Value::as_str), media: &media, meta: meta.as_ref(), deleted_at: deleted.as_deref() };        Quote { message: s(m, "id"), sender: self.who(m), line: bubble::line_of(&r), mark: bubble::mark_of(&r) }    }    fn bubble(&self, m: &Map<String, Value>, place: Place, around: &Around) -> Bubble {        let Place { head, tail, face } = place;        let id = s(m, "id").unwrap_or_default();        let media = media_of(m);        let meta = meta_of(m);        let deleted = s(m, "deleted_at");        let r = Row { body: m.get("body").and_then(Value::as_str), media: &media, meta: meta.as_ref(), deleted_at: deleted.as_deref() };        // An agent's words are never drawn as the person's own, even when this phone sent them (chat_agent).        let agent = super::chat_agent::agent_of(&meta_value_of(m));        let mine = s(m, "direction").as_deref() == Some("out") && agent.is_none();        let at = s(m, "sent_at").unwrap_or_default();        let (time, _, _) = self.clock.slip(&at);        let pinned = self.t.pinned_messages.contains(&id);        let text = bubble::text_of(&r);        let editable = cotton_core::messages::edit_window::edit_window_remaining_ms(&at, &self.clock.now_iso()) > 0;        let agent_tag = agent.as_ref().map(|(id, name)| {            let ours = s(m, "direction").as_deref() == Some("out");            let line = if ours { say(self.lines, "app.group.agent_yours", &[]) } else { say(self.lines, "app.group.agent_of", &[("name", &self.who_seat(m))]) };            cotton_core::messages::app::shapes::AgentTag { id: id.clone(), name: name.clone(), line }        });        let sender = (self.t.group && !mine).then(|| {            if let Some(tag) = &agent_tag {                let key = format!("agent:{}", tag.id);                return Sender { picture: picture(&key, &tag.name, None), tint: lay::tint(&key), name: tag.name.clone() };            }            let seat = s(m, "sender_participant_id").unwrap_or_else(|| sender_key(m));            let (name, photo) = self.named.seats.get(&seat).cloned().unwrap_or_else(|| (self.who(m), None));            Sender { picture: picture(&seat, &name, photo), tint: lay::tint(&seat), name }        });        let forwarded = (s(m, "forward_of_id").is_some() || meta.as_ref().and_then(|m| m.forwarded) == Some(true)).then(|| say(self.lines, "app.thread.forwarded", &[]));        let edited = ((s(m, "edited_at").is_some() || meta.as_ref().and_then(|m| m.edited) == Some(true)) && !r.deleted()).then(|| say(self.lines, "app.thread.edited", &[]));        let reply = s(m, "reply_to_id").map(|reply| match around.quoted.get(&reply) {            Some(q) => self.quote(q),            None => Quote { message: None, sender: String::new(), line: say(self.lines, "app.refused.no_message", &[]), mark: None },        });        // An agent's words this phone sent still say where they stand ("Sending", failed), as the person's own would.        let tick = bubble::tick_of(s(m, "send_state").as_deref(), s(m, "channel").as_deref() == Some("cotton"), mine || (agent.is_some() && s(m, "direction").as_deref() == Some("out")));        // The numbers in its words, so a tap opens that number's chat (FEEDBACK-2 A).        let numbers = text.as_deref().filter(|_| !r.deleted()).map(|words| cotton_core::messages::app::numbers::numbers_in(words, self.me.as_deref())).unwrap_or_default();        // A poll is drawn as one; its words are the card's, never the text (CONTRACT "Polls shown").        let poll = meta.as_ref().and_then(|m| m.poll.as_ref()).filter(|_| !r.deleted()).map(|p| {            let mut card = cotton_core::messages::app::poll::card(self.lines, p, &|who| around.voters.get(who).cloned().or_else(|| cotton_core::cotton_rules::phone::international_words(who)).unwrap_or_else(|| format!("+{who}")));            // He votes where his Mac's link sends, on a poll the link brought (CONTRACT "Documents and votes").            card.votable = self.t.whatsapp_votes && p.live() && whatsapp_send::answerable(s(m, "channel").as_deref(), s(m, "external_id").as_deref());            if card.votable {                card.spoken = format!("{} {}", card.spoken, say(self.lines, "app.poll.vote", &[]));            }            card        });        let (text, numbers) = if poll.is_some() { (None, Vec::new()) } else { (text, numbers) };        // The links in its words, so a tap opens the page inside Comms.        let links = text.as_deref().filter(|_| !r.deleted()).map(cotton_core::messages::links::links_at).unwrap_or_default();        // His own WhatsApp message deleted for everyone, here or from WhatsApp itself, says he did.        let text = if r.deleted() && mine && s(m, "channel").as_deref() == Some("whatsapp") { Some(say(self.lines, "app.thread.you_deleted", &[])) } else { text };        let reacting = around.reacting.get(&id);        let voting = around.voting.get(&id);        let changing = around.changing.get(&id);        Bubble {            message: id.clone(),            mine,            kind: bubble::kind_of(&r),            sender,            agent: agent_tag,            head,            tail,            face,            time,            tick,            quiet_until: bubble::quiet_until(tick, {                let written = meta_value_of(m)["cotton"]["written_at"].as_str().map(str::to_string).unwrap_or_else(|| at.clone());                chrono::DateTime::parse_from_rfc3339(&written).ok().map(|t| t.timestamp_millis())            }),            edited,            forwarded,            pinned,            reply,            reactions: bubble::reactions(around.reactions.get(&id).map(Vec::as_slice).unwrap_or(&[])),            media: bubble::media_parts(&r),            link: bubble::link_of(&r),            actions: {                let mut acts = self.can.message_actions(mine, editable, r.deleted(), pinned, text.is_some() && !r.deleted());                // A message of the person's own that failed offers to be sent again, first.                if mine && s(m, "send_state").as_deref() == Some("failed") && self.can.send {                    acts.insert(0, "retry".to_string());                }                // In a Cotton group, the person's own words say who has them (`chat.group.receipts`), before Select.                // Star, beside Pin: private, the person's own.                if !r.deleted() {                    let at = acts.iter().position(|a| a == "pin" || a == "unpin").map_or(acts.len(), |i| i + 1);                    acts.insert(at, if s(m, "starred_at").is_some() { "unstar" } else { "star" }.to_string());                }                if mine && self.t.group && self.t.source == "cotton" && !r.deleted() {                    let at = acts.iter().position(|a| a == "select").unwrap_or(acts.len());                    acts.insert(at, "info".to_string());                }                // Through the Mac, only a message WhatsApp holds by its id can be replied or reacted to (CONTRACT                // "Replies and reactions"): not an export's, not a Cotton one.                if self.t.whatsapp_sends && !whatsapp_send::answerable(s(m, "channel").as_deref(), s(m, "external_id").as_deref()) {                    acts.retain(|a| a != "reply" && a != "react");                }                if self.t.whatsapp_sends {                    whatsapp_acts(&mut acts, m, &r, poll.is_some(), &self.clock.now_iso());                }                // His reaction, vote, edit or delete that did not go offers to be sent again, first.                let now_ms = self.clock.now.timestamp_millis();                if reacting.is_some_and(|r| whatsapp_send::reaction_retryable(r, now_ms))                    || voting.is_some_and(|v| whatsapp_send::vote_retryable(v, now_ms))                    || changing.is_some_and(|c| whatsapp_send::change_retryable(c, now_ms))                {                    acts.insert(0, "retry".to_string());                }                acts            },            text,            marks: Vec::new(),            starred: s(m, "starred_at").is_some(),            // Where his reaction stands while it goes to WhatsApp ("Reaction waiting to send", โ€ฆ).            // His vote's, on a poll ("Vote waiting to send", โ€ฆ), before a reaction's.            // His edit's or delete's, before both ("Edit waiting to send", "Waiting to delete for everyone", โ€ฆ).            state: changing                .map(|c| whatsapp_send::change_words(self.lines, c))                .or_else(|| voting.map(|v| whatsapp_send::vote_words(self.lines, v)))                .or_else(|| reacting.map(|r| whatsapp_send::reaction_words(self.lines, r)))                .or_else(|| sms_state(self.lines, m, mine)),            // Where each went or came by, in a chat holding both (FEEDBACK-2 A). A text the person chose in a Cotton            // chat ("Send as SMS instead") always says it is not private (DISCOVERY OFF 2); so does each text he sends            // in an SMS chat with someone he asked on Cotton, until they accept (DISCOVERY OFF 3).            place: if s(m, "channel").as_deref() == Some(super::chat_sms::CHANNEL) && (self.t.source != super::chat_sms::CHANNEL || (self.t.sms_asked && mine)) {                Some(compose::place_mark(self.lines, "sms_not_private"))            } else {                self.t.mixed.then(|| compose::place_mark(self.lines, if s(m, "channel").as_deref() == Some("whatsapp") { "whatsapp" } else { "cotton" }))            },            numbers,            links,            poll,        }    }}/// A message's acts in a WhatsApp chat that sends (CONTRACT "Editing and deleting his own message"): Edit only on his/// own text WhatsApp holds by its id, within WhatsApp's own 15 minutes; Delete (for everyone) on his own message/// WhatsApp holds, within 48 hours; Delete for me on any message, a marker excepted, before Select.fn whatsapp_acts(acts: &mut Vec<String>, m: &Map<String, Value>, r: &Row<'_>, poll: bool, now: &str) {    let held = whatsapp_send::answerable(s(m, "channel").as_deref(), s(m, "external_id").as_deref());    let at = s(m, "sent_at").unwrap_or_default();    if !held || poll || !r.media.is_empty() {        acts.retain(|a| a != "edit");    }    let late = cotton_core::messages::edit_window::delete_window_remaining_ms(&at, now) <= 0;    if !held || late {        acts.retain(|a| a != "delete");    }    if !r.deleted() {        let at = acts.iter().position(|a| a == "select").unwrap_or(acts.len());        acts.insert(at, "deleteMine".to_string());    }}fn thread_answer(client: &ClientController, request: &Value) -> Result<ThreadAnswer, MethodError> {    let thread = request.get("thread").and_then(Value::as_str).filter(|t| !t.is_empty()).ok_or_else(|| bad("thread", "a chat's id"))?.to_string();    let before = request.get("before").and_then(Value::as_str).and_then(parse_thread_cursor);    let after = request.get("after").and_then(Value::as_str).and_then(parse_thread_cursor);    let around_id = request.get("around").and_then(Value::as_str).map(str::to_string);    // A search open over the thread (`chat.search { thread }`): its matches are marked.    let find = request.get("find").and_then(Value::as_str).and_then(cotton_core::messages::app::find::query_of);    // COMMS WITHOUT MAIL (mail CONTRACT row 21): Comms weaves no mail into a chat any more, whatever an older shell    // asks (`mail: true`); a person's mail is read in Cotton Post.    let lines = list::lines();    let clock = Clock::of(client);    let you = say(&lines, "app.list.you", &[]);    let found = read(client, "chat.thread", |ctx| {        let Some(mut t) = summaries(ctx, Some(&thread))?.into_iter().next() else { return Ok(None) };        routed(ctx, &mut t)?;        let named = names(ctx, &[&t], &you)?.remove(&t.id).unwrap_or_default();        let mut focus = None;        // The page, oldest first, and the one message on each side of it.        let (page, above, below) = if let Some(cursor) = &before {            let mut older = side(ctx, &t, Some(cursor), true, false, THREAD_PAGE + 1)?;            let above = (older.len() > THREAD_PAGE).then(|| older.pop()).flatten();            older.reverse();            let below = side(ctx, &t, Some(cursor), false, true, 1)?.pop();            (older, above, below)        } else if let Some(cursor) = &after {            let mut newer = side(ctx, &t, Some(cursor), false, false, THREAD_PAGE + 1)?;            let below = (newer.len() > THREAD_PAGE).then(|| newer.pop()).flatten();            let above = side(ctx, &t, Some(cursor), true, true, 1)?.pop();            (newer, above, below)        } else if let Some(target) = &around_id {            let Some(hit) = one(ctx, &format!("SELECT rowid AS _row, id, sent_at FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND id = ?"), &[ws(ctx), text(t.id.clone()), text(target.clone())])? else {                return Ok(None);            };            focus = Some(target.clone());            let point = (s(&hit, "sent_at").unwrap_or_default(), n(&hit, "_row"));            let half = THREAD_PAGE / 2;            let mut older = side(ctx, &t, Some(&point), true, true, half + 1)?;            let above = (older.len() > half).then(|| older.pop()).flatten();            older.reverse();            let mut newer = side(ctx, &t, Some(&point), false, false, half + 1)?;            let below = (newer.len() > half).then(|| newer.pop()).flatten();            older.extend(newer);            (older, above, below)        } else {            let mut newest = side(ctx, &t, None, true, false, THREAD_PAGE + 1)?;            let above = (newest.len() > THREAD_PAGE).then(|| newest.pop()).flatten();            newest.reverse();            (newest, above, None)        };        let unread_from = first_unread(ctx, &t)?;        let extras = around(ctx, &page)?;        let pinned_rows = if t.pinned_messages.is_empty() {            Vec::new()        } else {            rows_in(ctx, &format!("SELECT {MESSAGE_COLUMNS} FROM {MESSAGES} WHERE workspace_id = ? AND deleted_at IS NULL AND trashed_at IS NULL"), "id", &t.pinned_messages)?        };        // Jump to latest: what stands below the page.        // Counted to the badge's ceiling, never through the whole thread.        let below_count = match (&below, page.last()) {            (Some(_), Some(last)) => {                let at = s(last, "sent_at").unwrap_or_default();                n(                    &one(ctx, &format!("SELECT COUNT(*) AS n FROM (SELECT 1 FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND trashed_at IS NULL AND hidden_at IS NULL AND sent_at >= ? AND (sent_at > ? OR rowid < ?) LIMIT {COUNT_CEILING})"), &[ws(ctx), text(t.id.clone()), text(at.clone()), text(at), SqlValue::Integer(n(last, "_row"))])?.unwrap_or_default(),                    "n",                )            }            _ => 0,        };        let draft_quote = match &t.draft_reply {            Some(id) => one(ctx, &format!("SELECT {MESSAGE_COLUMNS} FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(id.clone())])?,            None => None,        };        // The texts on their way through the Mac stand at the foot of the newest page.        let pending = if (t.source == "whatsapp" || t.linked) && below.is_none() && before.is_none() { whatsapp_send::pending(ctx, &t.id)? } else { Vec::new() };        let pending_quotes = pending_quoted(ctx, &t.id, &pending)?;        let tiles = if t.source == "whatsapp" || t.linked { whatsapp_send::sent_tiles(ctx, &t.id)? } else { HashMap::new() };        Ok(Some((t, named, page, above, below, unread_from, extras, pinned_rows, below_count, focus, draft_quote, (pending, pending_quotes, tiles))))    })?;    let Some((t, named, mut page, above, below, unread_from, extras, pinned_rows, below_count, focus, draft_quote, (pending, pending_quotes, tiles))) = found else {        return Err(MethodError::new("not_found", say(&lines, "app.refused.no_message", &[])));    };    let can = t.can();    // A WhatsApp chat's timer is the person's own copy's (FEEDBACK-2 B.2): they set it wherever they read the chat.    // So is a Cotton chat whose words go to their WhatsApp (not on Cotton, FEEDBACK-2 A): there is no Cotton timer to    // agree on, and what lands there comes back from WhatsApp, so his copy's timer is the one there is (lane    // android-finish, 23 Nov 2026: the row stood on every chat but these).    let timer = if t.source == "cotton" || t.source == "whatsapp" {        let id = t.id.clone();        let seconds = read(client, "chat.timer", |ctx| super::chat_timer::timer_of(ctx, &id))?;        Some(if t.source == "cotton" && !t.whatsapp_sends { cotton_core::messages::app::timer::card(&lines, seconds, can.send) } else { cotton_core::messages::app::timer::own_card(&lines, seconds) })    } else {        None    };    let speaker = Speaker { lines: &lines, t: &t, named: &named, can, clock: &clock, me: cotton_chat::own_number(client) };    // One tap's pictures to WhatsApp, landed a message each, stand as one grid headed by the first (FEEDBACK-4 B3).    let mut joined: HashMap<String, Vec<Map<String, Value>>> = HashMap::new();    let runs = grids(&page, &tiles);    if !runs.is_empty() {        let skip: HashSet<usize> = runs.iter().flat_map(|run| run[1..].iter().copied()).collect();        for run in &runs {            joined.insert(s(&page[run[0]], "id").unwrap_or_default(), run[1..].iter().map(|i| page[*i].clone()).collect());        }        page = page.into_iter().enumerate().filter(|(i, _)| !skip.contains(i)).map(|(_, m)| m).collect();    }    let page_laid: Vec<Laid> = page.iter().map(|m| laid(&clock, &lines, m)).collect();    let above_laid = above.as_ref().map(|m| laid(&clock, &lines, m));    let below_laid = below.as_ref().map(|m| laid(&clock, &lines, m));    let unread_id = unread_from.as_ref().and_then(|m| s(m, "id"));    let mut items = Vec::with_capacity(page.len() + 4);    for slot in lay::lay(&page_laid, above_laid.as_ref(), below_laid.as_ref(), unread_id.as_deref()) {        match slot {            Slot::Day { index } => {                let (_, heading, day) = clock.slip(&s(&page[index], "sent_at").unwrap_or_default());                let (numeral, words) = clock.numeral(&lines, day);                items.push(Item::Day { label: heading, numeral: Some(numeral), words: Some(words) });            }            Slot::Unread { .. } => {                items.push(Item::Unread { label: say(&lines, "app.thread.unread", &[("n", &badge(t.unread))]) });            }            Slot::Message { index, head, tail, face } => {                let m = &page[index];                if page_laid[index].event {                    let media = media_of(m);                    let meta = meta_of(m);                    let r = Row { body: m.get("body").and_then(Value::as_str), media: &media, meta: meta.as_ref(), deleted_at: None };                    // A timer line says who set it, to whoever reads it (chat_timer); a safety number's line names them as this phone does (chat_safety).                    let meta_v = meta_value_of(m);                    let cotton = &meta_v["cotton"];                    let text = match cotton["timer"].as_u64() {                        Some(seconds) => {                            let by = (s(m, "direction").as_deref() != Some("out")).then(|| speaker.who(m));                            cotton_core::messages::app::timer::event_line(&lines, seconds as u32, by.as_deref())                        }                        None if cotton["safety"].is_object() => say(&lines, "app.safety.changed", &[("name", &speaker.who(m))]),                        None => imported_call(&lines, m).unwrap_or_else(|| bubble::line_of(&r)),                    };                    // A safety number's line opens its screen.                    let opens = cotton["safety"].is_object().then(|| "safety".to_string());                    items.push(Item::Event { message: s(m, "id").unwrap_or_default(), text, opens });                } else {                    let mut b = speaker.bubble(m, Place { head, tail, face }, &extras);                    mark_gone(client, m, &mut b);                    if let Some(rest) = joined.get(&b.message) {                        join_tiles(client, &mut b, rest);                    }                    if let (Some(q), Some(words)) = (&find, &b.text) {                        b.marks = cotton_core::messages::app::find::marks(words, q);                    }                    items.push(Item::Bubble(b));                }            }        }    }    for (i, tap) in whatsapp_send::taps(&pending).iter().enumerate() {        let head = i == 0 && !matches!(items.last(), Some(Item::Bubble(b)) if b.mine);        let mut b = whatsapp_send::tap_bubble(&lines, &clock, tap, head);        b.place = t.mixed.then(|| compose::place_mark(&lines, "whatsapp"));        b.reply = pending_quote(&speaker, tap[0], &pending_quotes);        items.push(Item::Bubble(b));    }    // One to one, a timer that is on stands under the name; a group's page says it beside its members.    let status = if t.group { Some(say(&lines, "app.thread.members", &[("n", &named.members.to_string())])) } else { timer.as_ref().and_then(|c| c.label.clone()) };    let acts = if t.whatsapp_source_acts {        vec![            Swipe { act: "blockOnWhatsApp".into(), label: say(&lines, "app.hold.block_on_whatsapp", &[]), confirm: Some(say(&lines, "app.confirm.block_on_whatsapp", &[("name", &named.name)])) },            // Its question carries the count, so the act answers it first (`count_first`).            Swipe { act: "deleteOnWhatsApp".into(), label: say(&lines, "app.hold.delete_on_whatsapp", &[]), confirm: None },        ]    } else {        Vec::new()    };    let header = Header { name: named.name.clone(), picture: picture(&t.id, &named.name, named.photo.clone()), group: t.group, source: t.source.clone(), status, place: t.place(&lines), acts };    // The newest pin stands in the bar.    let mut pins: Vec<&Map<String, Value>> = t.pinned_messages.iter().filter_map(|id| pinned_rows.iter().find(|r| s(r, "id").as_deref() == Some(id))).collect();    let pinned = pins.pop().map(|m| {        let count = (pins.len() + 1) as u32;        let title = if count > 1 { say(&lines, "app.thread.pinned_many", &[("i", &count.to_string()), ("n", &count.to_string())]) } else { say(&lines, "app.thread.pinned", &[]) };        PinnedBar { message: s(m, "id").unwrap_or_default(), title, line: speaker.quote(m).line, count }    });    let composer = can.send.then(|| {        let quoted = draft_quote.as_ref().map(|q| {            let quote = speaker.quote(q);            Quoted { message: quote.message.unwrap_or_default(), sender: quote.sender, line: quote.line }        });        let mut answer = compose::answer(&lines, &t.id, &can, t.draft.as_deref().unwrap_or(""), quoted.as_ref(), None, 0);        answer.place = t.place(&lines);        answer.poll = t.whatsapp_polls.then(|| compose::poll_maker(&lines));        answer.preview = offered_preview(client, &t, t.draft.as_deref().unwrap_or(""));        answer    });    // A Cotton group the person is out of (left or removed) says so; an imported chat says where it came from.    let read_only = (!can.send).then(|| {        if t.source == super::chat_sms::CHANNEL {            // Texts go only from the Android phone holding the SMS role; a sender with a name takes no reply.            return say(&lines, if t.sms_named { "app.sms.no_reply" } else { "app.sms.elsewhere" }, &[]);        }        if t.group && t.source == "cotton" { say(&lines, "app.group.left", &[]) } else { say(&lines, "app.thread.read_only", &[("source", &list::source_name(&lines, &t.source))]) }    });    let request = (t.request.as_deref() == Some("pending")).then(|| {        let title = if t.contact.is_some() { say(&lines, "request.title", &[("name", &named.name)]) } else { say(&lines, "request.unknown_title", &[]) };        RequestCard { title, line: say(&lines, "request.line", &[]), accept: say(&lines, "request.accept", &[]), block: say(&lines, "request.block", &[]), refuse: say(&lines, "request.refuse", &[]) }    });    Ok(ThreadAnswer {        request,        thread: t.id.clone(),        header,        pinned,        older: above.as_ref().and(page.first()).map(thread_cursor),        newer: below.as_ref().and(page.last()).map(thread_cursor),        focus,        unread: t.unread,        jump: (below_count > 0).then(|| Jump { count: below_count as u32, label: say(&lines, "app.thread.jump", &[]), badge: badge(below_count as u32) }),        composer,        read_only,        actions: action_words(&lines, t.whatsapp_sends),        loading: (items.is_empty() && crate::methods::shell_home::first_pull_running(client)).then(|| say(&lines, "app.thread.loading", &[])),        items,        timer,    })}// โ”€โ”€ the composer โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€fn compose_answer(client: &ClientController, request: &Value) -> Result<ComposeAnswer, MethodError> {    let thread = request.get("thread").and_then(Value::as_str).filter(|t| !t.is_empty()).ok_or_else(|| bad("thread", "a chat's id"))?.to_string();    let typed = request.get("text").and_then(Value::as_str).map(str::to_string);    let reply_to = request.get("replyTo").and_then(Value::as_str).map(str::to_string);    let edit = request.get("edit").and_then(Value::as_str).map(str::to_string);    let cancel = request.get("cancel").and_then(Value::as_bool).unwrap_or(false);    let keep = request.get("keep").and_then(Value::as_bool).unwrap_or(false);    // Pictures waiting in the writing box, to go with what is written as their caption.    let attached = request.get("attached").and_then(Value::as_u64).unwrap_or(0) as usize;    let lines = list::lines();    let clock = Clock::of(client);    let you = say(&lines, "app.list.you", &[]);    let t = read(client, "chat.compose", |ctx| {        let Some(mut t) = summaries(ctx, Some(&thread))?.into_iter().next() else { return Ok(None) };        routed(ctx, &mut t)?;        let named = names(ctx, &[&t], &you)?.remove(&t.id).unwrap_or_default();        let reply_id = if cancel { None } else { reply_to.clone().or_else(|| t.draft_reply.clone()) };        let fetch = |ctx: &mut Ctx<'_>, id: &Option<String>| -> Result<Option<Map<String, Value>>, String> {            match id {                Some(id) => one(ctx, &format!("SELECT {MESSAGE_COLUMNS} FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND id = ?"), &[ws(ctx), text(t.id.clone()), text(id.clone())]),                None => Ok(None),            }        };        let reply_row = fetch(ctx, &reply_id)?;        let edit_row = if cancel { None } else { fetch(ctx, &edit)? };        // A reply newly asked for in a chat whose words go to WhatsApp: only to a message WhatsApp holds.        let unanswered = match (&reply_to, t.whatsapp_sends && !cancel) {            (Some(id), true) => whatsapp_send::whatsapp_id_of(ctx, &t.id, id)?.err(),            _ => None,        };        Ok(Some((t, named, reply_row, edit_row, unanswered)))    })?    .ok_or_else(|| refuse(&lines, "not_found", "app.refused.no_message"))?;    let (t, named, reply_row, edit_row, unanswered) = (t.0, t.1, t.2, t.3, t.4);    let can = t.can();    if !can.send {        return Err(MethodError::new("cannot", say(&lines, "app.refused.cannot", &[])));    }    if reply_to.is_some() && !cancel && t.whatsapp_sends {        if !can.reply {            return Err(refuse(&lines, "cannot", "app.refused.cannot"));        }        if let Some(why) = unanswered {            return Err(unanswerable(&lines, why, false));        }    }    let speaker = Speaker { lines: &lines, t: &t, named: &named, can, clock: &clock, me: cotton_chat::own_number(client) };    let as_quoted = |m: &Map<String, Value>| {        let q = speaker.quote(m);        Quoted { message: q.message.unwrap_or_default(), sender: q.sender, line: q.line }    };    if let Some(m) = &edit_row {        if s(m, "direction").as_deref() != Some("out") || !can.edit {            return Err(MethodError::new("not_yours", say(&lines, "app.refused.not_yours", &[])));        }    }    let editing = edit_row.as_ref().map(as_quoted);    let replying = reply_row.as_ref().map(as_quoted);    // Starting an edit fills the field with the message as written.    let text_now = match (&typed, &edit_row) {        (Some(typed), _) => typed.clone(),        (None, Some(m)) if edit.is_some() => s(m, "body").unwrap_or_default(),        _ => t.draft.clone().unwrap_or_default(),    };    // The draft and its reply are kept on the device when the strip changes,    // or when the shell says the thread is being left (`keep`).    let reply_changed = cancel || (reply_to.is_some() && reply_to != t.draft_reply);    if editing.is_none() && (keep || reply_changed) {        let draft = Some(text_now.clone()).filter(|d| compose::has_text(d));        let reply_keep = replying.as_ref().map(|q| q.message.clone());        let id = t.id.clone();        write(client, "chat.draft", |ctx| {            let mut patch = Map::new();            patch.insert("draft".into(), draft.clone().map_or(Value::Null, Value::from));            patch.insert("draft_reply_to_id".into(), reply_keep.clone().map_or(Value::Null, Value::from));            update_row(ctx, THREADS, &id, patch).map_err(|f| f.to_string())?;            Ok(())        })?;    }    let mut answer = compose::answer(&lines, &t.id, &can, &text_now, replying.as_ref(), editing.as_ref(), attached);    answer.place = t.place(&lines);    answer.poll = (t.whatsapp_polls && editing.is_none()).then(|| compose::poll_maker(&lines));    answer.preview = if editing.is_none() { offered_preview(client, &t, &text_now) } else { None };    Ok(answer)}/// Whether a link card goes with what is written in `t` (FEEDBACK-4 B4): this phone fetches them, and the chat/// carries one (a Cotton chat, or WhatsApp where the served outbox has `link`).fn takes_previews(client: &ClientController, t: &Summary) -> bool {    let carries = if t.whatsapp_sends { t.whatsapp_links } else { t.source == "cotton" };    carries && t.can().send && cotton_chat::link_previews(client)}/// The link the words being written offer a card for, where one goes.fn offered_preview(client: &ClientController, t: &Summary, text: &str) -> Option<PreviewAsk> {    takes_previews(client, t).then(|| cotton_core::messages::app::preview::offer(text)).flatten().map(|url| PreviewAsk { url })}/// `chat.linkCard {thread, url, page}` (chat CONTRACT.md "Link previews"): the page this phone fetched from `url`,/// read as its card; `{}` where no card goes, or the page names no title.pub(crate) fn preview(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let thread = request.get("thread").and_then(Value::as_str).filter(|t| !t.is_empty()).ok_or_else(|| bad("thread", "a chat's id"))?.to_string();    let url = request.get("url").and_then(Value::as_str).ok_or_else(|| bad("url", "the link fetched"))?.to_string();    let page = request.get("page").and_then(Value::as_str).unwrap_or_default();    let t = read(client, "chat.linkCard", |ctx| {        let Some(mut t) = summaries(ctx, Some(&thread))?.into_iter().next() else { return Ok(None) };        routed(ctx, &mut t)?;        Ok(Some(t))    })?;    let card = t.filter(|t| takes_previews(client, t) && cotton_core::messages::app::preview::fetchable(&url)).and_then(|_| cotton_core::messages::app::preview::read_page(&url, page));    Ok(card.map(|c| serde_json::to_value(c).unwrap_or(Value::Null)).unwrap_or_else(|| json!({})))}/// Where a message written in `thread` goes, exactly as its page marks it (FEEDBACK-2 A): `None` on an unlinked copy/// or where nothing can be written. `chat.start` answers it.pub(crate) fn place_of(client: &ClientController, thread: &str) -> Result<Option<PlaceMark>, MethodError> {    let lines = list::lines();    let id = thread.to_string();    read(client, "chat.place", |ctx| {        let Some(mut t) = summaries(ctx, Some(&id))?.into_iter().next() else { return Ok(None) };        routed(ctx, &mut t)?;        Ok(t.place(&lines))    })}/// Where a text written in `t` goes (FEEDBACK-2 A): out through the Mac for a WhatsApp chat with an address, and for a/// Cotton chat with a number the route sends to WhatsApp (not on Cotton, on a linked copy); else on Cotton.fn routed(ctx: &mut Ctx<'_>, t: &mut Summary) -> Result<(), String> {    t.whatsapp_sends = match t.source.as_str() {        "whatsapp" => whatsapp_send::sends(ctx, &t.id)?,        "cotton" if !t.group => whatsapp_send::sends(ctx, &t.id)?,        _ => false,    };    t.whatsapp_files = t.whatsapp_sends && whatsapp_send::takes_files(ctx)?;    t.whatsapp_answers = t.whatsapp_sends && whatsapp_send::takes_answers(ctx)?;    t.whatsapp_documents = t.whatsapp_files && whatsapp_send::takes_documents(ctx)?;    t.whatsapp_votes = t.whatsapp_sends && whatsapp_send::takes_votes(ctx)?;    t.whatsapp_changes = t.whatsapp_sends && whatsapp_send::takes_changes(ctx)?;    t.whatsapp_polls = t.whatsapp_sends && whatsapp_send::takes_polls(ctx)?;    t.whatsapp_links = t.whatsapp_sends && whatsapp_send::takes_links(ctx)?;    t.whatsapp_source_acts = t.whatsapp_sends && !t.group && whatsapp_send::takes_source_acts(ctx)?;    t.linked = whatsapp_send::link(ctx)?.is_some();    t.mixed = t.linked && !t.group && whatsapp_send::mixed(ctx, &t.id)?;    t.sms_sends = t.source == super::chat_sms::CHANNEL && !t.group && t.sms_to.is_some() && super::chat_sms::held(ctx);    t.sms_asked = t.source == super::chat_sms::CHANNEL && !t.group && asked_not_yet(ctx, t.contact.as_deref())?;    Ok(())}/// Whether this contact was asked on Cotton from this phone and has not accepted (`asked_at` set, `on_cotton_at` not).fn asked_not_yet(ctx: &mut Ctx<'_>, contact: Option<&str>) -> Result<bool, String> {    let Some(contact) = contact else { return Ok(false) };    if !super::cotton_chat::holds(ctx, cotton_chat::CONTACTS, "asked_at")? {        return Ok(false);    }    Ok(cotton_chat::one(ctx, &format!("SELECT 1 AS one FROM {} WHERE workspace_id = ? AND id = ? AND asked_at IS NOT NULL AND on_cotton_at IS NULL", cotton_chat::CONTACTS), &[cotton_chat::ws(ctx), SqlValue::Text(contact.to_string())])?.is_some())}// โ”€โ”€ acts โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€/// A change to a Cotton message waits on its conversation for `chat.flush`/// to tell the other side; an imported one changes nothing elsewhere.fn tell_later(ctx: &mut Ctx<'_>, t: &Summary, message: &str, what: What, emoji: Option<&str>, body: Option<&str>, at: i64) -> Result<bool, String> {    if t.source != "cotton" {        return Ok(false);    }    let Some(external) = one(ctx, &format!("SELECT external_id FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(message.to_string())])?.and_then(|r| s(&r, "external_id")) else {        return Ok(false);    };    cotton_chat::wait_change(ctx, &t.id, what, &external, emoji, body, at)?;    Ok(true)}fn refuse(lines: &LineSet, code: &str, line: &str) -> MethodError {    MethodError::new(code, say(lines, line, &[]))}fn act(client: &ClientController, request: &Value) -> Result<ActAnswer, MethodError> {    let verb = request.get("act").and_then(Value::as_str).filter(|a| ACTS.contains(a)).ok_or_else(|| bad("act", &ACTS.join(", ")))?.to_string();    let thread = request.get("thread").and_then(Value::as_str).filter(|t| !t.is_empty()).ok_or_else(|| bad("thread", "a chat's id"))?.to_string();    let message = request.get("message").and_then(Value::as_str).map(str::to_string);    let lines = list::lines();    let clock = Clock::of(client);    let t = read(client, "chat.act", |ctx| {        let Some(mut t) = summaries(ctx, Some(&thread))?.into_iter().next() else { return Ok(None) };        routed(ctx, &mut t)?;        Ok(Some(t))    })?    .ok_or_else(|| refuse(&lines, "not_found", "app.refused.no_message"))?;    let can = t.can();    let now = clock.now_iso();    let at_ms = clock.now.timestamp_millis();    let mut answer = ActAnswer { ok: true, act: verb.clone(), thread: thread.clone(), message: message.clone(), bubble: None, row: None, sent_to: Vec::new(), flush: false, said: None };    let patch_thread = |patch: Map<String, Value>| -> Result<(), MethodError> {        let id = thread.clone();        write(client, "chat.act", |ctx| update_row(ctx, THREADS, &id, patch.clone()).map_err(|f| f.to_string()))    };    let said = |line: &str| Some(say(&lines, line, &[]));    match verb.as_str() {        "send" => {            if !can.send {                return Err(refuse(&lines, "cannot", "app.refused.cannot"));            }            let body = request.get("text").and_then(Value::as_str).map(str::to_string);            // Attachments: photos, videos, files, a voice message, each {path, mime, name?, width?, height?, kind?, durationMs?, waveform?}.            let attachments: Vec<Value> = request.get("attachments").and_then(Value::as_array).cloned().unwrap_or_default();            if !attachments.is_empty() && !can.attach {                return Err(refuse(&lines, "cannot", "app.refused.cannot"));            }            if attachments.iter().any(|a| a.get("kind").and_then(Value::as_str) == Some("voice")) && !can.voice {                return Err(refuse(&lines, "cannot", "app.refused.cannot"));            }            if !body.as_deref().is_some_and(compose::has_text) && attachments.is_empty() {                return Err(refuse(&lines, "empty", "app.refused.empty"));            }            if t.whatsapp_sends {                // Through the Mac's link: one outbox row, its WhatsApp id fixed by this tap. Not flushed: the Cotton                // network never carries it.                let words = body.clone().unwrap_or_default();                if words.len() > cotton_core::chat::payload::BODY_MAX {                    return Err(MethodError::new("too_long", "That message is too long to send."));                }                let th = thread.clone();                // A reply names the WhatsApp id it answers: only a message WhatsApp holds (CONTRACT "Replies and                // reactions"). Before, the quote was dropped and the reply went as a plain text.                let quoted = match request.get("replyTo").and_then(Value::as_str).map(str::to_string).or_else(|| t.draft_reply.clone()) {                    Some(reply) => {                        if !can.reply {                            return Err(refuse(&lines, "cannot", "app.refused.cannot"));                        }                        let found = read(client, "chat.send.quote", |ctx| whatsapp_send::whatsapp_id_of(ctx, &th, &reply))?;                        Some(found.map_err(|why| unanswerable(&lines, why, false))?)                    }                    None => None,                };                // Files first into his own media (the bubble's file, the one the Mac opens), then one row each.                // A text's link card, fetched by this phone, where the outbox carries one (FEEDBACK-4 B4).                let card = request.get("preview").filter(|_| attachments.is_empty() && takes_previews(client, &t)).and_then(|c| cotton_core::messages::app::preview::checked(c, &words));                let id = if let Some(card) = &card {                    write(client, "chat.send.whatsapp", |ctx| whatsapp_send::queue_with_link(ctx, &th, &words, quoted.as_deref(), card))?                } else if attachments.is_empty() {                    write(client, "chat.send.whatsapp", |ctx| whatsapp_send::queue(ctx, &th, &words, quoted.as_deref()))?                } else {                    let files = whatsapp_send::keep_files(client, &thread, &attachments, t.whatsapp_documents)?;                    let ids = write(client, "chat.send.whatsapp", |ctx| whatsapp_send::queue_files(ctx, &th, &words, &files, quoted.as_deref()))?;                    ids.into_iter().next().ok_or_else(|| refuse(&lines, "empty", "app.refused.empty"))?                };                let mut clear = Map::new();                clear.insert("draft".into(), Value::Null);                clear.insert("draft_reply_to_id".into(), Value::Null);                patch_thread(clear)?;                answer.bubble = pending_bubble(client, &t, &lines, &clock, &id)?;                answer.message = Some(format!("{}{id}", whatsapp_send::PENDING));                answer.said = Some(say(&lines, "state.queued", &[]));                return Ok(answer);            }            if t.sms_sends {                // A text from this phone (DECISIONS "SMS on Android"): one row waiting; the phone sends it on the data                // event (`chat.sms.outbox`) and says how it went (`chat.sms.sent`).                let words = body.clone().unwrap_or_default();                if !attachments.is_empty() {                    return Err(refuse(&lines, "cannot", "app.refused.cannot"));                }                let (th, to, ns) = (thread.clone(), t.sms_to.clone().unwrap_or_default(), cotton_chat::namespace(client)?);                let id: String = write(client, "chat.send.sms", |ctx| super::chat_sms::queue(ctx, &ns, &th, &to, &words, at_ms))?;                let mut clear = Map::new();                clear.insert("draft".into(), Value::Null);                clear.insert("draft_reply_to_id".into(), Value::Null);                patch_thread(clear)?;                answer.bubble = bubble_of(client, &t, &id)?;                answer.message = Some(id);                return Ok(answer);            }            if request.get("asSms").and_then(Value::as_bool) == Some(true) {                // "Send as SMS instead" (DISCOVERY OFF 2): in a Cotton chat with someone not on Cotton here, on the                // phone holding the SMS role, the person chose this one message to go as a text, words only. It is                // marked "SMS ยท not private" in the chat and goes by the phone's own outbox (`chat.sms.outbox`).                if t.source != "cotton" || t.group || !attachments.is_empty() || !super::chat_sms::texts_here(client)? {                    return Err(refuse(&lines, "cannot", "app.refused.cannot"));                }                let words = body.clone().unwrap_or_default();                let to = cotton_chat::thread_number(client, &thread)?;                let (th, ns) = (thread.clone(), cotton_chat::namespace(client)?);                let id: String = write(client, "chat.send.sms", |ctx| super::chat_sms::queue(ctx, &ns, &th, &to, &words, at_ms))?;                let mut clear = Map::new();                clear.insert("draft".into(), Value::Null);                clear.insert("draft_reply_to_id".into(), Value::Null);                patch_thread(clear)?;                answer.bubble = bubble_of(client, &t, &id)?;                answer.message = Some(id);                return Ok(answer);            }            // The strip the writing box stands answers the send, named again or not (the iPhone names it only to            // `chat.compose`): the owner's reply on 23 Nov 2026 went without its quote.            let reply = request.get("replyTo").and_then(Value::as_str).map(str::to_string).or_else(|| t.draft_reply.clone());            let card = request.get("preview").filter(|_| takes_previews(client, &t)).and_then(|c| cotton_core::messages::app::preview::checked(c, body.as_deref().unwrap_or_default()));            let id = cotton_chat::queue(client, &thread, body, attachments, reply, None)?;            // Its link card, fetched by this phone, kept with it and carried to them (FEEDBACK-4 B4).            if let Some(card) = &card {                cotton_chat::put_preview(client, &id, card)?;            }            let mut clear = Map::new();            clear.insert("draft".into(), Value::Null);            clear.insert("draft_reply_to_id".into(), Value::Null);            patch_thread(clear)?;            answer.bubble = bubble_of(client, &t, &id)?;            answer.message = Some(id);            answer.flush = true;        }        "transcript" => {            // The phone that recorded a voice message heard its words: kept on the message, then told as a change            // after it (the message never waits for them). Once only; no words, nothing changes.            let message = message.clone().ok_or_else(|| bad("message", "a message's id"))?;            if let Some(words) = request.get("text").and_then(Value::as_str).and_then(cotton_chat::transcript_of) {                let id = message.clone();                let told = write(client, "chat.act", |ctx| {                    let Some(m) = one(ctx, &format!("SELECT direction, meta FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND id = ?"), &[ws(ctx), text(thread.clone()), text(id.clone())])? else { return Ok(false) };                    let mut meta = cotton_chat::meta_value(m.get("meta").unwrap_or(&Value::Null));                    let voice = ["pictures", "pending_pictures"].iter().any(|list| meta["cotton"][*list].as_array().into_iter().flatten().any(|p| p["kind"] == json!("voice")));                    if s(&m, "direction").as_deref() != Some("out") || !voice || meta["cotton"]["transcript"].is_string() {                        return Ok(false);                    }                    meta["cotton"]["transcript"] = json!(words);                    let mut patch = Map::new();                    patch.insert("meta".into(), meta);                    update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?;                    tell_later(ctx, &t, &id, What::Transcript, None, Some(&words), at_ms)                })?;                answer.flush = told;            }            answer.bubble = bubble_of(client, &t, &message)?;        }        "played" => {            // A voice message of theirs played a second here (or to its end, when shorter): kept on the person's            // own copy, so their other phones draw it played too. Once set, never cleared, and never told to the            // sender: there is no "listened" receipt.            let message = message.clone().ok_or_else(|| bad("message", "a message's id"))?;            let id = message.clone();            let found = write(client, "chat.act", |ctx| {                let Some(m) = one(ctx, &format!("SELECT direction, media, meta FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND id = ?"), &[ws(ctx), text(thread.clone()), text(id.clone())])? else { return Ok(false) };                let mut meta = cotton_chat::meta_value(m.get("meta").unwrap_or(&Value::Null));                if s(&m, "direction").as_deref() == Some("out") || meta["cotton"]["played_at"].is_string() {                    return Ok(true);                }                let voice = media_of(&m).iter().any(|f| cotton_core::messages::preview::media_kind_of(f) == cotton_core::constants::MessageMediaKind::Voice);                if !voice {                    return Ok(true);                }                meta["cotton"]["played_at"] = json!(now);                let mut patch = Map::new();                patch.insert("meta".into(), meta);                update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?;                Ok(true)            })?;            if !found {                return Err(refuse(&lines, "not_found", "app.refused.no_message"));            }            answer.bubble = bubble_of(client, &t, &message)?;        }        "retry" => {            let message = message.clone().ok_or_else(|| bad("message", "a message's id"))?;            if let Some(id) = message.strip_prefix(whatsapp_send::PENDING) {                // A text through the Mac goes again under the same WhatsApp id: WhatsApp keeps one.                let (th, row) = (thread.clone(), id.to_string());                if !write(client, "chat.retry.whatsapp", |ctx| whatsapp_send::retry(ctx, &th, &row, at_ms))? {                    return Err(refuse(&lines, "cannot", "app.refused.cannot"));                }                answer.bubble = pending_bubble(client, &t, &lines, &clock, id)?;                return Ok(answer);            }            if t.whatsapp_sends {                // His vote or reaction on this message that did not go to WhatsApp: the same row and WhatsApp id again,                // the vote first.                let (th, m) = (thread.clone(), message.clone());                let retried = write(client, "chat.retry.reaction", |ctx| {                    // His edit, or his delete for everyone (named by the marker in the message's place), before both.                    let external = one(ctx, &format!("SELECT external_id FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND id = ?"), &[ws(ctx), text(th.clone()), text(m.clone())])?.and_then(|r| s(&r, "external_id"));                    if let Some(external) = external.filter(|e| !e.is_empty()) {                        if whatsapp_send::retry_change(ctx, &th, &external, at_ms)? {                            return Ok(true);                        }                    }                    match whatsapp_send::whatsapp_id_of(ctx, &th, &m)? {                        Ok(to) => Ok(whatsapp_send::retry_vote(ctx, &th, &to, at_ms)? || whatsapp_send::retry_reaction(ctx, &th, &to, at_ms)?),                        Err(_) => Ok(false),                    }                })?;                if !retried {                    return Err(refuse(&lines, "cannot", "app.refused.cannot"));                }                answer.bubble = bubble_of(client, &t, &message)?;                return Ok(answer);            }            cotton_chat::requeue(client, &message)?;            answer.bubble = bubble_of(client, &t, &message)?;            answer.flush = true;        }        "vote" => {            // A tap on option `option` of a WhatsApp poll (CONTRACT "Documents and votes"): his choice drawn on the            // poll at once, and one outbox row naming the poll's WhatsApp id with the words he picked; a change while            // it waits rewrites that row. The echo the Mac's link brings back is the same choice: nothing moves.            if !t.whatsapp_votes {                return Err(refuse(&lines, "cannot", "app.refused.cannot"));            }            let message = message.clone().ok_or_else(|| bad("message", "a message's id"))?;            let option = request.get("option").and_then(Value::as_u64).ok_or_else(|| bad("option", "an option's place, 0 first"))? as u32;            let (m, th, at) = (message.clone(), thread.clone(), now.clone());            let to = read(client, "chat.vote", |ctx| whatsapp_send::whatsapp_id_of(ctx, &th, &m))?.map_err(|why| unanswerable(&lines, why, true))?;            let voted = write(client, "chat.vote", |ctx| {                let Some(row) = one(ctx, &format!("SELECT meta FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(m.clone())])? else { return Ok(false) };                let mut meta = cotton_chat::meta_value(row.get("meta").unwrap_or(&Value::Null));                let Some(poll) = serde_json::from_value::<cotton_core::messages::MessagePoll>(meta["poll"].clone()).ok().filter(|p| p.live()) else { return Ok(false) };                if option as usize >= poll.options.len() {                    return Ok(false);                }                let chosen = cotton_core::messages::app::poll::tapped(&poll, option);                let picked: Vec<String> = chosen.iter().filter_map(|i| poll.options.get(*i as usize).map(|o| o.text.clone())).collect();                let poll = cotton_core::cotton_rules::import::messages_engine::voted(poll, cotton_core::messages::app::poll::ME, &chosen, &at);                meta["poll"] = serde_json::to_value(&poll).map_err(|e| e.to_string())?;                let mut patch = Map::new();                patch.insert("meta".into(), meta);                update_row(ctx, MESSAGES, &m, patch).map_err(|f| f.to_string())?;                whatsapp_send::queue_vote(ctx, &th, &to, &picked)?;                Ok(true)            })?;            if !voted {                return Err(refuse(&lines, "cannot", "app.refused.cannot"));            }            answer.bubble = bubble_of(client, &t, &message)?;            return Ok(answer);        }        "react" | "unreact" => {            if !can.react {                return Err(refuse(&lines, "cannot", "app.refused.cannot"));            }            let message = message.clone().ok_or_else(|| bad("message", "a message's id"))?;            let emoji = if verb == "react" { request.get("emoji").and_then(Value::as_str).map(str::trim).filter(|e| !e.is_empty()).ok_or_else(|| bad("emoji", "one emoji"))?.to_string() } else { String::new() };            let row_id = cotton_core::messages::ids::reaction_row_id(&message, SELF_ACTOR).map_err(|e| bad("message", &e.to_string()))?;            let (m, th) = (message.clone(), thread.clone());            if t.whatsapp_sends {                // Through the Mac (CONTRACT "Replies and reactions"): his own reactions row drawn at once, and one                // outbox row naming the message's WhatsApp id; a change while it waits rewrites that row.                let to = read(client, "chat.react.whatsapp", |ctx| whatsapp_send::whatsapp_id_of(ctx, &th, &m))?.map_err(|why| unanswerable(&lines, why, true))?;                write(client, "chat.react.whatsapp", |ctx| {                    let found = one(ctx, &format!("SELECT id FROM {REACTIONS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(row_id.clone())])?;                    if emoji.is_empty() {                        if found.is_some() {                            ctx.writer().map_err(|f| f.to_string())?.retract(REACTIONS, &row_id, cotton_tools::mcp::writer::Retract::Relation);                        }                    } else {                        let mut columns = Map::new();                        columns.insert("emoji".into(), json!(emoji));                        if found.is_some() {                            update_row(ctx, REACTIONS, &row_id, columns).map_err(|f| f.to_string())?;                        } else {                            columns.insert("thread_id".into(), json!(th));                            columns.insert("message_id".into(), json!(m));                            columns.insert("actor".into(), json!(SELF_ACTOR));                            insert_row(ctx, REACTIONS, &row_id, columns).map_err(|f| f.to_string())?;                        }                    }                    whatsapp_send::queue_reaction(ctx, &th, &to, &emoji)                })?;                answer.bubble = bubble_of(client, &t, &message)?;                return Ok(answer);            }            let told = write(client, "chat.react", |ctx| {                let found = one(ctx, &format!("SELECT id FROM {REACTIONS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(row_id.clone())])?;                if emoji.is_empty() {                    // Taken back: a reaction is a relation, and reacting again is an ordinary create.                    if found.is_some() {                        ctx.writer().map_err(|f| f.to_string())?.retract(REACTIONS, &row_id, cotton_tools::mcp::writer::Retract::Relation);                    }                    return tell_later(ctx, &t, &m, What::Unreact, None, None, at_ms);                }                let mut columns = Map::new();                columns.insert("emoji".into(), json!(emoji));                if found.is_some() {                    update_row(ctx, REACTIONS, &row_id, columns).map_err(|f| f.to_string())?;                } else {                    columns.insert("thread_id".into(), json!(th));                    columns.insert("message_id".into(), json!(m));                    columns.insert("actor".into(), json!(SELF_ACTOR));                    insert_row(ctx, REACTIONS, &row_id, columns).map_err(|f| f.to_string())?;                }                tell_later(ctx, &t, &m, What::React, Some(&emoji), None, at_ms)            })?;            answer.flush = told;            answer.bubble = bubble_of(client, &t, &message)?;        }        "edit" | "delete" => {            let message = message.clone().ok_or_else(|| bad("message", "a message's id"))?;            let allowed = if verb == "edit" { can.edit } else { can.delete };            if !allowed {                return Err(refuse(&lines, "cannot", "app.refused.cannot"));            }            let m = read(client, "chat.act", |ctx| one(ctx, &format!("SELECT id, direction, sent_at, meta, media FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND id = ?"), &[ws(ctx), text(thread.clone()), text(message.clone())]))?.ok_or_else(|| refuse(&lines, "not_found", "app.refused.no_message"))?;            if s(&m, "direction").as_deref() != Some("out") {                return Err(refuse(&lines, "not_yours", "app.refused.not_yours"));            }            if t.whatsapp_sends {                // A grid's Delete deletes every picture of it (FEEDBACK-4 B3); the first's answer is the act's.                if verb == "delete" {                    for other in acted_on(client, &t, &message)?.into_iter().filter(|o| *o != message) {                        let row = read(client, "chat.act", |ctx| one(ctx, &format!("SELECT id, direction, sent_at, meta, media FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND id = ?"), &[ws(ctx), text(thread.clone()), text(other.clone())]))?;                        if let Some(row) = row {                            whatsapp_change(client, &t, &lines, &clock, &verb, &other, &row, request, answer.clone())?;                        }                    }                }                return whatsapp_change(client, &t, &lines, &clock, &verb, &message, &m, request, answer);            }            let mut patch = Map::new();            if verb == "edit" {                let body = request.get("text").and_then(Value::as_str).map(cotton_core::messages::js_trim).filter(|b| !b.is_empty()).ok_or_else(|| refuse(&lines, "empty", "app.refused.empty"))?.to_string();                if cotton_core::messages::edit_window::edit_window_remaining_ms(&s(&m, "sent_at").unwrap_or_default(), &now) <= 0 {                    return Err(refuse(&lines, "too_late", "app.refused.too_late"));                }                let mut meta = cotton_chat::meta_value(m.get("meta").unwrap_or(&Value::Null));                meta["edited"] = json!(true);                patch.insert("body".into(), json!(body));                patch.insert("edited_at".into(), json!(now));                patch.insert("meta".into(), meta);            } else {                patch.insert("deleted_at".into(), json!(now));                patch.insert("body".into(), Value::Null);                patch.insert("media".into(), json!([]));                answer.said = said("app.said.deleted");            }            let id = message.clone();            let what = if verb == "edit" { What::Edit } else { What::Delete };            let body = patch.get("body").and_then(Value::as_str).map(str::to_string);            let told = write(client, "chat.act", |ctx| {                update_row(ctx, MESSAGES, &id, patch.clone()).map_err(|f| f.to_string())?;                tell_later(ctx, &t, &id, what, None, body.as_deref(), at_ms)            })?;            answer.flush = told;            answer.bubble = bubble_of(client, &t, &message)?;        }        "deleteMine" => {            // His copy only (CONTRACT "Delete for me"): nothing reaches WhatsApp, and nothing is written for the Mac.            if !t.whatsapp_sends {                return Err(refuse(&lines, "cannot", "app.refused.cannot"));            }            let message = message.clone().ok_or_else(|| bad("message", "a message's id"))?;            // A grid's every picture (FEEDBACK-4 B3), the first last.            let mut ids = acted_on(client, &t, &message)?;            ids.rotate_left(1);            let mut gone = false;            for id in ids {            let th = thread.clone();            gone = write(client, "chat.delete_mine", |ctx| {                let Some(m) = one(ctx, &format!("SELECT external_id, channel, sent_at, deleted_at, meta FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND id = ? AND trashed_at IS NULL"), &[ws(ctx), text(th.clone()), text(id.clone())])? else { return Ok(false) };                if !cotton_chat::meta_value(m.get("meta").unwrap_or(&Value::Null))["cotton"]["erased"].is_null() {                    return Ok(false);                }                let sent_at = s(&m, "sent_at").unwrap_or_default();                super::chat_timer::unword_lists(ctx, super::chat_timer::newest_of(&[(th.clone(), sent_at.clone())]), true)?;                cotton_tools::mcp::handlers::tables::forget_changes(ctx, &id).map_err(|f| f.to_string())?;                ctx.writer().map_err(|f| f.to_string())?.erase(MESSAGES, &id, DELETED_FOR_ME);                // A hidden, wordless marker under its WhatsApp id, so no import brings it back; its waiting rows go.                if let Some(external) = s(&m, "external_id").filter(|e| !e.is_empty() && s(&m, "channel").as_deref() == Some("whatsapp")) {                    whatsapp_send::erase_rows_about(ctx, &th, &external, DELETED_FOR_ME)?;                    let marker = cotton_core::chat::ids::erased_marker_id(&th, "whatsapp", &external);                    if one(ctx, &format!("SELECT id FROM {MESSAGES} WHERE id = ?"), &[text(marker.clone())])?.is_none() {                        let mut columns = super::chat_timer::marker_columns(&th, &external, &sent_at);                        columns.insert("meta".into(), json!({ "cotton": { "erased": DELETED_FOR_ME } }));                        insert_row(ctx, MESSAGES, &marker, columns).map_err(|f| f.to_string())?;                    }                }                Ok(true)            })?;            }            if !gone {                return Err(refuse(&lines, "not_found", "app.refused.no_message"));            }            answer.said = said("app.said.deleted");        }        "poll" => {            // A poll he makes in a WhatsApp chat (CONTRACT "Making a poll"): one outbox row, drawn at once as the poll.            if !t.whatsapp_polls {                return Err(refuse(&lines, "cannot", "app.refused.cannot"));            }            let question = request.get("question").and_then(Value::as_str).unwrap_or_default();            let options: Vec<String> = request.get("options").and_then(Value::as_array).into_iter().flatten().filter_map(|o| o.as_str().map(str::to_string)).collect();            let one_choice = !request.get("many").and_then(Value::as_bool).unwrap_or(false);            let (question, options) = compose::poll_of(question, &options).map_err(|line| refuse(&lines, "empty", line))?;            let th = thread.clone();            let id = write(client, "chat.poll", |ctx| whatsapp_send::queue_poll(ctx, &th, &question, &options, one_choice))?;            answer.bubble = pending_bubble(client, &t, &lines, &clock, &id)?;            answer.message = Some(format!("{}{id}", whatsapp_send::PENDING));            answer.said = Some(say(&lines, "state.queued", &[]));            return Ok(answer);        }        "star" | "unstar" => {            let message = message.clone().ok_or_else(|| bad("message", "a message's id"))?;            let ids = acted_on(client, &t, &message)?;            let stamp = if verb == "star" { json!(now) } else { Value::Null };            write(client, "chat.act", |ctx| {                if one(ctx, &format!("SELECT id FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND id = ? AND trashed_at IS NULL"), &[ws(ctx), text(thread.clone()), text(message.clone())])?.is_none() {                    return Ok(false);                }                // A grid's every picture (FEEDBACK-4 B3).                for id in &ids {                    let mut patch = Map::new();                    patch.insert("starred_at".into(), stamp.clone());                    update_row(ctx, MESSAGES, id, patch).map_err(|f| f.to_string())?;                }                Ok(true)            })?            .then_some(())            .ok_or_else(|| refuse(&lines, "not_found", "app.refused.no_message"))?;            answer.said = said(if verb == "star" { "app.said.starred" } else { "app.said.unstarred" });            answer.bubble = bubble_of(client, &t, &message)?;        }        "timer" => {            let seconds = request.get("seconds").and_then(Value::as_u64).map(|s| s as u32).filter(|s| cotton_core::messages::app::timer::CHOICES.contains(s)).ok_or_else(|| bad("seconds", "0, 86400, 604800 or 7776000"))?;            let ns = cotton_chat::namespace(client)?;            let external = cotton_chat::fresh_id();            let row_id = cotton_core::chat::ids::message_id(&ns, cotton_core::chat::ids::ME, &external);            let (tid, at) = (t.id.clone(), at_ms);            // A WhatsApp chat's timer is his own copy's: the line lands here and on his other phones by sync; nothing            // goes to WhatsApp, the Mac or the other person, so there is nothing to flush.            let own = t.source == "whatsapp" || (t.source == "cotton" && t.whatsapp_sends);            if !own && (t.source != "cotton" || !t.can().send) {                return Err(refuse(&lines, "read_only", "app.refused.no_message"));            }            answer.flush = write(client, "chat.act", |ctx| {                if super::chat_timer::timer_of(ctx, &tid)? == seconds {                    return Ok(false);                }                if own {                    super::chat_timer::write_line_on(ctx, &row_id, &tid, &external, seconds, true, None, None, at, "whatsapp")?;                    return Ok(false);                }                super::chat_timer::write_line(ctx, &row_id, &tid, &external, seconds, true, None, None, at)?;                cotton_chat::wait_change(ctx, &tid, What::Timer, &external, None, Some(&seconds.to_string()), at)?;                Ok(true)            })?;        }        "pin" | "unpin" => {            let message = message.clone().ok_or_else(|| bad("message", "a message's id"))?;            let mut pins: Vec<String> = t.pinned_messages.iter().filter(|p| **p != message).cloned().collect();            if verb == "pin" {                pins.push(message.clone());            }            let mut patch = Map::new();            patch.insert("pinned_messages".into(), if pins.is_empty() { Value::Null } else { json!(serde_json::to_string(&pins).unwrap_or_default()) });            patch_thread(patch)?;            answer.said = said(if verb == "pin" { "app.said.pinned" } else { "app.said.unpinned" });            let refreshed = read(client, "chat.act", |ctx| Ok(summaries(ctx, Some(&thread))?.into_iter().next()))?.unwrap_or(t.clone());            answer.bubble = bubble_of(client, &refreshed, &message)?;        }        "forward" => {            let mut sources: Vec<String> = request.get("messages").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default();            if let Some(m) = &message {                sources.insert(0, m.clone());            }            // A grid forwarded is its every picture (FEEDBACK-4 B3).            let mut every = Vec::new();            for source in sources {                every.extend(acted_on(client, &t, &source)?);            }            let sources = every;            let targets: Vec<String> = request.get("to").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default();            if sources.is_empty() || targets.is_empty() {                return Err(bad("to", "the chats to forward to, and the message"));            }            let found = read(client, "chat.forward", |ctx| {                let found = rows_in(ctx, &format!("SELECT id, body, meta FROM {MESSAGES} WHERE workspace_id = ? AND deleted_at IS NULL"), "id", &sources)?;                Ok(sources.iter().filter_map(|id| found.iter().find(|r| s(r, "id").as_deref() == Some(id)).cloned()).collect::<Vec<_>>())            })?;            // Each message's words and its Cotton files, opened here and sealed again for each conversation it goes to.            let dir = client.layout().client_dir().join("chat-forward");            let mut going: Vec<(String, Option<String>, Vec<Value>)> = Vec::new();            for m in &found {                let id = s(m, "id").unwrap_or_default();                let meta = cotton_chat::meta_value(m.get("meta").unwrap_or(&Value::Null));                let mut files = Vec::new();                for (index, p) in meta["cotton"]["pictures"].as_array().cloned().unwrap_or_default().iter().enumerate() {                    let opened = cotton_chat::over(client, "chat.picture", &json!({ "message": id, "index": index, "dir": dir.to_string_lossy() }))?;                    let mut file = json!({ "path": opened["path"], "mime": opened["mime"] });                    for key in ["width", "height", "kind", "name", "preview"] {                        if !p[key].is_null() {                            file[key] = p[key].clone();                        }                    }                    if let Some(ms) = p["duration_ms"].as_u64() {                        file["durationMs"] = json!(ms);                    }                    if let Some(wave) = p["waveform"].as_array() {                        file["waveform"] = json!(wave.iter().filter_map(Value::as_f64).map(|v| v / 255.0).collect::<Vec<_>>());                    }                    files.push(file);                }                let body = s(m, "body");                if body.is_some() || !files.is_empty() {                    going.push((id, body, files));                }            }            if going.is_empty() {                return Err(refuse(&lines, "cannot", "app.refused.cannot"));            }            for target in &targets {                let to = read(client, "chat.forward", |ctx| Ok(summaries(ctx, Some(target))?.into_iter().next()))?.ok_or_else(|| refuse(&lines, "not_found", "app.refused.no_message"))?;                if !to.can().send || (!to.can().attach && going.iter().any(|(_, _, files)| !files.is_empty())) {                    return Err(refuse(&lines, "cannot", "app.refused.cannot"));                }                for (from, body, files) in &going {                    cotton_chat::queue(client, target, body.clone(), files.clone(), None, Some(from.clone()))?;                }                answer.sent_to.push(target.clone());            }            answer.flush = true;            let count = answer.sent_to.len().to_string();            answer.said = Some(say(&lines, "app.said.forwarded", &[("n", &count)]));        }        "read" => {            let top = read(client, "chat.read", |ctx| Ok(n(&one(ctx, &format!("SELECT max(seq) AS n FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ?"), &[ws(ctx), text(thread.clone())])?.unwrap_or_default(), "n")))?;            // Theirs not yet read are stamped read (a message landed here has no            // sequence until the copy syncs), and in a Cotton chat this person's            // other phones are told, so their notifications go too.            let cotton = t.source == "cotton";            let (th, read_seq) = (thread.clone(), t.read_seq);            let told = write(client, "chat.read", |ctx| {                let found = rows(ctx, &format!("SELECT id, external_id FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND direction = 'in' AND origin = 'live' AND read_at IS NULL AND trashed_at IS NULL AND (seq IS NULL OR seq > ?) ORDER BY sent_at"), &[ws(ctx), text(th.clone()), SqlValue::Integer(read_seq)])?;                let mut external = Vec::new();                for row in &found {                    let Some(id) = s(row, "id") else { continue };                    let mut patch = Map::new();                    patch.insert("read_at".into(), json!(now));                    update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?;                    external.extend(s(row, "external_id"));                }                if cotton && !external.is_empty() {                    cotton_chat::wait_read(ctx, &th, &external, at_ms)?;                    return Ok(true);                }                Ok(false)            })?;            let mut patch = Map::new();            patch.insert("unread_marked_at".into(), Value::Null);            if top > t.read_seq {                patch.insert("read_seq".into(), json!(top));            }            patch_thread(patch)?;            notices::seen_thread(client, &thread);            answer.flush = told;        }        "unread" => {            let mut patch = Map::new();            patch.insert("unread_marked_at".into(), json!(now));            patch_thread(patch)?;        }        "mute" | "unmute" => {            let until = match verb.as_str() {                "mute" => json!(request.get("until").and_then(Value::as_str).unwrap_or(cotton_core::constants::MUTE_ALWAYS_UNTIL)),                _ => Value::Null,            };            let mut patch = Map::new();            patch.insert("muted_until".into(), until);            patch_thread(patch)?;            answer.said = said(if verb == "mute" { "app.said.muted" } else { "app.said.unmuted" });        }        "archive" | "unarchive" => {            let mut patch = Map::new();            patch.insert("archived".into(), json!(verb == "archive"));            patch_thread(patch)?;            answer.said = said(if verb == "archive" { "app.said.archived" } else { "app.said.unarchived" });        }        "pinChat" | "unpinChat" => {            let mut patch = Map::new();            patch.insert("pinned_at".into(), if verb == "pinChat" { json!(now) } else { Value::Null });            patch_thread(patch)?;        }        "blockOnWhatsApp" => {            if !t.whatsapp_source_acts {                return Err(refuse(&lines, "cannot", "app.refused.cannot"));            }            cotton_chat::whatsapp_block(client, &thread, true)?;            answer.said = said("app.said.blocked_on_whatsapp");        }        "deleteOnWhatsApp" => {            // ERASES on his WhatsApp, for him alone (CONTRACT "Blocking a WhatsApp sender, deleting a WhatsApp chat"):            // the count first, said back to him; only the same count, sent back, deletes. Here it goes as Delete does.            if !t.whatsapp_source_acts {                return Err(refuse(&lines, "cannot", "app.refused.cannot"));            }            let th = thread.clone();            let cleared = t.cleared_before.clone();            let (count, newest) = read(client, "chat.act.delete_on_whatsapp", |ctx| {                let mut sql = format!("SELECT count(*) AS n FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND trashed_at IS NULL AND hidden_at IS NULL");                let mut params = vec![ws(ctx), text(th.clone())];                if let Some(cut) = &cleared {                    sql.push_str(" AND sent_at > ?");                    params.push(text(cut.clone()));                }                let count = one(ctx, &sql, &params)?.map(|r| n(&r, "n")).unwrap_or(0);                let newest = one(ctx, &format!("SELECT external_id FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND channel = 'whatsapp' AND external_id IS NOT NULL AND external_id != '' ORDER BY sent_at DESC, rowid DESC LIMIT 1"), &[ws(ctx), text(th.clone())])?.and_then(|r| s(&r, "external_id"));                Ok((count, newest))            })?;            let Some(newest) = newest else { return Err(refuse(&lines, "not_in_whatsapp", "app.refused.chat_not_in_whatsapp")) };            if request.get("count").and_then(Value::as_i64) != Some(count) {                let named = read(client, "chat.act.name", |ctx| names(ctx, &[&t], &say(&lines, "app.list.you", &[])))?;                let name = named.get(&thread).map(|n| n.name.clone()).unwrap_or_default();                let asked = say(&lines, "app.confirm.delete_on_whatsapp", &[("name", &name), ("count", &count.to_string())]);                return Err(MethodError::new("count_first", asked).with_details(json!({ "count": count })));            }            let th = thread.clone();            write(client, "chat.act.delete_on_whatsapp", |ctx| whatsapp_send::queue_delete_chat(ctx, &th, &newest).map(|_| ()))?;            delete_here(client, &t, &thread, &now)?;            answer.said = said("app.said.deleted_on_whatsapp");        }        "deleteChat" => {            delete_here(client, &t, &thread, &now)?;            answer.said = said("app.said.chat_deleted");        }        "typing" => {            if !can.typing {                return Err(refuse(&lines, "cannot", "app.refused.cannot"));            }            let mut asked = request.clone();            asked["on"] = json!(request.get("on").and_then(Value::as_bool).unwrap_or(true));            cotton_chat::over(client, "chat.typing", &asked)?;        }        _ => return Err(bad("act", &ACTS.join(", "))),    }    if matches!(verb.as_str(), "read" | "unread" | "mute" | "unmute" | "archive" | "unarchive" | "pinChat" | "unpinChat" | "send") {        answer.row = one_row(client, &thread)?;    }    Ok(answer)}/// A chat off the list, its messages cleared here and on the person's other devices (`deleteChat`).fn delete_here(client: &ClientController, t: &Summary, thread: &str, now: &str) -> Result<(), MethodError> {    let now = now.to_string();    // Off the list, its messages cleared here and on the person's other devices (`cleared_before`); a    // message that arrives later brings the chat back, holding only what came after. The cut covers    // everything the chat holds, whatever its stamp (FEEDBACK-4 B2): a WhatsApp message carries the sending    // phone's clock, which may run ahead of this one, and a cut at this phone's now would leave it standing.    let th = thread.to_string();    let newest = read(client, "chat.act.delete", |ctx| {        let row = one(ctx, &format!("SELECT sent_at FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? ORDER BY sent_at DESC LIMIT 1"), &[ws(ctx), text(th.clone())])?;        Ok(row.and_then(|r| s(&r, "sent_at")))    })?;    let cut = [Some(now.clone()), t.last_at.clone(), newest].into_iter().flatten().max_by_key(|at| ms(at)).unwrap_or_else(|| now.clone());    let mut patch = Map::new();    patch.insert("cleared_before".into(), json!(cut));    patch.insert("pinned_at".into(), Value::Null);    patch.insert("unread_marked_at".into(), Value::Null);    patch.insert("draft".into(), Value::Null);    patch.insert("draft_reply_to_id".into(), Value::Null);    let id = thread.to_string();    write(client, "chat.act", |ctx| update_row(ctx, THREADS, &id, patch.clone()).map_err(|f| f.to_string()))}/// One message's bubble as the thread would draw it now./// The bubble of the text on its way through the Mac, outbox row `id`.fn pending_bubble(client: &ClientController, t: &Summary, lines: &LineSet, clock: &Clock, id: &str) -> Result<Option<Bubble>, MethodError> {    let you = say(lines, "app.list.you", &[]);    let found = read(client, "chat.pending", |ctx| {        let pending = whatsapp_send::pending(ctx, &t.id)?;        let Some(tap) = whatsapp_send::tap_of(&pending, id) else { return Ok(None) };        let tap: Vec<whatsapp_send::Pending> = tap.into_iter().cloned().collect();        let quotes = pending_quoted(ctx, &t.id, &tap[..1])?;        let named = names(ctx, &[t], &you)?.remove(&t.id).unwrap_or_default();        Ok(Some((tap, quotes, named)))    })?;    Ok(found.map(|(tap, quotes, named)| {        let speaker = Speaker { lines, t, named: &named, can: t.can(), clock, me: cotton_chat::own_number(client) };        // One tap's pictures answer as their grid (FEEDBACK-4 B3).        let tap: Vec<&whatsapp_send::Pending> = tap.iter().collect();        let mut b = whatsapp_send::tap_bubble(lines, clock, &tap, true);        b.reply = pending_quote(&speaker, tap[0], &quotes);        b    }))}/// The messages the pending replies of `thread` answer, by their WhatsApp id.fn pending_quoted(ctx: &mut Ctx<'_>, thread: &str, pending: &[whatsapp_send::Pending]) -> Result<HashMap<String, Map<String, Value>>, String> {    let mut out = HashMap::new();    for quoted in pending.iter().filter_map(|p| p.quoted.clone()) {        if out.contains_key(&quoted) {            continue;        }        let sql = format!("SELECT {MESSAGE_COLUMNS} FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND channel = 'whatsapp' AND external_id = ?");        if let Some(m) = one(ctx, &sql, &[ws(ctx), text(thread.to_string()), text(quoted.clone())])? {            out.insert(quoted, m);        }    }    Ok(out)}/// A pending reply's quote at once, as its message will draw it once it lands.fn pending_quote(speaker: &Speaker<'_>, p: &whatsapp_send::Pending, quotes: &HashMap<String, Map<String, Value>>) -> Option<Quote> {    let quoted = p.quoted.as_ref()?;    Some(match quotes.get(quoted) {        Some(m) => speaker.quote(m),        None => Quote { message: None, sender: String::new(), line: say(speaker.lines, "app.refused.no_message", &[]), mark: None },    })}/// Why a message cannot be replied (or reacted) to in WhatsApp, in the core's words./// The erase's reason, and the marker's `meta.cotton.erased`, for a message deleted in his copy only.const DELETED_FOR_ME: &str = "deleted_for_me";/// His edit, or his delete for everyone, of his own message in a WhatsApp chat (CONTRACT "Editing and deleting his/// own message"): drawn at once (the new words; the message erased, a marker in its place), and one outbox row for/// the Mac naming the message's WhatsApp id. Within WhatsApp's own windows only.#[allow(clippy::too_many_arguments)]fn whatsapp_change(client: &ClientController, t: &Summary, lines: &LineSet, clock: &Clock, verb: &str, message: &str, m: &Map<String, Value>, request: &Value, mut answer: ActAnswer) -> Result<ActAnswer, MethodError> {    let (th, id) = (t.id.clone(), message.to_string());    let target = read(client, "chat.change", |ctx| whatsapp_send::whatsapp_id_of(ctx, &th, &id))?.map_err(|why| unanswerable(lines, why, false))?;    let now = clock.now_iso();    let sent_at = s(m, "sent_at").unwrap_or_default();    if verb == "edit" {        let body = request.get("text").and_then(Value::as_str).map(cotton_core::messages::js_trim).filter(|b| !b.is_empty()).ok_or_else(|| refuse(lines, "empty", "app.refused.empty"))?.to_string();        // Words only: a picture's caption would need its WhatsApp upload, which no copy holds; a poll is not words.        let meta = cotton_chat::meta_value(m.get("meta").unwrap_or(&Value::Null));        if !media_of(m).is_empty() || !meta["poll"].is_null() {            return Err(refuse(lines, "cannot", "app.refused.cannot"));        }        if cotton_core::messages::edit_window::edit_window_remaining_ms(&sent_at, &now) <= 0 {            return Err(refuse(lines, "too_late", "app.refused.too_late"));        }        let mut meta = meta;        meta["edited"] = json!(true);        let mut patch = Map::new();        patch.insert("body".into(), json!(body));        patch.insert("edited_at".into(), json!(now));        patch.insert("meta".into(), meta);        write(client, "chat.edit.whatsapp", |ctx| {            update_row(ctx, MESSAGES, &id, patch.clone()).map_err(|f| f.to_string())?;            whatsapp_send::queue_edit(ctx, &th, &target, &body)        })?;        answer.bubble = bubble_of(client, t, message)?;        return Ok(answer);    }    if cotton_core::messages::edit_window::delete_window_remaining_ms(&sent_at, &now) <= 0 {        return Err(refuse(lines, "too_late_delete", "app.refused.too_late_delete"));    }    // Deleted for everyone, as a revoke from WhatsApp is: its words and files go now, and the sweep ERASES the row    // with every trace, a marker in its place (`chat_revoked`). Every other outbox row about it is erased too.    let mut patch = Map::new();    patch.insert("deleted_at".into(), json!(now));    patch.insert("body".into(), Value::Null);    patch.insert("media".into(), json!([]));    write(client, "chat.delete.whatsapp", |ctx| {        update_row(ctx, MESSAGES, &id, patch.clone()).map_err(|f| f.to_string())?;        whatsapp_send::queue_delete(ctx, &th, &target)    })?;    super::chat_revoked::sweep_revoked(client)?;    let marker = cotton_core::chat::ids::erased_marker_id(&th, "whatsapp", &target);    answer.bubble = bubble_of(client, t, &marker)?;    answer.message = Some(marker);    answer.said = Some(say(lines, "app.said.deleted", &[]));    Ok(answer)}fn unanswerable(lines: &LineSet, why: whatsapp_send::Unanswerable, react: bool) -> MethodError {    use whatsapp_send::Unanswerable::*;    match (why, react) {        (Gone, _) => refuse(lines, "not_found", "app.refused.no_message"),        (Deleted, false) => refuse(lines, "deleted", "app.refused.deleted"),        (Deleted, true) => refuse(lines, "deleted", "app.refused.react_deleted"),        (NotThere, false) => refuse(lines, "not_in_whatsapp", "app.refused.not_in_whatsapp"),        (NotThere, true) => refuse(lines, "not_in_whatsapp", "app.refused.react_not_in_whatsapp"),    }}fn bubble_of(client: &ClientController, t: &Summary, id: &str) -> Result<Option<Bubble>, MethodError> {    let lines = list::lines();    let clock = Clock::of(client);    let you = say(&lines, "app.list.you", &[]);    let found = read(client, "chat.bubble", |ctx| {        let Some(m) = one(ctx, &format!("SELECT {MESSAGE_COLUMNS} FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(id.to_string())])? else { return Ok(None) };        // The messages on each side, so a bubble answered alone (a pin, a star, a send) keeps its place in its run.        let point = (s(&m, "sent_at").unwrap_or_default(), n(&m, "_row"));        let above = side(ctx, t, Some(&point), true, false, 1)?.pop();        let below = side(ctx, t, Some(&point), false, false, 1)?.pop();        let unread = first_unread(ctx, t)?.and_then(|u| s(&u, "id"));        let named = names(ctx, &[t], &you)?.remove(&t.id).unwrap_or_default();        let extras = around(ctx, std::slice::from_ref(&m))?;        // A grid's first answers as the grid (FEEDBACK-4 B3).        let grid = grid_of(ctx, t, id)?;        let rest: Vec<Map<String, Value>> = if grid.first().and_then(|g| s(g, "id")).as_deref() == Some(id) { grid[1..].to_vec() } else { Vec::new() };        Ok(Some((m, above, below, unread, named, extras, rest)))    })?;    Ok(found.map(|(m, above, below, unread, named, extras, rest)| {        let page = [laid(&clock, &lines, &m)];        let (above, below) = (above.map(|a| laid(&clock, &lines, &a)), below.map(|b| laid(&clock, &lines, &b)));        let place = lay::lay(&page, above.as_ref(), below.as_ref(), unread.as_deref())            .into_iter()            .find_map(|slot| match slot {                Slot::Message { head, tail, face, .. } => Some(Place { head, tail, face }),                _ => None,            })            .unwrap_or(Place { head: true, tail: true, face: true });        let mut b = Speaker { lines: &lines, t, named: &named, can: t.can(), clock: &clock, me: cotton_chat::own_number(client) }.bubble(&m, place, &extras);        mark_gone(client, &m, &mut b);        if !rest.is_empty() {            join_tiles(client, &mut b, &rest);        }        b    }))}/// The runs of `page` (in its order) that one tap's pictures to WhatsApp made, each two or more indices, first the/// head: his messages, each only pictures or videos, whose WhatsApp ids are rows of the same tap in [`tiles`]/// (`whatsapp_send::sent_tiles`), next to one another (FEEDBACK-4 B3).fn grids(page: &[Map<String, Value>], tiles: &HashMap<String, (String, u32)>) -> Vec<Vec<usize>> {    if tiles.is_empty() {        return Vec::new();    }    let tap = |m: &Map<String, Value>| -> Option<String> {        if s(m, "direction").as_deref() != Some("out") || s(m, "deleted_at").is_some_and(|d| !d.is_empty()) || !whatsapp_send::visual(&media_of(m)) {            return None;        }        s(m, "external_id").and_then(|e| tiles.get(&e)).map(|(at, _)| at.clone())    };    let mut out: Vec<Vec<usize>> = Vec::new();    let mut last: Option<String> = None;    for (i, m) in page.iter().enumerate() {        let here = tap(m);        match (&here, &last, out.last_mut()) {            (Some(a), Some(b), Some(run)) if a == b && run.last() == Some(&(i - 1)) => run.push(i),            (Some(_), _, _) => out.push(vec![i]),            _ => {}        }        last = here;    }    out.retain(|run| run.len() > 1);    out}/// The grid message `id` stands in, its rows in the chat's order, the head first; empty when it stands alone.fn grid_of(ctx: &mut Ctx<'_>, t: &Summary, id: &str) -> Result<Vec<Map<String, Value>>, String> {    if !(t.source == "whatsapp" || t.linked) {        return Ok(Vec::new());    }    let tiles = whatsapp_send::sent_tiles(ctx, &t.id)?;    let Some(external) = one(ctx, &format!("SELECT external_id FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND id = ?"), &[ws(ctx), text(t.id.clone()), text(id.to_string())])?.and_then(|r| s(&r, "external_id")) else {        return Ok(Vec::new());    };    let Some((at, _)) = tiles.get(&external).cloned() else { return Ok(Vec::new()) };    let externals: Vec<String> = tiles.iter().filter(|(_, (a, _))| *a == at).map(|(e, _)| e.clone()).collect();    // `rows_in` binds the workspace alone: the chat is named in the query, quoted.    let mut rows = rows_in(ctx, &format!("SELECT {MESSAGE_COLUMNS} FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = '{}' AND trashed_at IS NULL AND hidden_at IS NULL", t.id.replace('\'', "''")), "external_id", &externals)?;    rows.sort_by(|a, b| (s(a, "sent_at").unwrap_or_default(), n(a, "_row")).cmp(&(s(b, "sent_at").unwrap_or_default(), n(b, "_row"))));    Ok(grids(&rows, &tiles).into_iter().find(|run| run.iter().any(|i| s(&rows[*i], "id").as_deref() == Some(id))).map(|run| run.into_iter().map(|i| rows[i].clone()).collect()).unwrap_or_default())}/// The ids an act on message `id` acts on: the grid's every picture when it heads one, else itself.fn acted_on(client: &ClientController, t: &Summary, id: &str) -> Result<Vec<String>, MethodError> {    let grid = read(client, "chat.grid", |ctx| grid_of(ctx, t, id))?;    if grid.first().and_then(|g| s(g, "id")).as_deref() == Some(id) {        return Ok(grid.iter().filter_map(|g| s(g, "id")).collect());    }    Ok(vec![id.to_string()])}/// The other pictures of a grid, after its head's: each tile names its message.fn join_tiles(client: &ClientController, b: &mut Bubble, rest: &[Map<String, Value>]) {    for m in rest {        let media = media_of(m);        let row = Row { body: None, media: &media, meta: None, deleted_at: None };        let mut one = Bubble { media: bubble::media_parts(&row), ..b.clone() };        mark_gone(client, m, &mut one);        let id = s(m, "id");        b.media.extend(one.media.into_iter().map(|mut part| {            part.message = id.clone();            part        }));    }    b.kind = BubbleKind::Album;}// โ”€โ”€ themes โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€/// The phone's own pick of theme by appearance, kept beside the copy as/// Story keeps its own (`story-theme.json`).const THEME_FILE: &str = "chat-theme.json";fn kept_theme(client: &ClientController) -> Map<String, Value> {    std::fs::read(client.layout().client_dir().join(THEME_FILE)).ok().and_then(|bytes| serde_json::from_slice(&bytes).ok()).unwrap_or_default()}fn themes_answer(client: &ClientController) -> Result<ThemesAnswer, MethodError> {    use cotton_core::messages::app::themes::{colours, known, themes};    let lines = list::lines();    let kept = kept_theme(client);    let all = themes();    let pick = |key: &str, ok: &dyn Fn(&str) -> bool, default: &str| kept.get(key).and_then(Value::as_str).filter(|id| ok(id)).unwrap_or(default).to_string();    let light = pick("light", &|id| known(id), &all.defaults.light_theme);    let dark = pick("dark", &|id| known(id), &all.defaults.dark_theme);    let text = pick("text", &|id| all.text.iter().any(|t| t.id == id), &all.defaults.text);    let ground = pick("ground", &|id| all.grounds.iter().any(|g| g == id), &all.defaults.ground);    Ok(ThemesAnswer {        themes: all            .themes            .iter()            .map(|theme| ChatTheme {                id: theme.id.clone(),                name: say(&lines, &format!("app.theme.names.{}", theme.id), &[]),                on: theme.id == light || theme.id == dark,                // A ground the person chose stands over the theme's own.                ground: if ground == "theme" { theme.ground.clone() } else { ground.clone() },                light: colours(theme, false),                dark: colours(theme, true),            })            .collect(),        text: Choosing {            title: say(&lines, "app.theme.text.title", &[]),            chosen: text,            options: all.text.iter().map(|t| Choice { label: say(&lines, &format!("app.theme.text.names.{}", t.id), &[]), id: t.id.clone(), scale: Some(t.scale) }).collect(),        },        ground: Choosing {            title: say(&lines, "app.theme.ground.title", &[]),            chosen: ground,            options: all.grounds.iter().map(|g| Choice { label: say(&lines, &format!("app.theme.ground.names.{g}"), &[]), id: g.clone(), scale: None }).collect(),        },        words: ThemeWords { title: say(&lines, "app.theme.title", &[]), light: say(&lines, "app.theme.light", &[]), dark: say(&lines, "app.theme.dark", &[]), settings: say(&lines, "app.theme.settings", &[]) },        light,        dark,    })}/// Keep one Settings choice on this phone, and answer the looks as they now stand.fn keep_choice(client: &ClientController, key: &str, value: &str) -> Result<ThemesAnswer, MethodError> {    let mut file = kept_theme(client);    file.insert(key.to_string(), json!(value));    let dir = client.layout().client_dir();    let bytes = serde_json::to_vec(&file).map_err(|why| MethodError::new("unwritable", why.to_string()))?;    // not a copy: the chat theme file.    cotton_client::whole_file::replace(&dir.join(THEME_FILE), &bytes)        .map_err(|why| MethodError::new("unwritable", format!("the look could not be kept: {why}")))?;    themes_answer(client)}/// `chat.theme.set {appearance, id}` and `chat.theme {theme, dark}`: the theme for one appearance.fn set_theme(client: &ClientController, request: &Value) -> Result<ThemesAnswer, MethodError> {    let appearance = match (request.get("appearance").and_then(Value::as_str), request.get("dark").and_then(Value::as_bool)) {        (Some(said @ ("light" | "dark")), _) => said,        (None, Some(true)) => "dark",        (None, Some(false)) => "light",        _ => return Err(bad("dark", "true for the dark appearance, false for the light")),    };    let lines = list::lines();    let id = request.get("id").or_else(|| request.get("theme")).and_then(Value::as_str).filter(|id| cotton_core::messages::app::themes::known(id)).ok_or_else(|| refuse(&lines, "not_found", "app.theme.unknown"))?;    keep_choice(client, appearance, id)}/// `chat.text {value}` and `chat.ground {ground}`.fn set_choice(client: &ClientController, request: &Value, key: &str, field: &str) -> Result<ThemesAnswer, MethodError> {    let all = cotton_core::messages::app::themes::themes();    let value = request.get(field).and_then(Value::as_str).ok_or_else(|| bad(field, "one of the choices chat.themes answers"))?;    let known = match key {        "text" => all.text.iter().any(|t| t.id == value),        _ => all.grounds.iter().any(|g| g == value),    };    if !known {        return Err(refuse(&list::lines(), "not_found", "app.theme.unknown"));    }    keep_choice(client, key, value)}#[cfg(test)]#[path = "chat_app_tests.rs"]mod tests;#[cfg(test)]#[path = "chat_delete_tests.rs"]mod delete_tests;