Cotton code
332 lines · 11.6 KB · RustRaw
//! 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};pub use 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)]pub struct DesiredLabels {    pub unread: bool,    pub starred: bool,    pub in_inbox: bool,}/// The label operations to send.#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct LabelOps {    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.pub fn label_ops_for(current: &[String], desired: DesiredLabels) -> LabelOps {    let mut ops = LabelOps::default();    let mut 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.pub fn labels_after(current: &[String], desired: DesiredLabels) -> Vec<String> {    let ops = label_ops_for(current, desired);    let mut 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)]pub struct EmailStatePatch {    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.pub fn email_row_patch(patch: EmailStatePatch, now: &str, is_gmail: bool) -> Map<String, Value> {    let mut row = Map::new();    if let Some(read) = patch.read {        row.insert("unread".to_string(), Value::Bool(!read));    }    if let Some(starred) = patch.starred {        row.insert("starred".to_string(), Value::Bool(starred));    }    if let Some(inbox) = patch.inbox {        row.insert("in_inbox".to_string(), Value::Bool(inbox));    }    if let Some(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)]pub enum EmailFolder {    Inbox,    Archived,    Bin,    All,}impl EmailFolder {    pub const fn as_str(self) -> &'static str {        match self {            EmailFolder::Inbox => "inbox",            EmailFolder::Archived => "archived",            EmailFolder::Bin => "bin",            EmailFolder::All => "all",        }    }    /// `EMAIL_FOLDERS`, in order.    pub const ALL: [EmailFolder; 4] = [        EmailFolder::Inbox,        EmailFolder::Archived,        EmailFolder::Bin,        EmailFolder::All,    ];    pub fn parse(value: &str) -> Option<Self> {        Self::ALL.into_iter().find(|f| f.as_str() == value)    }}impl std::fmt::Display for EmailFolder {    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)]pub struct EmailFolderFilter {    /// 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,}pub const fn 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.pub fn email_folder_sql(folder: EmailFolder, alias: &str) -> String {    let filter = email_folder_filter(folder);    let mut parts = vec![format!(        "{alias}.trashed_at IS {}",        if filter.binned { "NOT NULL" } else { "NULL" }    )];    if let Some(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)]pub struct EmailThreadMemberState {    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)]pub struct EmailThreadState {    /// 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.pub fn fold_thread_state(members: &[EmailThreadMemberState]) -> EmailThreadState {    if members.is_empty() {        return EmailThreadState::default();    }    let mut trashed_at: Option<&str> = None;    let mut all_trashed = true;    for member in members {        let Some(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)]pub enum ThreadMark {    Unread,    Starred,    Binned,    Archived,}impl ThreadMark {    /// The mark's line in set `email` (`kits/shell/lines/email.json`).    pub fn line(self) -> &'static str {        match self {            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.pub fn 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.pub fn 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;