//! The two read verbs. Participants resolve to the owner's people by exact //! address AT READ TIME — which is what makes identifying someone later //! retroactive for free, with no backfill. use std::collections::HashMap; use cotton_core::constants::SummaryKind; use cotton_core::rules::email_state::{email_folder_filter, fold_thread_state}; use rusqlite::types::Value as SqlValue; use serde_json::{Map, Value}; use super::shared::{ member_state, name_for, participant_out, people_by_address, role_rank, truthy, MatchedPerson, PARTICIPANT_COLUMNS, }; use super::validate::{validate_list_email_threads, validate_read_email_thread}; use crate::mcp::dispatch::{Ctx, ToolResult}; use crate::mcp::handlers::common::{ in_chunks, maybe_row, put, rows as read_rows, summary_out, text, }; use crate::mcp::protocol::ToolFailure; use crate::mcp::read_db::{Filter, Order, Query}; use cotton_core::rules::mail_predicate; /// The empty answer both reads share — `{ threads: [] }`. fn no_threads() -> ToolResult { let mut out = Map::new(); out.insert("threads".to_string(), Value::Array(Vec::new())); Ok(Value::Object(out)) } pub fn list_email_threads(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { list_email_threads_within(ctx, args, None) } /// [`list_email_threads`], narrowed to `within` — the conversation ids a /// caller has already decided are in play (the Mac's project scope, which the /// phone read resolves from `cotton_project_links`). /// /// Not a tool argument: the MCP surface is unchanged, and an assistant asks /// `get_project` for a project's mail. The narrowing happens BEFORE the /// 500-id cap below, which is the whole reason it is in here rather than a /// filter over this function's answer — an answer capped first and filtered /// second can drop a linked conversation that merely fell past the cap. pub fn list_email_threads_within( ctx: &mut Ctx<'_>, args: &Map, within: Option<&[String]>, ) -> ToolResult { let args = validate_list_email_threads(args)?; let mut thread_ids: Option> = None; if let Some(participant) = &args.participant { let found = read_rows( ctx, &Query::on("cotton_email_participants") .columns(&["thread_id"]) .eq("email", participant.to_string()), )?; let mut unique: Vec = Vec::new(); for row in &found { if let Some(id) = text(row, "thread_id") { if !unique.contains(&id) { unique.push(id); } } } if unique.is_empty() { return no_threads(); } thread_ids = Some(unique); } // The CONVERSATIONS the folder admits, newest first, paged where they are // stored: a conversation is in the folder when one of its messages is // (Gmail's own reading), asked of each conversation by its own messages' // index. Every message of the folder was read before the page — five // seconds on the owner's file (15 Oct 2026) — and only the first 500 // conversations in message order were kept, so a newer one could fall // past the cap. let filter = email_folder_filter(args.folder); let mut admits = if filter.binned { mail_predicate::binned("e.") } else { mail_predicate::live("e.") }; let mut admit_binds: Vec = Vec::new(); if let Some(in_inbox) = filter.in_inbox { admits.push_str(" AND e.in_inbox = ?"); admit_binds.push(SqlValue::Integer(i64::from(in_inbox))); } if let Some(sender) = &args.sender { admits.push_str(" AND e.from_email = ?"); admit_binds.push(SqlValue::Text(sender.to_string())); } let mut sql = format!( "SELECT t.id FROM cotton_email_threads t WHERE t.workspace_id = ? \ AND EXISTS (SELECT 1 FROM cotton_emails e WHERE e.thread_id = t.id AND {admits}{})", if args.unread_only.unwrap_or(false) { format!(" AND {}", mail_predicate::unread("e.")) } else { String::new() } ); let mut binds = vec![SqlValue::Text(ctx.workspace_id.to_string())]; binds.extend(admit_binds.iter().cloned()); for narrowed in [thread_ids.as_deref(), within].into_iter().flatten() { if narrowed.is_empty() { return no_threads(); } sql.push_str(&format!(" AND t.id IN ({})", vec!["?"; narrowed.len()].join(", "))); binds.extend(narrowed.iter().map(|id| SqlValue::Text(id.clone()))); } sql.push_str(" ORDER BY t.last_at DESC, t.id LIMIT ?"); binds.push(SqlValue::Integer(args.limit)); let page: Vec = ctx .db() .all(&sql, &binds) .map_err(|error| ToolFailure::new(error.to_string()))? .iter() .filter_map(|row| row.text("id").map(|id| SqlValue::Text(id.to_string()))) .collect(); if page.is_empty() { return no_threads(); } let rows = read_rows( ctx, &Query::on("cotton_email_threads") .columns(&[ "id", "subject", "first_at", "last_at", "email_count", "trashed_at", ]) .filter(Filter::In("id".to_string(), page.clone())) .order_by("last_at", Order::Desc) .order_by("id", Order::Asc), )?; // The page's messages the folder admits: each conversation's state is the // fold over exactly these. let mut query = Query::on("cotton_emails") .columns(&["id", "thread_id", "gmail_id", "unread", "starred", "in_inbox", "trashed_at"]) .filter(Filter::In("thread_id".to_string(), page)) .filter(if filter.binned { Filter::NotNull("trashed_at".to_string()) } else { Filter::IsNull("trashed_at".to_string()) }); if let Some(in_inbox) = filter.in_inbox { query = query.eq("in_inbox", in_inbox); } if let Some(sender) = &args.sender { query = query.eq("from_email", sender.to_string()); } let mut messages_by_thread: HashMap>> = HashMap::new(); for row in read_rows(ctx, &query)? { if let Some(thread_id) = text(&row, "thread_id") { messages_by_thread.entry(thread_id).or_default().push(row); } } let ids: Vec = rows.iter().filter_map(|row| text(row, "id")).collect(); let participants = in_chunks(&ids, |batch| { read_rows( ctx, &Query::on("cotton_email_participants") .columns(PARTICIPANT_COLUMNS) .filter(Filter::In( "thread_id".to_string(), batch.iter().map(|id| SqlValue::Text(id.clone())).collect(), )), ) })?; let people = people_by_address( ctx, &participants .iter() .filter_map(|row| text(row, "email")) .collect::>(), ); let mut by_thread: HashMap>> = HashMap::new(); for row in participants { if let Some(thread_id) = text(&row, "thread_id") { by_thread.entry(thread_id).or_default().push(row); } } let threads: Vec = rows .iter() .map(|row| { let id = text(row, "id").unwrap_or_default(); let state = fold_thread_state( &messages_by_thread .get(&id) .map(|messages| messages.iter().map(member_state).collect::>()) .unwrap_or_default(), ); let mut out = Map::new(); out.insert("id".to_string(), Value::from(id.clone())); out.insert( "subject".to_string(), text(row, "subject").map_or(Value::Null, Value::from), ); put(&mut out, "firstAt", text(row, "first_at").map(Value::from)); put(&mut out, "lastAt", text(row, "last_at").map(Value::from)); out.insert( "emailCount".to_string(), Value::from(row.get("email_count").and_then(Value::as_i64).unwrap_or(0)), ); out.insert("unread".to_string(), Value::from(state.unread)); out.insert("starred".to_string(), Value::from(state.starred)); out.insert("inInbox".to_string(), Value::from(state.in_inbox)); put( &mut out, "trashedAt", text(row, "trashed_at").map(Value::from), ); let mut people_rows = by_thread.get(&id).cloned().unwrap_or_default(); people_rows .sort_by_key(|part| -role_rank(text(part, "role").unwrap_or_default().as_str())); out.insert( "participants".to_string(), Value::Array( people_rows .iter() .map(|part| participant_out(part, &people)) .collect(), ), ); Value::Object(out) }) .collect(); let mut out = Map::new(); out.insert("threads".to_string(), Value::Array(threads)); Ok(Value::Object(out)) } /// Attachment echo with a five-minute link where bytes exist — the message /// `mediaOut` shape: the row is a fact even when no link can be minted. /// /// HOOK FOR 2f (the media rail). The TypeScript mints /// `documents.media.presignGet(key, 300)` and adds `url` + `expiresAt`; this /// server has no blocking presign seam on `ToolServices` yet, so every /// attachment answers as its BASE shape — name, mime, size and the key. That /// is the TypeScript's own answer where `ctx.documents` is absent, so the /// shape is right today and gains two fields when the rail lands. fn attachments_out(value: Option<&Value>) -> Vec { let parsed = match value { Some(Value::String(raw)) => serde_json::from_str::(raw).unwrap_or(Value::Null), Some(other) => other.clone(), None => Value::Null, }; let Some(entries) = parsed.as_array() else { return Vec::new(); }; let mut out = Vec::new(); for entry in entries { let Some(entry) = entry.as_object() else { continue; }; let Some(name) = entry.get("name").and_then(Value::as_str) else { continue; }; let mut base = Map::new(); base.insert("name".to_string(), Value::from(name)); if let Some(mime) = entry.get("mime").and_then(Value::as_str) { base.insert("mime".to_string(), Value::from(mime)); } if let Some(size) = entry.get("size").and_then(Value::as_f64) { base.insert( "size".to_string(), serde_json::Number::from_f64(size).map_or(Value::Null, Value::Number), ); } let key = entry .get("key") .and_then(Value::as_str) .filter(|key| !key.is_empty()); if let Some(key) = key { // The key is echoed whatever it is. The TypeScript's // `isKeyInWorkspace` guard sits in front of the PRESIGN, and with // no presign rail both of its branches answer the same base shape // — so the guard travels with the rail, not ahead of it. base.insert("key".to_string(), Value::from(key)); } out.push(Value::Object(base)); } out } /// The `recipients` json, as the reader needs it. fn recipients_of(value: Option<&Value>) -> Vec> { let parsed = match value { Some(Value::String(raw)) => serde_json::from_str::(raw).unwrap_or(Value::Null), Some(other) => other.clone(), None => Value::Null, }; let Some(entries) = parsed.as_array() else { return Vec::new(); }; entries .iter() .filter_map(Value::as_object) .filter(|entry| { entry.get("email").and_then(Value::as_str).is_some() && entry.get("kind").and_then(Value::as_str).is_some() }) .cloned() .collect() } pub fn read_email_thread(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let args = validate_read_email_thread(args)?; let thread = maybe_row( ctx, &Query::on("cotton_email_threads") .columns(&[ "id", "subject", "first_at", "last_at", "email_count", "summary", "summary_by", "summary_updated_at", "trashed_at", ]) .eq("id", args.thread_id.to_string()), )?; // One answer for "absent" and "not this workspace" — the probe-resistance // rule every thread read follows. let Some(thread) = thread else { return Err(ToolFailure::new("no such email thread in this workspace")); }; let thread_id = text(&thread, "id").unwrap_or_default(); let thread_subject = text(&thread, "subject"); let mut query = Query::on("cotton_emails") .columns(&[ "id", "subject", "from_email", "from_name", "recipients", "sent_at", "body", "attachments", "unread", "starred", "in_inbox", "trashed_at", ]) .eq("thread_id", thread_id.to_string()) .order_by("sent_at", Order::Desc) // The ID is the TIEBREAK, and it is what makes the cursor below sound. // Sixty imported emails can all carry the same `sent_at` — an archive // stamps what the header said — and an order that leaves a tie to // SQLite's own row order returns an arbitrary fifty on page one and a // different arbitrary fifty on page two. .order_by("id", Order::Desc) .limit(args.limit); query = match (&args.before, &args.before_id) { (Some(before), Some(before_id)) => query.filter(Filter::KeysetBefore { column: "sent_at".to_string(), value: SqlValue::Text(before.clone()), tie_column: "id".to_string(), tie: SqlValue::Text(before_id.clone()), }), // An instant with no id: the older, weaker cursor, kept because a // caller that already pages this tool passes exactly that. It drops a // tie at the boundary, which is why every caller in this repo now // sends both. (Some(before), None) => query.filter(Filter::Lt( "sent_at".to_string(), SqlValue::Text(before.clone()), )), _ => query, }; let mut rows = read_rows(ctx, &query)?; // The page handle is the OLDEST instant on the page, read BEFORE the // reverse — and on a page still ordered NEWEST FIRST that is `last()`, not // `first()`. // // It was `first()` until 4g, which read the newest instant instead. The // filter is `sent_at < before`, so paging on it returned the same page // less its newest row, for ever: a caller walking a sixty-message thread // read six hundred rows and never reached the beginning. The TypeScript it // was ported from reads `rows[0]` of a list `mergeTimelines` has ALREADY // put in chronological order (`packages/server/src/mcp/records.ts:4290`), // which is the oldest — the port took the index and lost the ordering it // depended on. `read_message_thread`'s Rust reads `ordered.first()` on its // own chronological list and was always right. // // The old shape survived its test because that test pages ONE row at a // time, where the oldest and the newest of a page are the same row. let last = (rows.len() as i64 == args.limit).then(|| rows.last()).flatten(); let next_before = last.and_then(|row| text(row, "sent_at")); let next_before_id = last.and_then(|row| text(row, "id")); rows.reverse(); // chronological, the way a conversation reads let participants = read_rows( ctx, &Query::on("cotton_email_participants") .columns(PARTICIPANT_COLUMNS) .eq("thread_id", thread_id.to_string()), )?; let mut addresses: Vec = participants .iter() .filter_map(|row| text(row, "email")) .collect(); addresses.extend(rows.iter().filter_map(|row| text(row, "from_email"))); for row in &rows { for entry in recipients_of(row.get("recipients")) { if let Some(email) = entry.get("email").and_then(Value::as_str) { addresses.push(email.to_string()); } } } let people = people_by_address(ctx, &addresses); let emails: Vec = rows .iter() .map(|row| email_out(row, thread_subject.as_deref(), &people)) .collect(); // ONE read per call, on the HEADER: the summary is about the conversation, // not about any email in it, and `summary_out` runs a count query. let summary = summary_out(ctx, SummaryKind::EmailThread, &thread_id, &thread)?; // The reader shows the whole conversation, so its state folds over the page // it read. `trashedAt` comes from the THREAD's own column, which the writer // stamped when the last message went in — a fold over one page could not // know about the messages it did not read. let state = fold_thread_state(&rows.iter().map(member_state).collect::>()); let mut header = Map::new(); header.insert("id".to_string(), Value::from(thread_id.clone())); header.insert( "subject".to_string(), thread_subject.clone().map_or(Value::Null, Value::from), ); header.insert( "emailCount".to_string(), Value::from( thread .get("email_count") .and_then(Value::as_i64) .unwrap_or(0), ), ); header.insert("unread".to_string(), Value::from(state.unread)); header.insert("starred".to_string(), Value::from(state.starred)); header.insert("inInbox".to_string(), Value::from(state.in_inbox)); put( &mut header, "trashedAt", text(&thread, "trashed_at").map(Value::from), ); put(&mut header, "summary", summary); header.insert( "participants".to_string(), Value::Array( participants .iter() .map(|row| participant_out(row, &people)) .collect(), ), ); let mut out = Map::new(); out.insert("thread".to_string(), Value::Object(header)); out.insert("emails".to_string(), Value::Array(emails)); out.insert( "nextBefore".to_string(), next_before.map_or(Value::Null, Value::from), ); // The two halves are answered together and must be passed back together. out.insert( "nextBeforeId".to_string(), next_before_id.map_or(Value::Null, Value::from), ); Ok(Value::Object(out)) } fn email_out( row: &Map, thread_subject: Option<&str>, people: &HashMap, ) -> Value { let recipients = recipients_of(row.get("recipients")); let slot = |kind: &str| -> Vec { recipients .iter() .filter(|entry| entry.get("kind").and_then(Value::as_str) == Some(kind)) .map(|entry| { let email = entry .get("email") .and_then(Value::as_str) .unwrap_or_default(); let mut one = Map::new(); one.insert("email".to_string(), Value::from(email)); one.insert( "name".to_string(), Value::from(name_for( email, entry.get("name").and_then(Value::as_str), people, )), ); Value::Object(one) }) .collect() }; let to = slot("to"); let cc = slot("cc"); let bcc = slot("bcc"); let attachments = attachments_out(row.get("attachments")); let from_email = text(row, "from_email").unwrap_or_default(); let mut from = Map::new(); from.insert("email".to_string(), Value::from(from_email.clone())); from.insert( "name".to_string(), Value::from(name_for( &from_email, text(row, "from_name").as_deref(), people, )), ); let mut out = Map::new(); out.insert( "id".to_string(), Value::from(text(row, "id").unwrap_or_default()), ); out.insert( "sentAt".to_string(), Value::from(text(row, "sent_at").unwrap_or_default()), ); out.insert("from".to_string(), Value::Object(from)); out.insert("to".to_string(), Value::Array(to)); if !cc.is_empty() { out.insert("cc".to_string(), Value::Array(cc)); } if !bcc.is_empty() { out.insert("bcc".to_string(), Value::Array(bcc)); } // The message's own subject, only when it differs from the thread's — a // conversation whose every subject matches its header says it once. if let Some(subject) = text(row, "subject") .filter(|subject| !subject.is_empty() && Some(subject.as_str()) != thread_subject) { out.insert("subject".to_string(), Value::from(subject)); } out.insert( "body".to_string(), text(row, "body").map_or(Value::Null, Value::from), ); if !attachments.is_empty() { out.insert("attachments".to_string(), Value::Array(attachments)); } out.insert("unread".to_string(), Value::from(truthy(row, "unread"))); out.insert("starred".to_string(), Value::from(truthy(row, "starred"))); out.insert("inInbox".to_string(), Value::from(truthy(row, "in_inbox"))); put( &mut out, "trashedAt", text(row, "trashed_at").map(Value::from), ); Value::Object(out) }