Cotton code
329 lines · 13.9 KB · RustRaw
//! One conversation per person, out of however many threads it took (schema//! v36, spec 2026-09-05-mac-ingest-messages-calls-design §D4). The port of//! `packages/core/src/engine/conversations.ts`.//!//! THE MERGE IS A READ, NOT A REWRITE. Storage keeps a thread per counterpart//! contact, and a person reachable from two numbers has two contacts and two//! threads. Merging them at WRITE time would mean that adding a second number//! to a person moves rows — an op per message, in a log that is forever, to//! express a fact that is one column on one contact. So the file stays as it//! is, and every reader — the app, the Mac window, MCP — groups DM threads by//! the person their contact resolves to and interleaves the messages by when//! they were sent.//!//! PURE, and takes its rows: no driver, no clock, no store. That is what lets//! the app and the server both use it and get the same answer, which is the//! whole reason it is one function in core rather than three implementations//! that agree until they do not.//!//! GROUPS NEVER MERGE. A WhatsApp group and an iMessage group with the same//! people in it are different groups — different admins, different history,//! different names — and folding them would put words in a room they were never//! said in.use std::cmp::Ordering;use std::collections::HashMap;use serde::{Deserialize, Serialize};use crate::constants::ThreadKind;/// The columns of a thread this grouping needs.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ConversationThread {    pub id: String,    pub kind: ThreadKind,    /// The counterpart, for a DM. `None` on a group, and on a DM nobody has    /// named.    pub contact_id: Option<String>,    /// The thread's own title — a group's name, or the label an unnamed DM    /// carries.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub title: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub last_message_at: Option<String>,}/// The columns of a contact this grouping needs.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ConversationContact {    pub id: String,    pub person_id: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub display_name: Option<String>,}/// The columns of a person this grouping needs.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ConversationPerson {    pub id: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub full_name: Option<String>,}/// One message, as a merged timeline carries it.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ConversationMessage {    pub id: String,    pub thread_id: String,    /// ISO-8601 UTC. The ONE thing the merge orders by.    pub sent_at: String,    /// Which transport it arrived over — the badge a merged conversation needs.    ///    /// A plain `String` rather than [`crate::constants::MessageChannel`],    /// deliberately: [`channels_present`] has to be able to REPORT a channel    /// this build has no word for, and an enum could not hold one.    pub channel: String,}/// A conversation: what a reader draws as ONE row and opens as ONE timeline.////// `person_id` is `None` for the conversations that did NOT merge — a group,/// and a DM whose contact resolves to nobody. Those are conversations of/// exactly one thread, which is the honest answer: two unnamed numbers are not/// known to be the same human, and guessing would put a stranger's words under/// somebody's name.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Conversation {    /// Stable across reads: `person:<id>` for a merged one, `thread:<id>` for a    /// lone one. Derived rather than minted, so a reader can key a list on it    /// and a re-read does not reshuffle anything.    pub key: String,    pub person_id: Option<String>,    /// The person's name for a merged conversation, the thread's title    /// otherwise, and `None` when neither exists. Core mints no English: a    /// reader with nothing here words the row itself.    pub title: Option<String>,    /// Every thread folded into this conversation.    pub thread_ids: Vec<String>,    /// The newest `last_message_at` across those threads, or `None`.    pub last_message_at: Option<String>,}/// A JavaScript truthy string: `null`, `undefined` and `""` are all falsy, and/// this engine tests `thread.contactId` and `contact.personId` that way.////// Ported rather than tightened, because `Option::is_some` alone would make a/// contact whose `person_id` is the empty string MERGE two threads under the/// key `person:` — an id nobody can open, which is exactly the outcome the/// "does not merge under a person the file no longer holds" rule exists to/// prevent. Pinned by vector.fn truthy(value: Option<&String>) -> Option<&str> {    value.map(String::as_str).filter(|v| !v.is_empty())}/// Group DM threads by the person their contact resolves to.////// The rules, in the order they apply://////   1. a GROUP is always its own conversation. Nothing merges into it and it///      merges into nothing.///   2. a DM whose contact has a `person_id` joins that person's conversation.///      Two numbers, one person, one conversation — which is the whole point.///   3. a DM whose contact resolves to nobody, or which has no contact at all,///      is its own conversation.////// Order is by activity, newest first, and a conversation with no activity at/// all sorts last rather than first: an empty thread is not news.pub fn group_threads_by_person(    threads: &[ConversationThread],    contacts: &[ConversationContact],    people: &[ConversationPerson],) -> Vec<Conversation> {    // `new Map(rows.map(…))` — a later row with the same id REPLACES an earlier    // one, which is what `HashMap::insert` does too.    let contact_by_id: HashMap<&str, &ConversationContact> = contacts        .iter()        .map(|contact| (contact.id.as_str(), contact))        .collect();    let person_by_id: HashMap<&str, &ConversationPerson> = people        .iter()        .map(|person| (person.id.as_str(), person))        .collect();    // Insertion-ordered, because the sort below is stable and the TypeScript's    // `order` array is what it sorts. A `HashMap` here would let the hasher's    // seed decide a tie between two silent conversations.    let mut conversations: Vec<Conversation> = Vec::new();    for thread in threads {        let contact = truthy(thread.contact_id.as_ref())            .and_then(|id| contact_by_id.get(id))            .copied();        // A person the file no longer holds is NOT a merge: an archived or        // deleted person leaves the contact pointing at nothing, and folding        // two threads under an id nobody can open would be worse than leaving        // them apart.        let person = if thread.kind == ThreadKind::Dm {            contact                .and_then(|c| truthy(c.person_id.as_ref()))                .and_then(|id| person_by_id.get(id))                .copied()        } else {            None        };        let key = match person {            Some(person) => format!("person:{}", person.id),            None => format!("thread:{}", thread.id),        };        if let Some(existing) = conversations.iter_mut().find(|c| c.key == key) {            existing.thread_ids.push(thread.id.clone());            existing.last_message_at = newer(                existing.last_message_at.as_deref(),                thread.last_message_at.as_deref(),            )            .map(str::to_string);            continue;        }        conversations.push(Conversation {            key,            person_id: person.map(|p| p.id.clone()),            // `??`, not `||`: an EMPTY title is a title, and it wins over the            // contact's display name exactly as an empty `full_name` wins over            // everything. Pinned by vector on both halves.            title: match person {                Some(person) => person.full_name.clone(),                None => thread                    .title                    .clone()                    .or_else(|| contact.and_then(|c| c.display_name.clone())),            },            thread_ids: vec![thread.id.clone()],            last_message_at: thread.last_message_at.clone(),        });    }    for conversation in &mut conversations {        // `Array.prototype.sort()` with no comparator, which is a UTF-16        // code-unit sort; Rust's is by UTF-8 bytes. The two agree on every        // string below U+E000, which every thread id (a ULID) is.        conversation.thread_ids.sort();    }    conversations.sort_by(by_last_message_desc);    conversations}/// Every message of a conversation's threads, as ONE list, oldest first.////// Oldest first because that is how a conversation is READ — the bubble above/// came before the bubble below — and a merged timeline that ran the other way/// would be the one place in the app where it did not.////// Ties break on `(thread_id, id)` rather than being left to the input order:/// two sources stamp to the second, so an iMessage and a WhatsApp message that/// landed in the same second must not swap places between two reads of the same/// file.////// The TypeScript takes a `Map<threadId, messages>` and reads only its/// `.values()`; this takes the per-thread lists themselves, because the keys/// are never looked at and the comparator is total, so the iteration order/// provably cannot reach the answer. (The TypeScript test proves the same thing/// by re-running with the map reversed; that case comes over as a test here.)////// The instants are compared as STRINGS, which is the TypeScript's own/// behaviour and not an approximation of it — an offset-bearing `sent_at` would/// sort by its text rather than by its moment. Every row this reads carries a/// `timestamp`-coded column, which is `…Z` with millisecond precision, so the/// two orders coincide on every input the function can see.pub fn merge_timelines<'a>(    messages_by_thread: impl IntoIterator<Item = &'a [ConversationMessage]>,) -> Vec<&'a ConversationMessage> {    let mut all: Vec<&ConversationMessage> = Vec::new();    for messages in messages_by_thread {        all.extend(messages);    }    all.sort_by(|a, b| {        a.sent_at            .cmp(&b.sent_at)            .then_with(|| a.thread_id.cmp(&b.thread_id))            .then_with(|| a.id.cmp(&b.id))    });    all}/// The channels a conversation actually holds, in `MESSAGE_CHANNELS` order.////// What the badges on a conversation row are drawn from. Ordered by the/// vocabulary rather than by first appearance, so the same two channels always/// render as the same pair of badges in the same places and a reader is not/// asked to notice that the order moved.////// Takes the channels rather than the conversation because a thread's channel/// is not a column — the CHANNEL IS ON THE MESSAGE, which is exactly what lets/// one DM thread carry an iMessage and an SMS to the same person. The/// TypeScript's parameter is `{ channel: string }[]` for the same reason: the/// thread list's aggregate knows a thread's distinct channels and nothing else/// about them, and a signature demanding a whole message would have made it/// invent ids and instants to satisfy a type.////// The vocabulary is `&[&str]` rather than/// `&[`[`crate::constants::MessageChannel`]`]` because the whole point of the/// tail is a channel the vocabulary does not contain.pub fn channels_present<'a>(    channels: impl IntoIterator<Item = &'a str>,    vocabulary: &[&str],) -> Vec<String> {    // A `Set`, so first-appearance order and duplicates are both gone before    // anything is ordered.    let mut present: Vec<&str> = Vec::new();    for channel in channels {        if !present.contains(&channel) {            present.push(channel);        }    }    let mut out: Vec<String> = vocabulary        .iter()        .filter(|channel| present.contains(channel))        .map(|channel| (*channel).to_string())        .collect();    // A channel outside the vocabulary is a file ahead of this build. It is    // REPORTED, at the end, rather than dropped: a badge nobody has a word for    // is better than a message that appears to have arrived from nowhere.    let mut extra: Vec<String> = present        .into_iter()        .filter(|channel| !vocabulary.contains(channel))        .map(str::to_string)        .collect();    // `.sort()` again — code units there, bytes here, and a channel name is    // ASCII in every build that has ever written one.    extra.sort();    out.extend(extra);    out}/// The later of two instants, either of which may be absent.fn newer<'a>(a: Option<&'a str>, b: Option<&'a str>) -> Option<&'a str> {    match (a, b) {        (None, b) => b,        (a, None) => a,        (Some(a), Some(b)) => Some(if a >= b { a } else { b }),    }}/// Newest activity first; a conversation with none sorts last, then by key.////// The instants are compared as STRINGS, exactly as the TypeScript does. Two/// spellings of one moment (`…14:00+05:30` and `…09:30Z`) therefore do not/// compare equal, and the one whose TEXT is larger sorts first. Pinned by/// vector rather than corrected, because a `last_message_at` is written by the/// store's `timestamp` codec and is always `…Z`.fn by_last_message_desc(a: &Conversation, b: &Conversation) -> Ordering {    if a.last_message_at == b.last_message_at {        return a.key.cmp(&b.key);    }    match (a.last_message_at.as_deref(), b.last_message_at.as_deref()) {        (None, _) => Ordering::Greater,        (_, None) => Ordering::Less,        (Some(a), Some(b)) => b.cmp(a),    }}#[cfg(test)]#[path = "conversations_tests.rs"]mod tests;