//! The reads behind people's traffic and money — sub-step 4g. //! //! Thirteen screens' answers live here (money, calls, email and the phone's own //! disk); the chat and picture halves are below them in this same file. Every //! one is either a [`crate::phone::reads::ReadSource::Composed`] — several tool //! handlers plus a join, over the SAME `Ctx` an assistant's call runs on — or a //! [`crate::phone::reads::ReadSource::Query`] over the replica's driver where //! the question is one nothing in the catalogue asks. //! //! Money pages use the generic records verbs and shared Rust engine views. //! //! `read.thread`'s messages carry each `media[]` entry worded: `kind` always, //! what the attachment is (`image`, `video`, `audio`, `voice`, `file`, //! `contact` — the stored kind, else the content type's, by //! `messages::preview::media_kind_of`), and `length` on audio, voice and video //! that know their `durationMs`: the playback length as `m:ss`, `h:mm:ss` past //! an hour (`messages::preview::format_duration`). use std::collections::{BTreeMap, BTreeSet}; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use crate::shell::file::ReadFile; use cotton_tools::mcp::dispatch::{handler_for, Ctx}; use cotton_tools::mcp::handlers::common::now_iso; use cotton_tools::mcp::handlers::media_tools; /// Every tool a composed read is allowed to reach, declared ONCE. /// /// **This list exists so a static guard can check the scopes.** A composed body /// calls `handler_for` directly and so bypasses `call_tool`'s own scope gate; /// `reads_tests.rs` sweeps `ReadSource::Tool` against the catalogue but cannot /// see inside a `Composed` body, which left the names below unchecked — a hole /// rather than an open door (the runtime backstop is real: `read_rows` rolls /// back and refuses the moment a body writes an op), and a hole is what a /// guard is for. `a_composed_read_only_ever_reaches_read_tools` walks this /// list, and `tool` refuses a name that is not on it, so adding a call without /// adding the name here is a refusal with the name in it rather than a silent /// widening. pub(crate) const COMPOSED_TOOLS: &[&str] = &[ "get_album", "get_photo", "get_record", "list_albums", "list_calls", "list_duplicates", "list_blocked_senders", "list_email_senders", "list_email_threads", "list_message_threads", "read_email_thread", "get_video", "read_message_thread", "search_messages", ]; /// Run another tool over the context this read already holds. /// /// The one way from a composed read to the catalogue — from ANY module's, not /// only this one's: `record_thread` reaches `get_record` through here so that /// `a_composed_read_only_ever_reaches_read_tools` keeps checking one list. A /// second entry point with a second list is a second thing to forget. It is `handler_for` /// rather than an import of the function because that is the table /// `reads_tests.rs` can check a name against — a renamed tool is a refusal with /// the name in it here, and a compile error there. /// /// **Every non-test source in `src/phone/` is swept for calls to this /// function** (`reads_tests::every_tool_a_composed_body_names_is_on_the_declared_list`, /// which reads the directory rather than a list of files), so a composed body /// in a new module is covered the day it is written. pub(crate) fn tool( ctx: &mut Ctx<'_>, name: &str, args: &Map, ) -> Result { if !COMPOSED_TOOLS.contains(&name) { return Err(format!( "{name} is not on `traffic::COMPOSED_TOOLS` — a composed read reaches the catalogue only through that list, which is what lets a guard check its scopes" )); } let handler = handler_for(name).ok_or_else(|| format!("{name} is not implemented on this build"))?; handler(ctx, args).map_err(|failure| failure.to_string()) } /// `{"key": value}` as a tool's arguments, without a `json!` object dance at /// every call site. fn args_of(pairs: &[(&str, Value)]) -> Map { pairs .iter() .map(|(key, value)| ((*key).to_string(), value.clone())) .collect() } fn text_arg(args: &Map, key: &str) -> Option { args.get(key) .and_then(Value::as_str) .map(str::trim) .filter(|value| !value.is_empty()) .map(str::to_string) } fn required(args: &Map, key: &str, what: &str) -> Result { text_arg(args, key).ok_or_else(|| format!("`{key}` is {what}")) } // ── calls ─────────────────────────────────────────────────────────────────── /// `/calls/history` — the PHONE's call log, which is a different thing from /// Cotton's own. /// /// A thin composition over `list_calls` for ONE reason: the limit. The screen /// asks for two hundred and does not paginate, where the tool's own default is /// fifty — so a read that simply forwarded the screen's arguments would drop /// the older three quarters of a person's log and look like an empty history /// rather than a truncated one. Two hundred is also the tool's maximum, so /// this is the whole of what the catalogue can answer. pub fn call_log(ctx: &mut Ctx<'_>, args: &Map) -> Result { let mut tool_args = args_of(&[("limit", Value::from(cotton_tools::mcp::handlers::common::WHOLE_SET))]); // `?person=` — the log filtered to one human, which the screen reaches from // a person's own page. if let Some(person) = text_arg(args, "personId") { tool_args.insert("personId".to_string(), Value::from(person)); } let mut answer = tool(ctx, "list_calls", &tool_args)?; // The person's photograph KEY, for the call strip's print (`pictures.rs`). crate::phone::pictures::stamp_calls(ctx, &mut answer)?; Ok(answer) } // ── email ─────────────────────────────────────────────────────────────────── /// `/email` — the folder, both ways round. /// /// The screen has one segment control and TWO lists behind it — threads, and /// the same folder grouped by sender — and switching between them is a local /// flip, not a new screen. So both come back together: the sender list is a /// count over the same rows the thread list already read, and asking for it /// separately would read the mailbox twice. pub fn email(ctx: &mut Ctx<'_>, args: &Map) -> Result { let folder = text_arg(args, "folder").unwrap_or_else(|| "inbox".to_string()); let mut thread_args = args_of(&[("folder", Value::from(folder.clone()))]); if let Some(sender) = text_arg(args, "sender") { thread_args.insert("sender".to_string(), Value::from(sender)); } // Both ceilings are the tools' maxima, and both are stated rather than // taken by default. The mailbox screen is unbounded — it has no limit // control at all — so the DEFAULTS (fifty threads, twenty senders) would // quietly hide the older end of a real mailbox, which is the shape of loss // that reads as "my old mail is gone" rather than as a page that stopped // early. thread_args.insert("limit".to_string(), Value::from(cotton_tools::mcp::handlers::common::WHOLE_SET)); // THE PROJECT SCOPE goes INTO the thread query (`phone/scope.rs`): the // tool caps its conversations at 500 before it orders them, so narrowing // its answer afterwards could lose a linked thread past the cap. The same // handler, handed the member ids — still a read, still one implementation. let threads = match crate::phone::scope::handed_record_ids(args) { None => tool(ctx, "list_email_threads", &thread_args)?, Some(within) => cotton_tools::mcp::handlers::emails::read::list_email_threads_within( ctx, &thread_args, Some(&within), ) .map_err(|failure| failure.to_string())?, }; let senders = tool( ctx, "list_email_senders", &args_of(&[ ("folder", Value::from(folder.clone())), ("limit", Value::from(cotton_tools::mcp::handlers::common::WHOLE_SET)), ]), )?; let blocked = tool(ctx, "list_blocked_senders", &Map::new())?; let mut threads = threads.get("threads").cloned().unwrap_or(Value::Array(Vec::new())); attach_thread_previews(ctx, &mut threads)?; Ok(json!({ "folder": folder, "threads": threads, "senders": senders.get("senders").cloned().unwrap_or(Value::Array(Vec::new())), "blockedSenders": blocked.get("blocked").cloned().unwrap_or(Value::Array(Vec::new())), })) } /// The most a mailbox row's preview carries. One line on a phone is well under /// it; the rest is the screen's to truncate, never the read's to guess. const EMAIL_PREVIEW_CHARS: usize = 160; /// Each listed thread gains `preview` — the start of its LATEST message, the /// line a mail client prints under the subject. /// /// The phone's read and not the tool's: `list_email_threads` is the assistant's /// verb and answers facts about a conversation, and a teaser line is a drawing /// decision. One seek per thread on `idx_cotton_emails_thread_sent`, and the /// body is cut in SQL so a 64k newsletter never crosses to be thrown away. /// A thread whose newest message says nothing has no `preview` key at all. fn attach_thread_previews(ctx: &Ctx<'_>, threads: &mut Value) -> Result<(), String> { let Some(rows) = threads.as_array_mut() else { return Ok(()); }; let workspace = SqlValue::Text(ctx.workspace_id.to_string()); for thread in rows.iter_mut() { let Some(id) = thread.get("id").and_then(Value::as_str).map(str::to_string) else { continue; }; let latest = ctx .db() .all( "SELECT snippet, substr(body, 1, 600) AS body FROM cotton_emails WHERE workspace_id = ? AND thread_id = ? ORDER BY sent_at DESC, id DESC LIMIT 1", &[workspace.clone(), SqlValue::Text(id)], ) .map_err(|error| error.to_string())?; let preview = latest .first() .and_then(|row| email_preview(row.text("snippet"), row.text("body"))); if let (Some(preview), Some(object)) = (preview, thread.as_object_mut()) { object.insert("preview".to_string(), Value::from(preview)); } } Ok(()) } /// One line of what a message says: the provider's snippet when it has one, /// else the body, whitespace collapsed and cut at a character boundary with an /// ellipsis. `None` when both are blank — a row with nothing to say draws no /// line rather than an empty one. pub(crate) fn email_preview(snippet: Option<&str>, body: Option<&str>) -> Option { let source = [snippet, body] .into_iter() .flatten() .find(|text| !text.trim().is_empty())?; let collapsed = source.split_whitespace().collect::>().join(" "); if collapsed.chars().count() <= EMAIL_PREVIEW_CHARS { return Some(collapsed); } let cut: String = collapsed.chars().take(EMAIL_PREVIEW_CHARS).collect(); Some(format!("{}\u{2026}", cut.trim_end())) } /// The owner's own addresses, as far as this file can say: every Google /// account connected to it, and every mailbox a message in THIS thread was /// imported from (an account since disconnected still wrote its mail). /// Lowercased and de-duplicated, in a stable order. /// /// The reader uses it to tell the owner's letters from everyone else's. It is /// an answer rather than a guess from names: "Asha" in a from line is a /// display name anyone can set, and an address the owner's own mailbox /// imported is not. fn own_email_addresses(ctx: &Ctx<'_>, thread_id: &str) -> Result, String> { cotton_tools::mcp::handlers::emails::shared::own_email_addresses(ctx,thread_id).map_err(|e|e.to_string()) } /// `/email/[id]` — one thread, whole. /// /// `emailsService.readThread` reads the WHOLE conversation and /// `read_email_thread` answers at most fifty messages a call. On a page whose /// entire job is the record of a correspondence, being short by default and /// silent about it is the worst possible way to be short — so the pages are /// walked with the tool's own `nextBefore` handle, the same shape the chat /// window uses and for the same reason. pub fn email_thread(ctx: &mut Ctx<'_>, args: &Map) -> Result { let thread_id = required(args, "threadId", "the thread to read")?; let mut emails: Vec = Vec::new(); let mut answer: Option = None; let mut cursor: Option<(String, String)> = None; // Whether the walk STOPPED because there was nothing older, rather than // because it hit the page ceiling below. The handle in the answer depends // on it: a spent handle is null, a truncated one is the last cursor. let mut reached_the_beginning = false; // A ceiling on the WALK, not on the conversation: a correspondence of ten // thousand messages would otherwise read the whole of it to draw a screen, // and this is the one place a runaway loop could cost a person their // battery rather than a row. for _ in 0..EMAIL_THREAD_PAGES { let mut page_args = args_of(&[ ("threadId", Value::from(thread_id.clone())), ("limit", Value::from(EMAIL_TOOL_PAGE)), ]); if let Some((before, before_id)) = &cursor { page_args.insert("before".to_string(), Value::from(before.clone())); // BOTH halves. A bare instant cursor with a strict `<` drops every // message that shares the boundary instant with the row the page // stopped on — sixty imported emails all stamped to the same // second read fifty and then nothing, under a header saying sixty. page_args.insert("beforeId".to_string(), Value::from(before_id.clone())); } // EVERY PAGE RE-RUNS THE HEADER. `read_email_thread` answers the // thread row, its participants and its counts beside the messages, and // this walk discards all but the first page's. Fixing that needs a // messages-only argument on the tool — an assistant-facing change this // read does not own — so it is a cost, not a defect, and it is written // down here rather than left to be found. let page = tool(ctx, "read_email_thread", &page_args)?; let mut rows = page .get("emails") .and_then(Value::as_array) .cloned() .unwrap_or_default(); // Each page is older than the one before, so it goes in FRONT and the // conversation still reads oldest to newest exactly once. rows.append(&mut emails); emails = rows; let next = page .get("nextBefore") .and_then(Value::as_str) .map(str::to_string) .zip( page.get("nextBeforeId") .and_then(Value::as_str) .map(str::to_string), ); if answer.is_none() { answer = Some(page); } match next { Some(next) => cursor = Some(next), None => { reached_the_beginning = true; break; } } } let Some(Value::Object(mut out)) = answer else { return Err("the thread answered nothing at all".to_string()); }; // **The header is folded over the ASSEMBLED conversation, not over page // one.** `read_email_thread` folds `unread` / `starred` / `inInbox` over // the page it read, and `emailsService.readThread` folds them over every // message there is. A sixty-email correspondence whose one unread message // is the third would otherwise read `unread: false` in the header while // `list_email_threads` — which folds over all of them — draws the dot; the // reader's `markReadOnce` is gated on that header and would never fire, so // the dot stayed on the mailbox row every time the person opened it. fold_email_header(&mut out, &emails); if reached_the_beginning { // The handle is spent: this read walked it to the end, and leaving it // in the answer would offer a screen a page that is already drawn. out.insert("nextBefore".to_string(), Value::Null); out.insert("nextBeforeId".to_string(), Value::Null); } else if let Some((before, before_id)) = cursor { // The ceiling stopped the walk, not the conversation. Answering null // here would tell a screen the whole correspondence is drawn when its // oldest two thousand are missing, so the LAST cursor rides out // instead — the truncation itself is in the ledger. out.insert("nextBefore".to_string(), Value::from(before)); out.insert("nextBeforeId".to_string(), Value::from(before_id)); } // **Where the thread opens.** A search hit names the message that said // the words (`at`); the reader is addressed by thread, so the anchor rides // beside the conversation and the screen opens at it. Null when nothing // was asked or the message is not in this thread — the reader then opens // at the newest, as it always has. let open_at = args .get("at") .and_then(Value::as_str) .filter(|at| emails.iter().any(|email| email.get("id").and_then(Value::as_str) == Some(*at))) .map(Value::from) .unwrap_or(Value::Null); out.insert("openAt".to_string(), open_at); out.insert("emails".to_string(), Value::Array(emails)); out.insert( "ownAddresses".to_string(), Value::from(own_email_addresses(ctx, &thread_id)?), ); Ok(Value::Object(out)) } /// Fold `unread` / `starred` / `inInbox` over every message in the thread. /// /// The tool's own rule, said over the whole conversation rather than over one /// page: a thread is unread if ANY message in it is, starred if any is, and in /// the inbox if any is. `trashedAt` is deliberately untouched — it comes from /// the THREAD's own column, which no fold over messages can know better. fn fold_email_header(out: &mut Map, emails: &[Value]) { let Some(Value::Object(header)) = out.get_mut("thread") else { return; }; let any = |field: &str| { emails.iter().any(|email| { email .get(field) .and_then(Value::as_bool) .unwrap_or(false) }) }; header.insert("unread".to_string(), Value::Bool(any("unread"))); header.insert("starred".to_string(), Value::Bool(any("starred"))); header.insert("inInbox".to_string(), Value::Bool(any("inInbox"))); } /// The most one call to `read_email_thread` answers, and how many of those a /// single read will walk. const EMAIL_TOOL_PAGE: i64 = 50; const EMAIL_THREAD_PAGES: usize = 40; /// `/messages`' search pill — what a person typed, over their own words. /// /// Not a read of its own: the pill is ON `/messages`, and a screen with two /// reads is two answers to one question, so [`threads`] answers it when asked /// with a `query`. /// /// A composition of one tool, for the ceiling: `search_messages` /// defaults to twenty hits where the screen shows thirty at a time and keeps /// going. Fifty is the tool's maximum and the most this read can answer — a /// search with more hits than that loses its tail, and the ledger says so, /// because `search_messages` has no cursor argument to page with the way /// `read_message_thread` does. fn message_search(ctx: &mut Ctx<'_>, args: &Map) -> Result { let query = required(args, "query", "what to search for")?; let tool_args = args_of(&[ ("query", Value::from(query)), ("limit", Value::from(cotton_tools::mcp::handlers::common::WHOLE_SET)), ]); tool(ctx, "search_messages", &tool_args) } // ── this phone's own disk ─────────────────────────────────────────────────── /// One object this device is holding, as `/storage` reads it. /// /// `toStorageEntry`, ported: the ledger is the spine and every other table is a /// LEFT JOIN onto it, so an orphan — bytes a delete left behind, with no row /// pointing at them — is counted rather than invisible, which is the whole /// reason this screen reads the ledger instead of walking the record tables. /// /// **An object is counted ONCE.** A chat photo's `cotton_photos.key` IS the /// message's key (nothing is copied), so a naive join matches the same bytes /// twice and tells a person their phone holds double what it does. The kind is /// resolved in ONE ordered expression and the row is emitted once. pub fn media_ledger_entries(replica: &ReadFile<'_>) -> Result, String> { let workspace = SqlValue::Text(replica.workspace_id.to_string()); // The two reserved key folders are both NINE characters at the offset the // tail already assumes — `messages/` and `meetings/` — which is what lets // one offset serve both. `substr` is 1-based, so `length(?1) + 1` is the // separating `/` and `length(?1) + 2` is the folder's first letter: the // leading slash is already skipped, and asking for ten characters there // yields `messages/t` and matches nothing. let rows = replica .driver .all( "WITH ledger AS ( SELECT m.key AS key, m.size_bytes AS size_bytes, m.content_type AS content_type, m.created_at AS ledger_at, CASE WHEN substr(m.key, length(?1) + 2, 9) = 'messages/' THEN substr(m.key, length(?1) + 11) END AS message_tail, CASE WHEN substr(m.key, length(?1) + 2, 9) = 'meetings/' THEN substr(m.key, length(?1) + 11) END AS meeting_tail FROM _media m WHERE m.workspace_id = ?1 AND m.local_path IS NOT NULL AND m.state <> 'delete_pending' ) SELECT l.key AS key, l.size_bytes AS size_bytes, l.content_type AS content_type, l.ledger_at AS ledger_at, p.id AS photo_id, p.caption AS photo_caption, p.review_note AS photo_note, p.review_by AS photo_by, p.taken_at AS photo_at, v.id AS video_id, v.caption AS video_caption, v.review_note AS video_note, v.review_by AS video_by, v.taken_at AS video_at, d.id AS document_id, d.title AS document_title, d.original_name AS document_name, d.created_at AS document_at, g.id AS meeting_id, g.title AS meeting_title, g.started_at AS meeting_at, l.message_tail AS message_tail, l.meeting_tail AS meeting_tail FROM ledger l LEFT JOIN cotton_photos p ON p.workspace_id = ?1 AND p.key = l.key LEFT JOIN cotton_videos v ON v.workspace_id = ?1 AND (v.key = l.key OR v.poster_key = l.key) LEFT JOIN cotton_documents d ON d.workspace_id = ?1 AND (d.storage_path = l.key OR d.decrypted_path = l.key) LEFT JOIN cotton_meetings g ON g.workspace_id = ?1 AND l.meeting_tail IS NOT NULL AND g.id = substr(l.meeting_tail, 1, instr(l.meeting_tail, '/') - 1) ORDER BY l.key ASC", std::slice::from_ref(&workspace), ) .map_err(|error| error.to_string())?; // The earliest sighting that names a thread is the chat a picture's bytes // are charged to — one chat per row, so the by-chat list adds up to the // total. let mut thread_of_record: BTreeMap = BTreeMap::new(); for row in replica .driver .all( "SELECT record_id, thread_id FROM cotton_media_sightings WHERE workspace_id = ? AND thread_id IS NOT NULL ORDER BY seen_at ASC, id ASC", std::slice::from_ref(&workspace), ) .map_err(|error| error.to_string())? .iter() { let (Some(record), Some(thread)) = (row.text("record_id"), row.text("thread_id")) else { continue; }; thread_of_record .entry(record.to_string()) .or_insert_with(|| thread.to_string()); } let mut thread_names: BTreeMap = BTreeMap::new(); for row in replica .driver .all( "SELECT t.id AS id, t.title AS title, k.display_name AS display_name FROM cotton_msg_threads t LEFT JOIN cotton_msg_contacts k ON k.id = t.contact_id WHERE t.workspace_id = ?", std::slice::from_ref(&workspace), ) .map_err(|error| error.to_string())? .iter() { let Some(id) = row.text("id") else { continue }; // The chat's own title, else the person on the other end of a DM. if let Some(name) = row.text("title").or_else(|| row.text("display_name")) { thread_names.insert(id.to_string(), name.to_string()); } } let mut entries: Vec = Vec::with_capacity(rows.len()); for row in &rows { let key = row.text("key").unwrap_or_default().to_string(); let record_id = row .text("photo_id") .or_else(|| row.text("video_id")) .or_else(|| row.text("document_id")) .or_else(|| row.text("meeting_id")) .map(str::to_string); let kind = storage_kind(row); // The chat: the sighting first, then the key's own folder — a message // attachment's key IS `{ws}/messages/{threadId}/{sha}.{ext}`, and // asking every message's media array instead is keys × messages. let thread_id = record_id .as_ref() .and_then(|id| thread_of_record.get(id).cloned()) .or_else(|| { row.text("message_tail").and_then(|tail| { tail.split_once('/') .map(|(thread, _)| thread.to_string()) .filter(|thread| !thread.is_empty()) }) }); entries.push(json!({ "key": key, "sizeBytes": row.int("size_bytes").unwrap_or(0), "kind": kind, "recordId": record_id, "title": row .text("photo_caption") .or_else(|| row.text("video_caption")) .or_else(|| row.text("document_title")) .or_else(|| row.text("document_name")) .or_else(|| row.text("meeting_title")), "threadId": thread_id.clone(), "threadName": thread_id.and_then(|id| thread_names.get(&id).cloned()), "reviewNote": row.text("photo_note").or_else(|| row.text("video_note")), "reviewBy": row.text("photo_by").or_else(|| row.text("video_by")), // The ledger's own stamp is LAST on purpose: an orphan has no // record to date it, and "when this phone first held these bytes" // is the only true thing left to say about one. "at": row .text("photo_at") .or_else(|| row.text("video_at")) .or_else(|| row.text("meeting_at")) .or_else(|| row.text("document_at")) .or_else(|| row.text("ledger_at")), })); } Ok(entries) } /// `kindOf`, ported — and the RECORD outranks the MIME type. /// /// A photographed bank statement is `image/jpeg` and is a DOCUMENT; reading it /// as a photo would put a person's papers in their picture-grid total. The /// final `other` is not a defect and is not hidden: bytes nothing points at are /// exactly what a person opening this screen wants to see. fn storage_kind(row: &cotton_store::driver::Row) -> &'static str { if row.text("photo_id").is_some() { return "photos"; } if row.text("video_id").is_some() { return "videos"; } if row.text("document_id").is_some() { return "documents"; } if row.text("meeting_id").is_some() { return "audio"; } let mime = row.text("content_type").unwrap_or_default().to_lowercase(); if mime.starts_with("image/") { return "photos"; } if mime.starts_with("video/") { return "videos"; } if mime.starts_with("audio/") { return "audio"; } if mime == "application/pdf" { return "documents"; } "other" } // ── the pictures ──────────────────────────────────────────────────────────── /// The whole library, and everything the grid's header offers to review. /// /// **`list_photos` cannot answer this screen, for two reasons that are both in /// the tool's own argument list.** It caps at two hundred, and the grid IS /// the library — a person with forty thousand pictures would be shown two /// hundred of them with nothing anywhere saying so; and it does not expose the /// `copies` filter at all, where the grid hides a picture the person has already /// agreed is a copy. So the rows come from `list_media_rows` — the SAME filter /// compiler, the same `media_out`, the same project and people joins the tool /// uses, with the two settings its arguments do not reach. /// /// **A copy is FILTERED, never deleted.** The row and its bytes stay until the /// person removes them from the picture's own page; the grid simply stops /// showing them twice. /// /// The three header pieces ride along because the screen draws them above the /// first tile: the albums strip, and the two review rows' counts. Each is /// deliberately OUTSIDE the grid's own read state in the app — a strip that /// could not be read hides itself and the pictures still draw — so **a header /// piece that refuses is SWALLOWED into its own empty field rather than /// failing the read**. The `?` those three carried until 4g's review meant a /// person with forty thousand pictures saw "Your photos could not be read" and /// no tiles at all because the duplicate pass had a bad row in it. The GRID is /// the screen; the header is what sits above it. /// /// **The videos ride in the same answer, because it is one library.** `/photos` /// draws pictures and films in the same month bands (the redesign's merge of /// the two screens), so the films are read here beside the pictures rather than /// by a second read the screen would have to keep in step. They are the /// library as much as the pictures are, so a refusal fails the read the same /// way — never swallowed into an empty list that would say "no videos" to /// somebody who has them. No `copies` filter on them: the duplicate pass looks /// at pictures. The two lists come back apart and the app interleaves them by /// `takenAt`, keeping each list's own order. pub fn photos(ctx: &mut Ctx<'_>, _args: &Map) -> Result { // The two reads that ARE the screen. These `?`s stay. let listed = media_rows(ctx, media_tools::PHOTO_SPEC, library_filters(Some(false)))?; let films = media_rows(ctx, media_tools::VIDEO_SPEC, library_filters(None))?; let album_rows = album_strip(ctx).unwrap_or_else(|_| Value::Array(Vec::new())); let duplicates = tool( ctx, "list_duplicates", &args_of(&[("state", Value::from("open")), ("limit", Value::from(cotton_tools::mcp::handlers::common::WHOLE_SET))]), ) .map(|found| duplicate_groups(&found)) .unwrap_or_default(); Ok(json!({ "photos": listed, "videos": films, "albums": album_rows, "duplicates": duplicates, "faceSuggestions": face_suggestion_rows(ctx).map_or(0, |rows| rows.len()), })) } /// The albums strip above the first tile, covers attached. /// /// Its own function so the whole strip — the list AND the covers — is one /// thing to swallow: half a strip is worse than none, since a card with no /// cover is a card that looks broken rather than absent. fn album_strip(ctx: &mut Ctx<'_>) -> Result { let mut albums = tool( ctx, "list_albums", &args_of(&[("limit", Value::from(cotton_tools::mcp::handlers::common::WHOLE_SET))]), )?; // The strip on `/photos` draws the same card the albums page does, so it // needs the same cover — see `attach_album_covers`. let mut album_rows = albums .get_mut("albums") .map(Value::take) .unwrap_or_else(|| Value::Array(Vec::new())); attach_album_covers(ctx, &mut album_rows)?; Ok(album_rows) } /// The whole library, newest first — no ceiling, by design. /// /// `pub(crate)` so the tests can assert the ABSENCE of a ceiling against the /// filter itself: a seeded fixture holds two pictures, and two rows come back /// two under any ceiling this could grow, so an assertion on the answer would /// go on passing the day somebody paged the grid. pub(crate) fn library_filters(copies: Option) -> media_tools::MediaListFilters { media_tools::MediaListFilters { copies, limit: None, ..Default::default() } } /// One media list, as the tool shapes it — plus the three fields a RENDERER /// needs and an assistant is deliberately not given. /// /// `media_out` is the assistant's row: it carries what a picture IS and never /// where its bytes are, because an assistant asks for bytes through /// `get_photo_bytes` and has no use for an object key. A tile has nothing else /// to draw with. So the key, the inline blur and (for a video) the poster's key /// are read here and merged onto the tool's own row — added beside it, never /// instead of it, so the record an assistant reads and the record a person taps /// stay one shape with one extra corner. fn media_rows( ctx: &mut Ctx<'_>, spec: media_tools::MediaKindSpec, filters: media_tools::MediaListFilters, ) -> Result { let noun = spec.noun; let answer = media_tools::list_media_rows(ctx, spec, &filters).map_err(|failure| failure.to_string())?; let mut rows: Vec = answer .get(format!("{noun}s")) .and_then(Value::as_array) .cloned() .unwrap_or_default(); // The ids already in hand, never `filters.ids`: with no filter that is // `None`, and `drawing_fields` would then re-scan the whole library beside // the scan `list_media_rows` just paid for. let drawn: Vec = rows .iter() .filter_map(|row| row.get("id").and_then(Value::as_str).map(str::to_string)) .collect(); let bytes = drawing_fields(ctx, spec, Some(&drawn))?; for row in &mut rows { let Some(object) = row.as_object_mut() else { continue; }; let id = object .get("id") .and_then(Value::as_str) .unwrap_or_default() .to_string(); if let Some(fields) = bytes.get(&id) { for (key, value) in fields { object.insert(key.clone(), value.clone()); } } } Ok(Value::Array(rows)) } /// Every row's key, blur and poster key, by id, in one pass. /// /// A video's tile resolves its POSTER and never the film: a grid pointed at the /// film would pull down half a gigabyte to draw twelve squares, when a video's /// bytes are meant to hydrate on first view. Until a poster exists the tile /// draws the blur and then a play glyph on quiet ground — the honest state, not /// a failure — which is why a null `posterKey` is answered rather than hidden. fn drawing_fields( ctx: &Ctx<'_>, spec: media_tools::MediaKindSpec, only: Option<&[String]>, ) -> Result>, String> { let poster = if spec.kind == "video" { ", poster_key" } else { "" }; let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())]; // The grid asks for the whole library and this is one scan of three // columns; a page that named its ids — a duplicate pair, a face's picture — // must not pay for that scan to draw two tiles. let narrow = match only { Some(ids) if !ids.is_empty() => { let holes = vec!["?"; ids.len()].join(","); for id in ids { params.push(SqlValue::Text(id.clone())); } format!(" AND id IN ({holes})") } _ => String::new(), }; let sql = format!( "SELECT id, key, preview{poster} FROM {} WHERE workspace_id = ?{narrow}", spec.table ); let mut out: BTreeMap> = BTreeMap::new(); for row in ctx .db() .all(&sql, ¶ms) .map_err(|error| error.to_string())? .iter() { let Some(id) = row.text("id") else { continue }; let mut fields = Map::new(); fields.insert("key".to_string(), json!(row.text("key"))); fields.insert("preview".to_string(), json!(row.text("preview"))); if spec.kind == "video" { fields.insert("posterKey".to_string(), json!(row.text("poster_key"))); } out.insert(id.to_string(), fields); } Ok(out) } /// How many GROUPS are waiting to be decided — the number the review row /// states. /// /// Groups, not pairs, and the distinction is the copy: `ReviewRows`' own /// comment reads *"groups the Mac proposes, decided at /photos/duplicates"*, /// and the screen counts `duplicates.data.length` over a list of groups. One /// picture with three look-alikes is ONE thing to decide, and saying "3" over /// it would send a person to a page with one card on it. fn duplicate_groups(answer: &Value) -> usize { answer .get("groups") .and_then(Value::as_array) .map_or(0, Vec::len) } /// `/photos/album/[id]` — the album, and enough of each member to DRAW it. /// /// `get_album` answers the album and its membership, and a member is /// `{id, kind, addedBy, sortAt}` — which says WHICH picture is in the album and /// nothing a grid can paint with. That is right for the tool: an assistant asks /// for bytes another way. It is useless for the page, which is a grid of /// tiles, so every tile drew empty and the album looked like a list of nothing. /// /// So the tool's answer is taken whole and the drawing fields are merged onto /// each member, exactly as `media_rows` merges them for the library's own grid /// — narrowed to the ids this album actually names, so a page of twelve /// pictures pays for twelve rows. Both kinds are asked for, because an album /// holds films as well as pictures and a film's tile resolves its POSTER. /// /// The cover rides the same way. `coverId` is a bare id in the tool's answer; /// `cover` is added beside it — the same three fields, for the one picture the /// album's header paints — rather than making the screen hunt for that id in /// the member list, which fails exactly when the cover is a picture the album /// no longer holds. pub fn album(ctx: &mut Ctx<'_>, args: &Map) -> Result { let id = required(args, "id", "the album to read")?; let mut answer = tool(ctx, "get_album", &args_of(&[("id", Value::from(id))]))?; let members: Vec<(String, String)> = answer .get("items") .and_then(Value::as_array) .map(|items| { items .iter() .filter_map(|item| { Some(( item.get("id").and_then(Value::as_str)?.to_string(), item.get("kind") .and_then(Value::as_str) .unwrap_or("photo") .to_string(), )) }) .collect() }) .unwrap_or_default(); // The cover is asked for with the members, so it costs no extra query even // when it is a picture the album has since dropped. let cover_id = answer .get("coverId") .and_then(Value::as_str) .map(str::to_string); let mut drawing: BTreeMap> = BTreeMap::new(); for spec in [media_tools::PHOTO_SPEC, media_tools::VIDEO_SPEC] { let mut wanted: Vec = members .iter() .filter(|(_, kind)| kind == spec.kind) .map(|(id, _)| id.clone()) .collect(); // A cover's kind is not stated anywhere, so it is asked of both tables; // the one that does not hold it simply answers nothing for that id. if let Some(cover) = &cover_id { wanted.push(cover.clone()); } if wanted.is_empty() { continue; } drawing.extend(drawing_fields(ctx, spec, Some(&wanted))?); } if let Some(items) = answer.get_mut("items").and_then(Value::as_array_mut) { for item in items.iter_mut() { let Some(object) = item.as_object_mut() else { continue; }; let Some(id) = object.get("id").and_then(Value::as_str).map(str::to_string) else { continue; }; if let Some(fields) = drawing.get(&id) { for (key, value) in fields { object.insert(key.clone(), value.clone()); } } } } if let Some(object) = answer.as_object_mut() { object.insert( "cover".to_string(), cover_id .and_then(|id| drawing.get(&id).cloned()) .map_or(Value::Null, Value::Object), ); } Ok(answer) } /// `/photos/albums` — every album, proposals first. /// /// Thin, and thin on purpose: the list arrives from `list_albums` already in the /// order the screen draws it, and a read that re-sorted would be a second /// opinion about a page whose whole job is to show the pass's own ranking. The /// one thing added is the ceiling. pub fn albums(ctx: &mut Ctx<'_>, _args: &Map) -> Result { let mut answer = tool( ctx, "list_albums", &args_of(&[("limit", Value::from(cotton_tools::mcp::handlers::common::WHOLE_SET))]), )?; if let Some(rows) = answer.get_mut("albums") { attach_album_covers(ctx, rows)?; } Ok(answer) } /// Every album card's cover, ready to draw. /// /// `list_albums` answers a `coverId` and nothing a renderer can use — the same /// gap `read.album` had, one level up. Without this a card NAMES an album and /// draws an empty square, which a person reads as "those pictures are not on /// this phone" about bytes sitting on the disk. /// /// Two queries however many albums there are, over the ids actually named: a /// cover's kind is not stated on the album row, so it is asked of both media /// tables and the one that does not hold it answers nothing for that id. An /// album with no cover gets an explicit `null` rather than a half object — the /// same shape `read.album` answers, so one Swift type reads both. fn attach_album_covers(ctx: &Ctx<'_>, albums: &mut Value) -> Result<(), String> { let Some(rows) = albums.as_array_mut() else { return Ok(()); }; let wanted: Vec = rows .iter() .filter_map(|row| row.get("coverId").and_then(Value::as_str)) .map(str::to_string) .collect::>() .into_iter() .collect(); let mut drawing: BTreeMap> = BTreeMap::new(); if !wanted.is_empty() { for spec in [media_tools::PHOTO_SPEC, media_tools::VIDEO_SPEC] { drawing.extend(drawing_fields(ctx, spec, Some(&wanted))?); } } for row in rows.iter_mut() { let Some(object) = row.as_object_mut() else { continue; }; let cover = object .get("coverId") .and_then(Value::as_str) .and_then(|id| drawing.get(id).cloned()) .map_or(Value::Null, Value::Object); object.insert("cover".to_string(), cover); } Ok(()) } /// `/photos/duplicates` — the pairs, with both pictures attached. /// /// The screen draws each side as a real tile with its size and dimensions, so /// the pictures are read here rather than fetched per pair: one list read /// over every id both halves name. /// /// **Nothing on that screen deletes.** A confirmed copy leaves the grid by the /// `copies` filter and its bytes stay until `remove_photo` on its own page, so /// this read has no verb and needs none. pub fn duplicates(ctx: &mut Ctx<'_>, _args: &Map) -> Result { let listed = tool( ctx, "list_duplicates", &args_of(&[("state", Value::from("open")), ("limit", Value::from(cotton_tools::mcp::handlers::common::WHOLE_SET))]), )?; let groups = listed .get("groups") .and_then(Value::as_array) .cloned() .unwrap_or_default(); let mut ids: BTreeSet = BTreeSet::new(); for group in &groups { if let Some(keep) = group.get("keepId").and_then(Value::as_str) { ids.insert(keep.to_string()); } for copy in group .get("copies") .and_then(Value::as_array) .into_iter() .flatten() { if let Some(id) = copy.get("copyId").and_then(Value::as_str) { ids.insert(id.to_string()); } } } // A picture a pair names may be GONE — deleted from the other side of the // pair, or from another device. The screen has a sentence for that, so the // read answers what it found rather than refusing the page. let photos = if ids.is_empty() { Value::Array(Vec::new()) } else { media_rows( ctx, media_tools::PHOTO_SPEC, media_tools::MediaListFilters { ids: Some(ids.into_iter().collect()), limit: None, ..Default::default() }, )? }; Ok(json!({ "groups": groups, "photos": photos })) } /// One face waiting to be confirmed, before the names are resolved. struct FaceSuggestion { id: String, record_id: String, suggested_person_id: String, suggested_distance: Option, /// The face's box in its picture — top-left corner, width and height, as /// fractions — so the slip can show the face rather than the picture. x: Option, y: Option, w: Option, h: Option, } /// Every face the Mac thinks it recognises and nobody has answered for. /// /// `person_id IS NULL AND suggested_person_id IS NOT NULL`, nearest first — /// `mediaFaces.service.ts:listFaceSuggestions`, condition for condition. /// `suggestion_dismissed_at` is deliberately NOT in the predicate: dismissing /// clears `suggested_person_id` in the same write, so the timestamp is a record /// of the answer rather than a second filter, and adding one would be a /// different rule wearing the same name. fn face_suggestion_rows(ctx: &Ctx<'_>) -> Result, String> { Ok(ctx .db() .all( "SELECT id, record_id, suggested_person_id, suggested_distance, x, y, w, h FROM cotton_media_faces WHERE workspace_id = ? AND person_id IS NULL AND suggested_person_id IS NOT NULL -- A face on a picture in the bin waits there with it. AND record_id NOT IN (SELECT id FROM cotton_photos WHERE trashed_at IS NOT NULL UNION ALL SELECT id FROM cotton_videos WHERE trashed_at IS NOT NULL) ORDER BY suggested_distance ASC, record_id ASC, id ASC", &[SqlValue::Text(ctx.workspace_id.to_string())], ) .map_err(|error| error.to_string())? .iter() .filter_map(|row| { Some(FaceSuggestion { id: row.text("id")?.to_string(), record_id: row.text("record_id")?.to_string(), suggested_person_id: row.text("suggested_person_id")?.to_string(), suggested_distance: row.real("suggested_distance"), x: row.real("x"), y: row.real("y"), w: row.real("w"), h: row.real("h"), }) }) .collect()) } /// `/photos/people` — who the Mac thinks it recognises, and in which picture. /// /// The names and the pictures are resolved ONCE for the whole list rather than /// once per row: a hook per row is how a screen with forty suggestions makes /// eighty reads. /// /// **The distance is carried, and the screen says it as a hedge.** "Very likely" /// or "Maybe", never a number — the pass only suggests under 0.45 and is rarely /// wrong under 0.3, and a decimal on a page about somebody's face invites a /// person to argue with arithmetic instead of looking at the picture. pub fn face_suggestions(ctx: &mut Ctx<'_>, _args: &Map) -> Result { let faces = face_suggestion_rows(ctx)?; let names: BTreeMap = ctx.read.driver().all( "SELECT id,full_name FROM cotton_people WHERE workspace_id=? AND archived_at IS NULL", &[SqlValue::Text(ctx.workspace_id.to_owned())], ).map_err(|error| error.to_string())?.iter().filter_map(|person| { Some((person.text("id")?.to_owned(), person.text("full_name")?.to_owned())) }).collect(); let ids: Vec = faces .iter() .map(|face| face.record_id.clone()) .collect::>() .into_iter() .collect(); let photos = if ids.is_empty() { Value::Array(Vec::new()) } else { media_rows( ctx, media_tools::PHOTO_SPEC, media_tools::MediaListFilters { ids: Some(ids), limit: None, ..Default::default() }, )? }; Ok(json!({ "faces": faces .iter() .map(|face| json!({ "id": face.id, "recordId": face.record_id, "suggestedPersonId": face.suggested_person_id, // A person the file no longer names is not a reason to hide the // face: the screen says "someone you have named" and the // question still gets asked. "suggestedName": names.get(&face.suggested_person_id), "distance": face.suggested_distance, // The face's rectangle, so the slip can cut the face out of its picture. "x": face.x, "y": face.y, "w": face.w, "h": face.h, })) .collect::>(), "photos": photos, })) } /// `/photos/album/[id]/add` — the pictures that can still go in this album. /// /// Three exclusions: what the album already holds, a screenshot, and a utility /// image. The last two are /// `cotton_core::rules::media::albums::album_admits_by_hand` — the SAME rule /// the nightly pass applies when it builds an album by itself, so a person /// adding by hand and the pass adding by machine agree about what a picture /// is. pub fn addable_photos(ctx: &mut Ctx<'_>, args: &Map) -> Result { let album_id = required(args, "albumId", "the album to add to")?; // The album has to EXIST before its library is offered. // `mediaAlbums.service.ts:299` calls `albumRow(albumId)` first and throws; // without it a stale deep link to a dismissed album drew the whole library // as addable and the tick then failed at `update_album`, which is a // refusal after the work rather than before it. let known = ctx .db() .get( "SELECT id FROM cotton_media_albums WHERE workspace_id = ? AND id = ?", &[ SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(album_id.clone()), ], ) .map_err(|error| error.to_string())?; if known.is_none() { return Err("no such album in this workspace".to_string()); } let held: BTreeSet = ctx .db() .all( "SELECT record_id FROM cotton_media_album_items WHERE workspace_id = ? AND album_id = ?", &[ SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(album_id.clone()), ], ) .map_err(|error| error.to_string())? .iter() .filter_map(|row| row.text("record_id").map(str::to_string)) .collect(); let all = media_rows(ctx, media_tools::PHOTO_SPEC, library_filters(None))?; let offered: Vec = all .as_array() .cloned() .unwrap_or_default() .into_iter() .filter(|photo| { let id = photo.get("id").and_then(Value::as_str).unwrap_or_default(); if held.contains(id) { return false; } // `media_out` calls the flag `utility`, and it leaves `subtypes` // OUT when the list is empty — an absent key is "no subtypes", not // "unknown". let is_utility = match photo.get("utility") { Some(Value::Bool(true)) => Some(1), Some(Value::Bool(false)) => Some(0), _ => None, }; let subtypes: Vec = photo .get("subtypes") .and_then(Value::as_array) .map(|list| { list.iter() .filter_map(|value| value.as_str().map(str::to_string)) .collect() }) .unwrap_or_default(); cotton_core::rules::media::albums::album_admits_by_hand(is_utility, &subtypes) }) .collect(); Ok(json!({ "photos": offered })) } /// `/photos/photo/[id]` and `/videos/video/[id]` — one picture, everything on /// its page. /// /// `get_photo` / `get_video` is the record and its faces whole. What it does not /// carry is where the picture has been SEEN, which the page's "Seen in" section /// draws with the chat's own name — so the sightings are joined here, oldest /// first, exactly as the section lists them. fn one_media( ctx: &mut Ctx<'_>, getter: &str, noun: &str, spec: media_tools::MediaKindSpec, args: &Map, ) -> Result { let id = required(args, "id", &format!("the {noun} to read"))?; let record = tool(ctx, getter, &args_of(&[("id", Value::from(id.clone()))]))?; let sightings = ctx .db() .all( "SELECT s.id AS id, s.source AS source, s.source_id AS source_id, s.thread_id AS thread_id, s.seen_at AS seen_at, t.title AS title, k.display_name AS display_name FROM cotton_media_sightings s LEFT JOIN cotton_msg_threads t ON t.id = s.thread_id LEFT JOIN cotton_msg_contacts k ON k.id = t.contact_id WHERE s.workspace_id = ? AND s.record_id = ? ORDER BY s.seen_at ASC, s.id ASC", &[ SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(id.clone()), ], ) .map_err(|error| error.to_string())? .iter() .map(|row| { json!({ "id": row.text("id"), "source": row.text("source"), "sourceId": row.text("source_id"), "threadId": row.text("thread_id"), // The chat's own title, else the person on the other end of a // DM; a sighting whose thread has gone says neither and the // screen calls it "A chat". "threadName": row.text("title").or_else(|| row.text("display_name")), "seenAt": row.text("seen_at"), }) }) .collect::>(); // THE OBJECT KEY, merged on exactly as the grid's rows carry it. // // `media_out` says what a picture IS and never where its bytes are — which // is right for an assistant and useless to a renderer. The grid gets round // that through `media_rows`, which merges `drawing_fields`; the DETAIL page // read did not, so `/photos/photo/[id]` and `/videos/video/[id]` were the // two screens in this lane that could name a picture and not draw it. A // film was the worse half: with no `posterKey` and no `key` the player had // nothing to resolve and the page said "not on this phone yet" about bytes // that were sitting on the disk. // // Narrowed to this one id, so the page pays for one row rather than the // scan the library's own grid pays for. // // NEVER the envelope, and the shape is CHECKED rather than assumed. Both // getters answer a media record FLAT — the row's own fields at the top // level — so the answer IS the record and there is no `{noun}` key to reach // into. `get_video` has a SECOND answer shape though: a raw MCP content // envelope (an image block and a text block, `videos.rs`) when a poster // exists, the store is reachable and the still is small enough. Handing // that up as the `video` field would decode on the Swift side to an // all-default row — a page that says "the film is not here" about bytes // sitting on the disk. It is unreachable today, because the envelope needs // `ctx.services.media_get` and the phone leaves it unset; that is exactly // why it must refuse now rather than wait to be discovered by the first // build that wires a store in. An envelope carries no `id`, a record always // does, so that is the whole test. let mut answer = record; if !answer.get("id").is_some_and(Value::is_string) { return Err(format!( "{getter} answered a content envelope rather than a {noun} row" )); } let drawing = drawing_fields(ctx, spec, Some(std::slice::from_ref(&id)))?; if let (Some(fields), Some(object)) = (drawing.get(&id), answer.as_object_mut()) { for (key, value) in fields { object.insert(key.clone(), value.clone()); } } // The albums this record is in, so the page can wear each as a tag. A // dismissed album is not one the person has — the albums page hides it — // so it is not worn here either. Newest album first, by where it starts. let albums = ctx .db() .all( "SELECT a.id AS id, a.title AS title, a.state AS state FROM cotton_media_album_items i JOIN cotton_media_albums a ON a.id = i.album_id AND a.workspace_id = i.workspace_id WHERE i.workspace_id = ? AND i.record_kind = ? AND i.record_id = ? AND a.state <> 'dismissed' ORDER BY a.starts_at DESC, a.id ASC", &[ SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(spec.kind.to_string()), SqlValue::Text(id.clone()), ], ) .map_err(|error| error.to_string())? .iter() .map(|row| { json!({ "id": row.text("id"), "title": row.text("title"), "state": row.text("state"), }) }) .collect::>(); let mut out = Map::new(); out.insert(noun.to_string(), answer); out.insert("sightings".to_string(), Value::Array(sightings)); out.insert("albums".to_string(), Value::Array(albums)); Ok(Value::Object(out)) } pub fn photo(ctx: &mut Ctx<'_>, args: &Map) -> Result { one_media(ctx, "get_photo", "photo", media_tools::PHOTO_SPEC, args) } pub fn video(ctx: &mut Ctx<'_>, args: &Map) -> Result { one_media(ctx, "get_video", "video", media_tools::VIDEO_SPEC, args) } // ── the chats ─────────────────────────────────────────────────────────────── /// `/messages` — the inbox, one row per CONVERSATION. /// /// The tool's OWN default, `groupBy: "person"`, which is core's /// `groupThreadsByPerson`. A person reachable on a WhatsApp number and an /// iMessage number has two contacts and two threads in the file, and the /// inbox has no toggle: a person is a person. Asking for `groupBy: "thread"` /// would draw that human twice, one channel mark each. /// /// **A merged row's `id` is the NEWEST thread's**, because that is what a tap /// opens: the row's thread is the newest-activity one. The tool sets `id` only /// for a lone thread and answers `threadIds` sorted by ID, which is stable but /// arbitrary, so the newest is resolved here from the threads' own /// `last_message_at`. /// /// **Archived is a FILTER the tool does not have.** The inbox hides archived /// conversations and offers a count that opens them, so the split is made here /// over the answer's own `archived` flag — which the tool sets for a merged /// row only when EVERY thread under it is archived, one live number meaning /// the person is not filed away. /// /// And because the tool cannot take that filter, the split happens AFTER its /// ceiling: two hundred threads are read and then divided. Under two hundred /// conversations — which is where this product is — that is exactly the right /// answer. Above it, a person whose oldest hundred are archived sees an inbox /// short by a hundred rather than a page that stopped at two hundred, which is /// the worse of the two failures. Giving it back needs an `archived` argument /// on `list_message_threads`; the ledger says so. /// /// **A `query` asks the search pill instead**, and answers `matches` — see /// [`message_search`]. A blank one is refused rather than answered with the /// list: the app never sends one, so one arriving is a bug to see. pub fn threads(ctx: &mut Ctx<'_>, args: &Map) -> Result { if args.contains_key("query") { return message_search(ctx, args); } let want_archived = args .get("archived") .and_then(Value::as_bool) .unwrap_or(false); let listed = tool( ctx, "list_message_threads", &args_of(&[("limit", Value::from(cotton_tools::mcp::handlers::common::WHOLE_SET))]), )?; let activity = thread_activity(ctx)?; let mut shown: Vec = Vec::new(); let mut archived_count = 0_usize; for mut thread in listed .get("threads") .and_then(Value::as_array) .cloned() .unwrap_or_default() { let is_archived = thread .get("archived") .and_then(Value::as_bool) .unwrap_or(false); if is_archived { archived_count += 1; } if is_archived != want_archived { continue; } // A merged conversation carries no `id`; the tap opens its newest. if thread.get("id").and_then(Value::as_str).is_none() { if let Some(newest) = newest_thread_id(&thread, &activity) { if let Some(row) = thread.as_object_mut() { row.insert("id".to_string(), Value::from(newest)); } } } shown.push(thread); } // The owner's own half — pin, mute and the deliberate unread flag. Neither // column is in the tool's projection, because neither is an assistant's // business; the phone draws and writes all three (4m). crate::phone::chat::own_list_state(ctx, &mut shown)?; // The picture each row is drawn with — a key, never bytes (`pictures.rs`). crate::phone::pictures::stamp_inbox(ctx, &mut shown)?; Ok(json!({ "threads": shown, "archived": want_archived, "archivedCount": archived_count, })) } /// When each conversation was last written in — `id` to `last_message_at`. /// /// One read for the whole page rather than one per merged row, and the only /// reason it exists is the tap target above. fn thread_activity(ctx: &Ctx<'_>) -> Result, String> { Ok(ctx .db() .all( "SELECT id, last_message_at FROM cotton_msg_threads WHERE workspace_id = ?", &[SqlValue::Text(ctx.workspace_id.to_string())], ) .map_err(|error| error.to_string())? .iter() .filter_map(|row| { let id = row.text("id")?; Some((id.to_string(), row.text("last_message_at")?.to_string())) }) .collect()) } /// The newest-activity thread of a merged conversation, else its first. /// /// A thread nobody has written in has no `last_message_at` and so is not in /// `activity`; it loses to any thread that has one, and the `threadIds` order /// — which core makes stable by sorting on the id — decides between two that /// are equally silent. fn newest_thread_id(thread: &Value, activity: &BTreeMap) -> Option { let ids: Vec<&str> = thread .get("threadIds") .and_then(Value::as_array) .map(|ids| ids.iter().filter_map(Value::as_str).collect()) .unwrap_or_default(); ids.iter() .max_by(|a, b| { activity .get(**a) .map(String::as_str) .unwrap_or("") .cmp(activity.get(**b).map(String::as_str).unwrap_or("")) // `max_by` keeps the LAST of equals, so a tie has to be broken // the other way round to land on the first id. .then(b.cmp(a)) }) .map(|id| (*id).to_string()) } /// `/messages/[thread]` — the conversation, newest window first. /// /// The window GROWS rather than paging: the screen reads fifty, then a /// hundred, then a hundred and fifty as the person pulls at the top, and /// re-reads the whole window each time. The tool caps one read at a hundred, /// so a window past that is assembled by asking again from the oldest message /// the last page returned — the tool's own `before` cursor, used for the /// reason it exists. /// /// A `personId` instead of a `threadId` is a merged conversation, and the tool /// answers that shape itself. pub fn thread(ctx: &mut Ctx<'_>, args: &Map) -> Result { let window = args .get("limit") .and_then(Value::as_i64) .unwrap_or(THREAD_WINDOW) .clamp(1, THREAD_WINDOW_MAX); let mut base = Map::new(); for key in ["threadId", "personId"] { if let Some(value) = text_arg(args, key) { base.insert(key.to_string(), Value::from(value)); } } if base.is_empty() { return Err("`threadId` or `personId` is the conversation to read".to_string()); } let mut messages: Vec = Vec::new(); let mut answer: Option = None; let mut cursor: Option<(String, String)> = None; while (messages.len() as i64) < window { let asking = (window - messages.len() as i64).min(THREAD_TOOL_PAGE); let mut page_args = base.clone(); page_args.insert("limit".to_string(), Value::from(asking)); if let Some((before, before_id)) = &cursor { page_args.insert("before".to_string(), Value::from(before.clone())); // BOTH halves, for the reason `email_thread` gives: two hundred // WhatsApp messages out of one backup can share a `sent_at` to the // second, and a bare instant cursor with a strict `<` would drop // every one of them past the page boundary, for ever. page_args.insert("beforeId".to_string(), Value::from(before_id.clone())); } let page = tool(ctx, "read_message_thread", &page_args)?; let rows = page .get("messages") .and_then(Value::as_array) .cloned() .unwrap_or_default(); // The tool's own handle, both halves — never re-derived from the rows. let next = page .get("nextBefore") .and_then(Value::as_str) .map(str::to_string) .zip( page.get("nextBeforeId") .and_then(Value::as_str) .map(str::to_string), ); let ran_out = (rows.len() as i64) < asking; // Each page is older than the one before, so it goes in FRONT — the // window stays one conversation read top to bottom. let mut merged = rows; merged.append(&mut messages); messages = merged; if answer.is_none() { answer = Some(page); } match next { Some(next) if !ran_out => cursor = Some(next), // Either the conversation has no more, or a page came back without // a handle to page on. Either way, asking again would read the same // page for ever. _ => { cursor = None; break; } } } let Some(Value::Object(mut out)) = answer else { return Err("the conversation answered nothing at all".to_string()); }; let filled = messages.len() as i64; // **The handle names the assembled window's own oldest row, or nothing.** // Page one's `nextBefore` rode through until 4g's review found it: after N // pages are stitched it points into the MIDDLE of the window, which is a // wrong answer rather than a stale one — and this is the crate's answer, // read by a test harness and by the next chat lane, not only by a Swift // model that happens to ignore it. `email_thread` does the same nineteen // hundred lines up. match cursor { Some((before, before_id)) => { out.insert("nextBefore".to_string(), Value::from(before)); out.insert("nextBeforeId".to_string(), Value::from(before_id)); } None => { out.insert("nextBefore".to_string(), Value::Null); out.insert("nextBeforeId".to_string(), Value::Null); } } for message in &mut messages { for entry in message.get_mut("media").and_then(Value::as_array_mut).into_iter().flatten() { if let Some(entry) = entry.as_object_mut() { word_media(entry); } } } out.insert("messages".to_string(), Value::Array(messages)); // The owner's own half (4m): the star, the reply anchor, whether the edit // and take-back windows are still open, this person's own reaction — and // the VISIBILITY RULE, which drops what this device has hidden or cleared. // Neither column is in the tool's projection, because neither is an // assistant's business, and without the filter `hide_chat_messages` and // `clear_thread` would write a row and change nothing anybody can see. // // A merged read (`personId`) covers several threads and has no single row // to read the conversation's own private columns off, so it passes `None` // and gets the per-MESSAGE half alone. let single = text_arg(args, "threadId"); let now = now_iso(ctx); crate::phone::chat::own_thread_state(ctx, single.as_deref(), &mut out, &now)?; // The header's print, and a group's head count (`pictures.rs`). crate::phone::pictures::stamp_thread(ctx, single.as_deref(), &mut out)?; // **Counted BEFORE the visibility filter, and that is the whole point.** // `hasMore` answers one question — did this READ reach the top of the // conversation — and only the number of rows the STORE handed back can // answer it. Counting after `own_thread_state` asked a different question: // "are there fifty rows left to draw", and the two diverge the moment this // device hides one message inside a full window. 4m's review found the // consequence: `hasMore` goes false, the Swift screen drops "Load older" // for that conversation, and it never comes back — because every later read // of the same window hides the same row. The filter may SHRINK a page; it // may not end the conversation. out.insert("hasMore".to_string(), Value::Bool(filled >= window)); out.insert("window".to_string(), Value::from(window)); Ok(Value::Object(out)) } /// One attachment worded in place: its `kind` always, its `length` when it /// plays and knows how long. fn word_media(entry: &mut Map) { use cotton_core::cotton_rules::messages::{MessageMedia, MessageMediaKind}; let probe = MessageMedia { content_type: entry.get("contentType").and_then(Value::as_str).unwrap_or_default().to_string(), kind: entry.get("kind").and_then(Value::as_str).and_then(MessageMediaKind::parse), ..MessageMedia::default() }; let kind = cotton_core::messages::preview::media_kind_of(&probe); entry.insert("kind".to_string(), Value::from(kind.as_str())); let plays = matches!(kind, MessageMediaKind::Audio | MessageMediaKind::Voice | MessageMediaKind::Video); if let Some(ms) = entry.get("durationMs").and_then(Value::as_f64).filter(|_| plays) { entry.insert("length".to_string(), Value::from(cotton_core::messages::preview::format_duration(ms))); } } /// The window the screen opens with, the biggest it will grow to, and the most /// one call to the tool can answer. const THREAD_WINDOW: i64 = 50; const THREAD_WINDOW_MAX: i64 = 1000; const THREAD_TOOL_PAGE: i64 = 100; /// `/messages/[thread]/info` — who is in it, and what it holds. pub fn thread_info(ctx: &mut Ctx<'_>, args: &Map) -> Result { let thread_id = required(args, "threadId", "the conversation to read")?; let workspace = SqlValue::Text(ctx.workspace_id.to_string()); let thread = ctx .db() .get( "SELECT t.id AS id, t.kind AS kind, t.title AS title, t.description AS description, t.photo_key AS photo_key, t.archived AS archived, t.muted_until AS muted_until, t.pinned_at AS pinned_at, t.created_at AS created_at, t.last_message_at AS last_message_at, t.summary AS summary, t.summary_by AS summary_by, t.summary_updated_at AS summary_updated_at, k.display_name AS display_name, k.id AS contact_id FROM cotton_msg_threads t LEFT JOIN cotton_msg_contacts k ON k.id = t.contact_id WHERE t.workspace_id = ? AND t.id = ?", &[workspace.clone(), SqlValue::Text(thread_id.clone())], ) .map_err(|error| error.to_string())?; let Some(thread) = thread else { // One answer for "absent" and "not this workspace" — the tool's own // probe-resistance rule, kept. return Err("no such conversation in this workspace".to_string()); }; let participants = ctx .db() .all( "SELECT p.id AS id, p.contact_id AS contact_id, p.display_name AS display_name, p.role AS role, p.left_at AS left_at, p.is_self AS is_self, k.display_name AS contact_name FROM cotton_msg_thread_participants p LEFT JOIN cotton_msg_contacts k ON k.id = p.contact_id WHERE p.workspace_id = ? AND p.thread_id = ? ORDER BY p.created_at ASC, p.id ASC", &[workspace.clone(), SqlValue::Text(thread_id.clone())], ) .map_err(|error| error.to_string())? .iter() .map(|row| { json!({ "id": row.text("id"), "contactId": row.text("contact_id"), // The participant's own name first: a group can name somebody // it has no contact for. "displayName": row.text("display_name").or_else(|| row.text("contact_name")), "role": row.text("role"), "leftAt": row.text("left_at"), "isSelf": row.int("is_self").unwrap_or(0) == 1, }) }) .collect::>(); Ok(json!({ "thread": { "id": thread.text("id"), "kind": thread.text("kind"), // A DM's name is the person on the other end of it. "title": thread.text("title").or_else(|| thread.text("display_name")), "description": thread.text("description"), "photoKey": thread.text("photo_key"), "contactId": thread.text("contact_id"), "archived": thread.int("archived").unwrap_or(0) == 1, "mutedUntil": thread.text("muted_until"), "pinnedAt": thread.text("pinned_at"), "createdAt": thread.text("created_at"), "lastMessageAt": thread.text("last_message_at"), "summary": thread.text("summary"), "summaryBy": thread.text("summary_by"), "summaryUpdatedAt": thread.text("summary_updated_at"), }, "participants": participants, "media": thread_media_rows(ctx, &thread_id)?, })) } /// `/messages/[thread]/media` — everything the conversation has carried. pub fn thread_media(ctx: &mut Ctx<'_>, args: &Map) -> Result { let thread_id = required(args, "threadId", "the conversation to read")?; Ok(json!({ "media": thread_media_rows(ctx, &thread_id)? })) } /// The attachments a conversation holds, newest first. /// /// The media live on the MESSAGE as a JSON array, so the rows come back whole /// and the array is handed on as it is stored — the app's own tile reads that /// shape, and re-shaping it here would be a second vocabulary for one field. fn thread_media_rows(ctx: &Ctx<'_>, thread_id: &str) -> Result, String> { Ok(ctx .db() .all( "SELECT id, sent_at, direction, media FROM cotton_msg_messages WHERE workspace_id = ? AND thread_id = ? AND hidden_at IS NULL AND deleted_at IS NULL AND media <> '[]' ORDER BY sent_at DESC, id DESC", &[ SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(thread_id.to_string()), ], ) .map_err(|error| error.to_string())? .iter() .map(|row| { json!({ "messageId": row.text("id"), "sentAt": row.text("sent_at"), "direction": row.text("direction"), "media": row .text("media") .and_then(|raw| serde_json::from_str::(raw).ok()) .unwrap_or(Value::Array(Vec::new())), }) }) .collect()) } /// `/messages/starred` — the messages the person kept. /// /// No tool asks this: starring is the OWNER's own column /// (`PRIVATE_STATE_COLUMNS`), never a peer's and never an assistant's, so there /// is nothing in the catalogue to call and this is a query rather than a /// restatement. /// /// **Two predicates that are the TypeScript's, exactly** (`listStarred`, /// `packages/core/src/services/chat/queries.ts`): /// /// * `cleared_before`. Clearing a conversation on another of the owner's /// devices sets it, and every message older than that instant is gone from /// that person's view. Reading only `starred_at` would keep drawing the /// BODIES of messages they cleared — the one list where a clear has to /// hold, since it is the one list a message reaches without its thread. /// * `hidden_at`, and NOT `deleted_at`. A message deleted for everyone keeps /// its tombstone here — the row a person starred is still a row they /// starred, and it draws as the deletion it is. Dropping it would /// silently shorten the list. pub fn starred(ctx: &mut Ctx<'_>, _args: &Map) -> Result { let rows = ctx .db() .all( "SELECT m.id AS id, m.thread_id AS thread_id, m.body AS body, m.media AS media, m.direction AS direction, m.sent_at AS sent_at, m.starred_at AS starred_at, m.deleted_at AS deleted_at, t.title AS title, k.display_name AS display_name FROM cotton_msg_messages m LEFT JOIN cotton_msg_threads t ON t.id = m.thread_id LEFT JOIN cotton_msg_contacts k ON k.id = t.contact_id WHERE m.workspace_id = ? AND m.starred_at IS NOT NULL AND m.hidden_at IS NULL AND m.trashed_at IS NULL AND (t.cleared_before IS NULL OR m.sent_at > t.cleared_before) ORDER BY m.starred_at DESC, m.id DESC", &[SqlValue::Text(ctx.workspace_id.to_string())], ) .map_err(|error| error.to_string())?; Ok(json!({ "messages": rows .iter() .map(|row| json!({ "id": row.text("id"), "threadId": row.text("thread_id"), "threadName": row.text("title").or_else(|| row.text("display_name")), "body": row.text("body"), "media": row .text("media") .and_then(|raw| serde_json::from_str::(raw).ok()) .unwrap_or(Value::Array(Vec::new())), "direction": row.text("direction"), "sentAt": row.text("sent_at"), "starredAt": row.text("starred_at"), // A message deleted for everyone keeps its row here and draws // as the deletion it is. "deletedAt": row.text("deleted_at"), })) .collect::>(), })) }