//! What every chat verb repeats: the table names, the two row reads that come //! before almost every write, and the ONE way this module authors a message. //! //! The port of `packages/core/src/services/chat/shared.ts`, plus the two //! helpers `groupVerbs.ts` kept to itself and `messageVerbs.ts` needed as well. //! //! A verb that cannot find its row fails LOUDLY. A mutation that quietly does //! nothing is worse than one that says it did nothing — and the refusal is the //! same sentence whether the row is absent or belongs to another workspace, //! which is this crate's probe-resistance rule everywhere else too. use serde_json::{Map, Value}; use cotton_core::messages::apply_message_write::MessageWriteThread; use cotton_core::messages::MessageMeta; use cotton_store::driver::Row; use rusqlite::types::Value as SqlValue; use crate::mcp::dispatch::Ctx; use crate::mcp::handlers::common::now_iso; use crate::mcp::protocol::ToolFailure; pub const THREADS: &str = "cotton_msg_threads"; pub const MESSAGES: &str = "cotton_msg_messages"; pub const CONTACTS: &str = "cotton_msg_contacts"; pub const PARTICIPANTS: &str = "cotton_msg_thread_participants"; pub const REACTIONS: &str = "cotton_msg_reactions"; pub const RECEIPTS: &str = "cotton_msg_receipts"; /// The thread this verb acts on, scoped to the workspace. /// /// ONE sentence for "no such thread" and for "not yours": a caller learns /// whether a row exists only if it is theirs. pub fn require_thread(ctx: &Ctx<'_>, thread_id: &str) -> Result { ctx.db() .get( "SELECT * FROM cotton_msg_threads WHERE workspace_id = ? AND id = ?", &[ SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(thread_id.to_string()), ], ) .map_err(|error| ToolFailure::new(error.to_string()))? .ok_or_else(|| ToolFailure::new("no such conversation in this database")) } /// The message this verb acts on, scoped to the workspace. pub fn require_message(ctx: &Ctx<'_>, message_id: &str) -> Result { ctx.db() .get( "SELECT * FROM cotton_msg_messages WHERE workspace_id = ? AND id = ?", &[ SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(message_id.to_string()), ], ) .map_err(|error| ToolFailure::new(error.to_string()))? .ok_or_else(|| ToolFailure::new("no such message in this database")) } /// The three columns [`apply_message_write`] needs off a thread row. pub fn write_target<'a>(thread: &'a Row, fallback_id: &'a str) -> MessageWriteThread<'a> { MessageWriteThread { id: thread.text("id").unwrap_or(fallback_id), workspace_id: thread.text("workspace_id").unwrap_or_default(), last_message_at: thread.text("last_message_at"), } } /// The thread's newest VISIBLE row — what the conversation list is quoting. /// /// "Visible" is the same three-part rule every reader applies: not hidden, not /// cleared away, and — with `exclude` — not one of the rows this call is about /// to hide. Passing the about-to-be-hidden ids rather than re-reading after the /// write is what lets the whole act stay ONE batch. pub fn newest_visible( ctx: &Ctx<'_>, thread: &Row, exclude: &[String], ) -> Result, ToolFailure> { let thread_id = thread.text("id").unwrap_or_default().to_string(); let mut sql = String::from( "SELECT * FROM cotton_msg_messages WHERE thread_id = ? AND hidden_at IS NULL AND trashed_at IS NULL", ); let mut params = vec![SqlValue::Text(thread_id)]; if let Some(cleared) = thread.text("cleared_before").filter(|at| !at.is_empty()) { sql.push_str(" AND sent_at > ?"); params.push(SqlValue::Text(cleared.to_string())); } if !exclude.is_empty() { sql.push_str(" AND id NOT IN ("); sql.push_str(&vec!["?"; exclude.len()].join(", ")); sql.push(')'); params.extend(exclude.iter().map(|id| SqlValue::Text(id.clone()))); } sql.push_str(" ORDER BY sent_at DESC, id DESC LIMIT 1"); ctx.db() .get(&sql, ¶ms) .map_err(|error| ToolFailure::new(error.to_string())) } /// Decode the current keyed media format; an invalid attachment fails the edit. pub fn media_of(row: &Row) -> Result, ToolFailure> { let raw = row.text("media") .ok_or_else(|| ToolFailure::new("message media must be JSON text"))?; serde_json::from_str(raw) .map_err(|error| ToolFailure::new(format!("invalid message media: {error}"))) } /// The `meta` column, decoded, or the empty object. pub fn meta_of(row: &Row) -> MessageMeta { row.text("meta") .and_then(|raw| serde_json::from_str(raw).ok()) .unwrap_or_default() } /// A thread patch, queued. Every private-state verb in [`super::threads`] is /// one of these. pub fn patch_thread( ctx: &mut Ctx<'_>, thread_id: &str, pairs: Vec<(&str, Value)>, ) -> Result<(), ToolFailure> { let mut patch = Map::new(); for (key, value) in pairs { patch.insert(key.to_string(), value); } ctx.writer()?.upsert(THREADS, thread_id, patch); Ok(()) } /// `now`, as every verb in this module stamps it. pub fn stamp(ctx: &Ctx<'_>) -> String { now_iso(ctx) } #[cfg(test)] mod tests { use super::*; // RULE: Invalid media must fail the edit, never erase attachments through an empty preview fallback. #[test] fn malformed_media_is_refused() { for value in [SqlValue::Null, SqlValue::Text("not json".into()), SqlValue::Text(r#"[{"url":"https://example.invalid/old.jpg","contentType":"image/jpeg"}]"#.into())] { let row = Row::new(vec![("media".into(), value)]); assert!(media_of(&row).is_err()); } assert!(media_of(&Row::default()).is_err()); assert!(media_of(&Row::new(vec![("media".into(), SqlValue::Text("[]".into()))])).unwrap().is_empty()); } }