//! What a mailbox's state IS, decided once (schema v33) — the port of//! `packages/core/src/engine/emailState.ts`.//!//! Three readers depend on these answers and must not each invent their own://! the Gmail import (a label set arrives and becomes columns), the push loop//! (columns changed and have to become label operations again), and both list//! surfaces — the server's `list_email_threads` and the app's own reader. "One//! implementation of who wins" is the standing rule for exactly this shape, and//! a disagreement here is a person watching a message they archived come back.//!//! Pure: no clock, no database, no network. Everything in this file is a//! function of a label array or a folder name.use serde_json::{Map, Value};pubuse cotton_rules::mail::state::{email_state_from_labels, gmail_labels, EmailState};/// The three facts a label operation can express — everything but the bin.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]pubstructDesiredLabels {pub unread: bool,pub starred: bool,pub in_inbox: bool,}/// The label operations to send.#[derive(Debug, Clone, PartialEq, Eq, Default)]pubstructLabelOps {pub add: Vec<String>,pub remove: Vec<String>,}/// The label set a message SHOULD carry, given Cotton's columns — the same/// answer as [`email_state_from_labels`] read backwards.////// `TRASH` is deliberately absent: Gmail moves a message to the bin through/// `messages.trash` / `messages.untrash`, not by adding a label, and a modify/// call that tried would be refused. The push loop makes that call separately.pubfn label_ops_for(current: &[String], desired: DesiredLabels) -> LabelOps {letmut ops = LabelOps::default();letmut want = |label: &str, on: bool| {let present = current.iter().any(|l| l == label);if on && !present { ops.add.push(label.to_string()); }if !on && present { ops.remove.push(label.to_string()); } };// The declaration order is the emission order — a test pins the arrays. want(gmail_labels::UNREAD, desired.unread); want(gmail_labels::STARRED, desired.starred); want(gmail_labels::INBOX, desired.in_inbox); ops}/// `labels`, rewritten to agree with the columns — what the push loop stores/// once Gmail has accepted the modify, so the next pass computes its operations/// against what the mailbox actually holds rather than what it held before.////// Every label Cotton has no column for is preserved in its original order.pubfn labels_after(current: &[String], desired: DesiredLabels) -> Vec<String> {let ops = label_ops_for(current, desired);letmut out: Vec<String> = current .iter() .filter(|label| !ops.remove.contains(label)) .cloned() .collect(); out.extend(ops.add); out}// ── the one patch ────────────────────────────────────────────────────────────/// What a caller can change about a message.////// The words the OWNER uses, not the column names: `read` (not `unread`),/// `inbox`, `bin`. `None` on a field is the TypeScript's `undefined` — leave it/// alone.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]pubstructEmailStatePatch {pub read: Option<bool>,pub starred: Option<bool>,/// `true` = in the inbox, `false` = archived.pub inbox: Option<bool>,/// `true` = in the bin, `false` = restored out of it.pub bin: Option<bool>,}/// The row patch a state change becomes — the ONE implementation, used by the/// MCP verbs on the server and by the app's own service.////// `sync_state` only moves for a row Gmail owns. Mail that arrived some other/// way has nothing to push, and marking it `pending` would tell the push loop/// to do something it structurally cannot (the masked-state ban).////// BOOLEANS, not 0/1: `unread`, `starred` and `in_inbox` carry the `bool`/// codec, and both writers encode through it. Handing them a number writes the/// wrong value silently. The map preserves insertion order (the workspace turns/// on serde_json's `preserve_order`), so the patch reads the same on both/// sides.pubfn email_row_patch(patch: EmailStatePatch, now: &str, is_gmail: bool) -> Map<String, Value> {letmut row = Map::new();ifletSome(read) = patch.read { row.insert("unread".to_string(), Value::Bool(!read)); }ifletSome(starred) = patch.starred { row.insert("starred".to_string(), Value::Bool(starred)); }ifletSome(inbox) = patch.inbox { row.insert("in_inbox".to_string(), Value::Bool(inbox)); }ifletSome(bin) = patch.bin { row.insert("trashed_at".to_string(),if bin {Value::String(now.to_string()) } else {Value::Null }, ); }if !row.is_empty() && is_gmail { row.insert("sync_state".to_string(),Value::String("pending".to_string()), ); } row}// ── folders ──────────────────────────────────────────────────────────────────/// The four ways to slice a mailbox.////// `All` is Gmail's own "All Mail" and means everything EXCEPT the bin — binned/// mail is reachable only through `Bin`. A folder that quietly included what/// the owner threw away would make "all" the one view where deleting changes/// nothing.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumEmailFolder {Inbox,Archived,Bin,All,}implEmailFolder {pubconstfn as_str(self) -> &'static str {matchself {EmailFolder::Inbox => "inbox",EmailFolder::Archived => "archived",EmailFolder::Bin => "bin",EmailFolder::All => "all", } }/// `EMAIL_FOLDERS`, in order.pubconst ALL: [EmailFolder; 4] = [EmailFolder::Inbox,EmailFolder::Archived,EmailFolder::Bin,EmailFolder::All, ];pubfn parse(value: &str) -> Option<Self> {Self::ALL.into_iter().find(|f| f.as_str() == value) }}impl std::fmt::DisplayforEmailFolder {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) }}/// A folder, as a filter over the columns.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubstructEmailFolderFilter {/// Constrain `in_inbox`, or leave it alone.pub in_inbox: Option<bool>,/// `true` = only binned rows; `false` = only rows that are not binned.pub binned: bool,}pubconstfn email_folder_filter(folder: EmailFolder) -> EmailFolderFilter {match folder {EmailFolder::Inbox => EmailFolderFilter { in_inbox: Some(true), binned: false, },EmailFolder::Archived => EmailFolderFilter { in_inbox: Some(false), binned: false, },EmailFolder::Bin => EmailFolderFilter { in_inbox: None, binned: true, },EmailFolder::All => EmailFolderFilter { in_inbox: None, binned: false, }, }}/// The same filter as a SQL predicate over one table alias — for the readers/// that write SQL rather than build a query object.pubfn email_folder_sql(folder: EmailFolder, alias: &str) -> String {let filter = email_folder_filter(folder);letmut parts = vec![format!("{alias}.trashed_at IS {}",if filter.binned { "NOT NULL" } else { "NULL" } )];ifletSome(in_inbox) = filter.in_inbox { parts.push(format!("{alias}.in_inbox = {}",if in_inbox { 1 } else { 0 } )); } parts.join(" AND ")}// ── a thread's state, which is its messages' ─────────────────────────────────/// The per-message facts a thread's row is folded from.#[derive(Debug, Clone, PartialEq, Eq, Default)]pubstructEmailThreadMemberState {pub unread: bool,pub starred: bool,pub in_inbox: bool,pub trashed_at: Option<String>,}/// A conversation's rolled-up state.#[derive(Debug, Clone, PartialEq, Eq, Default)]pubstructEmailThreadState {/// Any message unread.pub unread: bool,/// Any message starred — the star Gmail draws on a conversation.pub starred: bool,/// Any message still in the inbox.pub in_inbox: bool,/// EVERY message binned, and the latest instant one was — `None` otherwise./// A conversation is in the bin only when nothing of it is left outside.pub trashed_at: Option<String>,}/// A conversation's state is the OR over its messages, and its binning is the/// AND — Gmail's own model, and the reason `cotton_emails` carries the columns/// while `cotton_email_threads` carries only `trashed_at`. Two writers for one/// fact is what makes a badge disagree with the list under it.pubfn fold_thread_state(members: &[EmailThreadMemberState]) -> EmailThreadState {if members.is_empty() {returnEmailThreadState::default(); }letmut trashed_at: Option<&str> = None;letmut all_trashed = true;for member in members {letSome(at) = member.trashed_at.as_deref() else { all_trashed = false;continue; };// A string comparison, as the TypeScript's `>` is — these are ISO// instants in one shape, so lexical order is chronological order.if trashed_at.is_none_or(|current| at > current) { trashed_at = Some(at); } }EmailThreadState { unread: members.iter().any(|m| m.unread), starred: members.iter().any(|m| m.starred), in_inbox: members.iter().any(|m| m.in_inbox), trashed_at: if all_trashed { trashed_at.map(str::to_string) } else {None }, }}/// One mark a conversation wears beyond a read conversation in the inbox.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumThreadMark {Unread,Starred,Binned,Archived,}implThreadMark {/// The mark's line in set `email` (`kits/shell/lines/email.json`).pubfn line(self) -> &'static str {matchself {ThreadMark::Unread => "marks.unread",ThreadMark::Starred => "marks.starred",ThreadMark::Binned => "marks.binned",ThreadMark::Archived => "marks.archived", } }}/// A conversation's state as its marks, in order: what it is beyond a read/// conversation in the inbox. Empty when it is only that — the page draws/// marks, never a row per switch.pubfn thread_marks(unread: bool, starred: bool, in_inbox: bool, binned: bool) -> Vec<ThreadMark> { [ (unread, ThreadMark::Unread), (starred, ThreadMark::Starred), (binned, ThreadMark::Binned), (!binned && !in_inbox, ThreadMark::Archived), ] .into_iter() .filter_map(|(holds, mark)| holds.then_some(mark)) .collect()}/// The marks in `rows`' words (the kit's for a line they have none of),/// joined pairwise by the `marks.join` line; nothing for no marks.pubfn say_marks(marks: &[ThreadMark], rows: &[super::shell_lines::LineRow]) -> Option<String> {let line = |path: &str, fills: &[(&str, &str)]| {super::shell_lines::resolve("email", path, rows, fills).unwrap_or_default() }; marks .iter() .map(|mark| line(mark.line(), &[])) .reduce(|a, b| line("marks.join", &[("a", &a), ("b", &b)]))}#[cfg(test)]#[path = "email_state_tests.rs"]mod tests;