//! The OWNER'S OWN half of a conversation read (sub-step 4m). //! //! `read_message_thread` and `list_message_threads` are the ASSISTANT'S shape, //! and they are right to be: an assistant reading somebody's conversation has //! no business knowing which lines that person starred, what half-sentence is //! sitting in their composer or how far they have read. None of those columns //! is in either tool's projection, and none should be. //! //! The PHONE draws all of them, and — since 4m — writes them. So this module is //! the second half of the same read: the tool answers what was said, and this //! adds what the owner's own devices have written about it, straight off the //! replica the read is already holding open. //! //! **The visibility rule is the part that is not cosmetic.** Neither tool //! filters `hidden_at` or `cleared_before`, because neither column exists for //! an assistant. Without the filter, `hide_chat_messages` and `clear_thread` //! would both be verbs that write a row and change nothing anybody can see — //! which is the one failure a delete may not have. Every reader of a //! conversation applies the same three-part rule, and this is the phone's. use std::collections::HashMap; use cotton_core::messages::edit_window::{ can_delete_for_everyone, can_edit, edit_window_remaining_ms, WindowSubject, }; use cotton_core::constants::{MessageDirection, MessageOrigin}; use cotton_core::messages::group_event::OWNER_ACTOR; use rusqlite::types::Value as SqlValue; use serde_json::{Map, Value}; use cotton_tools::mcp::dispatch::Ctx; /// What this file's own devices have written about one message. struct OwnMessageState { starred_at: Option, hidden_at: Option, sent_at: String, direction: String, origin: String, reply_to_id: Option, } /// Every private column of the messages in this window, by id. fn own_message_state( ctx: &Ctx<'_>, ids: &[String], ) -> Result, String> { if ids.is_empty() { return Ok(HashMap::new()); } 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 rows = ctx .db() .all( &format!( "SELECT id, starred_at, hidden_at, sent_at, direction, origin, reply_to_id \ FROM cotton_msg_messages \ WHERE workspace_id = ? AND id IN ({placeholders})" ), ¶ms, ) .map_err(|error| error.to_string())?; Ok(rows .iter() .filter_map(|row| { Some(( row.text("id")?.to_string(), OwnMessageState { starred_at: row.text("starred_at").map(str::to_string), hidden_at: row.text("hidden_at").map(str::to_string), sent_at: row.text("sent_at").unwrap_or_default().to_string(), direction: row.text("direction").unwrap_or_default().to_string(), origin: row.text("origin").unwrap_or_default().to_string(), reply_to_id: row.text("reply_to_id").map(str::to_string), }, )) }) .collect()) } /// The window rule's subject, from what the replica holds. fn subject_of(state: &OwnMessageState) -> WindowSubject<'_> { WindowSubject { direction: if state.direction == "out" { MessageDirection::Out } else { MessageDirection::In }, sent_at: &state.sent_at, deleted_at: None, origin: if state.origin == "imported" { Some(MessageOrigin::Imported) } else { Some(MessageOrigin::Live) }, } } /// Add the owner's own half to a conversation read, and drop what this device /// has hidden. /// /// **`canEdit` and `canDeleteForEveryone` are ANSWERED, not left to the app.** /// The window rule is one pure function ([`can_edit`]) and both halves ask it: /// a long-press menu that offered "Edit" on its own arithmetic would be the app /// promising a write the verb then refuses, which a person reads as the app /// lying to them. A row already taken back carries neither, since the read /// hands back `deleted` and the menu has nothing left to offer. /// /// `myReaction` is the emoji this person put on the row, read off the same /// `reactions` array the tool already answered rather than from a second query: /// the owner's own reaction is the one whose author is the owner, which is the /// literal every other reader of this shape already uses. pub fn own_thread_state( ctx: &Ctx<'_>, thread_id: Option<&str>, out: &mut Map, now: &str, ) -> Result<(), String> { let messages = out .get("messages") .and_then(Value::as_array) .cloned() .unwrap_or_default(); let ids: Vec = messages .iter() .filter_map(|message| message.get("id").and_then(Value::as_str)) .map(str::to_string) .collect(); let state = own_message_state(ctx, &ids)?; // The conversation's own private columns. A MERGED read (`personId`) has // more than one thread under it and no single row to read them off, so it // gets none — which is right: there is nothing for a mute switch to write // to either. let cleared_before = match thread_id { Some(thread_id) => { let row = ctx .db() .get( "SELECT read_seq, delivered_seq, unread_marked_at, draft, \ draft_reply_to_id, muted_until, pinned_at, archived, cleared_before \ 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| error.to_string())?; match row { Some(row) => { let cleared = row.text("cleared_before").map(str::to_string); if let Some(Value::Object(head)) = out.get_mut("thread") { head.insert( "readSeq".to_string(), Value::from(row.int("read_seq").unwrap_or(0)), ); head.insert( "deliveredSeq".to_string(), Value::from(row.int("delivered_seq").unwrap_or(0)), ); head.insert( "unreadMarkedAt".to_string(), optional(row.text("unread_marked_at")), ); head.insert("draft".to_string(), optional(row.text("draft"))); head.insert( "draftReplyToId".to_string(), optional(row.text("draft_reply_to_id")), ); head.insert("mutedUntil".to_string(), optional(row.text("muted_until"))); head.insert("pinnedAt".to_string(), optional(row.text("pinned_at"))); head.insert( "archived".to_string(), Value::Bool(row.int("archived").unwrap_or(0) == 1), ); head.insert( "clearedBefore".to_string(), optional(row.text("cleared_before")), ); } cleared } None => None, } } None => None, }; let mut kept: Vec = Vec::new(); for mut message in messages { let Some(id) = message .get("id") .and_then(Value::as_str) .map(str::to_string) else { continue; }; let Some(own) = state.get(&id) else { // A row the tool answered and the replica no longer holds. Kept, so // a race between two reads never blanks a conversation. kept.push(message); continue; }; // The three-part visibility rule, the same one every reader applies. if own.hidden_at.is_some() { continue; } if let Some(cleared) = cleared_before.as_deref() { if !cleared.is_empty() && own.sent_at.as_str() <= cleared { continue; } } let deleted = message.get("deleted") == Some(&Value::Bool(true)); let mine = my_reaction(&message); if let Some(row) = message.as_object_mut() { row.insert("starredAt".to_string(), optional(own.starred_at.as_deref())); row.insert( "replyToId".to_string(), optional(own.reply_to_id.as_deref()), ); let subject = subject_of(own); row.insert( "canEdit".to_string(), Value::Bool(!deleted && can_edit(&subject, now)), ); row.insert( "canDeleteForEveryone".to_string(), Value::Bool(!deleted && can_delete_for_everyone(&subject, now)), ); // How long is left to correct it, for a countdown. Zero on anything // the window has closed on, which is what the boolean above says // too — never a negative number a screen would have to clamp. row.insert( "editWindowRemainingMs".to_string(), Value::from(if deleted { 0 } else { edit_window_remaining_ms(&own.sent_at, now) }), ); row.insert("myReaction".to_string(), mine); } kept.push(message); } out.insert("messages".to_string(), Value::Array(kept)); Ok(()) } /// The emoji this person put on a row, off the reactions the tool answered. /// /// The owner's own reaction is the one whose author is [`OWNER_ACTOR`] — the /// same word `from` carries on the owner's own messages, and the one the tool /// already substitutes for the stored `self` actor. The producer is in another /// crate (`records_2::messages::name_for`), so the word is the const rather /// than a literal on each side. Reading it here rather than querying again /// keeps ONE answer to "whose reaction is this". fn my_reaction(message: &Value) -> Value { message .get("reactions") .and_then(Value::as_array) .and_then(|reactions| { reactions .iter() .find(|reaction| { reaction.get("by").and_then(Value::as_str) == Some(OWNER_ACTOR) }) .and_then(|reaction| reaction.get("emoji")) .cloned() }) .unwrap_or(Value::Null) } /// The private columns the CONVERSATION LIST draws — pin, mute and the /// deliberate unread flag — folded onto each row the tool answered. /// /// A merged row covers several threads and takes the strongest answer of them: /// pinned if ANY of its threads is pinned, muted only if EVERY one is (a live /// number under a person who also has a muted one still rings), and flagged /// unread if any is. The alternative — dropping the columns for a merged row — /// would leave a person's own pin invisible on exactly the rows they merged. pub fn own_list_state(ctx: &Ctx<'_>, threads: &mut [Value]) -> Result<(), String> { /// What this device has written about one conversation in the list. struct ListState { pinned_at: Option, muted_until: Option, unread_marked_at: Option, } // THE PAGE'S OWN THREADS, bound one by one — not every conversation in the // file. The map exists to answer thirty rows; asking for the workspace's // whole `cotton_msg_threads` to build it puts a person with ten thousand // conversations through ten thousand rows on every read of the list, and // grows with their life rather than with the page. `own_message_state` // above binds its window exactly this way; this is the same shape. let wanted: Vec = threads .iter() .filter_map(|thread| thread.get("threadIds").and_then(Value::as_array)) .flatten() .filter_map(Value::as_str) .map(str::to_string) .collect(); let by_id: HashMap = if wanted.is_empty() { // No row on this page names a thread, so there is nothing to look up. // The fold below still runs, and still writes the three columns as // nulls, because the ANSWER's shape is not the page's business. HashMap::new() } else { let placeholders = vec!["?"; wanted.len()].join(", "); let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())]; params.extend(wanted.iter().map(|id| SqlValue::Text(id.clone()))); let rows = ctx .db() .all( &format!( "SELECT id, pinned_at, muted_until, unread_marked_at \ FROM cotton_msg_threads \ WHERE workspace_id = ? AND id IN ({placeholders})" ), ¶ms, ) .map_err(|error| error.to_string())?; rows.iter() .filter_map(|row| { Some(( row.text("id")?.to_string(), ListState { pinned_at: row.text("pinned_at").map(str::to_string), muted_until: row.text("muted_until").map(str::to_string), unread_marked_at: row.text("unread_marked_at").map(str::to_string), }, )) }) .collect() }; for thread in threads.iter_mut() { let ids: Vec = thread .get("threadIds") .and_then(Value::as_array) .map(|ids| { ids.iter() .filter_map(Value::as_str) .map(str::to_string) .collect() }) .unwrap_or_default(); let known: Vec<&ListState> = ids.iter().filter_map(|id| by_id.get(id)).collect(); let pinned_at = known.iter().filter_map(|state| state.pinned_at.clone()).max(); // Muted only when EVERY thread under this row is: one live number is // enough for the row to ring. let muted_until = if !known.is_empty() && known.iter().all(|state| state.muted_until.is_some()) { known .iter() .filter_map(|state| state.muted_until.clone()) .min() } else { None }; let unread_marked_at = known .iter() .filter_map(|state| state.unread_marked_at.clone()) .max(); if let Some(row) = thread.as_object_mut() { row.insert("pinnedAt".to_string(), optional(pinned_at.as_deref())); row.insert("mutedUntil".to_string(), optional(muted_until.as_deref())); row.insert( "unreadMarkedAt".to_string(), optional(unread_marked_at.as_deref()), ); } } Ok(()) } fn optional(value: Option<&str>) -> Value { match value { Some(value) => Value::from(value), None => Value::Null, } }