Cotton code
207 lines · 8.7 KB · RustRaw
//! The verbs that act on a MESSAGE.//!//! The port of `packages/core/src/services/chat/messageVerbs.ts`.//!//! Every one of them touches only the columns its side of the chat schema's//! split allows — shared content by its author, private state by the owner, a//! reaction as one row per actor — because a column written by two logical//! authors in one file is a column where last-write-wins has to arbitrate//! between two people, and the loser watches their edit vanish.//!//! **Note what is NOT here: a delete op on a message, ever.** "Delete for//! everyone" is an upsert that empties the row, because a tombstone cannot be//! relayed into somebody else's file as anything but "this row never existed".//! [`unreact_to_message`] is the one delete this file emits on a relayed table,//! and it is legitimate: the row is the actor's own, and the relay forwards it//! as a reaction delete.use serde_json::{Map, Value};use cotton_core::messages::preview::{preview_for_message, PreviewSource};use cotton_store::driver::Row;use rusqlite::types::Value as SqlValue;use crate::mcp::dispatch::{Ctx, ToolResult};use crate::mcp::handlers::common::{fail, optional_boolean, require_uuid};use crate::mcp::protocol::ToolFailure;use super::answer;use super::shared::{    media_of, meta_of, newest_visible, require_message, require_thread, stamp, MESSAGES,    THREADS,};// ── the two thread denorms a message change causes ──────────────────────────/// The thread denorm re-derived from a row that is becoming the newest visible/// one — or emptied, when hiding left the thread with nothing to show.////// This one moves the denorm BACKWARDS on purpose, which is why it does not go/// through `should_advance_thread`. That guard exists so an out-of-order/// arrival cannot drag a live thread into 2021; here the person has/// deliberately removed the newest line from their own copy, and the list has/// to follow them or "delete for me" is the one delete that visibly does not/// delete.////// Local only, and safe to be: `last_message_at` / `last_message_preview` are/// nobody's shared content — every file derives them from the rows it actually/// holds, and the next message re-advances them.fn denorm_from_head(head: Option<&Row>, now: &str) -> Result<Map<String, Value>, ToolFailure> {    let mut patch = Map::new();    match head {        Some(head) => {            patch.insert(                "last_message_at".to_string(),                Value::from(head.text("sent_at").unwrap_or(now)),            );            patch.insert(                "last_message_preview".to_string(),                Value::from(preview_for_message(&PreviewSource {                    body: head.text("body"),                    media: &media_of(head)?,                    deleted_at: head.text("deleted_at"),                    meta: Some(&meta_of(head)),                })),            );        }        None => {            patch.insert("last_message_at".to_string(), Value::Null);            patch.insert("last_message_preview".to_string(), Value::Null);        }    }    patch.insert("updated_at".to_string(), Value::from(now));    Ok(patch)}// ── edit_chat_message ───────────────────────────────────────────────────────pub struct EditArgs {    pub message_id: String,    pub body: String,}// ── delete_chat_message ─────────────────────────────────────────────────────// ── hide_chat_messages ──────────────────────────────────────────────────────/// Hide rows from MY copy.////// Private, so it works on anybody's message and never touches a word of what/// was said — the other members keep theirs. Every thread whose HEAD this hide/// removes follows it down, compared BEFORE and AFTER rather than assumed:/// hiding a row five hundred messages back must leave the list line exactly/// where it is.////// An empty list is an answer, not a refusal: a multi-select that ends with/// nothing selected is a tap, and a tap that says "0 hidden" is honest.pub fn hide_chat_messages(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let ids = match args.get("messageIds") {        Some(Value::Array(items)) if items.iter().all(Value::is_string) => items            .iter()            .filter_map(|item| item.as_str())            .map(str::to_string)            .collect::<Vec<String>>(),        _ => return Err(ToolFailure::new("messageIds is a list of message ids")),    };    if ids.is_empty() {        return Ok(answer(vec![("hidden", Value::from(0))]));    }    let placeholders = vec!["?"; ids.len()].join(", ");    let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())];    params.extend(ids.iter().map(|id| SqlValue::Text(id.clone())));    let found = ctx        .db()        .all(            &format!(                "SELECT id, thread_id FROM cotton_msg_messages \                 WHERE workspace_id = ? AND id IN ({placeholders}) AND hidden_at IS NULL"            ),            &params,        )        .map_err(|error| ToolFailure::new(error.to_string()))?;    if found.is_empty() {        return Ok(answer(vec![("hidden", Value::from(0))]));    }    let now = stamp(ctx);    let hiding: Vec<String> = found        .iter()        .filter_map(|row| row.text("id"))        .map(str::to_string)        .collect();    // The threads that lose their head, decided BEFORE anything is written.    let mut thread_ids: Vec<String> = found        .iter()        .filter_map(|row| row.text("thread_id"))        .map(str::to_string)        .collect();    thread_ids.sort();    thread_ids.dedup();    let mut denorms: Vec<(String, Map<String, Value>)> = Vec::new();    for thread_id in &thread_ids {        let thread = require_thread(ctx, thread_id)?;        let before = newest_visible(ctx, &thread, &[])?;        let head_is_going = before            .as_ref()            .and_then(|row| row.text("id"))            .is_some_and(|id| hiding.iter().any(|hidden| hidden == id));        if !head_is_going {            continue;        }        let after = newest_visible(ctx, &thread, &hiding)?;        denorms.push((thread_id.clone(), denorm_from_head(after.as_ref(), &now)?));    }    let writer = ctx.writer()?;    for id in &hiding {        let mut patch = Map::new();        patch.insert("hidden_at".to_string(), Value::from(now.clone()));        writer.upsert(MESSAGES, id, patch);    }    for (thread_id, patch) in denorms {        writer.upsert(THREADS, &thread_id, patch);    }    ctx.commit()?;    Ok(answer(vec![("hidden", Value::from(hiding.len()))]))}// ── forward_chat_messages ───────────────────────────────────────────────────// ── react_to_message / unreact_to_message ───────────────────────────────────// ── star_message ────────────────────────────────────────────────────────────/// Star or unstar — private, and the only index that makes "Starred" a screen.////// ONE verb with a boolean rather than the Expo pair, because the app's control/// is a toggle and two names would let a screen ask for the state it is already/// in twice. The stamp is rewritten on every star, as the Expo verb wrote it:/// `starred_at` records when the message was last starred, and there is no/// first-star rule of the kind a read stamp carries.pub fn star_message(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let message_id = require_uuid(args, "messageId")?;    let Some(starred) = optional_boolean(args, "starred")? else {        return fail("starred says whether the message is starred");    };    require_message(ctx, &message_id)?;    let now = stamp(ctx);    let mut patch = Map::new();    patch.insert(        "starred_at".to_string(),        if starred {            Value::from(now.clone())        } else {            Value::Null        },    );    ctx.writer()?.upsert(MESSAGES, &message_id, patch);    ctx.commit()?;    Ok(answer(vec![        ("messageId", Value::from(message_id)),        ("starred", Value::Bool(starred)),        (            "starredAt",            if starred { Value::from(now) } else { Value::Null },        ),    ]))}