Cotton code
1348 lines · 66.7 KB · RustRaw
//! A text written in Comms in a WhatsApp chat goes out through the Mac's link//! (owner, 22 Nov 2026; MACSCOPE 4).//!//! The owner's tap writes one `outbox` row (the personal table the Mac drains,//! `crates/cotton-mac/src/outbox.rs`): the chat, its WhatsApp address, the//! number it came in through when a message says so, the words, `queued`, and//! the WhatsApp id it will go out under, fixed now. Nothing else is written://! no message row. The Mac sends under that id (a retry too, so WhatsApp keeps//! one), and its link keeps what it sent as the owner's message, which lands//! in the chat under that id like any other. Until then the thread draws the//! row as the owner's bubble with its state in words: "Waiting to send" while//! the Mac has not taken it (asleep, off, not linked), "Sending…", "Not sent://! <why>" with Retry. It never looks sent before the Mac said so, and it//! leaves the page once the message with its id stands in the chat.//!//! A copy made before Comms drew the outbox has no definition of it until its//! object serves one: there the chat stays read only, never a send refused.//!//! Pictures, videos and voice notes go the same way (owner, FEEDBACK-3, 23 Nov//! 2026; CONTRACT.md "WhatsApp through the Mac: pictures, voice notes and//! video"). The tap keeps each file in his own media first ([`keep_files`]://! `<file>/messages/<thread>/<sha>.<ext>`, which the drain puts up sealed under//! his own key, as every file of his), then writes one outbox row per file//! naming it, the caption on the first picture or video ([`queue_files`]).//! The bubble draws the phone's own file at once; the Mac opens the same file//! with his data key.use cotton_core::messages::send::{self, PhoneTarget};use cotton_tools::mcp::handlers::tables;use super::*;/// The personal table the Mac drains.pub(super) const OUTBOX: &str = "outbox";/// The id a pending text's bubble carries: `outbox:<row id>`.pub(crate) const PENDING: &str = "outbox:";/// After this long `sending`, a text the Mac never marked offers Retry: it goes again under the same id, and/// WhatsApp keeps one.const STALE_SENDING_MS: i64 = 10 * 60 * 1000;/// WhatsApp's voice-note waveform: this many samples, each 0..=100.pub(super) const WAVEFORM_SAMPLES: usize = 64;/// What a file of another kind is refused with where the served outbox takes no document yet.const NOT_YET_FILES: &str = "Only pictures, videos and voice notes go to WhatsApp for now.";/// WhatsApp's own limit for a document (the Mac's `DOCUMENT_MAX`, and what his media takes); a picture, video or/// voice note stays at `chat::files::FILE_MAX`.const DOCUMENT_MAX: u64 = 100 << 20;fn object(value: Value) -> Map<String, Value> {    value.as_object().cloned().unwrap_or_default()}fn tool(failure: cotton_tools::mcp::protocol::ToolFailure) -> String {    failure.to_string()}/// Whether this copy draws the outbox, so a text can be queued here.pub(super) fn keeps_outbox(ctx: &mut Ctx<'_>) -> Result<bool, String> {    Ok(!cotton_tools::definitions::definition_rows(ctx, Some(OUTBOX)).map_err(|e| e.to_string())?.is_empty())}/// The columns a file row writes beside a text's (FEEDBACK-3).const FILE_COLUMNS: [&str; 10] = ["kind", "voice", "mime", "size_bytes", "width", "height", "duration_ms", "waveform", "preview", "part"];/// Whether this copy's outbox takes a file row: the definition its object serves carries every column a file row/// writes. A server still on the outbox of before (a Worker not yet deployed with them) serves words only, and the/// chat offers words only there, never a picture the copy would refuse (seen on emulator-5558, 23 Nov 2026: "Outgoing/// messages have no column "kind"" after he had picked the picture and written its caption).pub(super) fn takes_files(ctx: &mut Ctx<'_>) -> Result<bool, String> {    serves(ctx, &FILE_COLUMNS)}/// The column a document writes beside a file's (CONTRACT "Documents and votes").const DOCUMENT_COLUMNS: [&str; 1] = ["file_name"];/// Whether this copy's outbox takes a document: a file row, and its `file_name`.pub(super) fn takes_documents(ctx: &mut Ctx<'_>) -> Result<bool, String> {    Ok(serves(ctx, &FILE_COLUMNS)? && serves(ctx, &DOCUMENT_COLUMNS)?)}/// The columns a vote writes (CONTRACT "Documents and votes"), both sealed.const VOTE_COLUMNS: [&str; 2] = ["target", "options"];/// Whether this copy's outbox takes a vote: the served definition carries [`VOTE_COLUMNS`].pub(super) fn takes_votes(ctx: &mut Ctx<'_>) -> Result<bool, String> {    serves(ctx, &VOTE_COLUMNS)}/// The `kind` choices an edit and a delete for everyone write (CONTRACT "Editing and deleting his own message").const CHANGE_KINDS: [&str; 2] = ["edit", "delete"];/// Whether this copy's outbox takes an edit and a delete for everyone: the served definition carries `target` and/// offers both kinds. A Worker not yet deployed with them serves the outbox of before, and neither is offered there.pub(super) fn takes_changes(ctx: &mut Ctx<'_>) -> Result<bool, String> {    Ok(serves(ctx, &["target"])? && offers(ctx, &CHANGE_KINDS)?)}/// Whether this copy's outbox takes a poll he makes: the served definition offers `kind` poll and carries `options`/// and `selectable` (CONTRACT "Making a poll")./// Whether the served outbox carries a text's link card (`link`, FEEDBACK-4 B4): until the Worker serves it, a/// WhatsApp chat offers no card.pub(super) fn takes_links(ctx: &mut Ctx<'_>) -> Result<bool, String> {    serves(ctx, &["link"])}/// Queue a text with its link card: the card as JSON in `link`, for the Mac to send as WhatsApp's own preview.pub(super) fn queue_with_link(ctx: &mut Ctx<'_>, thread: &str, body: &str, quoted: Option<&str>, card: &cotton_core::messages::MessageLinkPreview) -> Result<String, String> {    let to = target(ctx, thread)?.map_err(str::to_string)?;    let mut fields = quote(quoted);    fields.insert("link".into(), json!(serde_json::to_string(card).map_err(|e| e.to_string())?));    made(ctx, thread, &to, fields, body.trim())}pub(super) fn takes_polls(ctx: &mut Ctx<'_>) -> Result<bool, String> {    Ok(serves(ctx, &["options", "selectable"])? && offers(ctx, &["poll"])?)}/// Whether the served outbox's `kind` offers every one of `kinds`.fn offers(ctx: &mut Ctx<'_>, kinds: &[&str]) -> Result<bool, String> {    let rows = cotton_tools::definitions::definition_rows(ctx, Some(OUTBOX)).map_err(|e| e.to_string())?;    Ok(rows.iter().any(|row| {        let definition: Value = serde_json::from_str(&row.definition).unwrap_or(Value::Null);        let choices: Vec<&str> = definition["columns"]            .as_array()            .into_iter()            .flatten()            .filter(|c| c["key"] == "kind")            .flat_map(|c| c["choices"].as_array().into_iter().flatten())            .filter_map(|c| c.as_str().or_else(|| c["value"].as_str()))            .collect();        kinds.iter().all(|kind| choices.contains(kind))    }))}/// The columns a reply or a reaction writes (FEEDBACK-3, CONTRACT "Replies and reactions"), all sealed.pub(super) const ANSWER_COLUMNS: [&str; 3] = ["quoted_id", "reaction_to", "emoji"];/// Whether this copy's outbox takes a reply and a reaction: the served definition carries [`ANSWER_COLUMNS`]. A/// Worker not yet deployed with them serves the outbox of before, and the chat offers neither there.pub(super) fn takes_answers(ctx: &mut Ctx<'_>) -> Result<bool, String> {    serves(ctx, &ANSWER_COLUMNS)}/// Whether the outbox definition this copy holds (its object's) carries every one of `columns`.fn serves(ctx: &mut Ctx<'_>, columns: &[&str]) -> Result<bool, String> {    let rows = cotton_tools::definitions::definition_rows(ctx, Some(OUTBOX)).map_err(|e| e.to_string())?;    Ok(rows.iter().any(|row| {        let definition: Value = serde_json::from_str(&row.definition).unwrap_or(Value::Null);        let keys: Vec<&str> = definition["columns"].as_array().into_iter().flatten().filter_map(|c| c["key"].as_str()).collect();        columns.iter().all(|column| keys.contains(column))    }))}/// Whether a message on `channel` with `external` can be named to WhatsApp: WhatsApp's own id, not an export's/// content fingerprint (`txt2:…`) nor a Cotton message's.pub(crate) fn answerable(channel: Option<&str>, external: Option<&str>) -> bool {    channel == Some("whatsapp") && external.is_some_and(|id| !id.trim().is_empty() && !id.contains(':'))}/// Why a message cannot be replied or reacted to in WhatsApp.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub(super) enum Unanswerable {    /// Not in this copy: erased (a timer's marker stands under another id), or never here.    Gone,    /// Deleted for everyone.    Deleted,    /// An export's message, or a Cotton one: WhatsApp holds no message by its id.    NotThere,}/// The WhatsApp id of message `id` of `thread`, when it can be replied or reacted to there.pub(super) fn whatsapp_id_of(ctx: &mut Ctx<'_>, thread: &str, id: &str) -> Result<Result<String, Unanswerable>, String> {    let sql = format!("SELECT channel, external_id, deleted_at, meta FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND id = ? AND trashed_at IS NULL");    let Some(m) = one(ctx, &sql, &[ws(ctx), text(thread.to_string()), text(id.to_string())])? else { return Ok(Err(Unanswerable::Gone)) };    let meta = super::cotton_chat::meta_value(m.get("meta").unwrap_or(&Value::Null));    if s(&m, "deleted_at").is_some_and(|d| !d.is_empty()) || !meta["cotton"]["erased"].is_null() {        return Ok(Err(Unanswerable::Deleted));    }    let external = s(&m, "external_id");    if !answerable(s(&m, "channel").as_deref(), external.as_deref()) {        return Ok(Err(Unanswerable::NotThere));    }    Ok(external.ok_or(Unanswerable::NotThere))}/// Whether this copy is linked to WhatsApp through the Mac: it draws the outbox, and holds messages the Mac's link/// brought in (FEEDBACK-2 A). Unlinked, writing to a number is as it always was.pub(crate) fn link(ctx: &mut Ctx<'_>) -> Result<Option<send::Link>, String> {    if !keeps_outbox(ctx)? {        return Ok(None);    }    let workspace = ctx.workspace_id.to_string();    let db = ctx.read.driver();    let mut reader = |sql: &str, params: &[String]| {        let bound: Vec<SqlValue> = params.iter().map(|param| SqlValue::Text(param.clone())).collect();        db.all(sql, &bound)    };    send::link_of(&mut reader, &workspace).map_err(|e| e.to_string())}/// Where a message written to `number` goes now (`send::route`): Cotton when the number is one of the person's Cotton/// connections, else its WhatsApp when linked, else the Cotton chat with the invite.pub(crate) fn route(ctx: &mut Ctx<'_>, number: &str) -> Result<send::Route, String> {    let on = super::super::chat_people::on_cotton(ctx, number)?;    let link = if on { None } else { link(ctx)? };    Ok(send::route(number, on, link.as_ref()))}/// The number of a Cotton chat with one person (`cotton:+…`), the chat a number opens.fn cotton_number(ctx: &mut Ctx<'_>, thread: &str) -> Result<Option<String>, String> {    let key = one(ctx, &format!("SELECT external_key FROM {THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(thread.to_string())])?.and_then(|r| s(&r, "external_key"));    Ok(key.as_deref().and_then(cotton_core::chat::ids::number_of_key).map(str::to_string))}/// Where a text from `thread` goes, as this phone decides it, or why it cannot. A Cotton chat with a number not on/// Cotton goes to that number's WhatsApp on a linked copy (`route`); a chat that came from WhatsApp, to its address.pub(crate) fn target(ctx: &mut Ctx<'_>, thread: &str) -> Result<Result<PhoneTarget, &'static str>, String> {    let db = ctx.read.driver();    let mut reader = |sql: &str, params: &[String]| {        let bound: Vec<SqlValue> = params.iter().map(|param| SqlValue::Text(param.clone())).collect();        db.all(sql, &bound)    };    let from_messages = send::phone_targets(&mut reader, &[thread.to_string()]).map_err(|e| e.to_string())?.remove(thread);    if let Some(number) = cotton_number(ctx, thread)? {        // A chat that holds WhatsApp's messages (it came from WhatsApp first) keeps the address and number they name.        return Ok(match route(ctx, &number)? {            send::Route::Whatsapp(target) => Ok(from_messages.and_then(Result::ok).unwrap_or(target)),            _ => Err(send::NOT_WHATSAPP),        });    }    Ok(from_messages.unwrap_or(Err(send::NOT_WHATSAPP)))}/// Whether `thread` holds both Cotton's messages and WhatsApp's: each bubble then says which (FEEDBACK-2 A).pub(super) fn mixed(ctx: &mut Ctx<'_>, thread: &str) -> Result<bool, String> {    let sql = format!("SELECT 1 AS here FROM {MESSAGES} WHERE thread_id = ? AND channel = ? LIMIT 1");    let cotton = one(ctx, &sql, &[text(thread.to_string()), text("cotton".to_string())])?.is_some();    Ok(cotton && one(ctx, &sql, &[text(thread.to_string()), text("whatsapp".to_string())])?.is_some())}/// Whether `thread` sends through the Mac from this phone.pub(super) fn sends(ctx: &mut Ctx<'_>, thread: &str) -> Result<bool, String> {    Ok(keeps_outbox(ctx)? && target(ctx, thread)?.is_ok())}/// Queue `body` for `thread`: one outbox row, its WhatsApp id fixed now, a reply to WhatsApp message `quoted` when/// given. Its id.pub(super) fn queue(ctx: &mut Ctx<'_>, thread: &str, body: &str, quoted: Option<&str>) -> Result<String, String> {    let to = target(ctx, thread)?.map_err(str::to_string)?;    made(ctx, thread, &to, quote(quoted), body.trim())}/// A reply's field: the WhatsApp id it answers (the Mac reads that message from its own copy for the quote).fn quote(quoted: Option<&str>) -> Map<String, Value> {    quoted.map(|id| object(json!({ "quoted_id": id }))).unwrap_or_default()}/// One outbox row for `thread`, going `to`, with `extra`'s fields beside the text's; its WhatsApp id fixed now.fn made(ctx: &mut Ctx<'_>, thread: &str, to: &PhoneTarget, extra: Map<String, Value>, body: &str) -> Result<String, String> {    let external = send::whatsapp_message_id(&super::cotton_chat::fresh_id(), 0);    let mut data = object(json!({        "thread_id": thread, "channel": "whatsapp", "to": to.chat, "body": body, "status": "queued", "sent_external_id": external,    }));    if let Some(account) = &to.account {        data.insert("account".into(), json!(account));    }    let picture = extra.get("kind").and_then(Value::as_str) == Some("photo");    data.extend(extra);    // The chat comes up the list as for any message he writes, back from Deleted too (FEEDBACK-2 A).    let now = super::cotton_chat::now_iso(ctx);    super::cotton_chat::touch_thread(ctx, thread, &now, Some(body), picture)?;    let made = tables::create_produced_record(ctx, &object(json!({ "table": OUTBOX, "data": Value::Object(data) }))).map_err(tool)?;    made["record"]["id"].as_str().or_else(|| made["id"].as_str()).map(str::to_string).ok_or_else(|| "no id for the queued text".to_string())}/// One file the tap sends to WhatsApp, kept in his own media.#[derive(Debug, Clone, PartialEq)]pub(super) struct Going {    /// `<file>/messages/<thread>/<sha256>.<ext>`: his own media, sealed when the drain puts it up.    pub key: String,    pub mime: String,    pub bytes: u64,    /// `photo`, `video`, `audio` or `document`.    pub kind: &'static str,    /// A document's name, as WhatsApp shows it.    pub file_name: Option<String>,    /// Audio sent as a WhatsApp voice note, never as a file.    pub voice: bool,    pub width: Option<u64>,    pub height: Option<u64>,    pub duration_ms: Option<u64>,    /// Base64 of [`WAVEFORM_SAMPLES`] bytes in 0..=100, as WhatsApp's `AudioMessage.waveform` holds it.    pub waveform: Option<String>,    /// The bubble's tiny JPEG, base64: WhatsApp's thumbnail.    pub preview: Option<String>,}impl Going {    /// A picture or a video: what a caption goes on.    fn visual(&self) -> bool {        matches!(self.kind, "photo" | "video")    }    /// The row's fields beside a text's.    fn fields(&self) -> Map<String, Value> {        let mut out = object(json!({ "kind": self.kind, "media_key": self.key, "mime": self.mime, "size_bytes": self.bytes }));        if self.voice {            out.insert("voice".into(), json!(true));        }        for (key, value) in [("width", self.width), ("height", self.height), ("duration_ms", self.duration_ms)] {            if let Some(value) = value {                out.insert(key.into(), json!(value));            }        }        if let Some(waveform) = &self.waveform {            out.insert("waveform".into(), json!(waveform));        }        if let Some(preview) = &self.preview {            out.insert("preview".into(), json!(preview));        }        if let Some(name) = &self.file_name {            out.insert("file_name".into(), json!(name));        }        out    }}/// A recorder's samples (0..1, any count) as WhatsApp's waveform: [`WAVEFORM_SAMPLES`] bytes in 0..=100, each the/// loudest of its stretch (a short note's samples repeat), base64. None for no samples.pub(super) fn waveform_of(samples: &[f64]) -> Option<String> {    use base64::Engine as _;    let levels: Vec<f64> = samples.iter().map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }).collect();    if levels.is_empty() {        return None;    }    let n = levels.len();    let bytes: Vec<u8> = (0..WAVEFORM_SAMPLES)        .map(|i| {            let from = (i * n / WAVEFORM_SAMPLES).min(n - 1);            let to = ((i + 1) * n / WAVEFORM_SAMPLES).clamp(from + 1, n);            let loudest = levels[from..to].iter().copied().fold(0.0_f64, f64::max);            (loudest * 100.0).round() as u8        })        .collect();    Some(base64::engine::general_purpose::STANDARD.encode(bytes))}/// What one attachment is as WhatsApp will carry it, or the refusal's words. A file picked as a file (`kind:/// "file"`, the attach sheet's Files) goes as a document where the outbox takes one, whatever its type, as WhatsApp's/// own Document does; anything not a picture, video or sound goes so too.fn kind_of(attachment: &Value, mime: &str, documents: bool) -> Result<(&'static str, bool), &'static str> {    match attachment.get("kind").and_then(Value::as_str) {        Some("voice") => return Ok(("audio", true)),        Some("file") if documents => return Ok(("document", false)),        _ => {}    }    match mime.split('/').next().unwrap_or_default() {        "image" => Ok(("photo", false)),        "video" => Ok(("video", false)),        "audio" => Ok(("audio", false)),        _ if documents => Ok(("document", false)),        _ => Err(NOT_YET_FILES),    }}/// Each attachment kept in his own media under `thread`'s folder, before any row names it: the file the bubble/// draws at once and the Mac opens. Refused whole, before anything is kept, when one cannot go.pub(super) fn keep_files(client: &ClientController, thread: &str, attachments: &[Value], documents: bool) -> Result<Vec<Going>, MethodError> {    use cotton_client::messages_import::media::{store_one_file, MediaLeg, MediaOutcome};    let too_large = || MethodError::new("picture_too_large", "That file is too large to send to WhatsApp.");    if attachments.len() > cotton_core::chat::payload::PICTURES_MAX {        return Err(bad("attachments", &format!("at most {}", cotton_core::chat::payload::PICTURES_MAX)));    }    let mut judged = Vec::new();    for attachment in attachments {        let path = attachment.get("path").and_then(Value::as_str).ok_or_else(|| bad("attachments", "each { path, mime, … }"))?;        let mime = attachment.get("mime").and_then(Value::as_str).filter(|m| !m.trim().is_empty()).unwrap_or("application/octet-stream").to_string();        let (kind, voice) = kind_of(attachment, &mime, documents).map_err(|why| MethodError::new("cannot", why))?;        let bytes = std::fs::metadata(path).map_err(|e| MethodError::new("unreadable", format!("the file could not be read ({e})")))?.len();        if bytes > if kind == "document" { DOCUMENT_MAX } else { cotton_core::chat::files::FILE_MAX as u64 } {            return Err(too_large());        }        judged.push((attachment, std::path::PathBuf::from(path), mime, kind, voice, bytes));    }    let layout = client.layout().clone();    let clock = client.clock();    let mut out = Vec::new();    for (attachment, path, mime, kind, voice, bytes) in judged {        let name = attachment.get("name").and_then(Value::as_str).map(str::to_string).or_else(|| path.file_name().map(|n| n.to_string_lossy().to_string()));        let thread_id = thread.to_string();        let outcome = client            .with_writer(|replica| {                let file_id = replica.identity.id().clone();                let leg = MediaLeg { layout: &layout, file: &file_id, thread_id: &thread_id, clock: clock.as_ref() };                let file = cotton_client::messages_import::MediaFile { external_id: format!("{PENDING}{thread_id}"), path: path.clone(), name: name.clone(), content_type: Some(mime.clone()) };                let outcome = store_one_file(&leg, replica.driver, &file);                // As a file sent in a Cotton chat is kept (`chat_files::keep`): Free up space may take it once it                // is in his account, and it lands back from there.                if let MediaOutcome::Stored { key, .. } = &outcome {                    replica.driver.run("UPDATE _media SET tier = 'original' WHERE key = ? AND tier IS NULL", &[SqlValue::Text(key.clone())]).map_err(|e| e.to_string())?;                }                Ok(outcome)            })            .map_err(|why| MethodError::new("unwritable", why))?;        let key = match outcome {            MediaOutcome::Stored { key, .. } => key,            MediaOutcome::Oversize => return Err(too_large()),            MediaOutcome::Missing => return Err(MethodError::new("unreadable", "The file could not be read.")),            MediaOutcome::UnsupportedType => return Err(MethodError::new("cannot", NOT_YET_FILES)),            MediaOutcome::Failed { detail } => return Err(MethodError::new("unwritable", detail)),        };        let number = |field: &str| attachment.get(field).and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0).map(|v| v.round() as u64);        let samples: Vec<f64> = attachment.get("waveform").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_f64).collect();        let document = kind == "document";        out.push(Going {            key,            mime,            bytes,            kind,            file_name: name.filter(|_| document),            voice,            width: number("width").filter(|_| !matches!(kind, "audio" | "document")),            height: number("height").filter(|_| !matches!(kind, "audio" | "document")),            duration_ms: number("durationMs").filter(|_| !matches!(kind, "photo" | "document")),            waveform: if voice { waveform_of(&samples) } else { None },            preview: attachment.get("preview").and_then(Value::as_str).and_then(cotton_core::chat::payload::preview_of).filter(|_| matches!(kind, "photo" | "video")),        });    }    Ok(out)}/// One tap's files and words for `thread`: one outbox row per file, in order, each its own WhatsApp id fixed now./// The words are the caption of the first picture or video; with none among the files, they go first as a text/// row of their own. The rows' ids, in the order they go.pub(super) fn queue_files(ctx: &mut Ctx<'_>, thread: &str, words: &str, files: &[Going], quoted: Option<&str>) -> Result<Vec<String>, String> {    let to = target(ctx, thread)?.map_err(str::to_string)?;    let words = words.trim();    let captioned = files.iter().position(Going::visual);    let mut ids = Vec::new();    // Each row's place in the tap (`part`, 0 first): the rows of one tap share its instant, and nothing else keeps    // them in the order they go (a text before its files, the files as picked).    // A reply's quote stands on the tap's first row: the words, or the first file.    let part = |n: usize| {        let mut fields = object(json!({ "part": n }));        if n == 0 {            fields.extend(quote(quoted));        }        fields    };    if captioned.is_none() && !words.is_empty() {        ids.push(made(ctx, thread, &to, part(0), words)?);    }    for (at, file) in files.iter().enumerate() {        let caption = if Some(at) == captioned { words } else { "" };        let mut fields = file.fields();        fields.extend(part(ids.len()));        ids.push(made(ctx, thread, &to, fields, caption)?);    }    Ok(ids)}/// One text or file still on its way, or failed.#[derive(Debug, Clone, PartialEq)]pub(super) struct Pending {    pub id: String,    pub body: String,    pub status: String,    pub error: Option<String>,    pub written_at: String,    /// A file row's file, named as the message will name it once it lands.    pub media: Option<MessageMedia>,    /// Its place in the tap that made it, 0 first.    pub part: u32,    /// A reply's: the WhatsApp id of the message it answers.    pub quoted: Option<String>,    /// A poll he made, drawn as the poll will be once it lands, with no votes.    pub poll: Option<cotton_core::messages::MessagePoll>,    /// A text's link card (FEEDBACK-4 B4), drawn at once.    pub link: Option<cotton_core::messages::MessageLinkPreview>,}/// A poll row's poll: the question, its options in order with no votes, and how many may be chosen.fn poll_of_row(data: &Map<String, Value>) -> Option<cotton_core::messages::MessagePoll> {    (s(data, "kind").as_deref() == Some("poll")).then_some(())?;    let options = match data.get("options") {        Some(Value::String(words)) => serde_json::from_str::<Vec<String>>(words).unwrap_or_default(),        Some(Value::Array(words)) => words.iter().filter_map(|w| w.as_str().map(str::to_string)).collect(),        _ => Vec::new(),    };    let selectable = data.get("selectable").and_then(Value::as_f64).map(|n| n.max(0.0) as u32).unwrap_or(0);    Some(cotton_core::messages::MessagePoll {        question: s(data, "body").unwrap_or_default(),        options: options.into_iter().map(|text| cotton_core::messages::MessagePollOption { text, votes: 0.0 }).collect(),        selectable: Some(selectable),        voters: Vec::new(),    })}/// A file row's file as a message names one, so its bubble is drawn as the message will be once it lands.pub(super) fn media_of_row(data: &Map<String, Value>) -> Option<MessageMedia> {    use base64::Engine as _;    use cotton_core::constants::MessageMediaKind;    let key = s(data, "media_key").filter(|k| !k.is_empty())?;    let voice = data.get("voice").and_then(Value::as_bool).unwrap_or(false);    let kind = match s(data, "kind").as_deref() {        Some("photo") => MessageMediaKind::Image,        Some("video") => MessageMediaKind::Video,        Some("audio") if voice => MessageMediaKind::Voice,        Some("audio") => MessageMediaKind::Audio,        Some("document") => MessageMediaKind::File,        _ => return None,    };    let number = |field: &str| data.get(field).and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0);    let waveform = s(data, "waveform")        .and_then(|w| base64::engine::general_purpose::STANDARD.decode(w).ok())        .map(|bytes| bytes.into_iter().map(|b| f64::from(b.min(100)) / 100.0).collect::<Vec<f64>>())        .filter(|w| !w.is_empty());    Some(MessageMedia {        key,        content_type: s(data, "mime").unwrap_or_else(|| "application/octet-stream".into()),        name: s(data, "file_name").filter(|n| !n.is_empty()),        width: number("width"),        height: number("height"),        size_bytes: number("size_bytes"),        kind: Some(kind),        duration_ms: number("duration_ms"),        playback_key: None,        playback_content_type: None,        waveform,        preview: s(data, "preview").filter(|p| !p.is_empty()),        contact: None,        file_key: None,    })}/// The file of outbox row `id` (a pending bubble's `outbox:<id>`), for `chat.picture`: the file's key and type.pub(crate) fn file_of(ctx: &mut Ctx<'_>, id: &str) -> Result<Option<(String, String)>, String> {    if !keeps_outbox(ctx)? {        return Ok(None);    }    let found = match tables::get_record_by_table(ctx, &object(json!({ "table": OUTBOX, "id": id }))) {        Ok(found) => found,        Err(_) => return Ok(None),    };    let record = if found["record"].is_object() { &found["record"] } else { &found };    Ok(media_of_row(&object(record["data"].clone())).map(|m| (m.key, m.content_type)))}fn rows_of(ctx: &mut Ctx<'_>, thread: &str) -> Result<Vec<(String, Map<String, Value>, String)>, String> {    let mut out = Vec::new();    let mut page = 0u64;    loop {        let ask = object(json!({ "table": OUTBOX, "where": { "thread_id": thread }, "limit": 500, "page": page }));        let listed = tables::list_records(ctx, &ask).map_err(tool)?;        let records = listed["records"].as_array().cloned().unwrap_or_default();        let got = records.len();        for record in records {            if record.get("deleted_at").is_some_and(|d| !d.is_null()) {                continue;            }            let Some(id) = record["id"].as_str() else { continue };            let at = record["created_at"].as_str().unwrap_or_default().to_string();            out.push((id.to_string(), object(record["data"].clone()), at));        }        match listed["next_page"].as_u64() {            Some(next) if got > 0 && next > page => page = next,            _ => break,        }    }    Ok(out)}/// The chat's texts and files not yet standing in it as messages, oldest first: queued, sending, failed, and sent/// until the message with their WhatsApp id has landed.pub(super) fn pending(ctx: &mut Ctx<'_>, thread: &str) -> Result<Vec<Pending>, String> {    if !keeps_outbox(ctx)? {        return Ok(Vec::new());    }    pending_kept(ctx, thread)}/// The newest of `thread`'s [`pending`], on a copy known to keep the outbox (the chat list asks once for all rows).pub(super) fn newest_pending(ctx: &mut Ctx<'_>, thread: &str) -> Result<Option<Pending>, String> {    Ok(pending_kept(ctx, thread)?.pop())}fn pending_kept(ctx: &mut Ctx<'_>, thread: &str) -> Result<Vec<Pending>, String> {    let mut out = Vec::new();    for (id, data, at) in rows_of(ctx, thread)? {        // A reaction, a vote, an edit or a delete is no bubble of its own: its state stands on the message it names.        if reaction_of(&data).is_some() || vote_of(&data).is_some() || change_of(&data).is_some() || s(&data, "kind").is_some_and(|k| SOURCE_ACTS.contains(&k.as_str())) {            continue;        }        let status = s(&data, "status").unwrap_or_else(|| "queued".into());        if !matches!(status.as_str(), "queued" | "sending" | "failed" | "sent") {            continue;        }        if let Some(external) = s(&data, "sent_external_id") {            let landed = one(ctx, &format!("SELECT 1 AS here FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND external_id = ? LIMIT 1"), &[ws(ctx), text(thread.to_string()), text(external)])?;            if landed.is_some() {                continue;            }        }        let media = media_of_row(&data);        let part = data.get("part").and_then(Value::as_f64).unwrap_or(0.0) as u32;        let quoted = s(&data, "quoted_id").filter(|q| !q.is_empty());        let poll = poll_of_row(&data);        let link = s(&data, "link").and_then(|l| serde_json::from_str(&l).ok());        out.push(Pending { id, body: s(&data, "body").unwrap_or_default(), status, error: s(&data, "error"), written_at: at, media, part, quoted, poll, link });    }    // The rows of one tap share its instant: their `part` keeps them in the order they go.    out.sort_by(|a, b| (&a.written_at, a.part, &a.id).cmp(&(&b.written_at, b.part, &b.id)));    Ok(out)}/// Whether `p` is a picture or a video: one tile of its tap's grid.fn tile(p: &Pending) -> bool {    p.poll.is_none() && p.media.as_ref().is_some_and(|m| visual(std::slice::from_ref(m)))}/// Whether every file of `media` is a picture or a video (and there is one).pub(super) fn visual(media: &[MessageMedia]) -> bool {    let row = Row { body: None, media, meta: None, deleted_at: None };    let parts = bubble::media_parts(&row);    !parts.is_empty() && parts.iter().all(|p| matches!(p.kind, cotton_core::messages::app::shapes::Mark::Photo | cotton_core::messages::app::shapes::Mark::Video))}/// How far apart one tap's rows may be written: they are made in one write, a millisecond or two apart.const TAP_SPAN_MS: i64 = 5_000;/// Whether a row written at `at` as place `part` follows `last` (written at `last_at`, place `last_part`) in the/// tap that began at `began`: the next place, written within [`TAP_SPAN_MS`] of its first.fn follows(began: &str, last_part: u32, at: &str, part: u32) -> bool {    let ms = |iso: &str| chrono::DateTime::parse_from_rfc3339(iso).map(|t| t.timestamp_millis()).ok();    part == last_part + 1 && matches!((ms(began), ms(at)), (Some(a), Some(b)) if (0..=TAP_SPAN_MS).contains(&(b - a)))}/// `pending` as the bubbles they stand as (FEEDBACK-4 B3): the pictures and videos of one tap together, one grid;/// any other row alone. In order.pub(super) fn taps(pending: &[Pending]) -> Vec<Vec<&Pending>> {    let mut out: Vec<Vec<&Pending>> = Vec::new();    for p in pending {        match out.last_mut() {            Some(tap) if tile(p) && tile(tap[0]) && tap.last().is_some_and(|q| follows(&tap[0].written_at, q.part, &p.written_at, p.part)) => tap.push(p),            _ => out.push(vec![p]),        }    }    out}/// The tap holding row `id`, among `pending`.pub(super) fn tap_of<'a>(pending: &'a [Pending], id: &str) -> Option<Vec<&'a Pending>> {    taps(pending).into_iter().find(|tap| tap.iter().any(|p| p.id == id))}/// One tap's bubble: a row alone as [`bubble`]; several pictures as one grid, headed by the first (its words and/// reply), each tile naming its row (`outbox:<id>`, index 0), its state the furthest from sent of them, Retry when/// any may go again.pub(super) fn tap_bubble(lines: &LineSet, clock: &Clock, tap: &[&Pending], head: bool) -> Bubble {    let first = tap[0];    let mut b = bubble(lines, clock, first, head);    if tap.len() < 2 {        return b;    }    let rank = |p: &Pending| match p.status.as_str() {        "failed" => 0,        "sending" => 1,        "queued" => 2,        _ => 3,    };    let lead = tap.iter().copied().min_by_key(|p| rank(p)).unwrap_or(first);    let led = bubble(lines, clock, lead, head);    b.tick = led.tick;    b.state = led.state;    let now = clock.now.timestamp_millis();    b.actions.retain(|a| a != "retry");    if tap.iter().any(|p| retryable(p, now)) {        b.actions.insert(0, "retry".to_string());    }    b.media = tap        .iter()        .flat_map(|p| {            let media: Vec<MessageMedia> = p.media.iter().cloned().collect();            let row = Row { body: None, media: &media, meta: None, deleted_at: None };            bubble::media_parts(&row).into_iter().map(|mut part| {                part.message = Some(format!("{PENDING}{}", p.id));                part            })        })        .collect();    b.kind = BubbleKind::Album;    b}/// The pictures and videos he sent from here in `thread`, by their WhatsApp id: the tap that made them (named by its/// first row's instant), and their place in it.pub(super) fn sent_tiles(ctx: &mut Ctx<'_>, thread: &str) -> Result<HashMap<String, (String, u32)>, String> {    let mut out = HashMap::new();    if !keeps_outbox(ctx)? {        return Ok(out);    }    let mut rows: Vec<(String, u32, String)> = Vec::new();    for (_, data, at) in rows_of(ctx, thread)? {        if !matches!(s(&data, "kind").as_deref(), Some("photo" | "video")) {            continue;        }        let Some(external) = s(&data, "sent_external_id").filter(|e| !e.is_empty()) else { continue };        rows.push((at, data.get("part").and_then(Value::as_f64).unwrap_or(0.0) as u32, external));    }    rows.sort();    // Each tap named by its first row's instant.    let (mut began, mut last): (Option<String>, Option<u32>) = (None, None);    for (at, part, external) in rows {        let tap = match (&began, last) {            (Some(b), Some(l)) if follows(b, l, &at, part) => b.clone(),            _ => at.clone(),        };        began = Some(tap.clone());        last = Some(part);        out.insert(external, (tap, part));    }    Ok(out)}fn stale(status: &str, written_at: &str, now_ms: i64) -> bool {    status == "sending" && chrono::DateTime::parse_from_rfc3339(written_at).is_ok_and(|at| now_ms - at.timestamp_millis() > STALE_SENDING_MS)}/// Whether the owner may send `p` again: failed, or `sending` far longer than a send takes.pub(super) fn retryable(p: &Pending, now_ms: i64) -> bool {    p.status == "failed" || stale(&p.status, &p.written_at, now_ms)}/// The words under a pending text: never "Sent" before the Mac said so.pub(super) fn state_words(lines: &LineSet, p: &Pending) -> String {    match (p.status.as_str(), &p.error) {        ("failed", Some(why)) => say(lines, "state.failed_why", &[("why", why)]),        ("failed", None) => say(lines, "state.failed", &[]),        ("sending", _) => say(lines, "state.sending", &[]),        ("sent", _) => say(lines, "state.sent", &[]),        _ => say(lines, "state.queued", &[]),    }}/// `p` as the owner's bubble at the foot of the chat: a file drawn from his own media, as its message will be.pub(super) fn bubble(lines: &LineSet, clock: &Clock, p: &Pending, head: bool) -> Bubble {    let at = if p.written_at.is_empty() { clock.now_iso() } else { p.written_at.clone() };    let (time, _, _) = clock.slip(&at);    let tick = match p.status.as_str() {        "failed" => Tick::Failed,        "sent" => Tick::Sent,        _ => Tick::Sending,    };    let media: Vec<MessageMedia> = p.media.iter().cloned().collect();    let meta = p.poll.clone().map(|poll| cotton_core::messages::MessageMeta { poll: Some(poll), ..Default::default() });    let row = Row { body: Some(&p.body), media: &media, meta: meta.as_ref(), deleted_at: None };    // A poll he made is drawn as its card, its words the card's (CONTRACT "Making a poll").    let poll = p.poll.as_ref().map(|poll| cotton_core::messages::app::poll::card(lines, poll, &|who| who.to_string()));    let text = if poll.is_some() { None } else { bubble::text_of(&row) };    let links = text.as_deref().map(cotton_core::messages::links::links_at).unwrap_or_default();    let mut actions = Vec::new();    if retryable(p, clock.now.timestamp_millis()) {        actions.push("retry".to_string());    }    if text.is_some() {        actions.push("copy".to_string());    }    Bubble {        message: format!("{PENDING}{}", p.id),        mine: true,        kind: bubble::kind_of(&row),        text,        sender: None,        agent: None,        head,        tail: true,        face: false,        time,        tick: Some(tick),        quiet_until: None,        state: Some(state_words(lines, p)),        edited: None,        forwarded: None,        pinned: false,        reply: None,        reactions: Vec::new(),        media: bubble::media_parts(&row),        link: p.link.as_ref().map(|card| LinkCard { url: card.url.clone(), site: card.site_name.clone(), title: card.title.clone(), description: card.description.clone(), thumb: card.thumb.clone() }),        actions,        marks: Vec::new(),        starred: false,        place: None,        numbers: Vec::new(),        links,        poll,    }}/// Send a failed (or long-stuck) text or file again: back to `queued`, its WhatsApp id and file unchanged, so it/// goes once. A grid of one tap's pictures sends again each of its rows that may go (FEEDBACK-4 B3). Refused when/// none is: on its way, or gone already.pub(super) fn retry(ctx: &mut Ctx<'_>, thread: &str, id: &str, now_ms: i64) -> Result<bool, String> {    let pending = pending(ctx, thread)?;    let Some(tap) = tap_of(&pending, id) else { return Ok(false) };    let again: Vec<String> = tap.iter().filter(|p| retryable(p, now_ms)).map(|p| p.id.clone()).collect();    for row in &again {        let patch = object(json!({ "status": "queued", "error": null }));        tables::update_produced_record(ctx, &object(json!({ "table": OUTBOX, "id": row, "patch": Value::Object(patch) }))).map_err(tool)?;    }    Ok(!again.is_empty())}// ── reactions (CONTRACT "Replies and reactions") ─────────────────────────/// One reaction row: his reaction on WhatsApp message `to`, `emoji` ("" takes it off).#[derive(Debug, Clone, PartialEq)]pub(super) struct Reacting {    pub id: String,    pub to: String,    pub emoji: String,    pub status: String,    pub error: Option<String>,    pub written_at: String,}/// The WhatsApp id a reaction row names, or None for a text or file row.fn reaction_of(data: &Map<String, Value>) -> Option<String> {    s(data, "reaction_to").filter(|to| !to.is_empty())}/// `thread`'s reaction rows, oldest first.fn reaction_rows(ctx: &mut Ctx<'_>, thread: &str) -> Result<Vec<Reacting>, String> {    let mut out: Vec<Reacting> = rows_of(ctx, thread)?        .into_iter()        .filter_map(|(id, data, at)| {            let to = reaction_of(&data)?;            Some(Reacting { id, to, emoji: s(&data, "emoji").unwrap_or_default(), status: s(&data, "status").unwrap_or_else(|| "queued".into()), error: s(&data, "error"), written_at: at })        })        .collect();    out.sort_by(|a, b| (&a.written_at, &a.id).cmp(&(&b.written_at, &b.id)));    Ok(out)}/// The newest reaction row of each WhatsApp message of `thread` that is not yet sent, by that message's WhatsApp id:/// its state stands on the message's bubble. Only the newest counts: an older failed row offers nothing.pub(super) fn reactions_waiting(ctx: &mut Ctx<'_>, thread: &str) -> Result<HashMap<String, Reacting>, String> {    if !keeps_outbox(ctx)? {        return Ok(HashMap::new());    }    let mut newest: HashMap<String, Reacting> = HashMap::new();    for r in reaction_rows(ctx, thread)? {        newest.insert(r.to.clone(), r);    }    newest.retain(|_, r| r.status != "sent");    Ok(newest)}/// Queue his reaction `emoji` ("" to take it off) on WhatsApp message `to` of `thread`. While that message's newest/// reaction row is still `queued` (the Mac has not taken it), the change rewrites it, so only the last goes; once/// taken, a new row with its own WhatsApp id, so an id WhatsApp may hold is never reused for another emoji. A sent/// row's emoji leaves the row here too (the Mac empties it as it marks it sent). The row's id.pub(super) fn queue_reaction(ctx: &mut Ctx<'_>, thread: &str, to: &str, emoji: &str) -> Result<String, String> {    let target = target(ctx, thread)?.map_err(str::to_string)?;    let rows = reaction_rows(ctx, thread)?;    for sent in rows.iter().filter(|r| r.status == "sent" && !r.emoji.is_empty()) {        patch_row(ctx, &sent.id, object(json!({ "emoji": "" })))?;    }    if let Some(newest) = rows.iter().rev().find(|r| r.to == to).filter(|r| r.status == "queued") {        if newest.emoji != emoji {            patch_row(ctx, &newest.id, object(json!({ "emoji": emoji })))?;        }        return Ok(newest.id.clone());    }    let external = send::whatsapp_message_id(&super::cotton_chat::fresh_id(), 0);    let mut data = object(json!({        "thread_id": thread, "channel": "whatsapp", "to": target.chat, "body": "", "status": "queued", "sent_external_id": external,        "reaction_to": to, "emoji": emoji,    }));    if let Some(account) = &target.account {        data.insert("account".into(), json!(account));    }    // Never the chat's list line, and the chat does not move: a reaction is no message.    let made = tables::create_produced_record(ctx, &object(json!({ "table": OUTBOX, "data": Value::Object(data) }))).map_err(tool)?;    made["record"]["id"].as_str().or_else(|| made["id"].as_str()).map(str::to_string).ok_or_else(|| "no id for the queued reaction".to_string())}fn patch_row(ctx: &mut Ctx<'_>, id: &str, patch: Map<String, Value>) -> Result<(), String> {    tables::update_produced_record(ctx, &object(json!({ "table": OUTBOX, "id": id, "patch": Value::Object(patch) }))).map_err(tool)?;    Ok(())}/// Whether the owner may send reaction `r` again: failed, or `sending` far longer than a send takes.pub(super) fn reaction_retryable(r: &Reacting, now_ms: i64) -> bool {    r.status == "failed" || stale(&r.status, &r.written_at, now_ms)}/// The words under the reacted message while its reaction is on its way.pub(super) fn reaction_words(lines: &LineSet, r: &Reacting) -> String {    match (r.status.as_str(), &r.error) {        ("failed", Some(why)) => say(lines, "state.reaction_failed_why", &[("why", why)]),        ("failed", None) => say(lines, "state.reaction_failed", &[]),        ("sending", _) => say(lines, "state.reaction_sending", &[]),        _ => say(lines, "state.reaction_queued", &[]),    }}/// Send the newest reaction on WhatsApp message `to` of `thread` again: back to `queued`, the same row and WhatsApp/// id. False when there is none to retry.pub(super) fn retry_reaction(ctx: &mut Ctx<'_>, thread: &str, to: &str, now_ms: i64) -> Result<bool, String> {    let Some(r) = reactions_waiting(ctx, thread)?.remove(to) else { return Ok(false) };    if !reaction_retryable(&r, now_ms) {        return Ok(false);    }    patch_row(ctx, &r.id, object(json!({ "status": "queued", "error": null })))?;    Ok(true)}// ── votes (CONTRACT "Documents and votes") ──────────────────────────────/// One vote row: his choice on WhatsApp poll `poll`, by the options' words (none takes his vote back).#[derive(Debug, Clone, PartialEq)]pub(super) struct Voting {    pub id: String,    pub poll: String,    pub options: Vec<String>,    pub status: String,    pub error: Option<String>,    pub written_at: String,}/// The WhatsApp poll a vote row names, or None for any other row.fn vote_of(data: &Map<String, Value>) -> Option<String> {    (s(data, "kind").as_deref() == Some("poll_vote")).then(|| s(data, "target")).flatten().filter(|t| !t.is_empty())}/// `thread`'s vote rows, oldest first.fn vote_rows(ctx: &mut Ctx<'_>, thread: &str) -> Result<Vec<Voting>, String> {    let mut out: Vec<Voting> = rows_of(ctx, thread)?        .into_iter()        .filter_map(|(id, data, at)| {            let poll = vote_of(&data)?;            let options = match data.get("options") {                Some(Value::String(words)) => serde_json::from_str::<Vec<String>>(words).unwrap_or_default(),                Some(Value::Array(words)) => words.iter().filter_map(|w| w.as_str().map(str::to_string)).collect(),                _ => Vec::new(),            };            Some(Voting { id, poll, options, status: s(&data, "status").unwrap_or_else(|| "queued".into()), error: s(&data, "error"), written_at: at })        })        .collect();    out.sort_by(|a, b| (&a.written_at, &a.id).cmp(&(&b.written_at, &b.id)));    Ok(out)}/// The newest vote row of each poll of `thread` that is not yet sent, by the poll's WhatsApp id: its state stands on/// the poll's bubble.pub(super) fn votes_waiting(ctx: &mut Ctx<'_>, thread: &str) -> Result<HashMap<String, Voting>, String> {    if !keeps_outbox(ctx)? {        return Ok(HashMap::new());    }    let mut newest: HashMap<String, Voting> = HashMap::new();    for v in vote_rows(ctx, thread)? {        newest.insert(v.poll.clone(), v);    }    newest.retain(|_, v| v.status != "sent");    Ok(newest)}/// Queue his vote on WhatsApp poll `poll` of `thread`: the words of the options he picked, none to take it back./// While that poll's newest vote row is still `queued`, the change rewrites it, so only the last goes; once taken, a/// new row with its own WhatsApp id. The row's id.pub(super) fn queue_vote(ctx: &mut Ctx<'_>, thread: &str, poll: &str, picked: &[String]) -> Result<String, String> {    let target = target(ctx, thread)?.map_err(str::to_string)?;    let words = serde_json::to_string(picked).map_err(|e| e.to_string())?;    if let Some(newest) = vote_rows(ctx, thread)?.into_iter().rev().find(|v| v.poll == poll).filter(|v| v.status == "queued") {        if newest.options != picked {            patch_row(ctx, &newest.id, object(json!({ "options": words })))?;        }        return Ok(newest.id);    }    let external = send::whatsapp_message_id(&super::cotton_chat::fresh_id(), 0);    let mut data = object(json!({        "thread_id": thread, "channel": "whatsapp", "to": target.chat, "body": "", "status": "queued", "sent_external_id": external,        "kind": "poll_vote", "target": poll, "options": words,    }));    if let Some(account) = &target.account {        data.insert("account".into(), json!(account));    }    // Never the chat's list line, and the chat does not move: a vote is no message.    let made = tables::create_produced_record(ctx, &object(json!({ "table": OUTBOX, "data": Value::Object(data) }))).map_err(tool)?;    made["record"]["id"].as_str().or_else(|| made["id"].as_str()).map(str::to_string).ok_or_else(|| "no id for the queued vote".to_string())}/// Whether the owner may send vote `v` again: failed, or `sending` far longer than a send takes.pub(super) fn vote_retryable(v: &Voting, now_ms: i64) -> bool {    v.status == "failed" || stale(&v.status, &v.written_at, now_ms)}/// The words under the poll while his vote is on its way.pub(super) fn vote_words(lines: &LineSet, v: &Voting) -> String {    match (v.status.as_str(), &v.error) {        ("failed", Some(why)) => say(lines, "state.vote_failed_why", &[("why", why)]),        ("failed", None) => say(lines, "state.vote_failed", &[]),        ("sending", _) => say(lines, "state.vote_sending", &[]),        _ => say(lines, "state.vote_queued", &[]),    }}/// Send the newest vote on WhatsApp poll `poll` of `thread` again: back to `queued`, the same row and WhatsApp id./// False when there is none to retry.pub(super) fn retry_vote(ctx: &mut Ctx<'_>, thread: &str, poll: &str, now_ms: i64) -> Result<bool, String> {    let Some(v) = votes_waiting(ctx, thread)?.remove(poll) else { return Ok(false) };    if !vote_retryable(&v, now_ms) {        return Ok(false);    }    patch_row(ctx, &v.id, object(json!({ "status": "queued", "error": null })))?;    Ok(true)}// ── edits and deletes for everyone (CONTRACT "Editing and deleting his own message") ──────────────────/// One edit or delete-for-everyone row: his change to his own WhatsApp message `target`.#[derive(Debug, Clone, PartialEq)]pub(super) struct Changing {    pub id: String,    /// `edit` or `delete`.    pub kind: String,    pub target: String,    pub body: String,    pub status: String,    pub error: Option<String>,    pub written_at: String,}/// The message an edit or a delete row names, with its kind, or None for any other row.fn change_of(data: &Map<String, Value>) -> Option<(String, String)> {    let kind = s(data, "kind").filter(|k| CHANGE_KINDS.contains(&k.as_str()))?;    Some((kind, s(data, "target").filter(|t| !t.is_empty())?))}/// `thread`'s edit and delete rows, oldest first.fn change_rows(ctx: &mut Ctx<'_>, thread: &str) -> Result<Vec<Changing>, String> {    let mut out: Vec<Changing> = rows_of(ctx, thread)?        .into_iter()        .filter_map(|(id, data, at)| {            let (kind, target) = change_of(&data)?;            Some(Changing { id, kind, target, body: s(&data, "body").unwrap_or_default(), status: s(&data, "status").unwrap_or_else(|| "queued".into()), error: s(&data, "error"), written_at: at })        })        .collect();    out.sort_by(|a, b| (&a.written_at, &a.id).cmp(&(&b.written_at, &b.id)));    Ok(out)}/// The newest edit or delete row of each of `thread`'s messages that is not yet sent, by the message's WhatsApp id:/// its state stands on the message's bubble (an edit's), or on the marker in its place (a delete's).pub(super) fn changes_waiting(ctx: &mut Ctx<'_>, thread: &str) -> Result<HashMap<String, Changing>, String> {    if !keeps_outbox(ctx)? {        return Ok(HashMap::new());    }    let mut newest: HashMap<String, Changing> = HashMap::new();    for c in change_rows(ctx, thread)? {        newest.insert(c.target.clone(), c);    }    newest.retain(|_, c| c.status != "sent");    Ok(newest)}/// The acts on his WhatsApp itself (owner, 24 Nov 2026; CONTRACT "Blocking a WhatsApp sender, deleting a WhatsApp/// chat"): a person blocked or unblocked, and a person's chat deleted for him alone, never for everyone.pub(super) const SOURCE_ACTS: [&str; 3] = ["block", "unblock", "delete_chat"];/// Whether this copy's outbox takes the source acts: the served `kind` offers all three. Until the Worker serves them,/// a WhatsApp chat offers neither Block on WhatsApp nor Delete on WhatsApp.pub(crate) fn takes_source_acts(ctx: &mut Ctx<'_>) -> Result<bool, String> {    Ok(keeps_outbox(ctx)? && offers(ctx, &SOURCE_ACTS)?)}/// Queue a block or unblock of the person `thread` is with, on WhatsApp. The row's id.pub(crate) fn queue_block(ctx: &mut Ctx<'_>, thread: &str, block: bool) -> Result<String, String> {    let to = target(ctx, thread)?.map_err(str::to_string)?;    if to.chat.ends_with("@g.us") {        return Err("a group is not blocked".to_string());    }    source_row(ctx, thread, &to, if block { "block" } else { "unblock" }, None)}/// ERASES on his WhatsApp: queue `thread` deleted for him there, up to its newest WhatsApp message `newest`. The row's/// id. The phone has asked him the count first (`chat.act deleteOnWhatsApp`).pub(super) fn queue_delete_chat(ctx: &mut Ctx<'_>, thread: &str, newest: &str) -> Result<String, String> {    let to = target(ctx, thread)?.map_err(str::to_string)?;    if to.chat.ends_with("@g.us") {        return Err("a group chat is not deleted on WhatsApp from here".to_string());    }    source_row(ctx, thread, &to, "delete_chat", Some(newest))}fn source_row(ctx: &mut Ctx<'_>, thread: &str, to: &PhoneTarget, kind: &str, target_id: Option<&str>) -> Result<String, String> {    let external = send::whatsapp_message_id(&super::cotton_chat::fresh_id(), 0);    let mut data = object(json!({ "thread_id": thread, "channel": "whatsapp", "to": to.chat, "body": "", "status": "queued", "sent_external_id": external, "kind": kind }));    if let Some(target_id) = target_id {        data.insert("target".into(), json!(target_id));    }    if let Some(account) = &to.account {        data.insert("account".into(), json!(account));    }    let made = tables::create_produced_record(ctx, &object(json!({ "table": OUTBOX, "data": Value::Object(data) }))).map_err(tool)?;    made["record"]["id"].as_str().or_else(|| made["id"].as_str()).map(str::to_string).ok_or_else(|| format!("no id for the queued {kind}"))}/// A new row of `kind` for `thread` naming his message `target`, its own WhatsApp id fixed now. Never the chat's/// list line, and the chat does not move.fn change_row(ctx: &mut Ctx<'_>, thread: &str, kind: &str, target_id: &str, body: &str) -> Result<String, String> {    let to = target(ctx, thread)?.map_err(str::to_string)?;    let external = send::whatsapp_message_id(&super::cotton_chat::fresh_id(), 0);    let mut data = object(json!({        "thread_id": thread, "channel": "whatsapp", "to": to.chat, "body": body, "status": "queued", "sent_external_id": external,        "kind": kind, "target": target_id,    }));    if let Some(account) = &to.account {        data.insert("account".into(), json!(account));    }    let made = tables::create_produced_record(ctx, &object(json!({ "table": OUTBOX, "data": Value::Object(data) }))).map_err(tool)?;    made["record"]["id"].as_str().or_else(|| made["id"].as_str()).map(str::to_string).ok_or_else(|| format!("no id for the queued {kind}"))}/// Queue his edit of his own WhatsApp message `target` of `thread` to `body`. While that message's newest edit row is/// still `queued` the edit rewrites it (only the last goes); once the Mac has taken it, a new row with its own/// WhatsApp id, and every older edit row of the message has its words emptied: they are no longer the message's.pub(super) fn queue_edit(ctx: &mut Ctx<'_>, thread: &str, target_id: &str, body: &str) -> Result<String, String> {    let edits: Vec<Changing> = change_rows(ctx, thread)?.into_iter().filter(|c| c.kind == "edit" && c.target == target_id).collect();    if let Some(newest) = edits.last().filter(|c| c.status == "queued") {        if newest.body != body {            patch_row(ctx, &newest.id, object(json!({ "body": body })))?;        }        return Ok(newest.id.clone());    }    for older in edits.iter().filter(|c| !c.body.is_empty()) {        patch_row(ctx, &older.id, object(json!({ "body": "" })))?;    }    change_row(ctx, thread, "edit", target_id, body)}/// Queue his delete for everyone of his own WhatsApp message `target` of `thread`. In the same act every other/// outbox row about that message is ERASED (its own send row, its edits, its reactions), so a waiting edit never goes/// and none of its words stay in the outbox.pub(super) fn queue_delete(ctx: &mut Ctx<'_>, thread: &str, target_id: &str) -> Result<String, String> {    erase_rows_about(ctx, thread, target_id, crate::phone::chat_revoked::REVOKED)?;    change_row(ctx, thread, "delete", target_id, "")}/// ERASE every outbox row of `thread` about WhatsApp message `target`: its send, its edits and deletes, its reactions/// and votes.pub(super) fn erase_rows_about(ctx: &mut Ctx<'_>, thread: &str, target_id: &str, reason: &str) -> Result<(), String> {    for (id, data, _) in rows_of(ctx, thread)? {        let about = s(&data, "sent_external_id").as_deref() == Some(target_id)            || s(&data, "target").as_deref() == Some(target_id)            || reaction_of(&data).as_deref() == Some(target_id);        if about {            tables::erase_record(ctx, &id, reason).map_err(tool)?;        }    }    Ok(())}/// Whether the owner may send change `c` again: failed, or `sending` far longer than a send takes.pub(super) fn change_retryable(c: &Changing, now_ms: i64) -> bool {    c.status == "failed" || stale(&c.status, &c.written_at, now_ms)}/// The words on the message (an edit) or its marker (a delete) while the change is on its way.pub(super) fn change_words(lines: &LineSet, c: &Changing) -> String {    let kind = if c.kind == "delete" { "delete" } else { "edit" };    match (c.status.as_str(), &c.error) {        ("failed", Some(why)) => say(lines, &format!("state.{kind}_failed_why"), &[("why", why)]),        ("failed", None) => say(lines, &format!("state.{kind}_failed"), &[]),        ("sending", _) => say(lines, &format!("state.{kind}_sending"), &[]),        _ => say(lines, &format!("state.{kind}_queued"), &[]),    }}/// Send the newest edit or delete of WhatsApp message `target` of `thread` again: back to `queued`, the same row and/// WhatsApp id. False when there is none to retry.pub(super) fn retry_change(ctx: &mut Ctx<'_>, thread: &str, target_id: &str, now_ms: i64) -> Result<bool, String> {    let Some(c) = changes_waiting(ctx, thread)?.remove(target_id) else { return Ok(false) };    if !change_retryable(&c, now_ms) {        return Ok(false);    }    patch_row(ctx, &c.id, object(json!({ "status": "queued", "error": null })))?;    Ok(true)}// ── a poll he makes (CONTRACT "Making a poll") ─────────────────────────/// Queue his poll in `thread`: the question, the options' words in order (at least two), one choice or any number./// One outbox row, its WhatsApp id fixed now; drawn at once as the poll, with no votes. The row's id.pub(super) fn queue_poll(ctx: &mut Ctx<'_>, thread: &str, question: &str, options: &[String], one: bool) -> Result<String, String> {    let to = target(ctx, thread)?.map_err(str::to_string)?;    let extra = object(json!({        "kind": "poll",        "options": serde_json::to_string(options).map_err(|e| e.to_string())?,        "selectable": if one { 1 } else { 0 },    }));    made(ctx, thread, &to, extra, question.trim())}#[cfg(test)]#[path = "chat_whatsapp_tests.rs"]mod tests;// ── a source act's state, for People (SENDERS.md) ──────────────────────/// One block, unblock or delete-chat row of a chat: what it asks of his WhatsApp and how it stands.#[derive(Debug, Clone, PartialEq)]pub(crate) struct SourceAct {    pub id: String,    /// `block`, `unblock` or `delete_chat`.    pub kind: String,    pub status: String,    pub error: Option<String>,    pub written_at: String,    /// The name the sender was shown by when the act was filed (a mail act's `body`), for a sender with nothing    /// left here (ACTS TRUTH, 24 Nov 2026). None for WhatsApp's acts.    pub name: Option<String>,    /// How many the Mac moved (a sender's Archive everything, a move to Trash), as it wrote back.    pub moved: Option<u64>,    /// What the Mac wrote in `sent_external_id`: `read_back` when it read his Inbox again after an archive and found    /// it done (SENDERS TRUE, CONTRACT "An archive is done when the Mac reads it back").    pub proof: Option<String>,    /// The Mac's count on the row (a sender's Delete or Archive everything), and whether the set it counted is fixed    /// on it (`uid_validity`, `uid_below`).    pub count: Option<u64>,    pub fixed: bool,    /// An unsubscribe's mail offered a one-click link (RFC 8058: an https List-Unsubscribe with    /// List-Unsubscribe-Post), as the mail Comms holds says.    pub offered: bool,}/// The Mac's own words when it counted first (`crates/cotton-mac/src/mail/trash.rs`, Mac 9), word for word.pub(crate) fn mac_asks(kind: &str, n: u64) -> Option<String> {    Some(match (kind, n) {        ("sender_trash", 1) => "Your mail holds 1 email from them. Try again to move it to Trash.".to_string(),        ("sender_trash", n) => format!("Your mail holds {n} emails from them. Try again to move those {n} to Trash."),        ("sender_archive", 1) => "1 email from them is in your Inbox. Try again to archive it.".to_string(),        ("sender_archive", n) => format!("{n} emails from them are in your Inbox. Try again to archive those {n}."),        _ => return None,    })}/// The acts whose `sent` is done only once the Mac read it back: Gmail can ignore a label change made in an open/// Inbox and still answer OK (mac-import, Mac 9, 24 Nov 2026).pub(crate) const READ_BACK_KINDS: [&str; 2] = ["sender_archive", "archive"];impl SourceAct {    /// The Mac counted and asks him first (Mac 9 on a row with no count fixed on it: Delete or Archive everything    /// filed before ARCHIVE COUNT): refused in its own words for that count, the set now fixed on the row. His Try    /// again moves exactly that set.    pub(crate) fn counted(&self) -> Option<u64> {        let n = self.count.filter(|&n| n > 0)?;        // `moved` is left as a build-8 Mac wrote it on his old rows, so only the words and the fixed set say it.        let asks = self.status == "failed" && self.fixed && self.error.as_deref() == Some(mac_asks(&self.kind, n)?.as_str());        asks.then_some(n)    }    /// The Mac did it, and for an archive read it back: nothing is left for it to do or for him to check.    pub(crate) fn done(&self) -> bool {        self.status == "sent" && (!READ_BACK_KINDS.contains(&self.kind.as_str()) || self.proof.as_deref() == Some("read_back"))    }    /// `sent` by a Mac that did not read it back: he is told so and may ask again.    pub(crate) fn unchecked(&self) -> bool {        self.status == "sent" && !self.done()    }}/// Every chat's newest source act, by chat: three reads of the outbox, one per kind, never one per chat.pub(crate) fn newest_source_acts(ctx: &mut Ctx<'_>) -> Result<HashMap<String, SourceAct>, String> {    let mut newest: HashMap<String, SourceAct> = HashMap::new();    if !keeps_outbox(ctx)? {        return Ok(newest);    }    for kind in SOURCE_ACTS {        // A kind the served outbox does not offer is not asked by (the read refuses it).        if !offers(ctx, &[kind])? {            continue;        }        let mut page = 0u64;        loop {            let ask = object(json!({ "table": OUTBOX, "where": { "kind": kind }, "limit": 500, "page": page }));            let listed = tables::list_records(ctx, &ask).map_err(tool)?;            let records = listed["records"].as_array().cloned().unwrap_or_default();            for record in &records {                if record.get("deleted_at").is_some_and(|d| !d.is_null()) {                    continue;                }                let data = object(record["data"].clone());                let (Some(id), Some(thread)) = (record["id"].as_str(), s(&data, "thread_id")) else { continue };                let act = SourceAct { id: id.to_string(), kind: kind.to_string(), status: s(&data, "status").unwrap_or_else(|| "queued".into()), error: s(&data, "error"), written_at: record["created_at"].as_str().unwrap_or_default().to_string(), name: None, moved: None, proof: None, count: None, fixed: false, offered: false };                let newer = newest.get(&thread).is_none_or(|held| (&held.written_at, &held.id) < (&act.written_at, &act.id));                if newer {                    newest.insert(thread, act);                }            }            match listed["next_page"].as_u64() {                Some(next) if !records.is_empty() && next > page => page = next,                _ => break,            }        }    }    Ok(newest)}/// Whether a source act may be sent again: failed, or `sending` far longer than a send takes.pub(crate) fn source_retryable(a: &SourceAct, now_ms: i64) -> bool {    a.status == "failed" || a.unchecked() || stale(&a.status, &a.written_at, now_ms)}/// Send source act `id` again: back to `queued`, the same row.pub(crate) fn retry_source(ctx: &mut Ctx<'_>, id: &str) -> Result<(), String> {    patch_row(ctx, id, object(json!({ "status": "queued", "error": null })))}/// Queue `thread` deleted for him on WhatsApp up to its newest WhatsApp message, if it has one and the outbox takes/// it (People's Delete everything, SENDERS.md). The row's id, or None.pub(crate) fn queue_delete_chat_if(ctx: &mut Ctx<'_>, thread: &str) -> Result<Option<String>, String> {    if !takes_source_acts(ctx)? {        return Ok(None);    }    let newest = super::cotton_chat::rows(        ctx,        &format!("SELECT external_id FROM {} 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", super::cotton_chat::MESSAGES),        &[super::cotton_chat::ws(ctx), rusqlite::types::Value::Text(thread.to_string())],    )?    .first()    .and_then(|r| s(r, "external_id"));    match newest {        Some(newest) => queue_delete_chat(ctx, thread, &newest).map(Some),        None => Ok(None),    }}/// Queue a block or unblock on WhatsApp of the person `thread` is with, if the outbox takes it. The row's id, or None.pub(crate) fn queue_block_if(ctx: &mut Ctx<'_>, thread: &str, block: bool) -> Result<Option<String>, String> {    if !takes_source_acts(ctx)? {        return Ok(None);    }    match target(ctx, thread)? {        Ok(to) if !to.chat.ends_with("@g.us") => queue_block(ctx, thread, block).map(Some),        _ => Ok(None),    }}