//! Exhaustive, because this is a PURE function every reader shares: the app, //! the Mac window and MCP all fold threads with it, and a disagreement between //! them would be one surface showing a person two conversations while another //! shows one. use super::*; use crate::constants::MessageChannel; /// `MESSAGE_CHANNELS`, as the vocabulary the badges are ordered by. fn vocabulary() -> [&'static str; 5] { MessageChannel::ALL.map(MessageChannel::as_str) } fn person(id: &str, full_name: Option<&str>) -> ConversationPerson { ConversationPerson { id: id.to_string(), full_name: full_name.map(str::to_string), } } fn contact(id: &str, person_id: Option<&str>, display_name: Option<&str>) -> ConversationContact { ConversationContact { id: id.to_string(), person_id: person_id.map(str::to_string), display_name: display_name.map(str::to_string), } } fn people() -> Vec { vec![ person("person-ravi", Some("Ravi Kumar")), person("person-asha", Some("Asha")), ] } fn contacts() -> Vec { vec![ contact("c-ravi-1", Some("person-ravi"), Some("Ravi")), contact("c-ravi-2", Some("person-ravi"), Some("Ravi (iCloud)")), contact("c-asha", Some("person-asha"), Some("Asha")), contact("c-unknown", None, Some("+91 98…")), contact("c-orphan", Some("person-deleted"), Some("Someone")), ] } /// The TypeScript's `thread({ … })` helper: a DM with no contact and no title /// unless the case says otherwise. fn thread(id: &str) -> ConversationThread { ConversationThread { id: id.to_string(), kind: ThreadKind::Dm, contact_id: None, title: None, last_message_at: None, } } fn dm(id: &str, contact_id: &str, last_message_at: Option<&str>) -> ConversationThread { ConversationThread { contact_id: Some(contact_id.to_string()), last_message_at: last_message_at.map(str::to_string), ..thread(id) } } fn message(id: &str, thread_id: &str, sent_at: &str, channel: &str) -> ConversationMessage { ConversationMessage { id: id.to_string(), thread_id: thread_id.to_string(), sent_at: sent_at.to_string(), channel: channel.to_string(), } } fn keyed(conversations: &[Conversation]) -> Vec<&str> { conversations.iter().map(|c| c.key.as_str()).collect() } // ── groupThreadsByPerson ───────────────────────────────────────────────────── /// The whole point: two contacts, two threads, one human. Storage never merges /// them, because adding a second number to a person would otherwise move rows /// in a log that is forever. #[test] fn folds_two_numbers_of_one_person_into_one_conversation() { let threads = [ dm("t-imessage", "c-ravi-2", Some("2026-09-05T10:00:00.000Z")), dm("t-whatsapp", "c-ravi-1", Some("2026-09-05T09:00:00.000Z")), ]; assert_eq!( group_threads_by_person(&threads, &contacts(), &people()), [Conversation { key: "person:person-ravi".into(), person_id: Some("person-ravi".into()), title: Some("Ravi Kumar".into()), thread_ids: vec!["t-imessage".into(), "t-whatsapp".into()], // The NEWEST of the two, so the merged row sorts where the person // last actually spoke. last_message_at: Some("2026-09-05T10:00:00.000Z".into()), }] ); } /// Two unnamed numbers are not known to be the same human, and guessing would /// put a stranger's words under somebody's name. #[test] fn leaves_an_unresolved_dm_as_its_own_conversation() { let threads = [ dm("t-1", "c-unknown", Some("2026-09-05T09:00:00.000Z")), ConversationThread { title: Some("Someone".into()), last_message_at: Some("2026-09-05T08:00:00.000Z".into()), ..thread("t-2") }, ]; let conversations = group_threads_by_person(&threads, &contacts(), &people()); assert_eq!( conversations .iter() .map(|c| (c.key.as_str(), c.person_id.as_deref(), c.title.as_deref())) .collect::>(), [ ("thread:t-1", None, Some("+91 98…")), ("thread:t-2", None, Some("Someone")), ] ); } /// A WhatsApp group and an iMessage group with the same people in them are /// different groups, and folding them would put words in a room they were never /// said in. #[test] fn never_merges_groups_even_when_they_share_a_contact_column() { let group = |id: &str, last: &str| ConversationThread { kind: ThreadKind::Group, title: Some("Quillby site".into()), last_message_at: Some(last.to_string()), ..thread(id) }; let threads = [ group("g-1", "2026-09-05T09:00:00.000Z"), group("g-2", "2026-09-05T08:00:00.000Z"), ]; let conversations = group_threads_by_person(&threads, &contacts(), &people()); assert_eq!(keyed(&conversations), ["thread:g-1", "thread:g-2"]); assert!(conversations.iter().all(|c| c.person_id.is_none())); } /// An archived or deleted person leaves the contact pointing at nothing; /// folding two threads under an id nobody can open is worse than leaving them /// apart. #[test] fn does_not_merge_under_a_person_the_file_no_longer_holds() { let threads = [dm("t-1", "c-orphan", None), dm("t-2", "c-orphan", None)]; let conversations = group_threads_by_person(&threads, &contacts(), &people()); assert_eq!(keyed(&conversations), ["thread:t-1", "thread:t-2"]); } #[test] fn orders_by_activity_newest_first_with_silent_conversations_last() { let threads = [ dm("t-quiet", "c-unknown", None), dm("t-old", "c-asha", Some("2026-09-01T09:00:00.000Z")), dm("t-new", "c-ravi-1", Some("2026-09-05T09:00:00.000Z")), ]; assert_eq!( keyed(&group_threads_by_person(&threads, &contacts(), &people())), [ "person:person-ravi", "person:person-asha", // An empty thread is not news. "thread:t-quiet", ] ); } #[test] fn answers_nothing_for_nothing() { assert!(group_threads_by_person(&[], &contacts(), &people()).is_empty()); } #[test] fn mints_no_english_for_a_person_with_no_name() { let threads = [dm("t-1", "c-ravi-1", None)]; let conversations = group_threads_by_person(&threads, &contacts(), &[person("person-ravi", None)]); assert_eq!(conversations[0].title, None); } // ── mergeTimelines ─────────────────────────────────────────────────────────── #[test] fn interleaves_two_threads_into_one_list_oldest_first() { let imessage = [ message("m-1", "t-imessage", "2026-09-05T09:00:00.000Z", "imessage"), message("m-3", "t-imessage", "2026-09-05T09:02:00.000Z", "imessage"), ]; let whatsapp = [message( "m-2", "t-whatsapp", "2026-09-05T09:01:00.000Z", "whatsapp", )]; let merged = merge_timelines([&imessage[..], &whatsapp[..]]); assert_eq!( merged .iter() .map(|m| (m.id.as_str(), m.channel.as_str())) .collect::>(), [ ("m-1", "imessage"), ("m-2", "whatsapp"), ("m-3", "imessage"), ] ); } /// 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. #[test] fn breaks_a_same_second_tie_the_same_way_every_time() { let same = "2026-09-05T09:00:00.000Z"; let b = [message("m-2", "t-b", same, "cotton")]; let a = [message("m-1", "t-a", same, "cotton")]; let ids = |merged: Vec<&ConversationMessage>| merged.iter().map(|m| m.id.clone()).collect::>(); assert_eq!(ids(merge_timelines([&b[..], &a[..]])), ["m-1", "m-2"]); // …and the reverse insertion order lands identically. The Rust port takes // the per-thread lists rather than a map, so this is the same proof one // step earlier: the answer cannot depend on which list arrived first. assert_eq!(ids(merge_timelines([&a[..], &b[..]])), ["m-1", "m-2"]); } #[test] fn breaks_a_tie_within_one_thread_on_the_message_id() { let same = "2026-09-05T09:00:00.000Z"; let one = [ message("m-b", "t-a", same, "cotton"), message("m-a", "t-a", same, "cotton"), ]; let merged = merge_timelines([&one[..]]); assert_eq!( merged.iter().map(|m| m.id.as_str()).collect::>(), ["m-a", "m-b"] ); } #[test] fn merge_answers_nothing_for_nothing() { assert!(merge_timelines([]).is_empty()); } // ── channelsPresent ────────────────────────────────────────────────────────── /// Vocabulary order, not first-appearance order, so the same pair of badges /// always renders the same way in the same places. #[test] fn reports_the_channels_a_conversation_holds_in_vocabulary_order() { assert_eq!( channels_present(["sms", "whatsapp", "sms"], &vocabulary()), ["whatsapp", "sms"] ); } /// A file ahead of this build. A badge nobody has a word for is better than a /// message that appears to have arrived from nowhere. #[test] fn reports_a_channel_outside_the_vocabulary_rather_than_dropping_it() { assert_eq!( channels_present(["cotton", "signal"], &vocabulary()), ["cotton", "signal"] ); } #[test] fn channels_answers_nothing_for_nothing() { assert!(channels_present([], &vocabulary()).is_empty()); } // ── vectors, read out of Node ──────────────────────────────────────────────── /// VECTOR — the vocabulary itself, in its declared order, which is the order /// the badges render in. #[test] fn the_message_channels_are_the_typescripts_own() { assert_eq!(vocabulary(), ["cotton", "whatsapp", "imessage", "sms", "instagram"]); } /// VECTOR — eight channel sets through the real vocabulary and through an /// EMPTY one, exactly as Node answered them. /// /// The last three pin things reasoning gets wrong: the extras are sorted by /// code unit, so `SMS` and `Signal` come before `signal` and `telegram`; the /// empty string is a channel like any other and sorts first among the extras; /// and with an empty vocabulary EVERY channel is an extra, so the whole answer /// is sorted rather than in the vocabulary's order. #[test] fn the_channel_lists_are_the_typescripts_own() { let vectors: &[(&[&str], &[&str], &[&str])] = &[ ( &["sms", "whatsapp", "sms"], &["whatsapp", "sms"], &["sms", "whatsapp"], ), ( &["cotton", "signal"], &["cotton", "signal"], &["cotton", "signal"], ), (&[], &[], &[]), ( &["sms", "imessage", "whatsapp", "cotton"], &["cotton", "whatsapp", "imessage", "sms"], &["cotton", "imessage", "sms", "whatsapp"], ), ( &["telegram", "signal", "Signal", "SMS", "sms"], &["sms", "SMS", "Signal", "signal", "telegram"], &["SMS", "Signal", "signal", "sms", "telegram"], ), ( &["zzz", "aaa", "zzz", "cotton"], &["cotton", "aaa", "zzz"], &["aaa", "cotton", "zzz"], ), (&["", "cotton"], &["cotton", ""], &["", "cotton"]), (&["imessage"], &["imessage"], &["imessage"]), ]; for (input, expected, expected_empty_vocabulary) in vectors { assert_eq!( channels_present(input.iter().copied(), &vocabulary()), *expected, "for {input:?}" ); assert_eq!( channels_present(input.iter().copied(), &[]), *expected_empty_vocabulary, "for {input:?} with no vocabulary" ); } } /// VECTOR — a person whose `fullName` is the EMPTY STRING keeps it as the /// conversation's title, and one with no `fullName` at all falls to `None` /// rather than to the contact's display name. `??` is nullish, not falsy, and /// the person branch never looks at the contact. #[test] fn a_persons_own_name_wins_even_when_it_is_empty() { let people = [ person("person-blank", Some("")), person("person-nameless", None), ]; let contacts = [ contact("c-blank", Some("person-blank"), Some("Blank")), contact("c-nameless", Some("person-nameless"), Some("Contact name")), ]; let blank = [dm("t-1", "c-blank", Some("2026-09-05T09:00:00.000Z"))]; let out = group_threads_by_person(&blank, &contacts, &people); assert_eq!(out[0].key, "person:person-blank"); assert_eq!(out[0].title.as_deref(), Some("")); let nameless = [dm("t-1", "c-nameless", Some("2026-09-05T09:00:00.000Z"))]; let out = group_threads_by_person(&nameless, &contacts, &people); assert_eq!(out[0].key, "person:person-nameless"); assert_eq!(out[0].title, None); } /// VECTOR — the EMPTY STRING is falsy in the two places this engine tests a /// string, and both matter. A contact whose `person_id` is `""` must not merge /// two threads under the key `person:`; a thread whose `contact_id` is `""` /// must not look a contact up at all. #[test] fn an_empty_id_is_falsy_the_way_javascript_reads_it() { let contacts = [ contact("c-empty-person", Some(""), Some("Empty person id")), contact("c-unknown", None, Some("+91 98…")), ]; let threads = [ dm("t-1", "c-empty-person", Some("2026-09-05T09:00:00.000Z")), dm("t-2", "c-empty-person", Some("2026-09-04T09:00:00.000Z")), ]; let out = group_threads_by_person(&threads, &contacts, &people()); assert_eq!(keyed(&out), ["thread:t-1", "thread:t-2"]); assert_eq!(out[0].title.as_deref(), Some("Empty person id")); let empty_contact = [ConversationThread { contact_id: Some(String::new()), title: Some("Titled".into()), last_message_at: Some("2026-09-05T09:00:00.000Z".into()), ..thread("t-1") }]; let out = group_threads_by_person(&empty_contact, &contacts, &people()); assert_eq!(keyed(&out), ["thread:t-1"]); assert_eq!(out[0].title.as_deref(), Some("Titled")); } /// VECTOR — the title fallback chain, all four rungs. #[test] fn the_title_falls_from_the_thread_to_the_contact_to_nothing() { let contacts = [ contact("c-unknown", None, Some("+91 98…")), contact("c-no-display", None, None), ]; let title_of = |t: ConversationThread| { group_threads_by_person(&[t], &contacts, &people())[0] .title .clone() }; // An EMPTY thread title beats the contact's display name — `??` again. assert_eq!( title_of(ConversationThread { title: Some(String::new()), ..dm("t-1", "c-unknown", None) }), Some(String::new()) ); // A missing one falls through to it. assert_eq!( title_of(dm("t-1", "c-unknown", None)), Some("+91 98…".to_string()) ); // Neither, and the answer is nothing at all. assert_eq!(title_of(dm("t-1", "c-no-display", None)), None); // A contact the contacts list does not hold is the same as no contact. assert_eq!(title_of(dm("t-1", "c-missing", None)), None); } /// VECTOR — a GROUP carrying a `contact_id` is still its own conversation, and /// the two of them break their `last_message_at` tie on the key. #[test] fn a_group_carrying_a_contact_id_is_still_its_own_conversation() { let group = |id: &str| ConversationThread { kind: ThreadKind::Group, contact_id: Some("c-ravi-1".into()), title: Some("Site".into()), last_message_at: Some("2026-09-05T09:00:00.000Z".into()), ..thread(id) }; let threads = [group("g-1"), group("g-2")]; let out = group_threads_by_person(&threads, &contacts(), &people()); assert_eq!(keyed(&out), ["thread:g-1", "thread:g-2"]); assert!(out.iter().all(|c| c.person_id.is_none())); } /// VECTOR — `thread_ids` come back SORTED, not in arrival order, and the sort /// is by code unit: digits before uppercase before lowercase. #[test] fn the_thread_ids_are_sorted_not_left_in_arrival_order() { let threads = [ dm("t-zulu", "c-ravi-1", Some("2026-09-01T09:00:00.000Z")), dm("t-Alpha", "c-ravi-2", Some("2026-09-05T09:00:00.000Z")), dm("t-10", "c-ravi-1", None), dm("t-2", "c-ravi-2", Some("2026-09-03T09:00:00.000Z")), ]; let out = group_threads_by_person(&threads, &contacts(), &people()); assert_eq!( out, [Conversation { key: "person:person-ravi".into(), person_id: Some("person-ravi".into()), title: Some("Ravi Kumar".into()), thread_ids: vec![ "t-10".into(), "t-2".into(), "t-Alpha".into(), "t-zulu".into() ], last_message_at: Some("2026-09-05T09:00:00.000Z".into()), }] ); } /// VECTOR — three conversations sharing one `last_message_at` sort by KEY, so /// `person:` sorts above `thread:` for no reason other than the alphabet, and /// two silent conversations do the same. #[test] fn an_equal_last_message_breaks_on_the_conversation_key() { let contacts = [ contact("c-unknown", None, Some("+91 98…")), contact("c-no-display", None, None), contact("c-asha", Some("person-asha"), Some("Asha")), ]; let at = "2026-09-05T09:00:00.000Z"; let threads = [ dm("t-b", "c-unknown", Some(at)), dm("t-a", "c-no-display", Some(at)), dm("t-c", "c-asha", Some(at)), ]; assert_eq!( keyed(&group_threads_by_person(&threads, &contacts, &people())), ["person:person-asha", "thread:t-a", "thread:t-b"] ); let silent = [thread("t-z"), thread("t-a")]; assert_eq!( keyed(&group_threads_by_person(&silent, &contacts, &people())), ["thread:t-a", "thread:t-z"] ); } /// VECTOR — the conversation order compares `last_message_at` as a STRING, and /// so does the merged timeline's `sent_at`. Two spellings of ONE moment /// (`…14:00:00.000+05:30` and `…09:30:00.000Z`) therefore do not compare equal, /// and the one whose TEXT is larger wins. Pinned rather than corrected: every /// value either function reads comes out of the store's `timestamp` codec, /// which is always `…Z` with millisecond precision, so the text order and the /// instant order coincide on every input they can see. #[test] fn instants_are_compared_lexically_not_as_moments() { let contacts = [ contact("c-unknown", None, Some("+91 98…")), contact("c-no-display", None, None), ]; let threads = [ dm( "t-offset", "c-unknown", Some("2026-09-05T14:00:00.000+05:30"), ), dm("t-utc", "c-no-display", Some("2026-09-05T09:30:00.000Z")), ]; assert_eq!( keyed(&group_threads_by_person(&threads, &contacts, &people())), ["thread:t-offset", "thread:t-utc"] ); let utc = [message( "x-utc", "t-a", "2026-09-05T09:30:00.000Z", "cotton", )]; let offset = [message( "x-offset", "t-b", "2026-09-05T14:00:00.000+05:30", "cotton", )]; assert_eq!( merge_timelines([&utc[..], &offset[..]]) .iter() .map(|m| m.id.as_str()) .collect::>(), ["x-utc", "x-offset"] ); } /// VECTOR — five messages across three threads, and the order Node merged them /// into from BOTH insertion orders. #[test] fn the_merged_orders_are_the_typescripts_own() { let b = [ message("m-4", "t-b", "2026-09-05T09:03:00.000Z", "cotton"), message("m-1", "t-b", "2026-09-05T09:00:00.000Z", "cotton"), ]; let a = [ message("m-2", "t-a", "2026-09-05T09:01:00.000Z", "cotton"), message("m-5", "t-a", "2026-09-05T09:04:00.000Z", "cotton"), ]; let c = [message("m-3", "t-c", "2026-09-05T09:02:00.000Z", "cotton")]; let ids = |merged: Vec<&ConversationMessage>| merged.iter().map(|m| m.id.clone()).collect::>(); assert_eq!( ids(merge_timelines([&b[..], &a[..], &c[..]])), ["m-1", "m-2", "m-3", "m-4", "m-5"] ); assert_eq!( ids(merge_timelines([&c[..], &a[..], &b[..]])), ["m-1", "m-2", "m-3", "m-4", "m-5"] ); // Same instant across two threads: the thread id decides first, the message // id second — so `t-a`'s pair comes whole before `t-b`'s. let same = "2026-09-05T09:00:00.000Z"; let tb = [ message("m-2", "t-b", same, "cotton"), message("m-1", "t-b", same, "cotton"), ]; let ta = [ message("m-9", "t-a", same, "cotton"), message("m-0", "t-a", same, "cotton"), ]; assert_eq!( ids(merge_timelines([&tb[..], &ta[..]])), ["m-0", "m-9", "m-1", "m-2"] ); // Two rows identical in all three sort keys keep their input order — the // sort is stable on both sides. let dup = [ message("dup", "t-a", same, "sms"), message("dup", "t-a", same, "imessage"), ]; assert_eq!( merge_timelines([&dup[..]]) .iter() .map(|m| m.channel.as_str()) .collect::>(), ["sms", "imessage"] ); } /// VECTOR — the whole shape of a three-thread read, field for field, as Node /// printed it. The merged conversation carries the NEWEST of its threads' /// instants, and the silent one is last. #[test] fn the_grouped_shape_is_the_typescripts_own() { let threads = [ dm("t-a", "c-ravi-1", Some("2026-09-05T09:00:00.000Z")), dm("t-b", "c-ravi-2", Some("2026-09-06T09:00:00.000Z")), dm("t-c", "c-asha", Some("2026-09-04T09:00:00.000Z")), dm("t-d", "c-unknown", None), ]; assert_eq!( group_threads_by_person(&threads, &contacts(), &people()), [ Conversation { key: "person:person-ravi".into(), person_id: Some("person-ravi".into()), title: Some("Ravi Kumar".into()), thread_ids: vec!["t-a".into(), "t-b".into()], last_message_at: Some("2026-09-06T09:00:00.000Z".into()), }, Conversation { key: "person:person-asha".into(), person_id: Some("person-asha".into()), title: Some("Asha".into()), thread_ids: vec!["t-c".into()], last_message_at: Some("2026-09-04T09:00:00.000Z".into()), }, Conversation { key: "thread:t-d".into(), person_id: None, title: Some("+91 98…".into()), thread_ids: vec!["t-d".into()], last_message_at: None, }, ] ); } /// The wire shape, since a `Conversation` crosses to a renderer as JSON. #[test] fn a_conversation_serialises_camel_case() { let threads = [dm("t-a", "c-ravi-1", Some("2026-09-05T09:00:00.000Z"))]; let conversation = &group_threads_by_person(&threads, &contacts(), &people())[0]; assert_eq!( serde_json::to_value(conversation).expect("a conversation serialises"), serde_json::json!({ "key": "person:person-ravi", "personId": "person-ravi", "title": "Ravi Kumar", "threadIds": ["t-a"], "lastMessageAt": "2026-09-05T09:00:00.000Z", }) ); }