Cotton code
1004 lines · 56.2 KB · RustRaw
//! Disappearing messages on this phone (chat-search, 21 Nov 2026). The rules//! and words are `cotton_core::messages::app::timer`; CONTRACT.md//! "Disappearing messages" says what each side sees.//!//! A chat's timer is its newest timer line (`meta.cotton.timer`, read through//! `idx_cotton_msg_messages_timer`). Either person sets it with `chat.act {//! act: "timer" }`: the line lands here at once and goes to the other side as//! a sealed change (`What::Timer`), which lands the same line there (and on//! every phone of both people, under one id). A message written while it is on//! names when it goes (`meta.cotton.expiresAt`, by the writer's clock, sealed//! in its box as `timer`). Past that moment it is hidden wherever it is read//! ([`due_unbinned`]); once the phone's clock AND the server's time this copy//! last heard are both past it, the sweep ERASES it: the row, its history, its//! reactions (which it owns) and its search entry, here and, by the erase's own//! receipt, on the person's other phones (the timer both people agreed).//!//! A WhatsApp chat's own timer is different: it never erases (ABSENCE 6). Due//! messages are hidden at read, and the sweep after a pass moves them to the//! Bin, out of the chat and restorable, counted on the chat's line ("N messages//! removed by the timer") until he restores them or erases them for good//! (`chat.timer.erase`, his act).use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use cotton_core::chat::payload::{Item, Payload};use cotton_core::messages::app::{list, timer};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{insert_row, update_row};use super::cotton_chat::{exists, iso, now_ms, one, read, rows, touch_thread, write, ws, MESSAGES};use crate::methods::MethodError;use crate::shell::client::ClientController;/// What an erase of a disappeared message names as its reason.pub(crate) const REASON: &str = "disappeared";/// Messages one sweep erases at most; the next sweep takes the rest.const SWEEP_MAX: i64 = 500;/// The chat's timer now, seconds (0: off): its newest timer line's. One rule for every reader of the lines/// ([`line_seconds`]): a line in the Bin still marks when the timer changed and counts as off.pub(crate) fn timer_of(ctx: &mut Ctx<'_>, thread: &str) -> Result<u32, String> {    let row = one(        ctx,        &format!("SELECT json_extract(meta, '$.cotton.timer') AS timer, trashed_at, deleted_at FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND json_extract(meta, '$.cotton.timer') IS NOT NULL ORDER BY sent_at DESC, _hlc DESC LIMIT 1"),        &[ws(ctx), SqlValue::Text(thread.to_string())],    )?;    Ok(row.as_ref().map_or(0, line_seconds))}/// A timer line's seconds as every reader takes them (ABSENCE 3): a line in the Bin (trashed or deleted) still ends/// the span before it, but starts none.fn line_seconds(line: &Map<String, Value>) -> u32 {    let binned = |k: &str| line.get(k).is_some_and(|v| !v.is_null());    if binned("trashed_at") || binned("deleted_at") {        return 0;    }    line.get("timer").and_then(Value::as_u64).unwrap_or(0) as u32}/// What a message the timer put in the Bin carries (`meta.cotton.timer_binned`): the timer line it went by.const TIMER_BINNED: &str = "timer_binned";/// A message written at `written_ms` under `seconds` names when it goes.pub(crate) fn stamp(meta: &mut Value, written_ms: i64, seconds: u32) {    if let Some(at) = timer::expires_at(written_ms, seconds) {        meta["cotton"]["expiresAt"] = json!(iso(at));        meta["cotton"]["expiresIn"] = json!(seconds);    }}/// The seconds a message of this person's own was written under, for its box.pub(crate) fn seconds_of(meta: &Value) -> Option<u32> {    meta["cotton"]["expiresIn"].as_u64().map(|s| s as u32).filter(|s| *s > 0)}/// The timer line, written on this phone: by this person (`sender` none) or/// by `sender` (a number), under the id every phone keeps it by.#[allow(clippy::too_many_arguments)]pub(crate) fn write_line(ctx: &mut Ctx<'_>, row_id: &str, thread: &str, external: &str, seconds: u32, out: bool, sender: Option<&str>, seat: Option<&str>, at_ms: i64) -> Result<bool, String> {    write_line_on(ctx, row_id, thread, external, seconds, out, sender, seat, at_ms, cotton_core::chat::CHANNEL)}/// The timer line on `channel`: a WhatsApp chat's is `whatsapp`, as its other rows are, so the chat stays/// WhatsApp's (a chat's source is its newest row's channel).#[allow(clippy::too_many_arguments)]pub(crate) fn write_line_on(ctx: &mut Ctx<'_>, row_id: &str, thread: &str, external: &str, seconds: u32, out: bool, sender: Option<&str>, seat: Option<&str>, at_ms: i64, channel: &str) -> Result<bool, String> {    if exists(ctx, MESSAGES, row_id)? {        return Ok(false);    }    let lines = list::lines();    let at = iso(at_ms);    // The body is said the same on every phone (the list's last line, an older    // build); the conversation says who set it, per reader (`chat.thread`).    let body = list::say(&lines, "app.timer.on", &[("length", &timer::length(&lines, seconds))]);    let mut columns = Map::new();    columns.insert("thread_id".into(), json!(thread));    columns.insert("direction".into(), json!(if out { "out" } else { "in" }));    columns.insert("channel".into(), json!(channel));    columns.insert("origin".into(), json!("live"));    columns.insert("body".into(), json!(body));    columns.insert("external_id".into(), json!(external));    columns.insert("sent_at".into(), json!(at));    if out {        columns.insert("send_state".into(), json!("sent"));    }    if let Some(seat) = seat {        columns.insert("sender_participant_id".into(), json!(seat));    }    let mut cotton = json!({ "timer": seconds, "written_at": at });    if let Some(sender) = sender {        cotton["from"] = json!(sender);    }    columns.insert("meta".into(), json!({ "system": true, "cotton": cotton }));    insert_row(ctx, MESSAGES, row_id, columns).map_err(|f| f.to_string())?;    touch_thread(ctx, thread, &at, Some(&body), false)?;    Ok(true)}/// A timer change arriving (`What::Timer`): its line lands, once.pub(crate) fn land(ctx: &mut Ctx<'_>, ns: &str, thread: &str, item: &Item, payload: &Payload, sender: &str) -> Result<Value, String> {    let Some(change) = &payload.change else { return Ok(Value::Null) };    let Some(seconds) = payload.body.as_deref().and_then(|b| b.parse::<u32>().ok()).filter(|s| timer::CHOICES.contains(s)) else {        return Ok(Value::Null);    };    let author = if item.out { cotton_core::chat::ids::ME } else { sender };    let row_id = cotton_core::chat::ids::message_id(ns, author, &change.message);    let seat = match (&item.group, item.out) {        (Some(group), false) => Some(super::chat_group::seat_id(ns, group, sender)),        _ => None,    };    let new = write_line(ctx, &row_id, thread, &change.message, seconds, item.out, (!item.out).then_some(sender), seat.as_deref(), payload.at)?;    Ok(if new { json!({ "thread": thread, "message": row_id, "timer": seconds }) } else { Value::Null })}/// Erase every message whose moment has come. Answers how many went; the/// shells need do nothing (each answer that follows no longer holds them)./// What a chat's screen asks before it draws: Cotton's own agreed timer (each message names when it goes, read by its/// index) and WhatsApp's deletes for everyone; never the WhatsApp timer's sweep nor Blocked (ABSENCE 6, M4: those run/// after a pass, on their own turn), and nothing at all in a search or the list.pub(crate) fn sweep_screen(client: &ClientController) -> Result<usize, MethodError> {    // And what WhatsApp says was deleted for everyone: his contact's own act, not an inference, read by its marker.    Ok(sweep_cotton(client, &iso(now_ms(client)))? + super::chat_revoked::sweep_revoked(client)?)}pub(crate) fn sweep(client: &ClientController) -> Result<usize, MethodError> {    // His erase a kill or a failure stopped part way goes on first (ABSENCE 7, item 3).    finish_erasing(client)?;    let at = now_ms(client);    Ok(sweep_cotton(client, &iso(at))? + sweep_whatsapp(client, at)? + super::chat_revoked::sweep_revoked(client)?)}/// Whether this copy holds every message it can know of now: the phone's own copy (nothing to pull), or an account's/// whose last pass ended caught up with the data key held and no message row parked. Until then a timer span with no/// end held here erases nothing (ABSENCE 2).fn knows_every_message(client: &ClientController) -> bool {    knows_every(client, &["message", "thread"])}/// Whether this copy holds every row of these synced tables (by their wire names) it can know of now: the phone's own/// copy that never had an account, or an account's whose last pass ended caught up, data key held and none of these/// rows parked. A cleanup that judges by what is missing waits until then (ABSENCE 2 and 3, blocked senders).pub(crate) fn knows_every(client: &ClientController, tables: &[&str]) -> bool {    #[cfg(test)]    if let Some(knows) = TEST.with(|t| t.borrow().knows) {        return knows;    }    let signed_in = match cotton_client::connection::read_record(&client.layout().connection_json()) {        Ok(Some(record)) => record.mine.mode.has_server(),        Ok(None) => false,        Err(_) => return false,    };    // None of these rows parked, on any copy: unopened (ABSENCE 5), or pulled and waiting (a newer build's, one waiting    // on a parent, one in conflict: ABSENCE 6, H2). Named by wire or by store table.    let parked = client        .with_file(|file| {            let db = &file.driver;            let mut names: Vec<rusqlite::types::Value> = tables.iter().map(|t| rusqlite::types::Value::Text((*t).to_string())).collect();            for t in tables {                if let Some(store) = store_of(t) {                    names.push(rusqlite::types::Value::Text(store.to_string()));                }            }            let marks = vec!["?"; names.len()].join(", ");            let has = |table: &str| -> Result<bool, String> { Ok(db.get("SELECT 1 AS v FROM sqlite_master WHERE type = 'table' AND name = ?", &[rusqlite::types::Value::Text(table.into())]).map_err(|e| e.to_string())?.is_some()) };            let unopened = has("_seal_parked")? && db.get(&format!("SELECT 1 AS v FROM _seal_parked WHERE tbl IN ({marks}) LIMIT 1"), &names).map_err(|e| e.to_string())?.is_some();            let waiting = has("_parked")? && db.get(&format!("SELECT 1 AS v FROM _parked WHERE direction = 'pull' AND tbl IN ({marks}) LIMIT 1"), &names).map_err(|e| e.to_string())?.is_some();            Ok(unopened || waiting)        })        .unwrap_or(true);    if parked {        return false;    }    if !signed_in {        // The phone's own copy knows every message only if it was never an account's: one signed out part way through        // a pull may lack an "off" line (ABSENCE 3).        let Ok(database) = client.current_database() else { return false };        return matches!(crate::phone::adopt::former_copy(&client.layout().replica(&database)), Ok(false));    }    let Ok(database) = client.current_database() else { return false };    use cotton_client::seal::DataKeyStore as _;    client.caught_up(&database) && client.data_keys().data_key(&database).is_ok_and(|k| k.is_some())}/// The store table of a wire name the gate asks about.fn store_of(wire: &str) -> Option<&'static str> {    Some(match wire {        "message" => "cotton_msg_messages",        "thread" => "cotton_msg_threads",        "email" => "cotton_emails",        "email_sender" => "cotton_blocked_senders",        _ => return None,    })}/// What a marker says erased it, in `meta.cotton.erased`.pub(crate) const ERASED: &str = "disappeared";/// One WhatsApp message whose time has come under the person's own timer.#[derive(Clone)]struct Due {    id: String,    thread: String,    external: Option<String>,    sent_at: String,    /// The timer line it went by: the marker's only time.    line_at: String,    /// When the timer put it in the Bin, if it did.    binned_at: Option<String>,}fn ms_of(at: &str) -> Option<i64> {    chrono::DateTime::parse_from_rfc3339(at).ok().map(|t| t.timestamp_millis())}/// Writes per transaction: a large chat's timer acts go a chunk at a time, so no one write holds the copy or the queue.const WRITE_CHUNK: usize = 200;/// A message he brought back from the timer's Bin: the timer never takes it again.const TIMER_KEPT: &str = "timer_kept";/// Written only by the timer's own put-back, and taken off by the Writer before it is stored.const TIMER_BACK: &str = "timer_back";#[cfg(test)]#[derive(Default)]pub(crate) struct TestClock {    pub(crate) knows: Option<bool>,    pub(crate) chunks_left: Option<usize>,    /// His erase stops after this many more writes of 200.    pub(crate) erase_left: Option<usize>,    /// The judge time a test says this copy heard: `Some(None)` none at all; `None` the phone's own clock.    pub(crate) judge: Option<Option<i64>>,}#[cfg(test)]thread_local! {    pub(crate) static TEST: std::cell::RefCell<TestClock> = std::cell::RefCell::new(TestClock::default());}/// One WhatsApp chat's timer lines, as every reader takes them: (sent ms, seconds, sent_at).fn lines_of(ctx: &mut Ctx<'_>, thread: &str) -> Result<Vec<(i64, u32, String)>, String> {    Ok(rows(        ctx,        &format!("SELECT sent_at, json_extract(meta, '$.cotton.timer') AS timer, trashed_at, deleted_at FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND json_extract(meta, '$.cotton.timer') IS NOT NULL ORDER BY sent_at, _hlc"),        &[ws(ctx), SqlValue::Text(thread.to_string())],    )?    .iter()    .filter_map(|l| {        let at = l.get("sent_at").and_then(Value::as_str)?;        Some((ms_of(at)?, line_seconds(l), at.to_string()))    })    .collect())}/// A WhatsApp chat's timer is the person's own copy's (FEEDBACK-2 B.2; CONTRACT.md "WhatsApp through the Mac")./// Its messages carry no moment of their own (the Mac's import writes them), so each goes by the timer line standing/// when it was sent ([`timer::due_spans`]), incoming and outgoing, never one sent before the timer was turned on.////// THE TIMER NEVER ERASES (ABSENCE 6). What it decides is about lines that may not all be here (another phone may hold/// the "off"), so it only moves messages to the Bin: out of the chat, restorable, counted in the chat's "removed by the/// timer" line, until he erases them himself ([`erase_binned`]). And only through ONE gate, on every span: this copy/// knows every message ([`knows_every_message`]). Messages it binned that no timer covers now come back, every sweep,/// in a fixed order, past any cap.fn sweep_whatsapp(client: &ClientController, now: i64) -> Result<usize, MethodError> {    drop_old_counts(client);    let mut count = restore_uncovered(client)?;    if !knows_every_message(client) {        return Ok(count);    }    let to_bin = {        let mut bin: Vec<Due> = Vec::new();        read(client, "chat.disappear.whatsapp", |ctx| {            bin.clear();            let threads: Vec<String> = rows(                ctx,                &format!("SELECT DISTINCT thread_id FROM {MESSAGES} WHERE json_extract(meta, '$.cotton.timer') IS NOT NULL AND channel = 'whatsapp' AND workspace_id = ? ORDER BY thread_id"),                &[ws(ctx)],            )?            .iter()            .filter_map(|r| r.get("thread_id").and_then(Value::as_str).map(str::to_string))            .collect();            for thread in threads {                let held = lines_of(ctx, &thread)?;                let spans: Vec<(i64, u32)> = held.iter().map(|(ms, s, _)| (*ms, *s)).collect();                // How far this copy knows the chat: just after the newest message it holds.                let open_end = rows(                    ctx,                    &format!("SELECT MAX(sent_at) AS last FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND channel = 'whatsapp' AND json_extract(meta, '$.cotton.timer') IS NULL"),                    &[ws(ctx), SqlValue::Text(thread.clone())],                )?                .first()                .and_then(|r| r.get("last").and_then(Value::as_str).and_then(ms_of))                .map(|ms| ms + 1);                for (from, until) in timer::due_spans(&spans, now, open_end) {                    let line_at = held.iter().find(|(ms, _, _)| *ms == from).map(|(_, _, at)| at.clone()).unwrap_or_else(|| iso(from));                    let span = format!("{MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND channel = 'whatsapp' AND sent_at >= ? AND sent_at < ? AND json_extract(meta, '$.cotton.timer') IS NULL AND json_extract(meta, '$.cotton.erased') IS NULL");                    let args = [ws(ctx), SqlValue::Text(thread.clone()), SqlValue::Text(iso(from)), SqlValue::Text(iso(until))];                    // To the Bin: only what is not there yet, and never what he brought back (the cap counts these alone).                    let room = SWEEP_MAX - bin.len() as i64;                    if room > 0 {                        for row in rows(ctx, &format!("SELECT id, external_id, sent_at FROM {span} AND trashed_at IS NULL AND json_extract(meta, '$.cotton.{TIMER_KEPT}') IS NULL AND json_extract(meta, '$.cotton.{TIMER_BINNED}') IS NULL ORDER BY sent_at, id LIMIT {room}"), &args)? {                            let text = |key: &str| row.get(key).and_then(Value::as_str).map(str::to_string);                            let (Some(id), Some(sent_at)) = (text("id"), text("sent_at")) else { continue };                            bin.push(Due { id, thread: thread.clone(), external: text("external_id"), sent_at, line_at: line_at.clone(), binned_at: None });                        }                    }                }            }            Ok(Value::Null)        })?;        bin    };    let now_iso = iso(now);    for chat in by_chat(to_bin) {        for chunk in chat.chunks(WRITE_CHUNK) {            let chunk = chunk.to_vec();            count += chunk.len();            let at = now_iso.clone();            #[cfg(test)]            if TEST.with(|t| { let mut t = t.borrow_mut(); t.chunks_left.as_mut().is_some_and(|n| { if *n == 0 { true } else { *n -= 1; false } }) }) {                return Err(MethodError::new("killed", "test: killed between writes"));            }            write(client, "chat.disappear.bin", move |ctx| {                for d in &chunk {                    // Asked again in this write: still out of the Bin, and never one he brought back (ABSENCE 5, item 3).                    let Some(row) = one(ctx, &format!("SELECT meta FROM {MESSAGES} WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL AND json_extract(meta, '$.cotton.{TIMER_KEPT}') IS NULL AND json_extract(meta, '$.cotton.{TIMER_BINNED}') IS NULL"), &[ws(ctx), SqlValue::Text(d.id.clone())])? else { continue };                    let mut meta = meta_of(&row);                    meta["cotton"][TIMER_BINNED] = json!(d.line_at);                    let mut patch = Map::new();                    patch.insert("trashed_at".into(), json!(at));                    patch.insert("meta".into(), meta);                    update_row(ctx, MESSAGES, &d.id, patch).map_err(|f| f.to_string())?;                }                unword_lists(ctx, newest_of(&chunk.iter().map(|d| (d.thread.clone(), d.sent_at.clone())).collect::<Vec<_>>()), true)?;                Ok(Value::Null)            })?;        }    }    Ok(count)}/// The counts ABSENCE 5 kept for the timer's erase, gone with it.fn drop_old_counts(client: &ClientController) {    static DROPPED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);    if DROPPED.swap(true, std::sync::atomic::Ordering::Relaxed) && !cfg!(test) {        return;    }    let _ = client.with_writer(|file| file.driver.run("DROP TABLE IF EXISTS _timer_seen", &[]).and_then(|_| file.driver.run("DROP TABLE IF EXISTS _timer_clock", &[])).map(|_| ()).map_err(|e| e.to_string()));}/// `due`, one chat's after another's, each in the order it was found.fn by_chat(due: Vec<Due>) -> Vec<Vec<Due>> {    let mut chats: Vec<Vec<Due>> = Vec::new();    for d in due {        match chats.iter_mut().find(|c| c[0].thread == d.thread) {            Some(chat) => chat.push(d),            None => chats.push(vec![d]),        }    }    chats}fn meta_of(row: &Map<String, Value>) -> Value {    let mut meta: Value = row.get("meta").and_then(Value::as_str).and_then(|m| serde_json::from_str(m).ok()).unwrap_or_else(|| json!({}));    if !meta.is_object() {        meta = json!({});    }    if !meta["cotton"].is_object() {        meta["cotton"] = json!({});    }    meta}/// Messages the timer put in the Bin that no timer covers now (an "off" line came, or was put back) come back: every/// binned message looked at in a fixed order (chat, time, id), a page at a time, past any cap; restored a chunk at a/// time, each chat's list line filled again.fn restore_uncovered(client: &ClientController) -> Result<usize, MethodError> {    // Bounded per run (ABSENCE 7, item 6): RESTORE_PAGES pages at most, from where the last run stopped; once the walk    // reaches the end the next run starts from the first binned message again.    let mut back: Vec<(String, String)> = Vec::new();    let copy = client.layout().root().to_path_buf();    let mut after = RESTORE_CURSOR.lock().unwrap_or_else(|p| p.into_inner()).get_or_insert_with(Default::default).remove(&copy).unwrap_or_default();    let mut pages = 0usize;    let mut lines: Option<(String, Vec<(i64, u32)>)> = None;    loop {        let page = read(client, "chat.disappear.back", |ctx| {            let found = rows(                ctx,                &format!("SELECT id, thread_id, sent_at FROM {MESSAGES} WHERE workspace_id = ? AND channel = 'whatsapp' AND trashed_at IS NOT NULL AND json_extract(meta, '$.cotton.{TIMER_BINNED}') IS NOT NULL AND (thread_id, sent_at, id) > (?, ?, ?) ORDER BY thread_id, sent_at, id LIMIT {SWEEP_MAX}"),                &[ws(ctx), SqlValue::Text(after.0.clone()), SqlValue::Text(after.1.clone()), SqlValue::Text(after.2.clone())],            )?;            let mut out = Vec::new();            for row in found {                let (Some(id), Some(thread), Some(sent_at)) = (row.get("id").and_then(Value::as_str), row.get("thread_id").and_then(Value::as_str), row.get("sent_at").and_then(Value::as_str)) else { continue };                if lines.as_ref().is_none_or(|(t, _)| t != thread) {                    lines = Some((thread.to_string(), lines_of(ctx, thread)?.into_iter().map(|(ms, s, _)| (ms, s)).collect()));                }                let covered = ms_of(sent_at).is_some_and(|sent| lines.as_ref().is_some_and(|(_, l)| timer::due_at(l, sent).is_some()));                out.push(json!([id, thread, sent_at, covered]));            }            Ok(json!(out))        })?;        let page = page.as_array().cloned().unwrap_or_default();        for row in &page {            let field = |i: usize| row[i].as_str().unwrap_or_default().to_string();            after = (field(1), field(2), field(0));            if row[3] != json!(true) {                back.push((field(0), field(1)));            }        }        pages += 1;        if (page.len() as i64) < SWEEP_MAX {            break;        }        if pages >= RESTORE_PAGES {            RESTORE_CURSOR.lock().unwrap_or_else(|p| p.into_inner()).get_or_insert_with(Default::default).insert(copy.clone(), after.clone());            break;        }    }    put_back(client, &back, false)?;    Ok(back.len())}/// Pages of binned messages one sweep looks at for a put-back.const RESTORE_PAGES: usize = 4;/// Where each copy's last bounded walk stopped: (chat, time, id), by the copy's folder. The process's own; a new/// process starts from the first binned message.static RESTORE_CURSOR: std::sync::Mutex<Option<std::collections::HashMap<std::path::PathBuf, (String, String, String)>>> = std::sync::Mutex::new(None);/// Bring these messages (`(id, thread)`) out of the timer's Bin, a chunk at a time, and fill each chat's list line/// again. `kept`: he asked, so the timer never takes them again.fn put_back(client: &ClientController, back: &[(String, String)], kept: bool) -> Result<(), MethodError> {    for chunk in back.chunks(WRITE_CHUNK) {        let chunk = chunk.to_vec();        write(client, "chat.disappear.restore", move |ctx| {            let mut chats: Vec<(String, (String, String))> = Vec::new();            for (id, thread) in &chunk {                let Some(row) = one(ctx, &format!("SELECT meta, sent_at, body FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.clone())])? else { continue };                let mut meta = meta_of(&row);                if let Some(c) = meta["cotton"].as_object_mut() {                    c.remove(TIMER_BINNED);                    if kept {                        c.insert(TIMER_KEPT.into(), json!(true));                    } else {                        // The timer's own put-back says so (the Writer takes the mark off): a person's undo writes no                        // such mark, so the Writer keeps it and the timer never bins it again (ABSENCE 7, item 4).                        c.insert(TIMER_BACK.into(), json!(true));                    }                }                let mut patch = Map::new();                patch.insert("trashed_at".into(), Value::Null);                patch.insert("meta".into(), meta);                update_row(ctx, MESSAGES, id, patch).map_err(|f| f.to_string())?;                let back = (row.get("sent_at").and_then(Value::as_str).unwrap_or_default().to_string(), row.get("body").and_then(Value::as_str).unwrap_or_default().to_string());                match chats.iter_mut().find(|(t, _)| t == thread) {                    Some((_, newest)) if newest.0 < back.0 => *newest = back,                    Some(_) => {}                    None => chats.push((thread.clone(), back)),                }            }            // In the same write (ABSENCE 5, item 9): the newest of what stands and what came back.            for (thread, back) in &chats {                refill_list(ctx, thread, back)?;            }            Ok(Value::Null)        })?;    }    Ok(())}/// A chat's list line names its newest message again, once messages came back from the Bin: the newest of what/// stands and `back` (the newest that came back, `(sent_at, body)`, read before this write).fn refill_list(ctx: &mut Ctx<'_>, thread: &str, back: &(String, String)) -> Result<(), String> {    let standing = one(        ctx,        &format!("SELECT body, sent_at FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND trashed_at IS NULL AND deleted_at IS NULL AND hidden_at IS NULL AND json_extract(meta, '$.cotton.timer') IS NULL ORDER BY sent_at DESC LIMIT 1"),        &[ws(ctx), SqlValue::Text(thread.to_string())],    )?;    let mut newest = Map::new();    newest.insert("sent_at".into(), json!(back.0));    newest.insert("body".into(), json!(back.1));    if let Some(standing) = standing.filter(|r| r.get("sent_at").and_then(Value::as_str).unwrap_or_default() > back.0.as_str()) {        newest = standing;    }    let Some(row) = one(ctx, &format!("SELECT last_message_at, last_message_preview, trashed_at FROM {} WHERE workspace_id = ? AND id = ?", super::cotton_chat::THREADS), &[ws(ctx), SqlValue::Text(thread.to_string())])? else { return Ok(()) };    let sent = newest.get("sent_at").and_then(Value::as_str).unwrap_or_default();    let shown = row.get("last_message_at").and_then(Value::as_str).unwrap_or_default();    let empty = row.get("last_message_preview").and_then(Value::as_str).is_none_or(str::is_empty);    if !empty && shown > sent {        return Ok(());    }    let mut patch = Map::new();    patch.insert("last_message_preview".into(), json!(newest.get("body").and_then(Value::as_str).unwrap_or_default().chars().take(200).collect::<String>()));    patch.insert("last_message_at".into(), json!(if shown > sent { shown } else { sent }));    patch.insert("trashed_at".into(), row.get("trashed_at").cloned().unwrap_or(Value::Null));    update_row(ctx, super::cotton_chat::THREADS, thread, patch).map_err(|f| f.to_string())?;    Ok(())}/// What the timer binned in this chat and holds in the Bin: (id, sent_at, body), oldest first.fn binned_in(ctx: &mut Ctx<'_>, thread: &str) -> Result<Vec<(String, String, String)>, String> {    Ok(rows(        ctx,        &format!("SELECT id, sent_at, body FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND trashed_at IS NOT NULL AND json_extract(meta, '$.cotton.{TIMER_BINNED}') IS NOT NULL ORDER BY sent_at, id"),        &[ws(ctx), SqlValue::Text(thread.to_string())],    )?    .iter()    .filter_map(|r| Some((r.get("id")?.as_str()?.to_string(), r.get("sent_at")?.as_str()?.to_string(), r.get("body").and_then(Value::as_str).unwrap_or_default().to_string())))    .collect())}fn chat_say(line: &str, fills: &[(&str, &str)]) -> String {    cotton_core::rules::shell_lines::LineSet::shipped("chat").and_then(|lines| lines.say(line, fills)).unwrap_or_default()}/// The chat's line while the timer holds messages of it in the Bin: "412 messages removed by the timer", with Show,/// Restore and Erase (the erase carries the count and snapshot of the set shown). `None` while it holds none.pub(crate) fn binned_card(client: &ClientController, thread: &str) -> Result<Option<Value>, MethodError> {    let thread = thread.to_string();    let ids = binned_ids(client, &thread)?;    let n = ids.len();    if n == 0 {        return Ok(None);    }    let snapshot = snapshot_of(&ids);    let line = binned_line(n);    Ok(Some(json!({        "count": n,        "line": line,        "show": { "label": chat_say("app.timer_binned.show", &[]), "method": "chat.timer.binned" },        "restore": { "label": chat_say("app.timer_binned.restore", &[]), "method": "chat.timer.restore" },        "erase": { "label": chat_say("app.timer_binned.erase", &[]), "method": "chat.timer.erase", "count": n, "snapshot": snapshot },    })))}/// `chat.timer.binned { thread }`: what the timer binned in this chat, oldest first.////// `chat.timer.binned { thread, limit, before? }`: Show's page (TIMER LINE iPhone): newest first, `limit` a page, keyed/// (`before` is the `next` the last page answered: the last row's `sent_at|id`), with the chat's line and count as they/// stand now and the page's own words. Erase sends the `count` this answer gives.pub(crate) fn binned(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let thread = request.get("thread").and_then(Value::as_str).ok_or_else(|| MethodError::new("bad_request", "thread"))?.to_string();    let Some(limit) = request.get("limit").and_then(Value::as_u64).map(|n| n.clamp(1, 500) as usize) else {        let found = read(client, "chat.timer.binned", |ctx| Ok(json!(binned_in(ctx, &thread)?.into_iter().map(|(id, at, body)| json!({ "id": id, "at": at, "body": body })).collect::<Vec<_>>())))?;        let ids: Vec<String> = found.as_array().into_iter().flatten().filter_map(|r| r["id"].as_str().map(str::to_string)).collect();        return Ok(json!({ "rows": found, "snapshot": snapshot_of(&ids) }));    };    let before = request.get("before").and_then(Value::as_str).and_then(|key| key.split_once('|')).map(|(at, id)| (at.to_string(), id.to_string()));    let all = read(client, "chat.timer.binned", |ctx| Ok(json!(binned_in(ctx, &thread)?.into_iter().map(|(id, at, body)| json!([id, at, body])).collect::<Vec<_>>())))?;    let all: Vec<(String, String, String)> = all        .as_array()        .into_iter()        .flatten()        .filter_map(|r| Some((r[0].as_str()?.to_string(), r[1].as_str()?.to_string(), r[2].as_str().unwrap_or_default().to_string())))        .collect();    let n = all.len();    let snapshot = snapshot_of(&all.iter().map(|(id, _, _)| id.clone()).collect::<Vec<_>>());    // Newest first, after the key.    let mut page: Vec<&(String, String, String)> = all        .iter()        .rev()        .filter(|(id, at, _)| before.as_ref().is_none_or(|(b_at, b_id)| (at.as_str(), id.as_str()) < (b_at.as_str(), b_id.as_str())))        .take(limit + 1)        .collect();    let more = page.len() > limit;    page.truncate(limit);    let next = more.then(|| page.last().map(|(id, at, _)| format!("{at}|{id}"))).flatten();    let line = if n == 1 { chat_say("app.timer_binned.line_one", &[]) } else { chat_say("app.timer_binned.line", &[("n", &n.to_string())]) };    let ask = if n == 1 { chat_say("app.timer_binned.erase_ask_one", &[]) } else { chat_say("app.timer_binned.erase_ask", &[("n", &n.to_string())]) };    Ok(json!({        "rows": page.iter().map(|(id, at, body)| json!({ "id": id, "at": at, "body": body })).collect::<Vec<_>>(),        "next": next,        "count": n,        "snapshot": snapshot,        "line": line,        "words": {            "title": chat_say("app.timer_binned.title", &[]),            "restore": chat_say("app.timer_binned.restore", &[]),            "restore_all": chat_say("app.timer_binned.restore_all", &[]),            "erase": chat_say("app.timer_binned.erase", &[]),            "erase_ask": ask,            "erase_line": chat_say("app.timer_binned.erase_line", &[]),            "erase_yes": chat_say("app.timer_binned.erase_yes", &[]),            "erase_no": chat_say("app.timer_binned.erase_no", &[]),            "empty": chat_say("app.timer_binned.empty", &[]),            "no_words": chat_say("app.timer_binned.no_words", &[]),            "loading": chat_say("app.timer_binned.loading", &[]),            "again": chat_say("app.timer_binned.again", &[]),        },    }))}/// `chat.timer.restore { thread, ids? }`: these messages (every one the timer binned in the chat, without `ids`) come/// back, and the timer never takes them again.pub(crate) fn restore(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let thread = request.get("thread").and_then(Value::as_str).ok_or_else(|| MethodError::new("bad_request", "thread"))?.to_string();    let only: Option<Vec<String>> = request.get("ids").and_then(Value::as_array).map(|ids| ids.iter().filter_map(|v| v.as_str().map(str::to_string)).collect());    let held = read(client, "chat.timer.binned", |ctx| Ok(json!(binned_in(ctx, &thread)?.into_iter().map(|(id, _, _)| id).collect::<Vec<_>>())))?;    let back: Vec<(String, String)> = held.as_array().into_iter().flatten().filter_map(Value::as_str).filter(|id| only.as_ref().is_none_or(|o| o.iter().any(|x| x == id))).map(|id| (id.to_string(), thread.clone())).collect();    put_back(client, &back, true)?;    let n = back.len();    Ok(json!({ "restored": n, "said": if n == 1 { chat_say("app.timer_binned.restored_one", &[]) } else { chat_say("app.timer_binned.restored", &[("n", &n.to_string())]) } }))}/// The chats' stored list lines (`last_message_preview`) keep no words of a message erased there. Where the line/// names the newest message erased and `empty` (the timer's erase), it is emptied; otherwise it is written again as it/// stands (a revoke's is already "This message was deleted"). Either way the write names every field an earlier/// list-line write named (`last_message_at`, `last_message_preview`, `trashed_at`, each as it stands), so no earlier/// receipt of the thread still wins a field, and the fold drops them all, with any words of the message in their bytes,/// even when a later line has since replaced its words. `newest`: each chat with the newest `sent_at` erased there.pub(crate) fn unword_lists(ctx: &mut Ctx<'_>, newest: Vec<(String, String)>, empty: bool) -> Result<(), String> {    for (thread, at) in newest {        let row = one(ctx, &format!("SELECT last_message_at, last_message_preview, trashed_at FROM {} WHERE workspace_id = ? AND id = ?", super::cotton_chat::THREADS), &[ws(ctx), SqlValue::Text(thread.clone())])?;        let Some(row) = row else { continue };        let named = row.get("last_message_at").and_then(Value::as_str).is_some_and(|last| last <= at.as_str());        let line = if empty && named { json!("") } else { row.get("last_message_preview").cloned().unwrap_or(Value::Null) };        let mut patch = Map::new();        patch.insert("last_message_preview".into(), line);        patch.insert("last_message_at".into(), row.get("last_message_at").cloned().unwrap_or(Value::Null));        patch.insert("trashed_at".into(), row.get("trashed_at").cloned().unwrap_or(Value::Null));        cotton_tools::mcp::handlers::common::update_row(ctx, super::cotton_chat::THREADS, &thread, patch).map_err(|f| f.to_string())?;    }    Ok(())}/// Each chat with the newest `sent_at` among `erased` (`(thread, sent_at)`).pub(crate) fn newest_of(erased: &[(String, String)]) -> Vec<(String, String)> {    let mut newest: Vec<(String, String)> = Vec::new();    for (thread, sent_at) in erased {        match newest.iter_mut().find(|(t, _)| t == thread) {            Some((_, at)) if at.as_str() < sent_at.as_str() => *at = sent_at.clone(),            Some(_) => {}            None => newest.push((thread.clone(), sent_at.clone())),        }    }    newest}/// The marker in place of an erased WhatsApp message: no words, media, sender, quote, reaction or time of its own/// (its time is the timer line's), hidden wherever messages are read, and held under the message's own WhatsApp id.pub(crate) fn marker_columns(thread: &str, external: &str, line_at: &str) -> Map<String, Value> {    let mut columns = Map::new();    columns.insert("thread_id".into(), json!(thread));    columns.insert("direction".into(), json!("in"));    columns.insert("channel".into(), json!("whatsapp"));    columns.insert("origin".into(), json!("imported"));    columns.insert("body".into(), json!(""));    columns.insert("external_id".into(), json!(external));    columns.insert("sent_at".into(), json!(line_at));    columns.insert("deleted_at".into(), json!(line_at));    columns.insert("hidden_at".into(), json!(line_at));    columns.insert("meta".into(), json!({ "cotton": { "erased": ERASED } }));    columns}/// The wait, in ms from now, until the next message goes in `thread` (or in any chat: `None`, for the list), so the/// phone asks again then and the core sweeps it: a message never stays on screen past its time while nothing else/// changes (coordinator, 23 Nov 2026). `None` when nothing is set to go. Only what is not yet due counts: what is due/// the sweep before this answer took.pub(crate) fn erases_in(client: &ClientController, thread: Option<&str>) -> Result<Option<i64>, MethodError> {    let now = now_ms(client);    let thread = thread.map(str::to_string);    let found = read(client, "chat.disappear.next", |ctx| {        let scoped = |ctx: &mut Ctx<'_>| -> (String, Vec<SqlValue>) {            match &thread {                Some(t) => (" AND thread_id = ?".to_string(), vec![ws(ctx), SqlValue::Text(t.clone())]),                None => (String::new(), vec![ws(ctx)]),            }        };        let mut dues: Vec<i64> = Vec::new();        // A Cotton chat's message names when it goes.        let (scope, mut params) = scoped(ctx);        params.push(SqlValue::Text(iso(now)));        let soonest = one(            ctx,            &format!("SELECT MIN(json_extract(meta, '$.cotton.expiresAt')) AS at FROM {MESSAGES} WHERE json_extract(meta, '$.cotton.expiresAt') IS NOT NULL AND workspace_id = ?{scope} AND json_extract(meta, '$.cotton.expiresAt') > ?"),            &params,        )?;        dues.extend(soonest.and_then(|r| r.get("at").and_then(Value::as_str).and_then(ms_of)));        // A WhatsApp chat's go by the timer line standing when each was sent: the earliest held message of each        // span still waiting is the next of it to go.        let (scope, params) = scoped(ctx);        let lines = rows(            ctx,            &format!("SELECT thread_id, sent_at, json_extract(meta, '$.cotton.timer') AS timer, trashed_at, deleted_at FROM {MESSAGES} WHERE json_extract(meta, '$.cotton.timer') IS NOT NULL AND channel = 'whatsapp' AND workspace_id = ?{scope} ORDER BY thread_id, sent_at, _hlc"),            &params,        )?;        let mut by_thread: Vec<(String, Vec<(i64, u32)>)> = Vec::new();        for line in lines {            let (Some(chat), Some(at)) = (line.get("thread_id").and_then(Value::as_str), line.get("sent_at").and_then(Value::as_str).and_then(ms_of)) else { continue };            let seconds = line_seconds(&line);            match by_thread.last_mut() {                Some((t, held)) if t == chat => held.push((at, seconds)),                _ => by_thread.push((chat.to_string(), vec![(at, seconds)])),            }        }        for (chat, held) in by_thread {            let mut earliest = Vec::new();            for (from, until, _) in timer::waiting_spans(&held, now) {                let mut params = vec![ws(ctx), SqlValue::Text(chat.clone()), SqlValue::Text(iso(from))];                let before = if until == i64::MAX { String::new() } else { params.push(SqlValue::Text(iso(until))); " AND sent_at < ?".to_string() };                let first = one(                    ctx,                    &format!("SELECT MIN(sent_at) AS at FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND channel = 'whatsapp' AND sent_at >= ?{before} AND json_extract(meta, '$.cotton.timer') IS NULL AND json_extract(meta, '$.cotton.erased') IS NULL"),                    &params,                )?;                earliest.extend(first.and_then(|r| r.get("at").and_then(Value::as_str).and_then(ms_of)));            }            dues.extend(timer::next_due(&held, &earliest, now));        }        Ok(dues.into_iter().filter(|due| *due > now).min().map_or(Value::Null, |due| json!(timer::wait_until(due, now))))    })?;    Ok(found.as_i64())}fn sweep_cotton(client: &ClientController, now: &str) -> Result<usize, MethodError> {    // Erased only once the phone's clock AND the server's time this copy last heard (judge time) are both past the    // moment, so a phone clock set ahead never erases early on every device (ABSENCE 7, item 5). No judge time: none    // erased. Until then the message is hidden where it is read ([`due_unbinned`]).    let Some(judged) = judge_now(client) else { return Ok(0) };    let now = std::cmp::min(now.to_string(), iso(judged));    let due = read(client, "chat.disappear", |ctx| {        let found = rows(            ctx,            &format!("SELECT id, thread_id, sent_at FROM {MESSAGES} WHERE json_extract(meta, '$.cotton.expiresAt') IS NOT NULL AND json_extract(meta, '$.cotton.expiresAt') <= ? AND workspace_id = ? LIMIT {SWEEP_MAX}"),            &[SqlValue::Text(now.clone()), ws(ctx)],        )?;        Ok(Value::Array(found.into_iter().map(Value::Object).collect()))    })?;    let text = |row: &Value, key: &str| row.get(key).and_then(Value::as_str).unwrap_or_default().to_string();    let gone: Vec<(String, String, String)> = due.as_array().into_iter().flatten().map(|r| (text(r, "id"), text(r, "thread_id"), text(r, "sent_at"))).filter(|(id, _, _)| !id.is_empty()).collect();    if gone.is_empty() {        return Ok(0);    }    let count = gone.len();    write(client, "chat.disappear", move |ctx| {        // Erased already (another of the person's phones went first, and its erase folded here).        let mut live = Vec::new();        for (id, thread, sent_at) in &gone {            if exists(ctx, MESSAGES, id)? {                live.push((id.clone(), thread.clone(), sent_at.clone()));            }        }        // The list lines first, as on a WhatsApp chat.        unword_lists(ctx, newest_of(&live.iter().map(|(_, thread, sent_at)| (thread.clone(), sent_at.clone())).collect::<Vec<_>>()), true)?;        for (id, _, _) in &live {            // Its reactions are its own: the erase takes them with it.            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, REASON);        }        Ok(Value::Null)    })?;    Ok(count)}#[cfg(test)]#[path = "chat_timer_whatsapp_tests.rs"]mod whatsapp_tests;/// The server's time as this copy last heard it, carried on its continuous clock; none when it has heard none.fn judge_now(client: &ClientController) -> Option<i64> {    #[cfg(test)]    if let Some(judged) = TEST.with(|t| t.borrow().judge) {        return judged;    }    #[cfg(test)]    return Some(now_ms(client));    #[cfg(not(test))]    client.judge_now()}/// The ids the timer holds in this chat's Bin.fn binned_ids(client: &ClientController, thread: &str) -> Result<Vec<String>, MethodError> {    let thread = thread.to_string();    let held = read(client, "chat.timer.binned", |ctx| Ok(json!(binned_in(ctx, &thread)?.into_iter().map(|(id, _, _)| id).collect::<Vec<_>>())))?;    Ok(held.as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_string)).collect())}/// The snapshot of a set of binned messages he was shown: a number that changes when any id does (FNV-1a over the/// sorted ids), so a set swapped for another of the same size is refused.pub(crate) fn snapshot_of(ids: &[String]) -> String {    let mut sorted: Vec<&String> = ids.iter().collect();    sorted.sort();    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;    for id in sorted {        for byte in id.bytes().chain(std::iter::once(0)) {            hash ^= u64::from(byte);            hash = hash.wrapping_mul(0x0100_0000_01b3);        }    }    format!("{hash:016x}")}fn binned_line(n: usize) -> String {    if n == 1 { chat_say("app.timer_binned.line_one", &[]) } else { chat_say("app.timer_binned.line", &[("n", &n.to_string())]) }}/// His erase still going (device-local, never synced): the ids of an act that stopped part way.const ERASING: &str = "_timer_erasing";/// Erase these ids (each with its chat) for good, if each is still in the timer's Bin and not a timer line: the marker/// that stops a re-import beside each. Inside the caller's write. Answers how many went.fn erase_these(ctx: &mut Ctx<'_>, ids: &[(String, String)]) -> Result<usize, String> {    let mut n = 0;    for (id, thread) in ids {        let Some(row) = one(ctx, &format!("SELECT external_id, json_extract(meta, '$.cotton.{TIMER_BINNED}') AS line_at FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND id = ? AND trashed_at IS NOT NULL AND json_extract(meta, '$.cotton.{TIMER_BINNED}') IS NOT NULL AND json_extract(meta, '$.cotton.timer') IS NULL"), &[ws(ctx), SqlValue::Text(thread.clone()), SqlValue::Text(id.clone())])? else { continue };        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, REASON);        if let (Some(external), Some(line_at)) = (row.get("external_id").and_then(Value::as_str), row.get("line_at").and_then(Value::as_str)) {            let marker = cotton_core::chat::ids::erased_marker_id(thread, "whatsapp", external);            if !exists(ctx, MESSAGES, &marker)? {                insert_row(ctx, MESSAGES, &marker, marker_columns(thread, external, line_at)).map_err(|f| f.to_string())?;            }        }        n += 1;    }    Ok(n)}/// `chat.timer.erase { thread, count, snapshot, ids? }`: HIS act, "Erase these for good" beside Show and Restore. The/// messages the timer binned in this chat (only `ids`, when given) are erased for good. The set is asked inside the/// first write: it must be the one he was shown, by count and by snapshot (a set swapped for another of the same/// size is refused), else nothing goes and the answer asks again with the set as it stands. The first 200 go in that/// write; the rest are written down on this device and go 200 a write, each struck off as it goes, so a failure part/// way is finished by the next act or the next sweep. A timer line is never among them. The answer says how many/// went. (A confirm step is the shell's.)pub(crate) fn erase_binned(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let thread = request.get("thread").and_then(Value::as_str).ok_or_else(|| MethodError::new("bad_request", "thread"))?.to_string();    let shown = request.get("count").and_then(Value::as_u64).ok_or_else(|| MethodError::new("bad_request", "count"))?;    let snapshot = request.get("snapshot").and_then(Value::as_str).ok_or_else(|| MethodError::new("bad_request", "snapshot"))?.to_string();    let only: Option<Vec<String>> = request.get("ids").and_then(Value::as_array).map(|ids| ids.iter().filter_map(|v| v.as_str().map(str::to_string)).collect());    // An earlier act that stopped part way is finished first: those went then, not now.    finish_erasing(client)?;    let first = {        let thread = thread.clone();        write(client, "chat.timer.erase", move |ctx| {            let held: Vec<String> = binned_in(ctx, &thread)?.into_iter().map(|(id, _, _)| id).filter(|id| only.as_ref().is_none_or(|o| o.contains(id))).collect();            let now = snapshot_of(&held);            if held.len() as u64 != shown || snapshot != now {                let n = held.len();                return Ok(json!({ "ask": { "count": n, "snapshot": now, "line": binned_line(n) } }));            }            let mut ids: Vec<(String, String)> = held.into_iter().map(|id| (id, thread.clone())).collect();            let rest = ids.split_off(ids.len().min(WRITE_CHUNK));            let n = erase_these(ctx, &ids)?;            Ok(json!({ "erased": n, "rest": rest.into_iter().map(|(id, _)| id).collect::<Vec<_>>() }))        })?    };    if first.get("ask").is_some() {        return Ok(first);    }    let rest: Vec<String> = first["rest"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_string)).collect();    if !rest.is_empty() {        client            .with_writer(|file| {                let run = |sql: &str, args: &[SqlValue]| file.driver.run(sql, args).map(|_| ()).map_err(|e| e.to_string());                run(&format!("CREATE TABLE IF NOT EXISTS {ERASING} (id TEXT PRIMARY KEY, thread TEXT NOT NULL)"), &[])?;                for id in &rest {                    run(&format!("INSERT OR IGNORE INTO {ERASING} (id, thread) VALUES (?, ?)"), &[SqlValue::Text(id.clone()), SqlValue::Text(thread.clone())])?;                }                Ok(())            })            .map_err(|e| MethodError::new("unwritable", e))?;    }    let erased = first["erased"].as_u64().unwrap_or(0) as usize + finish_erasing(client)?;    Ok(json!({ "erased": erased, "said": if erased == 1 { chat_say("app.timer_binned.erased_one", &[]) } else { chat_say("app.timer_binned.erased", &[("n", &erased.to_string())]) } }))}/// Go on with his erase where it stopped: what is written down goes 200 a write, each struck off once its write is in./// Answers how many went now.pub(crate) fn finish_erasing(client: &ClientController) -> Result<usize, MethodError> {    let mut erased = 0usize;    loop {        let chunk: Vec<(String, String)> = client            .with_writer(|file| {                if file.driver.get("SELECT 1 AS v FROM sqlite_master WHERE type = 'table' AND name = ?", &[SqlValue::Text(ERASING.into())]).map_err(|e| e.to_string())?.is_none() {                    return Ok(Vec::new());                }                Ok(file                    .driver                    .all(&format!("SELECT id, thread FROM {ERASING} ORDER BY thread, id LIMIT {WRITE_CHUNK}"), &[])                    .map_err(|e| e.to_string())?                    .iter()                    .filter_map(|r| Some((r.text("id")?.to_string(), r.text("thread")?.to_string())))                    .collect())            })            .map_err(|e| MethodError::new("unreadable", e))?;        if chunk.is_empty() {            return Ok(erased);        }        #[cfg(test)]        if TEST.with(|t| t.borrow_mut().erase_left.as_mut().is_some_and(|n| if *n == 0 { true } else { *n -= 1; false })) {            return Err(MethodError::new("failed", "test: stopped between writes"));        }        let go = chunk.clone();        let n = write(client, "chat.timer.erase", move |ctx| Ok(json!(erase_these(ctx, &go)?)))?;        erased += n.as_u64().unwrap_or(0) as usize;        client            .with_writer(|file| {                for (id, _) in &chunk {                    file.driver.run(&format!("DELETE FROM {ERASING} WHERE id = ?"), &[SqlValue::Text(id.clone())]).map_err(|e| e.to_string())?;                }                Ok(())            })            .map_err(|e| MethodError::new("unwritable", e))?;    }}/// Messages a WhatsApp chat's timer says are due now and the sweep (after a pass) has not binned yet: hidden wherever/// they are read, with no write (ABSENCE 7, item 2). Never one he kept or brought back, never a timer line. `thread`:/// that chat only; else every WhatsApp chat with a timer line.pub(crate) fn due_unbinned(client: &ClientController, thread: Option<&str>) -> Result<std::collections::HashSet<String>, MethodError> {    let now = now_ms(client);    let only = thread.map(str::to_string);    let found = read(client, "chat.timer.due", |ctx| {        let threads: Vec<String> = match &only {            Some(t) => vec![t.clone()],            None => rows(                ctx,                &format!("SELECT DISTINCT thread_id FROM {MESSAGES} WHERE json_extract(meta, '$.cotton.timer') IS NOT NULL AND channel = 'whatsapp' AND workspace_id = ?"),                &[ws(ctx)],            )?            .iter()            .filter_map(|r| r.get("thread_id").and_then(Value::as_str).map(str::to_string))            .collect(),        };        let mut ids = Vec::new();        // Cotton's agreed timer: past its moment on this phone's clock and not erased yet (the erase waits for judge        // time too, item 5).        let mut args = vec![SqlValue::Text(iso(now)), ws(ctx)];        let scope = match &only {            Some(t) => {                args.push(SqlValue::Text(t.clone()));                " AND thread_id = ?"            }            None => "",        };        for row in rows(ctx, &format!("SELECT id FROM {MESSAGES} WHERE json_extract(meta, '$.cotton.expiresAt') IS NOT NULL AND json_extract(meta, '$.cotton.expiresAt') <= ? AND workspace_id = ?{scope} LIMIT 5000"), &args)? {            if let Some(id) = row.get("id").and_then(Value::as_str) {                ids.push(json!(id));            }        }        for t in threads {            let spans: Vec<(i64, u32)> = lines_of(ctx, &t)?.into_iter().map(|(ms, s, _)| (ms, s)).collect();            if spans.is_empty() {                continue;            }            for (from, until) in timer::due_spans(&spans, now, Some(now + 1)) {                for row in rows(                    ctx,                    &format!("SELECT id FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND channel = 'whatsapp' AND sent_at >= ? AND sent_at < ? AND trashed_at IS NULL AND json_extract(meta, '$.cotton.timer') IS NULL AND json_extract(meta, '$.cotton.{TIMER_KEPT}') IS NULL AND json_extract(meta, '$.cotton.{TIMER_BINNED}') IS NULL LIMIT 5000"),                    &[ws(ctx), SqlValue::Text(t.clone()), SqlValue::Text(iso(from)), SqlValue::Text(iso(until))],                )? {                    if let Some(id) = row.get("id").and_then(Value::as_str) {                        ids.push(json!(id));                    }                }            }        }        Ok(json!(ids))    })?;    Ok(found.as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_string)).collect())}/// What a chat's list line says when its newest message is one of `hidden`: `None` when the newest is not hidden (the/// line stands); `Some(None)` when nothing drawn is left; else `Some((body, mine))` of the newest drawn message, a timer/// line among them.pub(crate) fn newest_shown(client: &ClientController, thread: &str, hidden: &std::collections::HashSet<String>) -> Result<Option<Option<(String, bool)>>, MethodError> {    let thread = thread.to_string();    let found = read(client, "chat.timer.newest", |ctx| {        Ok(json!(rows(            ctx,            &format!("SELECT id, body, direction FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND trashed_at IS NULL AND hidden_at IS NULL AND deleted_at IS NULL AND json_extract(meta, '$.cotton.erased') IS NULL ORDER BY sent_at DESC LIMIT 50"),            &[ws(ctx), SqlValue::Text(thread.clone())],        )?))    })?;    let found: Vec<Value> = found.as_array().cloned().unwrap_or_default();    let is_hidden = |r: &Value| r["id"].as_str().is_some_and(|id| hidden.contains(id));    if !found.first().is_some_and(is_hidden) {        return Ok(None);    }    Ok(Some(found.iter().find(|r| !is_hidden(r)).map(|r| (r["body"].as_str().unwrap_or_default().to_string(), r["direction"] == "out"))))}