//! The verbs that act on a THREAD — and in the personal database every one of//! them writes a column that belongs to THIS FILE'S OWNER ALONE.//!//! The port of `packages/core/src/services/chat/threadVerbs.ts`.//!//! That is the whole reason they are worth grouping. The chat schema splits//! every column into "shared content, written by its author and mirrored by the//! server" and "private, written only by the owner's devices" — and//! last-write-wins only stays correct while no column has two logical authors.//! Read cursors, drafts, mute, pin, archive and mark-as-unread are all on the//! private side, so a mirror can never contend with the person's own phone for//! them.//!//! [`mark_thread_read`] is the one to look at twice. Before the cursor model it//! stamped `read_at` on every unread row — one op each, and the op log is what//! every device replays forever. It is now ONE patch, whatever the backlog.usecrate::mcp::writer::Retract;use serde_json::{Map, Value};use cotton_core::messages::unread::next_read_seq;use cotton_store::link_rule::FileKind;use cotton_store::protocol::js::parse_date_ms;use rusqlite::types::ValueasSqlValue;usecrate::mcp::dispatch::{Ctx, ToolResult};usecrate::mcp::handlers::common::{fail, optional_boolean, require_uuid, Valid};usecrate::mcp::protocol::ToolFailure;usesuper::answer;usesuper::shared::{ patch_thread, require_thread, stamp, MESSAGES, PARTICIPANTS, REACTIONS, RECEIPTS, THREADS,};// ── mark_thread_read ────────────────────────────────────────────────────────pubstructMarkReadArgs {pub thread_id: String,/// How far to move the cursor, or `None` for "the foot of the/// conversation" — which is what the app means every time somebody opens/// one. The app must NOT compute this itself: the window it draws has had/// hidden and cleared rows taken out of it, so its own highest sequence/// number can be behind the conversation's, and a cursor short of the foot/// leaves an unread divider over messages the person has just read.pub up_to_seq: Option<i64>,}pubfn validate_mark_thread_read(args: &Map<String, Value>) -> Valid<MarkReadArgs> {let thread_id = require_uuid(args, "threadId")?;let up_to_seq = match args.get("upToSeq") {None | Some(Value::Null) => None,Some(value) => {letSome(seq) = value.as_i64() else {return fail("upToSeq is the sequence number read up to"); };if seq < 0 {return fail("upToSeq is a sequence number, so never negative"); }Some(seq) } };Ok(MarkReadArgs { thread_id, up_to_seq, })}/// The highest sequence number the conversation holds, or 0 for one nothing has/// ever been relayed in. An imported row carries no sequence number at all and/// is passed over: a cursor is a position in the RELAY's order, and an archive/// was never in it.fn newest_seq(ctx: &mutCtx<'_>, thread_id: &str) -> Result<i64, ToolFailure> {let row = ctx .db() .get( &format!("SELECT MAX(seq) AS seq FROM {MESSAGES} \ WHERE workspace_id = ? AND thread_id = ? AND seq IS NOT NULL" ), &[SqlValue::Text(ctx.workspace_id.to_string()),SqlValue::Text(thread_id.to_string()), ], ) .map_err(|error| ToolFailure::new(error.to_string()))?;Ok(row.and_then(|row| row.int("seq")).unwrap_or(0))}/// Move the read cursor.////// MONOTONIC: two devices at different scroll positions must not let the one/// further back drag the cursor down, and a fold of the other device's older/// patch has to be a no-op. That is `next_read_seq`, which is a `max` and/// nothing cleverer.////// **It writes nothing when there is nothing to say.** The thread screen calls/// this on every new inbound row while it is focused, and an op per no-op would/// fill an append-only log with the fact that somebody was looking at a screen.pubfn mark_thread_read(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_mark_thread_read(args)?;let thread = require_thread(ctx, &args.thread_id)?;let current = thread.int("read_seq").unwrap_or(0);// A filed copy is read by everybody in its database, and a cursor says// how far ONE of them has read: there is nobody's to move. The copy// counts nothing unread (it carries no cursor), so nothing is owed.if ctx.file_kind()? == FileKind::Shared {returnOk(answer(vec![ ("threadId", Value::from(args.thread_id)), ("readSeq", Value::from(current)), ("changed", Value::Bool(false)), ])); }let up_to_seq = match args.up_to_seq {Some(seq) => seq,None => newest_seq(ctx, &args.thread_id)?, };let read_seq = next_read_seq(current, up_to_seq);let marked_unread = thread.text("unread_marked_at").is_some();letmut pairs: Vec<(&str, Value)> = Vec::new();if read_seq != current { pairs.push(("read_seq", Value::from(read_seq))); }if marked_unread { pairs.push(("unread_marked_at", Value::Null)); }let wrote = !pairs.is_empty();if wrote { patch_thread(ctx, &args.thread_id, pairs)?; ctx.commit()?; }Ok(answer(vec![ ("threadId", Value::from(args.thread_id)), ("readSeq", Value::from(read_seq)), ("changed", Value::Bool(wrote)), ]))}// ── mark_thread_unread ──────────────────────────────────────────────────────/// "Mark as unread" — a deliberate flag, not a rewound cursor.////// Rewinding `read_seq` would tell every other member's receipts that these/// messages had been UN-read, which is not what the person meant: they meant/// "put a mark on this conversation so I come back to it".pubfn mark_thread_unread(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let thread_id = require_uuid(args, "threadId")?; require_thread(ctx, &thread_id)?;let now = stamp(ctx); patch_thread( ctx, &thread_id, vec![("unread_marked_at", Value::from(now.clone()))], )?; ctx.commit()?;Ok(answer(vec![ ("threadId", Value::from(thread_id)), ("unreadMarkedAt", Value::from(now)), ]))}// ── set_thread_draft ────────────────────────────────────────────────────────// ── set_thread_muted ────────────────────────────────────────────────────────/// Mute until an instant, or unmute.////// ON THE THREAD, not on the contact — a group has no contact, so before the/// column moved a group could not be muted at all. "Always" is the frozen far/// date `MUTE_ALWAYS_UNTIL` and passes this check like any other timestamp,/// which is why there is no separate forever flag to keep in step with it.pubfn set_thread_muted(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let thread_id = require_uuid(args, "threadId")?; require_thread(ctx, &thread_id)?;let until = match args.get("until") {None | Some(Value::Null) => None,Some(Value::String(value)) => {if parse_date_ms(value).is_none() {returnErr(ToolFailure::new("that is not a time")); }Some(value.clone()) }Some(_) => returnErr(ToolFailure::new("until is an instant, or null to unmute")), }; patch_thread( ctx, &thread_id, vec![("muted_until",match &until {Some(value) => Value::from(value.clone()),None => Value::Null, }, )], )?; ctx.commit()?;Ok(answer(vec![ ("threadId", Value::from(thread_id)), ("mutedUntil", until.map(Value::from).unwrap_or(Value::Null), ), ]))}// ── set_thread_pinned ───────────────────────────────────────────────────────/// Pin a conversation to the top of the list, or take the pin off.pubfn set_thread_pinned(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let thread_id = require_uuid(args, "threadId")?;letSome(pinned) = optional_boolean(args, "pinned")? else {return fail("pinned says whether the conversation is pinned"); };let now = stamp(ctx); require_thread(ctx, &thread_id)?; patch_thread( ctx, &thread_id, vec![("pinned_at",if pinned {Value::from(now.clone()) } else {Value::Null }, )], )?; ctx.commit()?;Ok(answer(vec![ ("threadId", Value::from(thread_id)), ("pinned", Value::Bool(pinned)), ("pinnedAt",if pinned { Value::from(now) } else { Value::Null }, ), ]))}// ── set_thread_archived ─────────────────────────────────────────────────────/// Archive a conversation, or bring it back.pubfn set_thread_archived(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let thread_id = require_uuid(args, "threadId")?;letSome(archived) = optional_boolean(args, "archived")? else {return fail("archived says whether the conversation is archived"); }; require_thread(ctx, &thread_id)?;let now = stamp(ctx); patch_thread( ctx, &thread_id, vec![ ("archived", Value::Bool(archived)), ("updated_at", Value::from(now)), ], )?; ctx.commit()?;Ok(answer(vec![ ("threadId", Value::from(thread_id)), ("archived", Value::Bool(archived)), ]))}// ── clear_thread ────────────────────────────────────────────────────────────/// "Clear chat" — hide everything said before now, in ONE op.////// A MARKER, not a sweep. The obvious implementation stamps `hidden_at` on/// every row, which mints one op PER ROW — and the op log is append-only and/// replayed by every device forever, so a forty-thousand-message archive would/// cost forty thousand permanent ops for one tap. `cleared_before` is a single/// private column and every reader filters on it, so clearing a huge/// conversation costs exactly what clearing an empty one does.////// It only ever moves FORWARD: two devices clearing at different moments must/// not let the earlier one un-hide what the later one already hid.////// The conversation's own denorm goes with it — the list would otherwise keep/// quoting a conversation the person has just cleared.pubfn clear_thread(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let thread_id = require_uuid(args, "threadId")?;let now = stamp(ctx);let thread = require_thread(ctx, &thread_id)?;let cleared_before = match thread.text("cleared_before") {Some(existing) if !existing.is_empty() && existing > now.as_str() => existing.to_string(), _ => now.clone(), }; patch_thread( ctx, &thread_id, vec![ ("cleared_before", Value::from(cleared_before.clone())), ("updated_at", Value::from(now)), ("last_message_preview", Value::Null), ], )?; ctx.commit()?;Ok(answer(vec![ ("threadId", Value::from(thread_id)), ("clearedBefore", Value::from(cleared_before)), ]))}// ── delete_thread ───────────────────────────────────────────────────────────/// "Delete chat" — the conversation and everything hanging off it.////// ONE retract, of the thread: the store takes its receipts, reactions,/// messages and participants out with it (they own nothing without it), and/// refuses an act that names a child beside its owner. `rowsRemoved` counts/// what went with it.pubfn delete_thread(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let thread_id = require_uuid(args, "threadId")?; require_thread(ctx, &thread_id)?;letmut removed = 0usize;for table in [RECEIPTS, REACTIONS, MESSAGES, PARTICIPANTS] {let row = ctx .db() .get( &format!("SELECT COUNT(*) AS n FROM {table} WHERE thread_id = ?"), &[SqlValue::Text(thread_id.clone())], ) .map_err(|error| ToolFailure::new(error.to_string()))?; removed += row.and_then(|row| row.int("n")).unwrap_or(0) as usize; } ctx.writer()?.retract(THREADS, &thread_id, Retract::Verb("delete_thread")); ctx.commit()?;Ok(answer(vec![ ("threadId", Value::from(thread_id)), ("deleted", Value::Bool(true)), ("rowsRemoved", Value::from(removed)), ]))}// ── stamp_threads_delivered ─────────────────────────────────────────────────