//! What the messages engine answers beyond a chat's and a message's stored //! columns, for every generic caller: a chat's name (a dm stores no title — //! its name is its contact's), its members, channels and last line, and a //! message's words, sender, quoted reply, reactions and media entries. //! //! The words are `cotton_core::messages::display`'s; this module only reads //! what they need — once for a whole page of records ([`ChatReads`]), never //! once per record. use std::collections::HashMap; use cotton_core::messages::display::{ direct_name, group_name, is_aside, list_line, message_line, note_words, shared_contact, reaction_line, UNKNOWN_NAME, }; use cotton_core::messages::preview::PreviewSource; use cotton_core::messages::send::outgoing_targets; use cotton_core::messages::{MessageMedia, MessageMeta}; use cotton_core::records::{Condition, Data}; use rusqlite::types::Value as SqlValue; use serde_json::{Map, Value}; use crate::mcp::dispatch::Ctx; use crate::mcp::handlers::common::{in_chunks, now_iso, rows, text, Valid}; use crate::mcp::handlers::records_2::messages::{ channels_by_thread, in_values, js_truthy, media_out, unique_ids, unread_threads, }; use crate::mcp::read_db::{Filter, Order, Query}; /// What the owner's own messages are signed. const OWNER_NAME: &str = "You"; /// Why nobody sends into a filed copy: it is a copy, carried one way out of /// the filer's personal Messages, and a line written into it would be said /// to nobody. const FILED_COPY_IS_READ: &str = "A filed chat is read here. Reply from your own Messages."; /// Store columns the engine reads beyond the definition's — see /// `builtin::extra_reads`. pub(super) const THREAD_READS: &[&str] = &["contact_id", "unread_marked_at", "cleared_before"]; pub(super) const MESSAGE_READS: &[&str] = &["meta", "sender_participant_id", "workspace_id"]; /// What a page of chats or messages reads once for all of them. #[derive(Default)] pub(super) struct ChatReads { /// Chat id → its name. names: HashMap, /// Chat id → `dm` or `group`. kinds: HashMap, /// Chat id → the people in it, by name. members: HashMap>, /// Chats the owner still sits in, and each chat's sitting members who /// have no person record — with `people`, everyone `members` names. with_owner: std::collections::HashSet, unmatched: HashMap>, /// Chat id → the people (person records) in it. people: HashMap>, /// Chat id → the channels its messages came by. channels: HashMap>, /// The message definition's `channel` column, whose labels say each /// channel in words ("sms" → "Text message"). channel_column: Option, /// Chat id → its newest message's line, where the stored one is blank. last_lines: HashMap, /// Group chat id → who said its newest message, by first name ("You" for /// the owner); absent where a system line is the newest. last_senders: HashMap, /// Participant id → the name a message of theirs is signed. seats: HashMap, /// Participant id → their person's picture, where they have one. seat_photos: HashMap, /// Message id → its reactions' emoji, oldest first. reactions: HashMap>, /// Message id → "who: what they said", for a message another replies to. quoted: HashMap, /// Chat id → why the owner's app cannot send into it, `None` where it can /// (`cotton_core::messages::send`). send_blocked: HashMap>, /// These are chats of the personal Messages (a shared database holds /// copies, read by everybody there). fileable: bool, /// Chats holding a message the owner has not read (personal Messages /// only: a filed copy keeps no read cursor of its reader's). unread: std::collections::HashSet, /// Set in a SHARED database, where every chat is a filed copy. "Out" is /// only "mine" to the one who filed the chat, so his lines are said from /// a seat bound to the person he is there (`messages::filing_copy`), and /// everybody who reads the copy reads that seat's name — never "You". filed: bool, } /// Whether these reads are of a SHARED database ([`ChatReads::filed`]). fn is_filed(ctx: &Ctx<'_>) -> Valid { Ok(ctx.file_kind()? == cotton_store::link_rule::FileKind::Shared) } fn said(value: Option) -> Option { value.map(|text| text.trim().to_string()).filter(|text| !text.is_empty()) } fn ids_of(found: &[Map], column: &str) -> Vec { unique_ids(found.iter().filter_map(|row| text(row, column))) } /// A channel as a person reads it: the message definition's words for it. fn channel_word(reads: &ChatReads, channel: &str) -> String { match &reads.channel_column { Some(column) => column.choice_label(channel), None => cotton_core::definitions::key_as_words(channel), } } /// A message's media entries, however the column was read: its tree, or its /// text. An entry this build cannot read is left out. fn media_entries(value: Option<&Value>) -> Vec { let parsed; let entries = match value { Some(Value::Array(entries)) => entries, Some(Value::String(raw)) => match serde_json::from_str::(raw) { Ok(Value::Array(entries)) => { parsed = entries; &parsed } _ => return Vec::new(), }, _ => return Vec::new(), }; entries .iter() .filter_map(|entry| serde_json::from_value(entry.clone()).ok()) .collect() } fn meta_tree(value: Option<&Value>) -> Value { match value { Some(Value::String(raw)) => serde_json::from_str(raw).unwrap_or(Value::Null), Some(other) => other.clone(), None => Value::Null, } } /// One message row as the words read it. struct Read { body: Option, media: Vec, deleted_at: Option, meta: MessageMeta, system: bool, } impl Read { fn of(row: &Map) -> Self { let tree = meta_tree(row.get("meta")); Self { body: text(row, "body"), media: media_entries(row.get("media")), deleted_at: said(text(row, "deleted_at")), system: js_truthy(tree.get("system")), meta: serde_json::from_value(tree).unwrap_or_default(), } } fn source(&self) -> PreviewSource<'_> { PreviewSource { body: self.body.as_deref(), media: &self.media, deleted_at: self.deleted_at.as_deref(), meta: Some(&self.meta), } } } /// Name `threads` (rows holding `id`, `kind`, `title`, `contact_id`), their /// members and every seat in them. fn name_chats(ctx: &Ctx<'_>, threads: &[Map], reads: &mut ChatReads) -> Valid<()> { let thread_ids = ids_of(threads, "id"); let seats = in_chunks(&thread_ids, |batch| { rows( ctx, &Query::on("cotton_msg_thread_participants") .columns(&["id", "thread_id", "contact_id", "display_name", "left_at", "is_self"]) .filter(Filter::In("thread_id".to_string(), in_values(batch))) .order_by("created_at", Order::Asc) .order_by("id", Order::Asc), ) })?; let mut contact_ids = ids_of(threads, "contact_id"); contact_ids.extend(ids_of(&seats, "contact_id")); let contact_ids = unique_ids(contact_ids); let contacts = in_chunks(&contact_ids, |batch| { rows( ctx, &Query::on("cotton_msg_contacts") .columns(&["id", "display_name", "phone_e164", "person_id"]) .filter(Filter::In("id".to_string(), in_values(batch))), ) })?; let people = in_chunks(&ids_of(&contacts, "person_id"), |batch| { rows( ctx, &Query::on("cotton_people") .columns(&["id", "full_name", "avatar_key"]) .filter(Filter::In("id".to_string(), in_values(batch))), ) })?; let avatars: HashMap = people .iter() .filter_map(|row| Some((text(row, "id")?, said(text(row, "avatar_key"))?))) .collect(); let people: HashMap = people .iter() .filter_map(|row| Some((text(row, "id")?, said(text(row, "full_name"))?))) .collect(); // Another address, for a contact with neither a name nor a number. let bare: Vec = contacts .iter() .filter(|row| said(text(row, "display_name")).is_none() && said(text(row, "phone_e164")).is_none()) .filter_map(|row| text(row, "id")) .collect(); let mut handles: HashMap = HashMap::new(); for row in in_chunks(&bare, |batch| { rows( ctx, &Query::on("cotton_msg_contact_handles") .columns(&["contact_id", "value"]) .filter(Filter::In("contact_id".to_string(), in_values(batch))) .order_by("created_at", Order::Asc), ) })? { if let (Some(contact), Some(value)) = (text(&row, "contact_id"), said(text(&row, "value"))) { handles.entry(contact).or_insert(value); } } let contacts: HashMap> = contacts .iter() .filter_map(|row| Some((text(row, "id")?, row))) .collect(); let contact_name = |id: &str, title: Option<&str>| -> String { let row = contacts.get(id); let person = row.and_then(|row| text(row, "person_id")).and_then(|person| people.get(&person).cloned()); direct_name( person.as_deref(), row.and_then(|row| text(row, "display_name")).as_deref(), title, row.and_then(|row| text(row, "phone_e164")).as_deref(), handles.get(id).map(String::as_str), ) }; let person_of = |contact: Option| -> Option { contacts.get(&contact?).and_then(|row| said(text(row, "person_id"))) }; // The groups whose owner's own seat says they left: in every other group // of this archive the owner is a member, seat or none — an import that // wrote no seat for the owner still holds their messages (walk, 5 Oct: 'Weekend plans' had no You). let mut owner_left: std::collections::HashSet = std::collections::HashSet::new(); for seat in &seats { let (Some(id), Some(thread)) = (text(seat, "id"), text(seat, "thread_id")) else { continue; }; let is_self = seat.get("is_self").and_then(Value::as_bool) == Some(true); let matched = person_of(text(seat, "contact_id")); let has_person = matched.is_some(); if let Some(person) = matched { if let Some(photo) = avatars.get(&person) { reads.seat_photos.insert(id.clone(), photo.clone()); } let people = reads.people.entry(thread.clone()).or_default(); if !people.contains(&person) { people.push(person); } } let name = if is_self { OWNER_NAME.to_string() } else { match text(seat, "contact_id").filter(|contact| !contact.is_empty()) { Some(contact) => contact_name(&contact, text(seat, "display_name").as_deref()), None => said(text(seat, "display_name")).unwrap_or_else(|| UNKNOWN_NAME.to_string()), } }; if is_self && said(text(seat, "left_at")).is_some() { owner_left.insert(thread.clone()); } if said(text(seat, "left_at")).is_none() { if is_self { reads.with_owner.insert(thread.clone()); } else if !has_person { reads.unmatched.entry(thread.clone()).or_default().push(name.clone()); } reads.members.entry(thread).or_default().push(name.clone()); } reads.seats.insert(id, name); } for thread in threads { let Some(id) = text(thread, "id") else { continue }; let kind = text(thread, "kind").unwrap_or_default(); if kind == "group" && !owner_left.contains(&id) { reads.with_owner.insert(id.clone()); } let title = text(thread, "title"); let contact = text(thread, "contact_id").filter(|contact| !contact.is_empty()); let name = match (kind.as_str(), contact) { ("dm", Some(contact)) => contact_name(&contact, title.as_deref()), ("dm", None) => direct_name(None, None, title.as_deref(), None, None), _ => { let others: Vec = reads .members .get(&id) .map(|names| names.iter().filter(|name| *name != OWNER_NAME).cloned().collect()) .unwrap_or_default(); group_name(title.as_deref(), &others) } }; if let Some(person) = person_of(text(thread, "contact_id")) { let people = reads.people.entry(id.clone()).or_default(); if !people.contains(&person) { people.push(person); } } reads.names.insert(id.clone(), name); reads.kinds.insert(id, kind); } reads.channels = channels_by_thread(ctx, &thread_ids)?; reads.channel_column = super::definition(ctx, "message")?.column("channel").cloned(); Ok(()) } /// A statement over text parameters in this file — how the send decision /// (`cotton_core::messages::send`) reads it. pub(super) fn file_reader( db: &cotton_store::Driver, ) -> impl FnMut(&str, &[String]) -> cotton_store::Result> + '_ { move |sql, params| { let bound: Vec = params.iter().map(|param| SqlValue::Text(param.clone())).collect(); db.all(sql, &bound) } } /// What a page of chats reads. pub(super) fn thread_reads(ctx: &Ctx<'_>, found: &[Map]) -> Valid { let mut reads = ChatReads { filed: is_filed(ctx)?, ..ChatReads::default() }; name_chats(ctx, found, &mut reads)?; let sends = outgoing_targets(&mut file_reader(ctx.read.driver()), &ids_of(found, "id")) .map_err(|error| crate::mcp::protocol::ToolFailure::new(error.to_string()))?; reads.send_blocked = sends.into_iter().map(|(id, decision)| (id, decision.err())).collect(); // A Cotton conversation sends through the phone's own object (`chat.send`), // never through a Mac: it sends unless it is archived. for row in found { if let (Some(id), Some(true)) = (text(row, "id"), text(row, "external_key").map(|key| cotton_core::chat::ids::is_cotton_key(&key))) { let archived = js_truthy(row.get("archived")); reads.send_blocked.insert(id, archived.then_some(cotton_core::messages::send::ARCHIVED)); } } // A chat of the personal Messages keeps its read cursor; a shared // database's copies keep none. if ctx.file_kind()? != cotton_store::link_rule::FileKind::Shared { reads.fileable = true; reads.unread = unread_threads(ctx, &ids_of(found, "id"))?; } // A chat that holds messages and stores no last line: its newest visible // message says it. // And a group's last line is signed: its newest visible message's // sender, by first name, so the list says who spoke last. for thread in found { let group = text(thread, "kind").as_deref() == Some("group"); // Cleared past its last message: the stored line quotes something // cleared away. The personal chat's line is blanked by the clear // itself; a filed copy's is the filing's to write, so it is read. let cleared = said(text(thread, "cleared_before")) .is_some_and(|before| text(thread, "last_message_at").is_some_and(|last| last <= before)); let blank = cleared || said(text(thread, "last_message_preview")).is_none(); if said(text(thread, "last_message_at")).is_none() || !(group || blank) { continue; } let Some(id) = text(thread, "id") else { continue }; // Past what this reader cleared (on a filed copy the marker is the // reader's own, laid over the row; the static rule reads the copy's). let mut after = Query::on("cotton_msg_messages"); if let Some(before) = said(text(thread, "cleared_before")) { after = after.filter(Filter::Gt("sent_at".to_string(), SqlValue::Text(before.to_string()))); } let newest = rows( ctx, &after .columns(&[ "id", "thread_id", "direction", "body", "media", "deleted_at", "meta", "sender_participant_id", ]) .eq("thread_id", id.clone()) .filter(Filter::Static(super::builtin::MESSAGE_VISIBLE)) .order_by("sent_at", Order::Desc) .order_by("id", Order::Desc) .limit(1), )?; if let Some(row) = newest.first() { let read = Read::of(row); if group { if let Some(who) = sender(row, &read, &reads) { let first = who.split_whitespace().next().unwrap_or(&who).to_string(); reads.last_senders.insert(id.clone(), first); } } if blank { reads.last_lines.insert(id, message_line(&read.source())); } } else if cleared { reads.last_lines.insert(id, list_line(None)); } } Ok(reads) } /// What a page of messages reads. pub(super) fn message_reads(ctx: &Ctx<'_>, found: &[Map]) -> Valid { let mut reads = ChatReads { filed: is_filed(ctx)?, ..ChatReads::default() }; let thread_ids = ids_of(found, "thread_id"); let threads = in_chunks(&thread_ids, |batch| { rows( ctx, &Query::on("cotton_msg_threads") .columns(&["id", "kind", "title", "contact_id"]) .filter(Filter::In("id".to_string(), in_values(batch))), ) })?; name_chats(ctx, &threads, &mut reads)?; for row in in_chunks(&ids_of(found, "id"), |batch| { rows( ctx, &Query::on("cotton_msg_reactions") .columns(&["message_id", "emoji", "created_at"]) .filter(Filter::In("message_id".to_string(), in_values(batch))) .order_by("created_at", Order::Asc), ) })? { if let (Some(message), Some(emoji)) = (text(&row, "message_id"), text(&row, "emoji")) { reads.reactions.entry(message).or_default().push(emoji); } } let quoted = in_chunks(&ids_of(found, "reply_to_id"), |batch| { rows( ctx, &Query::on("cotton_msg_messages") .columns(&[ "id", "thread_id", "direction", "body", "media", "deleted_at", "meta", "sender_participant_id", ]) .filter(Filter::In("id".to_string(), in_values(batch))) .filter(Filter::Static(super::builtin::MESSAGE_VISIBLE)), ) })?; for row in "ed { let Some(id) = text(row, "id") else { continue }; let read = Read::of(row); let line = message_line(&read.source()); let line = match sender(row, &read, &reads) { Some(who) => format!("{who}: {line}"), None => line, }; reads.quoted.insert(id, line); } Ok(reads) } /// Who a message is signed: the owner, its seat's name (in a shared /// database the person who filed the chat is a seat too), else — a dm's /// seatless inbound line — the chat's own name. A system line is nobody's. fn sender(row: &Map, read: &Read, reads: &ChatReads) -> Option { if read.system { return None; } let out = text(row, "direction").as_deref() == Some("out"); if out && !reads.filed { return Some(OWNER_NAME.to_string()); } if let Some(seat) = text(row, "sender_participant_id").filter(|seat| !seat.is_empty()) { return Some(reads.seats.get(&seat).cloned().unwrap_or_else(|| UNKNOWN_NAME.to_string())); } if out { return Some(UNKNOWN_NAME.to_string()); } let thread = text(row, "thread_id")?; (reads.kinds.get(&thread).map(String::as_str) == Some("dm")) .then(|| reads.names.get(&thread).cloned()) .flatten() } /// A chat's computed columns. pub(super) fn thread_extras(ctx: &Ctx<'_>, row: &Map, reads: &ChatReads, data: &mut Data) { let id = text(row, "id").unwrap_or_default(); data.insert( "name".into(), Value::from(reads.names.get(&id).cloned().unwrap_or_else(|| UNKNOWN_NAME.to_string())), ); if let Some(members) = reads.members.get(&id).filter(|members| !members.is_empty()) { data.insert("members".into(), Value::from(members.join("\n"))); } if let Some(people) = reads.people.get(&id).filter(|people| !people.is_empty()) { data.insert("member_people".into(), Value::from(people.clone())); } // The rest of the one list of members: the owner first, and after the // people those with no person record, as plain names. "You" is the one // whose Messages these are: a filed copy is read by everybody in its // database, and is nobody's "You". if reads.fileable && reads.with_owner.contains(&id) { data.insert("member_self".into(), Value::from(OWNER_NAME)); } if let Some(unmatched) = reads.unmatched.get(&id).filter(|names| !names.is_empty()) { data.insert("members_unmatched".into(), Value::from(unmatched.join("\n"))); } if let Some(channels) = reads.channels.get(&id).filter(|channels| !channels.is_empty()) { let words: Vec = channels.iter().map(|channel| channel_word(reads, channel)).collect(); data.insert("channels".into(), Value::from(words.join(" · "))); } // The stored last line, said in words — never blank, never a marker. let line = match reads.last_lines.get(&id) { Some(line) => line.clone(), None => list_line(text(row, "last_message_preview").as_deref()), }; let line = match reads.last_senders.get(&id) { Some(who) => format!("{who}: {line}"), None => line, }; data.insert("last_message_preview".into(), Value::from(line)); // Unread: marked so by hand, or a message came in past what was read. let unread = said(text(row, "unread_marked_at")).is_some() || reads.unread.contains(&id); data.insert("unread".into(), Value::from(if unread { "unread" } else { "read" })); let mut state: Vec<&str> = Vec::new(); let pinned = said(text(row, "pinned_at")).is_some(); data.insert("pinned".into(), Value::Bool(pinned)); let muted = said(text(row, "muted_until")).is_some_and(|until| until > now_iso(ctx)); data.insert("muted".into(), Value::Bool(muted)); if pinned { state.push("Pinned"); } if muted { state.push("Muted"); } if !state.is_empty() { data.insert("state_line".into(), Value::from(state.join(" · "))); } // A copy in a shared database: Clear chat asks in the copy's own words, // since it clears it for everybody in this database. if !reads.fileable { data.insert("filed_copy".into(), Value::Bool(true)); } let blocked = reads.send_blocked.get(&id).copied().unwrap_or(Some(cotton_core::messages::send::NOT_WHATSAPP)); let blocked = if reads.fileable { blocked } else { Some(FILED_COPY_IS_READ) }; data.insert("sendable".into(), Value::Bool(blocked.is_none())); data.insert("send_blocked_reason".into(), blocked.map_or(Value::Null, Value::from)); } /// A stored message's shared post, as its `meta.share` keeps it: who posted /// it, its caption, and whether its media came. Only read for display — the /// rows stay, though nothing writes new ones. #[derive(serde::Deserialize)] struct SharedMedia { author: Option, caption: Option, status: ShareStatus, } #[derive(serde::Deserialize)] struct SharedAuthor { handle: Option, display_name: String, } #[derive(Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] enum ShareStatus { #[serde(alias = "not_followed")] Pending, Available, Unavailable, } /// A message's computed columns. pub(super) fn message_extras(row: &Map, reads: &ChatReads, data: &mut Data) { let read = Read::of(row); let thread = text(row, "thread_id").unwrap_or_default(); // In a shared database the chat is a filed copy, read by everybody // there: "out" is only "mine" to the one who filed it, so no line is // answered as the reader's own. Each is somebody's, and says whose — the // filer's by the person he claimed there (`sender`). let filed = reads.filed; if filed { data.insert("direction".into(), Value::from("in")); } let inbound = filed || text(row, "direction").as_deref() != Some("out"); let group = reads.kinds.get(&thread).map(String::as_str) == Some("group"); let mut put = |key: &str, value: Option| { if let Some(value) = said(value) { data.insert(key.into(), Value::from(value)); } }; // A shared contact is drawn as its card (`resolve_message`'s media), so // its note says nothing. let card = read.deleted_at.is_none() && read.media.is_empty() && read.body.as_deref().and_then(shared_contact).is_some(); put("display_body", (!card).then(|| note_words(&read.source()))); put("preview", Some(message_line(&read.source()))); if read.deleted_at.is_none() { if let Some(share) = read.meta.extra.get("share").and_then(|value| serde_json::from_value::(value.clone()).ok()) { put("shared_author", share.author.as_ref().map(|author| author.display_name.clone())); put("shared_handle", share.author.and_then(|author| author.handle)); put("shared_caption", share.caption); let status = if share.status == ShareStatus::Available && read.media.is_empty() { ShareStatus::Pending } else { share.status }; put("shared_status", serde_json::to_value(status).ok().and_then(|value| value.as_str().map(str::to_string))); put("shared_link", read.meta.extra.get("link").and_then(Value::as_str).map(str::to_string)); } } let who = sender(row, &read, reads); if (group || filed) && inbound { put("sender_label", who.clone()); put("paper_sender", who.clone()); let seat = text(row, "sender_participant_id").unwrap_or_default(); put("sender_photo", reads.seat_photos.get(&seat).cloned()); } // What a sign-in code in an inbound line is for; the code itself is the // sign-in engine's alone and is never put here. if inbound && read.deleted_at.is_none() { let code = read.body.as_deref().and_then(|body| cotton_core::messages::sign_in::read(body, who.as_deref())); put("code_for", code.and_then(|code| code.code_for)); } put("sender_name", who); let channel = text(row, "channel"); let mut provenance = Vec::new(); if reads.channels.get(&thread).is_some_and(|channels| channels.len() > 1) { if let Some(channel) = channel { provenance.push(channel_word(reads, &channel)); } } put("provenance", Some(provenance.join(" · "))); if read.deleted_at.is_none() { let quoted = text(row, "reply_to_id").and_then(|id| reads.quoted.get(&id).cloned()); put("reply_preview", quoted.map(|line| format!("↩ {line}"))); let edited = read.meta.edited == Some(true) || said(text(row, "edited_at")).is_some(); put("edited_label", edited.then(|| "edited".to_string())); } let kept = said(text(row, "starred_at")).is_some(); put("starred_label", kept.then(|| "kept".to_string())); data.insert("kept".into(), Value::Bool(kept)); // Keeping a line, and deleting one from "my copy", are one reader's own // marks: they are put on a line of his own Messages, never on a filed // copy's, which is everybody's — the two commands are not offered on it. if filed { data.insert("filed_copy".into(), Value::Bool(true)); } if super::mail_chat_writes::binnable(text(row, "direction").as_deref(), text(row, "send_state").as_deref()) { data.insert("can_delete".into(), Value::Bool(true)); } // A deleted line and one the export left out are lines about the chat, // not something said in it: the conversation writes them as it writes a // system line, in pencil, never as a note. data.insert("is_system".into(), Value::Bool(read.system || is_aside(&read.source()))); } /// A message's `media` and `reactions` as the definition answers them: the /// entries a conversation draws (none on a deleted message), and the /// reactions as one line. pub(super) fn resolve_message(ctx: &Ctx<'_>, key: &str, row: &Map, reads: &ChatReads) -> Value { match key { "media" => { if said(text(row, "deleted_at")).is_some() { return Value::Null; } let parsed; let value = match row.get("media") { Some(Value::String(raw)) => { parsed = serde_json::from_str::(raw).unwrap_or(Value::Null); Some(&parsed) } other => other, }; let mut entries = media_out(ctx, value, &text(row, "workspace_id").unwrap_or_default()); // A shared contact with no file of its own: one entry that is // the card, by name. if entries.is_empty() { if let Some(name) = text(row, "body").as_deref().and_then(shared_contact) { entries.push(serde_json::json!({ "kind": "contact", "name": name })); } } if entries.is_empty() { Value::Null } else { Value::Array(entries) } } "reactions" => { let read = Read::of(row); if read.deleted_at.is_some() { return Value::Null; } if text(row,"channel").as_deref() == Some("instagram") { if let Some(reactions) = read.meta.source.as_ref().and_then(|source|source.instagram_reactions()) { let emojis: Vec<_> = reactions.iter().map(|reaction|reaction.emoji.clone()).collect(); return reaction_line(&emojis).map_or(Value::Null,Value::from); } } let id = text(row, "id").unwrap_or_default(); reads .reactions .get(&id) .and_then(|emojis| reaction_line(emojis)) .map_or(Value::Null, Value::from) } _ => Value::Null, } } /// `where kept`: a kept message is one with a `starred_at`. pub(super) fn kept( _ctx: &Ctx<'_>, _definition: &cotton_core::definitions::TableDefinition, condition: &Condition, ) -> Valid> { let wanted = match condition { Condition::Is(value) => value.as_bool().unwrap_or(false), Condition::OneOf(values) => values.iter().any(|value| value.as_bool() == Some(true)), Condition::Present(present) => *present, Condition::NoneOf(_) | Condition::Month(_) | Condition::WithinDays(_) | Condition::Bound(_) | Condition::On(_) => unreachable!("narrow refuses not, month, within_days and bounds before a table's own narrowing"), }; Ok(vec![if wanted { Filter::NotBlank("starred_at".to_string()) } else { Filter::Blank("starred_at".to_string()) }]) } /// `where channels`: the chats a message came into by that channel — a /// message's own `channel` (`whatsapp`, `sms`, `instagram`, …), the one /// `thread_extras` says in words as `channels`. Messages' WhatsApp, Texts /// and Instagram views read their chats by it. Each chat is asked whether it /// holds one (a probe of the thread's own messages), never every message. pub(super) fn by_channel( ctx: &Ctx<'_>, _definition: &cotton_core::definitions::TableDefinition, condition: &Condition, ) -> Valid> { let channels: Vec = match condition { Condition::Is(value) => value.as_str().map(str::to_string).into_iter().collect(), Condition::OneOf(values) => values.iter().filter_map(|value| value.as_str().map(str::to_string)).collect(), Condition::Present(_) => { return Err(crate::mcp::protocol::ToolFailure::new( "Chats are narrowed by a channel, not by whether one is known", )) } Condition::NoneOf(_) | Condition::Month(_) | Condition::WithinDays(_) | Condition::Bound(_) | Condition::On(_) => unreachable!("narrow refuses not, month, within_days and bounds before a table's own narrowing"), }; let mut ids: Vec = Vec::new(); if !channels.is_empty() { let holes = vec!["?"; channels.len()].join(", "); let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())]; params.extend(channels.into_iter().map(SqlValue::Text)); for row in ctx .read .driver() .all( &format!( "SELECT t.id AS id FROM cotton_msg_threads t WHERE t.workspace_id = ?1 \ AND EXISTS (SELECT 1 FROM cotton_msg_messages m WHERE m.thread_id = t.id AND m.channel IN ({holes}))" ), ¶ms, ) .map_err(super::sql_err)? { if let Some(id) = row.text("id") { ids.push(SqlValue::Text(id.to_string())); } } } Ok(vec![Filter::In("id".to_string(), ids)]) } /// `where member_people`: the chats a person is in — the dm with a contact /// of theirs, and every chat a contact of theirs has a seat in. pub(super) fn with_person( ctx: &Ctx<'_>, _definition: &cotton_core::definitions::TableDefinition, condition: &Condition, ) -> Valid> { let people: Vec = match condition { Condition::Is(value) => value.as_str().map(str::to_string).into_iter().collect(), Condition::OneOf(values) => values.iter().filter_map(|value| value.as_str().map(str::to_string)).collect(), Condition::Present(_) => { return Err(crate::mcp::protocol::ToolFailure::new( "Chats are narrowed by a person, not by whether one is known", )) } Condition::NoneOf(_) | Condition::Month(_) | Condition::WithinDays(_) | Condition::Bound(_) | Condition::On(_) => unreachable!("narrow refuses not, month, within_days and bounds before a table's own narrowing"), }; let contacts = ids_of( &in_chunks(&unique_ids(people), |batch| { rows( ctx, &Query::on("cotton_msg_contacts") .columns(&["id"]) .filter(Filter::In("person_id".to_string(), in_values(batch))), ) })?, "id", ); let mut ids = ids_of( &in_chunks(&contacts, |batch| { rows( ctx, &Query::on("cotton_msg_threads") .columns(&["id"]) .filter(Filter::In("contact_id".to_string(), in_values(batch))), ) })?, "id", ); ids.extend(ids_of( &in_chunks(&contacts, |batch| { rows( ctx, &Query::on("cotton_msg_thread_participants") .columns(&["thread_id"]) .filter(Filter::In("contact_id".to_string(), in_values(batch))), ) })?, "thread_id", )); Ok(vec![Filter::In( "id".to_string(), unique_ids(ids).into_iter().map(SqlValue::Text).collect(), )]) } /// How many of a word's best message hits name their chats: a word said in /// more messages than this still finds the chats of its best hits. const MESSAGE_HITS: i64 = 10_000; /// The chats a search for `words` finds: by title, by a contact's name or /// number, by a member's name, by what a message in it says — every word /// somewhere among them. pub(super) fn thread_search(ctx: &Ctx<'_>, words: &str) -> Valid { let mut found: Option> = None; for word in words.split_whitespace() { let pattern = format!("%{}%", word.replace(['%', '_'], "")); let mut ids = ids_of( &rows( ctx, &Query::on("cotton_msg_threads") .columns(&["id"]) .filter(Filter::Like("title".to_string(), pattern.clone())), )?, "id", ); let mut contacts: Vec = Vec::new(); for column in ["display_name", "phone_e164"] { contacts.extend(ids_of( &rows( ctx, &Query::on("cotton_msg_contacts") .columns(&["id"]) .filter(Filter::Like(column.to_string(), pattern.clone())), )?, "id", )); } ids.extend(ids_of( &in_chunks(&unique_ids(contacts), |batch| { rows( ctx, &Query::on("cotton_msg_threads") .columns(&["id"]) .filter(Filter::In("contact_id".to_string(), in_values(batch))), ) })?, "id", )); ids.extend(ids_of( &rows( ctx, &Query::on("cotton_msg_thread_participants") .columns(&["thread_id"]) .filter(Filter::Like("display_name".to_string(), pattern)), )?, "thread_id", )); // The words of its messages, off the search index — a deleted one // says nothing, so it finds nothing. let said: Vec = cotton_store::search::search_all( ctx.read.driver(), word, Some(&["cotton_msg_messages".to_string()][..]), Some(MESSAGE_HITS), ) .map_err(super::sql_err)? .into_iter() .map(|hit| hit.row_id) .collect(); ids.extend(ids_of( &in_chunks(&said, |batch| { rows( ctx, &Query::on("cotton_msg_messages") .columns(&["thread_id"]) .filter(Filter::In("id".to_string(), in_values(batch))) .filter(Filter::IsNull("deleted_at".to_string())), ) })?, "thread_id", )); let ids = unique_ids(ids); found = Some(match found { Some(before) => before.into_iter().filter(|id| ids.contains(id)).collect(), None => ids, }); } Ok(Filter::In( "id".to_string(), found.unwrap_or_default().into_iter().map(SqlValue::Text).collect(), )) } #[cfg(test)] mod share_tests { use super::*; /// RULE: Resolving a media-info URL does not make a message's video available; its typed display status stays pending until an attachment entry exists. #[test] fn shared_media_status_stays_pending_until_media_is_attached() { for (media, expected) in [ (serde_json::json!([]), "pending"), (serde_json::json!([{"key":"synthetic/messages/video.mp4","contentType":"video/mp4"}]), "available"), ] { let row = serde_json::json!({"body":"An invented forward","media":media,"meta":{ "share":{"media_id":"64","author":null,"caption":null,"status":"available"} }}).as_object().unwrap().clone(); let mut data = Data::new(); message_extras(&row, &ChatReads::default(), &mut data); assert_eq!(data["shared_status"], expected); assert_eq!(row["meta"]["share"]["status"], "available", "display must not rewrite the durable resolution fact"); } } /// RULE: Shared media remains typed author/caption/status/link columns; the engine never invents an unavailable-message sentence. #[test] fn shared_media_facts_are_columns() { let row = serde_json::json!({"body":"A person's own words", "meta":{ "link":"https://www.instagram.com/reel/Invented/", "share":{"media_id":"9001","author":{"handle":"mira.example","display_name":"Mira Example"},"caption":"A reel caption","status":"unavailable"} }}).as_object().unwrap().clone(); let mut data=Data::new(); message_extras(&row,&ChatReads::default(),&mut data); assert_eq!(data["shared_author"],"Mira Example"); assert_eq!(data["shared_caption"],"A reel caption"); assert_eq!(data["shared_status"],"unavailable"); assert_eq!(data["shared_link"],"https://www.instagram.com/reel/Invented/"); let mut deleted=row;deleted.insert("deleted_at".into(),Value::from("2026-10-15T00:00:00.000Z")); let mut data=Data::new();message_extras(&deleted,&ChatReads::default(),&mut data); assert!(!data.contains_key("shared_caption")); } }