2742 lines · 99.5 KB · RustRaw
//! `packages/core/__tests__/services/messagesImport.service.test.ts`, case for//! case — 42 of its 43 (the `authentication` block asks a service about a//! session, and there is no session in this crate).//!//! The tests that matter are the ones that were the DATABASE's job when this//! engine lived on an edge function: idempotence (the unique index), group//! resolution by key then by fingerprint overlap, and the fact that an import//! writes nothing twice. A port that got any of those wrong would look fine on//! the first run and duplicate a decade of somebody's conversations on the//! second.//!//! # The file these tests run against//!//! The library is driver-in and opens nothing; these tests drive it against a//! REAL in-memory SQLite file built from `cotton_store`'s generated schema — the//! same text the phone's file is created from — exactly as the sharing suite//! does. A hand-rolled fake driver would be a second answer to "what shape is//! this table", and every case here would keep passing after the shape changed//! under it. The CHECKs are the point: `uq_cotton_msg_messages_external` IS//! idempotence, and `json_type(meta) = 'object'` is what a doubly-encoded patch//! dies on.//!//! Every number, name and message body is invented//! [nothing-real-ever-goes-in-cotton-s-public-tree].use std::cell::RefCell;use rusqlite::types::Value as RVal;use cotton_store::create::apply_schema;use cotton_store::driver::Driver;use super::*;use std::collections::BTreeSet;use serde_json::Map;use cotton_store::protocol::fingerprint::message::{content_fingerprint, ContentFingerprintInput, CONTENT_EXTERNAL_ID_PREFIX};use crate::import::group::group_external_key;use crate::import::envelope::{EnvelopeMessage, EnvelopeThread, EnvelopeThreadParticipant, ImportBatch};use crate::messages::resolve_contact::{ContactDriver, ContactError, ContactHandle, ContactHandleKind, Region};use cotton_rules::change::{Change, OpKind};use crate::import::envelope::{Direction, EnvelopeMedia, EnvelopeReaction};const WORKSPACE: &str = "11111111-1111-4111-8111-111111111111";const OWNER: &str = "22222222-2222-4222-8222-222222222222";const NOW: &str = "2026-08-22T00:00:00.000Z";const RESERVED: &str = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";// ── the file ────────────────────────────────────────────────────────────────struct TestFile { db: Driver, minted: RefCell<usize>,}impl TestFile { fn open() -> TestFile { let db = Driver::open_in_memory().expect("an in-memory file opens"); apply_schema(&db).expect("the schema applies"); db.run( "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)", &[text(WORKSPACE), text("Test Owner"), text(OWNER), text(NOW)], ) .expect("the workspace row"); TestFile { db, minted: RefCell::new(0), } } /// A minted row id. Shaped like a uuid so nothing downstream can tell it /// from one, and COUNTED so a test can name the id it expects. fn next_id(&self) -> String { let mut minted = self.minted.borrow_mut(); *minted += 1; format!("00000000-0000-4000-8000-{:012}", *minted) } fn seed(&self, table: &str, values: &[(&str, RVal)]) { let columns: Vec<&str> = values.iter().map(|(name, _)| *name).collect(); let holes = vec!["?"; columns.len()].join(", "); let sql = format!( "INSERT INTO {table} ({}) VALUES ({holes})", columns.join(", ") ); let bound: Vec<RVal> = values.iter().map(|(_, value)| value.clone()).collect(); self.db .run(&sql, &bound) .unwrap_or_else(|error| panic!("seeding {table}: {error}")); } fn run(&self, sql: &str, params: &[RVal]) { self.db.run(sql, params).expect("the statement runs"); } fn rows(&self, sql: &str) -> Vec<cotton_store::driver::Row> { self.db.all(sql, &[]).expect("a read") } fn one(&self, sql: &str) -> Option<cotton_store::driver::Row> { self.db.get(sql, &[]).expect("a read") } fn count(&self, table: &str) -> i64 { self.one(&format!("SELECT COUNT(*) AS n FROM {table}")) .and_then(|row| row.int("n")) .unwrap_or(0) } /// Apply a batch of changes the way the fold does: update the row where it /// exists, insert it where it does not. The engine's patches are partial on /// purpose (a title heal writes two columns), so an insert-only apply would /// die on a NOT NULL the engine never meant to fill. fn apply(&self, changes: &[Change]) -> Result<(), String> { for change in changes { if change.kind == OpKind::Delete { self.db .run(&format!("DELETE FROM {} WHERE id = ?", change.table), &[text(&change.row_id)]) .map_err(|error| error.to_string())?; continue; } let Some(patch) = &change.patch else { continue; }; let exists = self .db .get( &format!("SELECT id FROM {} WHERE id = ?", change.table), &[text(&change.row_id)], ) .map_err(|error| error.to_string())? .is_some(); let columns: Vec<&str> = patch.keys().map(String::as_str).collect(); let mut bound: Vec<RVal> = patch.values().map(to_sql).collect(); let sql = if exists { bound.push(text(&change.row_id)); format!( "UPDATE {} SET {} WHERE id = ?", change.table, columns .iter() .map(|column| format!("{column} = ?")) .collect::<Vec<_>>() .join(", ") ) } else { format!( "INSERT INTO {} ({}) VALUES ({})", change.table, columns.join(", "), vec!["?"; columns.len()].join(", ") ) }; self.db .run(&sql, &bound) .map_err(|error| format!("{}: {error}", change.table))?; } Ok(()) }}fn text(value: &str) -> RVal { RVal::Text(value.to_string())}fn maybe(value: Option<&str>) -> RVal { value.map(text).unwrap_or(RVal::Null)}/// A JSON patch value as the column holds it. An array or an object is stored as/// its TEXT, which is what the `json_type` CHECKs read.fn to_sql(value: &Value) -> RVal { match value { Value::Null => RVal::Null, Value::Bool(flag) => RVal::Integer(i64::from(*flag)), Value::Number(number) => match number.as_i64() { Some(integer) => RVal::Integer(integer), None => RVal::Real(number.as_f64().unwrap_or_default()), }, Value::String(string) => RVal::Text(string.clone()), other => RVal::Text(other.to_string()), }}// ── the driver ──────────────────────────────────────────────────────────────impl ContactDriver for TestFile { fn people_handles( &self, workspace_id: &str, kind: ContactHandleKind, ) -> Result<Vec<crate::messages::resolve_contact::PersonHandleRow>, ContactError> { let rows = self .db .all( &crate::messages::resolve_contact::people_handles_sql(cotton_store::protocol::who::shared_held(&self.db), kind), &[text(workspace_id)], ) .map_err(|error| ContactError(error.to_string()))?; Ok(rows .iter() .map(|row| crate::messages::resolve_contact::PersonHandleRow { id: row.text("id").unwrap_or_default().to_string(), full_name: row.text("full_name").map(str::to_string), value: row.text("value").map(str::to_string), }) .collect()) } fn contact_by_handle( &self, workspace_id: &str, handle: &ContactHandle, ) -> Result<Option<crate::messages::resolve_contact::ContactRow>, ContactError> { let row = self .db .get( &crate::messages::resolve_contact::contact_by_handle_sql(cotton_store::protocol::who::shared_held(&self.db)), &[ text(workspace_id), text(handle.kind.as_str()), text(&handle.value), ], ) .map_err(|error| ContactError(error.to_string()))?; Ok(row.map(|row| contact_row(&row))) } fn contact_by_phone( &self, workspace_id: &str, phone: &str, ) -> Result<Option<crate::messages::resolve_contact::ContactRow>, ContactError> { let row = self .db .get( &crate::messages::resolve_contact::contact_by_phone_sql(cotton_store::protocol::who::shared_held(&self.db)), &[text(workspace_id), text(phone)], ) .map_err(|error| ContactError(error.to_string()))?; Ok(row.map(|row| contact_row(&row))) }}fn contact_row(row: &cotton_store::driver::Row) -> crate::messages::resolve_contact::ContactRow { crate::messages::resolve_contact::ContactRow { id: row.text("id").unwrap_or_default().to_string(), display_name: row.text("display_name").map(str::to_string), person_id: row.text("person_id").map(str::to_string), }}/// Every method runs the statement the module DECLARES, so the suite tests the/// SQL the engine ships rather than a paraphrase written beside it.impl ImportDriver for TestFile { fn dm_thread_for_contact( &self, workspace_id: &str, contact_id: &str, ) -> Result<Option<String>, ContactError> { Ok(self .db .get( DM_THREAD_BY_CONTACT_SQL, &[text(workspace_id), text(contact_id)], ) .map_err(sql_error)? .and_then(|row| row.text("id").map(str::to_string))) } fn thread_by_id( &self, workspace_id: &str, id: &str, kind: ThreadKind, ) -> Result<Option<ThreadHit>, ContactError> { Ok(self .db .get( THREAD_BY_ID_SQL, &[text(id), text(workspace_id), text(kind.as_str())], ) .map_err(sql_error)? .map(|row| ThreadHit { id: row.text("id").unwrap_or_default().to_string(), contact_id: row.text("contact_id").map(str::to_string), })) } fn known_external_ids( &self, thread_id: &str, channel: &str, ids: &[&str], ) -> Result<BTreeSet<String>, ContactError> { let mut bound = vec![text(thread_id), text(channel)]; bound.extend(ids.iter().map(|id| text(id))); Ok(self .db .all(&known_external_ids_sql(ids.len()), &bound) .map_err(sql_error)? .iter() .filter_map(|row| row.text("external_id").map(str::to_string)) .collect()) } fn thread_stats(&self, thread_id: &str, channel: &str) -> Result<ThreadStats, ContactError> { let row = self .db .get(THREAD_STATS_SQL, &[text(thread_id), text(channel)]) .map_err(sql_error)?; Ok(match row { Some(row) => ThreadStats { count: row.int("n").unwrap_or(0), oldest_sent_at: row.text("oldest").map(str::to_string), newest_sent_at: row.text("newest").map(str::to_string), }, None => ThreadStats::default(), }) } fn group_thread_by_key( &self, workspace_id: &str, external_key: &str, ) -> Result<Option<(String, Option<String>)>, ContactError> { Ok(self .db .get( GROUP_THREAD_BY_KEY_SQL, &[text(workspace_id), text(external_key)], ) .map_err(sql_error)? .map(|row| { ( row.text("id").unwrap_or_default().to_string(), row.text("title").map(str::to_string), ) })) } fn thread_by_overlap( &self, workspace_id: &str, channel: &str, kind: ThreadKind, ids: &[&str], ) -> Result<Option<OverlapHit>, ContactError> { let mut bound = vec![text(workspace_id), text(kind.as_str()), text(channel)]; bound.extend(ids.iter().map(|id| text(id))); Ok(self .db .get(&overlap_sql(ids.len()), &bound) .map_err(sql_error)? .map(|row| OverlapHit { thread_id: row.text("thread_id").unwrap_or_default().to_string(), contact_id: row.text("contact_id").map(str::to_string), matched: row.int("n").unwrap_or(0), })) } fn jid_group_threads( &self, workspace_id: &str, ) -> Result<Vec<(String, Option<String>)>, ContactError> { Ok(self .db .all(JID_GROUP_THREADS_SQL, &[text(workspace_id)]) .map_err(sql_error)? .iter() .map(|row| { ( row.text("id").unwrap_or_default().to_string(), row.text("title").map(str::to_string), ) }) .collect()) } fn participants_of(&self, thread_id: &str) -> Result<Vec<ParticipantRow>, ContactError> { Ok(self .db .all(PARTICIPANTS_SQL, &[text(thread_id)]) .map_err(sql_error)? .iter() .map(|row| ParticipantRow { id: row.text("id").unwrap_or_default().to_string(), contact_id: row.text("contact_id").map(str::to_string), display_name: row.text("display_name").map(str::to_string), }) .collect()) } fn thread_last_message_at( &self, thread_id: &str, ) -> Result<Option<Option<String>>, ContactError> { Ok(self .db .get(THREAD_LAST_MESSAGE_AT_SQL, &[text(thread_id)]) .map_err(sql_error)? .map(|row| row.text("last_message_at").map(str::to_string))) } fn thread_external_key(&self, thread_id: &str) -> Result<Option<Option<String>>, ContactError> { Ok(self .db .get(THREAD_EXTERNAL_KEY_SQL, &[text(thread_id)]) .map_err(sql_error)? .map(|row| row.text("external_key").map(str::to_string))) } fn unlinked_replies(&self, thread_id: &str) -> Result<Vec<(String, String)>, ContactError> { Ok(self .db .all(UNLINKED_REPLIES_SQL, &[text(thread_id)]) .map_err(sql_error)? .iter() .map(|row| { ( row.text("id").unwrap_or_default().to_string(), row.text("reply_to_external_id") .unwrap_or_default() .to_string(), ) }) .collect()) } fn held_without_media( &self, thread_id: &str, channel: &str, ids: &[&str], ) -> Result<Vec<BareRow>, ContactError> { let mut bound = vec![text(thread_id), text(channel)]; bound.extend(ids.iter().map(|id| text(id))); Ok(self .db .all(&held_without_media_sql(ids.len()), &bound) .map_err(sql_error)? .iter() .map(|row| BareRow { id: row.text("id").unwrap_or_default().to_string(), external_id: row.text("external_id").unwrap_or_default().to_string(), body: row.text("body").map(str::to_string), meta: row.text("meta").map(str::to_string), }) .collect()) } fn messages_by_external_ids( &self, thread_id: &str, channel: &str, ids: &[&str], ) -> Result<Vec<(String, String)>, ContactError> { let mut bound = vec![text(thread_id), text(channel)]; bound.extend(ids.iter().map(|id| text(id))); Ok(self .db .all(&reply_targets_sql(ids.len()), &bound) .map_err(sql_error)? .iter() .map(|row| { ( row.text("id").unwrap_or_default().to_string(), row.text("external_id").unwrap_or_default().to_string(), ) }) .collect()) } fn rows_in_minute( &self, thread_id: &str, channel: &str, minute: &str, ) -> Result<Vec<MinuteRow>, ContactError> { Ok(self .db .all(ROWS_IN_MINUTE_SQL, &[text(thread_id), text(channel), text(minute), text(minute)]) .map_err(sql_error)? .iter() .map(|row| MinuteRow { id: row.text("id").unwrap_or_default().to_string(), external_id: row.text("external_id").map(str::to_string), direction: row.text("direction").unwrap_or_default().to_string(), body: row.text("body").map(str::to_string), meta: row.text("meta").map(str::to_string), }) .collect()) } fn real_id_bodies_in_minute( &self, thread_id: &str, channel: &str, minute: &str, ) -> Result<Vec<String>, ContactError> { Ok(self .db .all(REAL_ID_BODIES_IN_MINUTE_SQL, &[text(thread_id), text(channel), text(minute), text(minute)]) .map_err(sql_error)? .iter() .filter_map(|row| row.text("body").map(str::to_string)) .collect()) } fn message_by_external_id( &self, workspace_id: &str, channel: &str, external_id: &str, ) -> Result<Option<ChangeTarget>, ContactError> { Ok(self .db .get(MESSAGE_BY_EXTERNAL_ID_SQL, &[text(workspace_id), text(channel), text(external_id)]) .map_err(sql_error)? .map(|row| change_target(&row))) } fn self_names_json(&self, workspace_id: &str) -> Result<Option<Option<String>>, ContactError> { Ok(self .db .get(SELF_NAMES_SQL, &[text(workspace_id)]) .map_err(sql_error)? .map(|row| row.text("msg_import_self_names").map(str::to_string))) } fn owner_region(&self, workspace_id: &str) -> Result<Option<Region>, ContactError> { cotton_store::phone_fold::region_hint(&self.db, workspace_id).map_err(sql_error) }}fn sql_error(error: cotton_store::error::StoreError) -> ContactError { ContactError(error.to_string())}// ── the fixtures ────────────────────────────────────────────────────────────fn envelope(external_id: &str) -> EnvelopeMessage { EnvelopeMessage { phone: Some("919999000011".to_string()), email: None, sender_label: None, display_name: Some("Ravi".to_string()), direction: Direction::In, body: "hello".to_string(), media: None, sent_at: "2021-03-04T09:00:00.000Z".to_string(), external_id: external_id.to_string(), reply_to_external_id: None, reactions: None, meta: None, }}/// The group form: no phone on the message, a label instead.fn from_label(external_id: &str, sender_label: &str) -> EnvelopeMessage { EnvelopeMessage { phone: None, sender_label: Some(sender_label.to_string()), display_name: None, ..envelope(external_id) }}/// A counterpart nobody named — the dm-block form.fn anonymous(external_id: &str, body: &str) -> EnvelopeMessage { EnvelopeMessage { phone: None, display_name: None, body: body.to_string(), ..envelope(external_id) }}fn batch(messages: Vec<EnvelopeMessage>) -> ImportBatch { ImportBatch { workspace_id: WORKSPACE.to_string(), channel: "whatsapp".to_string(), thread: None, dm: None, messages, new_thread_id: None, }}fn participant(label: &str, phone: Option<&str>) -> EnvelopeThreadParticipant { EnvelopeThreadParticipant { label: label.to_string(), phone: phone.map(str::to_string), email: None, person_id: None, handle: None, }}fn group_block( title: &str, key: &str, participants: Vec<EnvelopeThreadParticipant>,) -> EnvelopeThread { EnvelopeThread { kind: "group".to_string(), title: title.to_string(), external_key: key.to_string(), participants, }}/// One run, applied — the Rust twin of the TypeScript's `run(...)`.fn import(file: &TestFile, batch: &ImportBatch) -> ImportReport { try_import(file, batch).expect("the import runs")}fn try_import(file: &TestFile, batch: &ImportBatch) -> Result<ImportReport, ImportError> { let mut new_id = || file.next_id(); run_import( file, ImportArgs { batch, namespace: WORKSPACE, now: NOW, new_id: &mut new_id, }, &mut |changes| file.apply(changes), )}fn probe(file: &TestFile, batch: &ImportBatch) -> ProbeReport { probe_import(file, batch).expect("the probe runs")}fn seed_person(file: &TestFile, id: &str, name: &str) { file.seed( "cotton_people", &[ ("id", text(id)), ("workspace_id", text(WORKSPACE)), ("full_name", text(name)), ("created_at", text(NOW)), ("updated_at", text(NOW)), ], );}fn seed_contact(file: &TestFile, id: &str, phone: &str, display_name: Option<&str>) { file.seed( "cotton_msg_contacts", &[ ("id", text(id)), ("workspace_id", text(WORKSPACE)), ("phone_e164", text(phone)), ("display_name", maybe(display_name)), ("created_at", text(NOW)), ("updated_at", text(NOW)), ], );}fn column(file: &TestFile, sql: &str, name: &str) -> Vec<Option<String>> { file.rows(sql) .iter() .map(|row| row.text(name).map(str::to_string)) .collect()}fn one_text(file: &TestFile, sql: &str, name: &str) -> Option<String> { file.one(sql) .and_then(|row| row.text(name).map(str::to_string))}// ── the pure helpers ────────────────────────────────────────────────────────#[test]fn a_label_key_ignores_layout_and_case() { assert_eq!(import_label_key(" ODO VARNISH "), "odo varnish"); assert_eq!(import_label_key("WRENNA"), "wrenna"); assert_eq!(import_label_key("\u{feff} Ravi \n"), "ravi");}#[test]fn a_label_that_is_a_number_is_not_a_name() { assert!(label_looks_like_phone("+91 99990 00011")); assert!(label_looks_like_phone("(020) 7946-0000")); assert!(!label_looks_like_phone("Ravi")); // Seven characters is under the floor, `+` or no `+`. assert!(!label_looks_like_phone("1234567")); assert!(!label_looks_like_phone("+")); // A number with a letter in it is a name that happens to have digits. assert!(!label_looks_like_phone("Room 101 crew"));}// ── dm import ───────────────────────────────────────────────────────────────#[test]fn creates_the_contact_and_thread_and_files_the_messages_as_imported() { let file = TestFile::open(); let report = import( &file, &batch(vec![ EnvelopeMessage { body: "first".to_string(), ..envelope("wa:1") }, EnvelopeMessage { body: "second".to_string(), direction: Direction::Out, ..envelope("wa:2") }, ]), ); assert_eq!(report.totals.chats, 1); assert_eq!(report.totals.inserted, 2); assert_eq!(report.totals.skipped, 0); let rows = file .rows("SELECT origin, channel, external_id FROM cotton_msg_messages ORDER BY external_id"); let seen: Vec<(String, String, String)> = rows .iter() .map(|row| { ( row.text("origin").unwrap_or_default().to_string(), row.text("channel").unwrap_or_default().to_string(), row.text("external_id").unwrap_or_default().to_string(), ) }) .collect(); assert_eq!( seen, vec![ ( "imported".to_string(), "whatsapp".to_string(), "wa:1".to_string() ), ( "imported".to_string(), "whatsapp".to_string(), "wa:2".to_string() ), ] ); // Nobody verified anything, and an archive of 400 chats must not redecorate // the People page. let contact = file .one("SELECT phone_e164, auth_user_id, person_id FROM cotton_msg_contacts") .expect("a contact"); assert_eq!(contact.text("phone_e164"), Some("919999000011")); assert_eq!(contact.text("auth_user_id"), None); assert_eq!(contact.text("person_id"), None);}#[test]fn re_running_the_same_export_writes_zero_new_rows() { let file = TestFile::open(); let again = batch(vec![ envelope("wa:1"), EnvelopeMessage { body: "two".to_string(), ..envelope("wa:2") }, ]); import(&file, &again); let second = import(&file, &again); assert_eq!(second.totals.inserted, 0); assert_eq!(second.totals.skipped, 2); assert_eq!(file.count("cotton_msg_messages"), 2);}#[test]fn dedupes_within_a_batch_because_an_export_can_repeat_a_line() { let file = TestFile::open(); let report = import(&file, &batch(vec![envelope("wa:1"), envelope("wa:1")])); assert_eq!(report.totals.inserted, 1); assert_eq!(report.totals.skipped, 1); assert_eq!(file.count("cotton_msg_messages"), 1);}#[test]fn keeps_an_owner_corrected_name_over_whatever_the_export_says() { let file = TestFile::open(); seed_contact(&file, "c1", "919999000011", Some("Ravi Kumar")); import( &file, &batch(vec![EnvelopeMessage { display_name: Some("ravi (work)".to_string()), ..envelope("wa:1") }]), ); assert_eq!( one_text( &file, "SELECT display_name FROM cotton_msg_contacts WHERE id = 'c1'", "display_name" ) .as_deref(), Some("Ravi Kumar") );}#[test]fn fills_a_name_we_never_had() { let file = TestFile::open(); seed_contact(&file, "c1", "919999000011", None); import(&file, &batch(vec![envelope("wa:1")])); assert_eq!( one_text( &file, "SELECT display_name FROM cotton_msg_contacts WHERE id = 'c1'", "display_name" ) .as_deref(), Some("Ravi") );}#[test]fn reuses_an_existing_dm_thread_rather_than_forking_the_conversation() { let file = TestFile::open(); import(&file, &batch(vec![envelope("wa:1")])); import( &file, &batch(vec![EnvelopeMessage { body: "later".to_string(), ..envelope("wa:2") }]), ); assert_eq!(file.count("cotton_msg_threads"), 1); assert_eq!(file.count("cotton_msg_contacts"), 1);}#[test]fn splits_a_batch_into_one_thread_per_person() { let file = TestFile::open(); import( &file, &batch(vec![ envelope("wa:1"), EnvelopeMessage { phone: Some("919999000022".to_string()), display_name: Some("Priya".to_string()), ..envelope("wa:2") }, ]), ); assert_eq!(file.count("cotton_msg_threads"), 2); assert_eq!(file.count("cotton_msg_contacts"), 2);}// ── the caller's reserved thread id ─────────────────────────────────────────#[test]fn creates_a_dm_thread_under_the_id_the_caller_reserved() { let file = TestFile::open(); import( &file, &ImportBatch { dm: Some(participant("Ravi", Some("919999000011"))), new_thread_id: Some(RESERVED.to_string()), ..batch(vec![envelope("wa:1")]) }, ); assert_eq!( column(&file, "SELECT id FROM cotton_msg_threads", "id"), vec![Some(RESERVED.to_string())] );}#[test]fn mints_its_own_ids_where_one_reserved_id_cannot_serve_n_threads() { let file = TestFile::open(); import( &file, &ImportBatch { new_thread_id: Some(RESERVED.to_string()), ..batch(vec![ envelope("wa:1"), EnvelopeMessage { phone: Some("919999000022".to_string()), display_name: Some("Asha".to_string()), ..envelope("wa:2") }, ]) }, ); let ids = column(&file, "SELECT id FROM cotton_msg_threads", "id"); assert_eq!(ids.len(), 2); assert!(!ids.contains(&Some(RESERVED.to_string())));}#[test]fn creates_a_group_thread_under_the_reserved_id_too() { let file = TestFile::open(); import( &file, &ImportBatch { thread: Some(group_block( "Weekend", "wa:group:weekend", vec![participant("Asha", None)], )), new_thread_id: Some(RESERVED.to_string()), ..batch(vec![from_label("wa:g1", "Asha")]) }, ); assert_eq!( column(&file, "SELECT id FROM cotton_msg_threads", "id"), vec![Some(RESERVED.to_string())] );}#[test]fn the_reserved_id_is_ignored_when_the_conversation_already_exists() { let file = TestFile::open(); import( &file, &ImportBatch { dm: Some(participant("Ravi", Some("919999000011"))), ..batch(vec![envelope("wa:1")]) }, ); let existing = column(&file, "SELECT id FROM cotton_msg_threads", "id"); import( &file, &ImportBatch { dm: Some(participant("Ravi", Some("919999000011"))), new_thread_id: Some(RESERVED.to_string()), ..batch(vec![EnvelopeMessage { body: "again".to_string(), ..envelope("wa:2") }]) }, ); assert_eq!( column(&file, "SELECT id FROM cotton_msg_threads", "id"), existing );}// ── the thread denorm ───────────────────────────────────────────────────────#[test]fn stamps_last_message_at_and_the_preview_from_the_newest_imported_row() { let file = TestFile::open(); import( &file, &batch(vec![ EnvelopeMessage { sent_at: "2021-03-04T09:00:00.000Z".to_string(), body: "old line".to_string(), ..envelope("wa:1") }, EnvelopeMessage { sent_at: "2023-06-01T10:00:00.000Z".to_string(), body: "newest line".to_string(), ..envelope("wa:2") }, ]), ); let thread = file .one("SELECT last_message_at, last_message_preview FROM cotton_msg_threads") .expect("a thread"); assert_eq!( thread.text("last_message_at"), Some("2023-06-01T10:00:00.000Z") ); assert_eq!(thread.text("last_message_preview"), Some("newest line"));}#[test]fn never_drags_a_live_threads_stamp_backwards() { let file = TestFile::open(); import( &file, &batch(vec![EnvelopeMessage { sent_at: "2026-01-01T00:00:00.000Z".to_string(), body: "current".to_string(), ..envelope("wa:new") }]), ); import( &file, &batch(vec![EnvelopeMessage { sent_at: "2020-01-01T00:00:00.000Z".to_string(), body: "ancient".to_string(), ..envelope("wa:old") }]), ); let thread = file .one("SELECT last_message_at, last_message_preview FROM cotton_msg_threads") .expect("a thread"); assert_eq!( thread.text("last_message_at"), Some("2026-01-01T00:00:00.000Z") ); assert_eq!(thread.text("last_message_preview"), Some("current"));}#[test]fn stamps_a_group_thread_the_same_way() { let file = TestFile::open(); import( &file, &ImportBatch { thread: Some(group_block( "Site crew", "wa:group:site-crew", vec![participant("Ravi", Some("919999000011"))], )), ..batch(vec![EnvelopeMessage { sent_at: "2024-02-02T08:00:00.000Z".to_string(), body: "group word".to_string(), ..from_label("wa:g1", "Ravi") }]) }, ); let thread = file .one("SELECT last_message_at, last_message_preview FROM cotton_msg_threads WHERE kind = 'group'") .expect("a group thread"); assert_eq!( thread.text("last_message_at"), Some("2024-02-02T08:00:00.000Z") ); assert_eq!(thread.text("last_message_preview"), Some("group word"));}// ── replies ─────────────────────────────────────────────────────────────────#[test]fn links_a_reply_to_the_line_it_quotes_whichever_arrives_first() { let file = TestFile::open(); // The reply lands in the FIRST batch, before the message it quotes. import( &file, &batch(vec![EnvelopeMessage { body: "yes".to_string(), reply_to_external_id: Some("wa:1".to_string()), ..envelope("wa:2") }]), ); assert_eq!( one_text( &file, "SELECT reply_to_id FROM cotton_msg_messages WHERE external_id = 'wa:2'", "reply_to_id" ), None ); import( &file, &batch(vec![EnvelopeMessage { body: "are you there?".to_string(), ..envelope("wa:1") }]), ); let quoted = one_text( &file, "SELECT id FROM cotton_msg_messages WHERE external_id = 'wa:1'", "id", ); assert_eq!( one_text( &file, "SELECT reply_to_id FROM cotton_msg_messages WHERE external_id = 'wa:2'", "reply_to_id" ), quoted );}#[test]fn reports_what_it_still_could_not_link_so_a_truncated_export_says_so() { let file = TestFile::open(); let report = import( &file, &batch(vec![EnvelopeMessage { body: "yes".to_string(), reply_to_external_id: Some("wa:never-exported".to_string()), ..envelope("wa:2") }]), ); assert_eq!(report.totals.unresolved_replies, 1);}// ── group import ────────────────────────────────────────────────────────────fn cricket(messages: Vec<EnvelopeMessage>, title: &str) -> ImportBatch { ImportBatch { thread: Some(group_block( title, "wa:group:cricket", vec![ participant("Ravi", Some("919999000011")), participant("Priya", Some("919999000022")), ], )), ..batch(messages) }}#[test]fn creates_the_thread_its_members_and_attributes_each_sender() { let file = TestFile::open(); let report = import( &file, &cricket( vec![ from_label("wa:1", "Ravi"), EnvelopeMessage { body: "hi".to_string(), ..from_label("wa:2", "Priya") }, EnvelopeMessage { phone: None, sender_label: None, display_name: None, direction: Direction::Out, body: "me".to_string(), ..envelope("wa:3") }, ], "Cricket", ), ); let group = report.group.expect("a group"); assert!(group.thread_created); assert_eq!(group.participant_count, 2); let thread = file .one("SELECT kind, contact_id, title FROM cotton_msg_threads") .expect("a thread"); // A group carries no contact_id — the invariant that makes it structurally // unreachable to a visitor. assert_eq!(thread.text("kind"), Some("group")); assert_eq!(thread.text("contact_id"), None); assert_eq!(thread.text("title"), Some("Cricket")); assert_eq!(file.count("cotton_msg_thread_participants"), 2); let senders = column( &file, "SELECT sender_participant_id FROM cotton_msg_messages ORDER BY external_id", "sender_participant_id", ); assert!(senders[0].is_some()); assert!(senders[1].is_some()); assert_ne!(senders[0], senders[1]); // The owner's own line has no participant row. assert_eq!(senders[2], None); assert!(column( &file, "SELECT sender_contact_id FROM cotton_msg_messages", "sender_contact_id" ) .iter() .all(Option::is_none)); let seats = file.rows( "SELECT display_name, contact_id FROM cotton_msg_thread_participants ORDER BY display_name", ); assert_eq!(seats[0].text("display_name"), Some("Priya")); assert!(seats[0].text("contact_id").is_some()); assert_eq!(seats[1].text("display_name"), Some("Ravi")); assert!(seats[1].text("contact_id").is_some());}#[test]fn finds_the_same_group_again_by_its_key() { let file = TestFile::open(); import(&file, &cricket(vec![from_label("wa:1", "Ravi")], "Cricket")); let second = import( &file, &cricket( vec![EnvelopeMessage { body: "more".to_string(), ..from_label("wa:2", "Ravi") }], "Cricket", ), ); assert!(!second.group.expect("a group").thread_created); assert_eq!(file.count("cotton_msg_threads"), 1);}#[test]fn finds_a_renamed_group_by_message_overlap_and_inherits_the_new_key() { let file = TestFile::open(); import( &file, &cricket( vec![ from_label("wa:1", "Ravi"), EnvelopeMessage { body: "hi".to_string(), ..from_label("wa:2", "Priya") }, ], "Cricket", ), ); let thread_id = one_text(&file, "SELECT id FROM cotton_msg_threads", "id").expect("a thread"); // The owner renamed the group: a new export, a new key. file.run("UPDATE cotton_msg_threads SET external_key = NULL", &[]); let second = import( &file, &ImportBatch { thread: Some(group_block( "Cricket 2026", "wa:group:cricket-2026", vec![participant("Ravi", Some("919999000011"))], )), ..batch(vec![ EnvelopeMessage { body: "hi".to_string(), ..from_label("wa:2", "Ravi") }, EnvelopeMessage { body: "new".to_string(), ..from_label("wa:9", "Ravi") }, ]) }, ); assert_eq!(file.count("cotton_msg_threads"), 1); let group = second.group.expect("a group"); assert_eq!(group.thread_id, thread_id); assert!(!group.thread_created); assert_eq!( one_text( &file, "SELECT external_key FROM cotton_msg_threads", "external_key" ) .as_deref(), Some("wa:group:cricket-2026") );}#[test]fn never_clobbers_a_title_the_owner_set() { let file = TestFile::open(); import(&file, &cricket(vec![from_label("wa:1", "Ravi")], "Cricket")); file.run( "UPDATE cotton_msg_threads SET title = 'Sunday cricket'", &[], ); import( &file, &cricket( vec![EnvelopeMessage { body: "x".to_string(), ..from_label("wa:2", "Ravi") }], "Cricket", ), ); assert_eq!( one_text(&file, "SELECT title FROM cotton_msg_threads", "title").as_deref(), Some("Sunday cricket") );}#[test]fn keeps_a_member_who_left_because_they_still_said_what_they_said() { let file = TestFile::open(); import(&file, &cricket(vec![from_label("wa:1", "Ravi")], "Cricket")); import( &file, &ImportBatch { thread: Some(group_block( "Cricket", "wa:group:cricket", vec![participant("Ravi", Some("919999000011"))], )), ..batch(vec![EnvelopeMessage { body: "x".to_string(), ..from_label("wa:2", "Ravi") }]) }, ); assert_eq!(file.count("cotton_msg_thread_participants"), 2);}// ── probe ───────────────────────────────────────────────────────────────────#[test]fn a_probe_writes_nothing_and_reports_what_an_import_would_do() { let file = TestFile::open(); let report = probe(&file, &batch(vec![envelope("wa:1"), envelope("wa:2")])); assert_eq!(report.totals.chats, 1); assert_eq!(report.totals.would_insert, 2); assert_eq!(report.totals.would_skip, 0); assert_eq!(file.count("cotton_msg_messages"), 0); assert_eq!(file.count("cotton_msg_threads"), 0); assert_eq!(file.count("cotton_msg_contacts"), 0);}#[test]fn a_probe_counts_what_is_already_there() { let file = TestFile::open(); import(&file, &batch(vec![envelope("wa:1")])); let report = probe(&file, &batch(vec![envelope("wa:1"), envelope("wa:2")])); assert_eq!(report.totals.would_insert, 1); assert_eq!(report.totals.would_skip, 1); assert_eq!( report.chats[0].existing.as_ref().expect("the counts").count, 1 );}#[test]fn a_probe_resolves_a_group_by_key_without_writing() { let file = TestFile::open(); file.seed( "cotton_msg_threads", &[ ("id", text("g1")), ("workspace_id", text(WORKSPACE)), ("contact_id", RVal::Null), ("kind", text("group")), ("title", text("Cricket")), ("external_key", text("wa:group:cricket")), ("created_at", text(NOW)), ("updated_at", text(NOW)), ], ); let report = probe( &file, &ImportBatch { thread: Some(group_block( "Cricket", "wa:group:cricket", vec![participant("Ravi", Some("919999000011"))], )), ..batch(vec![from_label("wa:1", "Ravi")]) }, ); let group = report.group.expect("a group"); assert_eq!(group.thread_id.as_deref(), Some("g1")); assert_eq!(group.matched_by, Some(MatchedBy::Key)); assert_eq!( report.participants, ParticipantsSummary { total: 1, identified: 1, unidentified: 0, unidentified_labels: Vec::new(), } ); assert_eq!(file.count("cotton_msg_contacts"), 0);}// ── unidentified participants ───────────────────────────────────────────────fn tf(messages: Vec<EnvelopeMessage>, participants: Vec<EnvelopeThreadParticipant>) -> ImportBatch { ImportBatch { thread: Some(group_block("TF", "wa:group:tf", participants)), ..batch(messages) }}#[test]fn a_label_without_a_contact_still_gets_a_participant_row() { let file = TestFile::open(); seed_person(&file, "person-odo", "Odo Varnish"); import( &file, &tf( vec![ from_label("x1", "Wrenna"), EnvelopeMessage { body: "yo".to_string(), ..from_label("x2", "Odo Varnish") }, ], vec![ participant("Wrenna", None), EnvelopeThreadParticipant { person_id: Some("person-odo".to_string()), ..participant("Odo Varnish", Some("910123462077")) }, ], ), ); let seats = file.rows( "SELECT display_name, contact_id FROM cotton_msg_thread_participants ORDER BY display_name", ); assert_eq!(seats[0].text("display_name"), Some("Odo Varnish")); assert!(seats[0].text("contact_id").is_some()); assert_eq!(seats[1].text("display_name"), Some("Wrenna")); assert_eq!(seats[1].text("contact_id"), None); assert!(column( &file, "SELECT sender_participant_id FROM cotton_msg_messages", "sender_participant_id" ) .iter() .all(Option::is_some)); assert_eq!( column( &file, "SELECT person_id FROM cotton_msg_contacts", "person_id" ), vec![Some("person-odo".to_string())] );}#[test]fn re_uses_the_participant_row_and_identifies_it_when_the_label_gains_a_number() { let file = TestFile::open(); import( &file, &tf( vec![from_label("x1", "Wrenna")], vec![participant("Wrenna", None)], ), ); import( &file, &tf( vec![from_label("x1", "Wrenna")], vec![participant(" wrenna", Some("919999000099"))], ), ); let seats = file.rows("SELECT contact_id FROM cotton_msg_thread_participants"); assert_eq!(seats.len(), 1); assert!(seats[0].text("contact_id").is_some());}#[test]fn a_probe_reports_who_is_still_to_identify() { let file = TestFile::open(); import( &file, &tf( vec![from_label("x1", "Ravi")], vec![participant("Ravi", Some("919999000011"))], ), ); let report = probe( &file, &tf( vec![EnvelopeMessage { body: "new".to_string(), ..from_label("x2", "Wrenna") }], vec![participant("Ravi", None), participant("Wrenna", None)], ), ); assert_eq!( report.participants, ParticipantsSummary { total: 2, identified: 1, unidentified: 1, unidentified_labels: vec!["Wrenna".to_string()], } );}// ── a dm with an unidentified counterpart ───────────────────────────────────#[test]fn an_unidentified_dm_becomes_a_titled_thread_found_again_by_overlap() { let file = TestFile::open(); let first = import( &file, &ImportBatch { dm: Some(participant("Asha", None)), ..batch(vec![anonymous("d1", "hello")]) }, ); assert_eq!(first.totals.inserted, 1); let thread = file .one("SELECT kind, contact_id, title FROM cotton_msg_threads") .expect("a thread"); assert_eq!(thread.text("kind"), Some("dm")); assert_eq!(thread.text("contact_id"), None); assert_eq!(thread.text("title"), Some("Asha")); assert_eq!(file.count("cotton_msg_contacts"), 0); let both = vec![ anonymous("d1", "hello"), EnvelopeMessage { direction: Direction::Out, ..anonymous("d2", "hi") }, ]; let report = probe( &file, &ImportBatch { dm: Some(participant("Asha (renamed)", None)), ..batch(both.clone()) }, ); assert_eq!(report.totals.would_insert, 1); assert_eq!(report.totals.would_skip, 1); assert_eq!( report.participants, ParticipantsSummary { total: 1, identified: 0, unidentified: 1, unidentified_labels: vec!["Asha (renamed)".to_string()], } ); import( &file, &ImportBatch { dm: Some(participant("Asha (renamed)", None)), ..batch(both) }, ); assert_eq!(file.count("cotton_msg_threads"), 1); assert_eq!(file.count("cotton_msg_messages"), 2);}#[test]fn one_shared_line_does_not_fold_a_chat_into_a_strangers_thread() { // A fingerprint is minute plus body, so a greeting forwarded to two people // in the same minute is ONE id living in two conversations. Only a MAJORITY // of the probed ids says "same conversation". let file = TestFile::open(); import( &file, &ImportBatch { dm: Some(participant("Asha", None)), ..batch( ["a1", "a2", "a3", "a4"] .iter() .map(|id| anonymous(id, id)) .collect(), ) }, ); let priya = import( &file, &ImportBatch { dm: Some(participant("Priya", None)), ..batch( ["a1", "p2", "p3", "p4", "p5"] .iter() .map(|id| anonymous(id, id)) .collect(), ) }, ); assert_eq!(priya.totals.inserted, 5); assert_eq!(priya.totals.skipped, 0); assert_eq!( column( &file, "SELECT title FROM cotton_msg_threads ORDER BY title", "title" ), vec![Some("Asha".to_string()), Some("Priya".to_string())] ); assert_eq!(file.count("cotton_msg_messages"), 9);}#[test]fn a_part_that_overlaps_nothing_lands_in_the_thread_the_caller_resolved() { let file = TestFile::open(); import( &file, &ImportBatch { dm: Some(participant("Asha", None)), ..batch( ["a1", "a2", "a3"] .iter() .map(|id| anonymous(id, id)) .collect(), ) }, ); let thread = file .one("SELECT id, created_at FROM cotton_msg_threads") .expect("a thread"); let thread_id = thread.text("id").unwrap_or_default().to_string(); let created_at = thread.text("created_at").unwrap_or_default().to_string(); // The owner identified Asha since the first import. seed_contact(&file, "c-asha", "919999000011", Some("Asha")); file.run("UPDATE cotton_msg_threads SET contact_id = 'c-asha'", &[]); // The newest part of a re-export: none of its lines are in the file yet, and // the caller hands over the thread an older part resolved. let tail: Vec<EnvelopeMessage> = ["a8", "a9"].iter().map(|id| anonymous(id, id)).collect(); let report = probe( &file, &ImportBatch { dm: Some(participant("Asha", None)), new_thread_id: Some(thread_id.clone()), ..batch(tail.clone()) }, ); assert_eq!( report.chats[0].thread_id.as_deref(), Some(thread_id.as_str()) ); assert_eq!( report.chats[0].existing.as_ref().expect("the counts").count, 3 ); assert_eq!(report.chats[0].would_insert, 2); assert_eq!(report.participants.identified, 1); assert_eq!(report.participants.unidentified, 0); let written = import( &file, &ImportBatch { dm: Some(participant("Asha", None)), new_thread_id: Some(thread_id.clone()), ..batch(tail) }, ); assert_eq!(written.totals.inserted, 2); let after = file .one("SELECT id, contact_id, created_at FROM cotton_msg_threads") .expect("one thread"); assert_eq!(after.text("id"), Some(thread_id.as_str())); assert_eq!(after.text("contact_id"), Some("c-asha")); assert_eq!(after.text("created_at"), Some(created_at.as_str())); assert_eq!( column( &file, "SELECT thread_id FROM cotton_msg_messages", "thread_id" ), vec![Some(thread_id); 5] );}#[test]fn a_dm_block_with_a_phone_behaves_like_the_phone_keyed_path() { let file = TestFile::open(); seed_person(&file, "person-asha", "Asha"); import( &file, &ImportBatch { dm: Some(EnvelopeThreadParticipant { person_id: Some("person-asha".to_string()), ..participant("Asha", Some("919999000011")) }), ..batch(vec![anonymous("d1", "hello")]) }, ); let contact = file .one("SELECT display_name, person_id FROM cotton_msg_contacts") .expect("a contact"); assert_eq!(contact.text("display_name"), Some("Asha")); assert_eq!(contact.text("person_id"), Some("person-asha")); assert_eq!( one_text(&file, "SELECT title FROM cotton_msg_threads", "title"), None );}#[test]fn a_number_as_the_label_never_becomes_a_display_name() { let file = TestFile::open(); import( &file, &ImportBatch { dm: Some(participant("+91 99990 00011", Some("919999000011"))), ..batch(vec![anonymous("d1", "hello")]) }, ); assert_eq!( column( &file, "SELECT display_name FROM cotton_msg_contacts", "display_name" ), vec![None] );}// ── the owner's export name ─────────────────────────────────────────────────#[test]fn the_owners_export_name_is_remembered_per_channel() { let file = TestFile::open(); assert_eq!( self_names(&file, WORKSPACE, "whatsapp").expect("a read"), Vec::<String>::new() ); let change = set_self_name_change(&file, WORKSPACE, "whatsapp", " Alpaca One ") .expect("the name is stored") .expect("a change"); file.apply(&[change]).expect("the write lands"); assert_eq!( self_names(&file, WORKSPACE, "whatsapp").expect("a read"), vec!["Alpaca One".to_string()] ); assert_eq!( self_names(&file, WORKSPACE, "telegram").expect("a read"), Vec::<String>::new() ); // Writing the same name again is not a write. assert_eq!( set_self_name_change(&file, WORKSPACE, "whatsapp", "Alpaca One").expect("no change"), None ); assert_eq!( set_self_name_change(&file, WORKSPACE, "whatsapp", " ").unwrap_err(), ImportError::BlankSelfName ); assert_eq!(ImportError::BlankSelfName.code(), "VALIDATION");}/// **EVERY answered name is kept, most recent first.** The owner is one person/// with several spellings — a contact name in one export, a number in another —/// and a memory that held only the latest asked "which one is you?" again on/// the very next export (the walk of 15 Sep 2026, finding d).#[test]fn every_name_the_owner_answers_with_is_remembered_most_recent_first() { let file = TestFile::open(); for name in ["Alpaca One", "+91 98765 43210", "Alpaca"] { let change = set_self_name_change(&file, WORKSPACE, "whatsapp", name) .expect("the name is stored") .expect("a change"); file.apply(&[change]).expect("the write lands"); } assert_eq!( self_names(&file, WORKSPACE, "whatsapp").expect("a read"), vec![ "Alpaca".to_string(), "+91 98765 43210".to_string(), "Alpaca One".to_string(), ], "three spellings of one person, newest first" ); // An earlier one answered again moves to the front and is not duplicated — // case and layout are not identity. let change = set_self_name_change(&file, WORKSPACE, "whatsapp", "alpaca one") .expect("stored") .expect("a change"); file.apply(&[change]).expect("the write lands"); assert_eq!( self_names(&file, WORKSPACE, "whatsapp").expect("a read"), vec![ "alpaca one".to_string(), "Alpaca".to_string(), "+91 98765 43210".to_string(), ] ); // And a second channel keeps its own list. assert_eq!( self_names(&file, WORKSPACE, "telegram").expect("a read"), Vec::<String>::new() );}#[test]fn a_workspace_that_is_not_there_is_a_not_found() { let file = TestFile::open(); let missing = self_names(&file, "99999999-9999-4999-8999-999999999999", "whatsapp"); assert_eq!(missing.unwrap_err(), ImportError::WorkspaceNotFound); assert_eq!(ImportError::WorkspaceNotFound.code(), "NOT_FOUND");}// ── imported reactions become rows ──────────────────────────────────────────fn reaction(emoji: &str, actor: &str, at: Option<&str>) -> EnvelopeReaction { EnvelopeReaction { emoji: emoji.to_string(), actor: actor.to_string(), at: at.map(str::to_string), }}#[test]fn writes_one_reaction_row_per_entry_and_leaves_the_column_empty() { let file = TestFile::open(); import( &file, &batch(vec![EnvelopeMessage { body: "the tarpaulin arrived".to_string(), reactions: Some(vec![ reaction("❤️", "owner", Some("2021-03-04T09:01:00.000Z")), reaction("👍", "919999000011", Some("2021-03-04T09:02:00.000Z")), ]), ..envelope("txt2:0123456789abcdef0123456789abcdef") }]), ); let message = file .one("SELECT id, reactions, external_id FROM cotton_msg_messages") .expect("a message"); // The fingerprint is untouched — this changes where reactions land, never // what makes two rows the same row. assert_eq!( message.text("external_id"), Some("txt2:0123456789abcdef0123456789abcdef") ); assert_eq!(message.text("reactions"), Some("[]")); let message_id = message.text("id").unwrap_or_default().to_string(); let rows = file.rows( "SELECT id, message_id, actor, emoji, created_at FROM cotton_msg_reactions ORDER BY actor", ); assert_eq!(rows.len(), 2); assert_eq!( rows[0].text("id"), Some(format!("react:{message_id}:919999000011").as_str()) ); assert_eq!(rows[0].text("emoji"), Some("👍")); assert_eq!(rows[0].text("created_at"), Some("2021-03-04T09:02:00.000Z")); assert_eq!( rows[1].text("id"), Some(format!("react:{message_id}:self").as_str()) ); assert_eq!(rows[1].text("actor"), Some("self")); assert_eq!(rows[1].text("created_at"), Some("2021-03-04T09:01:00.000Z"));}#[test]fn re_importing_the_same_chat_adds_no_second_reaction_row() { let file = TestFile::open(); let again = batch(vec![EnvelopeMessage { reactions: Some(vec![reaction( "❤️", "owner", Some("2021-03-04T09:01:00.000Z"), )]), ..envelope("txt2:0123456789abcdef0123456789abcdef") }]); import(&file, &again); import(&file, &again); assert_eq!(file.count("cotton_msg_messages"), 1); assert_eq!(file.count("cotton_msg_reactions"), 1);}#[test]fn a_reaction_with_no_instant_falls_back_to_the_messages_own() { let file = TestFile::open(); import( &file, &batch(vec![EnvelopeMessage { reactions: Some(vec![reaction("❤️", "owner", None)]), ..envelope("txt2:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") }]), ); assert_eq!( column( &file, "SELECT created_at FROM cotton_msg_reactions", "created_at" ), vec![Some("2021-03-04T09:00:00.000Z".to_string())] );}#[test]fn drops_a_reaction_whose_actor_is_not_a_phone_rather_than_minting_a_broken_id() { let file = TestFile::open(); import( &file, &batch(vec![EnvelopeMessage { reactions: Some(vec![ reaction("❤️", "Some Name", Some("2021-03-04T09:01:00.000Z")), reaction(" ", "owner", None), ]), ..envelope("txt2:ffffffffffffffffffffffffffffffff") }]), ); assert_eq!(file.count("cotton_msg_reactions"), 0); // The message still landed — a reaction we cannot key is not a reason to // lose the words. assert_eq!(file.count("cotton_msg_messages"), 1);}// ── any channel, and an email as an identity ────────────────────────────────fn on_channel(channel: &str, messages: Vec<EnvelopeMessage>) -> ImportBatch { ImportBatch { channel: channel.to_string(), ..batch(messages) }}#[test]fn imports_on_every_channel_and_stamps_each_row_with_the_one_it_arrived_on() { let file = TestFile::open(); for channel in ["whatsapp", "imessage", "sms"] { let report = import( &file, &on_channel( channel, vec![EnvelopeMessage { body: format!("hello over {channel}"), ..envelope(&format!("{channel}:1")) }], ), ); assert_eq!(report.totals.inserted, 1, "{channel}"); } let rows = file.rows("SELECT channel, origin FROM cotton_msg_messages ORDER BY channel"); let seen: Vec<(Option<&str>, Option<&str>)> = rows .iter() .map(|row| (row.text("channel"), row.text("origin"))) .collect(); // Every imported channel carries `origin: "imported"`, which is what keeps // the relay from ever mirroring one of these to anybody. assert_eq!( seen, vec![ (Some("imessage"), Some("imported")), (Some("sms"), Some("imported")), (Some("whatsapp"), Some("imported")), ] );}#[test]fn makes_a_contact_for_an_email_counterpart_not_a_nameless_thread() { let file = TestFile::open(); import( &file, &ImportBatch { dm: Some(EnvelopeThreadParticipant { email: Some("Ravi@iCloud.com".to_string()), ..participant("Ravi", None) }), ..on_channel( "imessage", vec![EnvelopeMessage { body: "on my way".to_string(), sent_at: "2026-09-05T09:00:00.000Z".to_string(), ..anonymous("im:1", "on my way") }], ) }, ); let contact = file .one("SELECT id, phone_e164, display_name FROM cotton_msg_contacts") .expect("a contact"); // No number at all — an Apple ID is an identity, and inventing a number // would put a fake handle in front of a real person. assert_eq!(contact.text("phone_e164"), None); assert_eq!(contact.text("display_name"), Some("Ravi")); let contact_id = contact.text("id").unwrap_or_default().to_string(); let handle = file .one("SELECT kind, value, contact_id FROM cotton_msg_contact_handles") .expect("a handle row"); assert_eq!(handle.text("kind"), Some("email")); assert_eq!(handle.text("value"), Some("ravi@icloud.com")); assert_eq!(handle.text("contact_id"), Some(contact_id.as_str())); // The thread hangs off the contact, not off a title. let thread = file .one("SELECT contact_id, title FROM cotton_msg_threads") .expect("a thread"); assert_eq!(thread.text("contact_id"), Some(contact_id.as_str())); assert_eq!(thread.text("title"), None);}#[test]fn keeps_the_label_only_path_for_a_counterpart_who_named_no_handle() { let file = TestFile::open(); import( &file, &ImportBatch { dm: Some(participant("Someone from the site", None)), ..batch(vec![anonymous("wa:label", "hello")]) }, ); let thread = file .one("SELECT contact_id, title FROM cotton_msg_threads") .expect("a thread"); assert_eq!(thread.text("contact_id"), None); assert_eq!(thread.text("title"), Some("Someone from the site")); assert_eq!(file.count("cotton_msg_contacts"), 0);}#[test]fn records_both_handles_a_counterpart_named_on_one_contact() { let file = TestFile::open(); import( &file, &ImportBatch { dm: Some(EnvelopeThreadParticipant { email: Some("ravi@icloud.com".to_string()), ..participant("Ravi", Some("919999000011")) }), ..on_channel("imessage", vec![anonymous("im:2", "hi")]) }, ); // Keeping only the one we keyed on would mean the next batch, carrying only // the other, mints a second contact beside them. assert_eq!(file.count("cotton_msg_contacts"), 1); let rows = file.rows("SELECT kind, value FROM cotton_msg_contact_handles ORDER BY kind"); let seen: Vec<(Option<&str>, Option<&str>)> = rows .iter() .map(|row| (row.text("kind"), row.text("value"))) .collect(); assert_eq!( seen, vec![ (Some("email"), Some("ravi@icloud.com")), // The phone stays the PRIMARY, which is what every other part of the // file keys on. (Some("phone"), Some("919999000011")), ] );}#[test]fn lets_meta_source_through_untouched_because_provenance_is_the_rows_own() { let file = TestFile::open(); let mut source = Map::new(); source.insert("service".to_string(), Value::from("iMessage")); source.insert("device".to_string(), Value::from("mac-a")); source.insert("externalId".to_string(), Value::from("guid-1")); let mut meta = Map::new(); meta.insert("source".to_string(), Value::Object(source.clone())); import( &file, &on_channel( "imessage", vec![EnvelopeMessage { meta: Some(meta), ..envelope("im:3") }], ), ); let stored = one_text( &file, "SELECT meta FROM cotton_msg_messages WHERE external_id = 'im:3'", "meta", ) .expect("the meta column"); let parsed: Value = serde_json::from_str(&stored).expect("the column holds JSON"); assert_eq!(parsed.get("source"), Some(&Value::Object(source)));}// ── the seams the TypeScript could not have ─────────────────────────────────#[test]fn a_batch_naming_no_counterpart_at_all_refuses_in_words() { let file = TestFile::open(); let refused = try_import(&file, &batch(vec![anonymous("d1", "hello")])); assert_eq!(refused.unwrap_err(), ImportError::NoUsableHandle); assert_eq!(ImportError::NoUsableHandle.code(), "IMPORT_SHAPE"); assert_eq!(file.count("cotton_msg_messages"), 0);}#[test]fn a_media_entry_rides_into_the_column_and_names_the_preview() { let file = TestFile::open(); import( &file, &batch(vec![EnvelopeMessage { body: String::new(), media: Some(vec![EnvelopeMedia { key: format!("{WORKSPACE}/messages/t/{}.jpg", "a".repeat(64)), content_type: "image/jpeg".to_string(), name: None, size_bytes: None, width: None, height: None, contact: None, duration_ms: None, playback_key: None, playback_content_type: None, file_key: None, kind: None, waveform: None, preview: None, }]), ..envelope("wa:pic") }]), ); let stored = one_text(&file, "SELECT media FROM cotton_msg_messages", "media") .expect("the media column"); let parsed: Value = serde_json::from_str(&stored).expect("the column holds JSON"); assert_eq!(parsed.as_array().map(Vec::len), Some(1)); // The denorm's preview is the one `previewForMessage` writes, not the body. assert_eq!( one_text( &file, "SELECT last_message_preview FROM cotton_msg_threads", "last_message_preview" ) .as_deref(), Some("Photo") );}/// RULE: a message sent from the phone through the Mac comes back carrying the attachment's kind, waveform and/// preview the phone made (CONTRACT "WhatsApp through the Mac": the Mac copies them from the outbox row it sent), so/// a voice note stays a voice note with its bars and a picture draws its preview at once. A Mac that sends none/// (an older one) changes nothing already landed: the same message again leaves the row as it was.#[test]fn a_sent_attachment_keeps_its_kind_waveform_and_preview_and_an_older_mac_takes_none_away() { let file = TestFile::open(); let voice = |kind: Option<crate::constants::MessageMediaKind>, waveform: Option<Vec<f64>>, preview: Option<String>| EnvelopeMedia { key: format!("{WORKSPACE}/messages/t/{}.m4a", "b".repeat(64)), content_type: "audio/mp4".to_string(), name: None, size_bytes: Some(2048.0), width: None, height: None, contact: None, duration_ms: Some(4200.0), playback_key: None, playback_content_type: None, file_key: None, kind, waveform, preview, }; let peaks = vec![0.1, 0.5, 1.0, 0.25]; let sent = EnvelopeMessage { body: String::new(), media: Some(vec![voice(Some(crate::constants::MessageMediaKind::Voice), Some(peaks.clone()), Some("PREVIEW".into()))]), ..envelope("3EB0SENTVOICE") }; import(&file, &batch(vec![sent.clone()])); let stored: Value = serde_json::from_str(&one_text(&file, "SELECT media FROM cotton_msg_messages", "media").expect("the media column")).unwrap(); assert_eq!(stored[0]["kind"], "voice"); assert_eq!(stored[0]["waveform"], serde_json::json!(peaks)); assert_eq!(stored[0]["preview"], "PREVIEW"); let media: Vec<crate::messages::MessageMedia> = serde_json::from_value(stored.clone()).expect("a message's media"); assert_eq!(crate::messages::preview::media_kind_of(&media[0]), crate::constants::MessageMediaKind::Voice, "an m4a that is a voice note"); // An older Mac sends the same message with none of the three: one row still, and what it had stays. import(&file, &batch(vec![EnvelopeMessage { media: Some(vec![voice(None, None, None)]), ..sent }])); assert_eq!(file.count("cotton_msg_messages"), 1); let again: Value = serde_json::from_str(&one_text(&file, "SELECT media FROM cotton_msg_messages", "media").unwrap()).unwrap(); assert_eq!(again, stored);}// ── one WhatsApp message, one row, whichever door it came through ──────────/// An export line: no id, keyed by its content fingerprint.fn exported(body: &str, sent_at: &str, occurrence: u64) -> EnvelopeMessage { EnvelopeMessage { body: body.to_string(), sent_at: sent_at.to_string(), external_id: content_fingerprint(&ContentFingerprintInput { sent_at, body, occurrence }) .expect("a fingerprint"), ..envelope("unused") }}/// RULE: a WhatsApp message carrying its real id takes over the export row with the same minute and text instead of writing a second copy./// Repeats of one text in one minute are claimed one each; the owner sees one row per message whichever door brought it.#[test]fn a_message_with_its_real_id_takes_over_the_export_row() { let file = TestFile::open(); import( &file, &batch(vec![ exported("on my way", "2021-03-04T09:00:00.000Z", 0), exported("on my way", "2021-03-04T09:00:00.000Z", 1), exported("later", "2021-03-04T09:05:00.000Z", 0), ]), ); let linked = |id: &str, seconds: &str| EnvelopeMessage { body: "on my way".to_string(), sent_at: format!("2021-03-04T09:00:{seconds}.000Z"), ..envelope(id) }; let report = import(&file, &batch(vec![linked("3EB0A", "12"), linked("3EB0B", "40")])); assert_eq!(report.totals.inserted, 2); assert_eq!( column(&file, "SELECT external_id FROM cotton_msg_messages ORDER BY external_id", "external_id") .into_iter() .map(|id| id.unwrap_or_default().starts_with(CONTENT_EXTERNAL_ID_PREFIX)) .collect::<Vec<_>>(), vec![false, false, true], "both repeats were taken over, 'later' was not" ); assert_eq!(file.rows("SELECT id FROM cotton_msg_messages").len(), 3); assert_eq!( one_text(&file, "SELECT sent_at FROM cotton_msg_messages WHERE external_id = '3EB0B'", "sent_at").as_deref(), Some("2021-03-04T09:00:40.000Z") ); // A re-read of the same linked messages writes nothing. let again = import(&file, &batch(vec![linked("3EB0A", "12")])); assert_eq!(again.totals.inserted, 0);}/// RULE: an export line the thread already holds under WhatsApp's real id (same minute, same text) is skipped, never written twice./// The mirror of the takeover, for an export that arrives after the linked device or the backup.#[test]fn an_export_after_the_link_writes_only_what_the_link_lacks() { let file = TestFile::open(); let linked = |id: &str, body: &str, seconds: &str| EnvelopeMessage { body: body.to_string(), sent_at: format!("2021-03-04T09:00:{seconds}.000Z"), ..envelope(id) }; import(&file, &batch(vec![linked("3EB0A", "on my way", "12"), linked("3EB0B", "on my way", "40")])); let report = import( &file, &batch(vec![ exported("on my way", "2021-03-04T09:00:00.000Z", 0), exported("on my way", "2021-03-04T09:00:00.000Z", 1), exported("on my way", "2021-03-04T09:00:00.000Z", 2), exported("later", "2021-03-04T09:05:00.000Z", 0), ]), ); assert_eq!(report.totals.inserted, 2, "a third repeat and 'later' are new; two repeats were held"); assert_eq!(report.totals.skipped, 2); assert_eq!(file.rows("SELECT id FROM cotton_msg_messages").len(), 4);}/// An export's caption-less media line: the placeholder body the importer/// writes, the empty text it is fingerprinted by, `meta.attachment`.fn exported_media(placeholder: &str, name: Option<&str>, sent_at: &str, occurrence: u64) -> EnvelopeMessage { let mut attachment = Map::new(); attachment.insert("omitted".to_string(), Value::Bool(name.is_none())); if let Some(name) = name { attachment.insert("name".to_string(), Value::from(name)); } let mut meta = Map::new(); meta.insert("attachment".to_string(), Value::Object(attachment)); EnvelopeMessage { body: placeholder.to_string(), sent_at: sent_at.to_string(), external_id: content_fingerprint(&ContentFingerprintInput { sent_at, body: "", occurrence }) .expect("a fingerprint"), meta: Some(meta), ..envelope("unused") }}/// A linked-device message that is a picture (or other media) and no words.fn linked_media(id: &str, kind: &str, body: &str, sent_at: &str) -> EnvelopeMessage { let mut meta = Map::new(); meta.insert(MEDIA_ONLY_META.to_string(), Value::from(kind)); EnvelopeMessage { body: body.to_string(), sent_at: sent_at.to_string(), meta: Some(meta), ..envelope(id) }}/// RULE: a picture-only WhatsApp message with its real id takes over the export's media line of the same minute, side and kind, instead of a second row./// The export writes it as '[image omitted]' under an empty text, so the text take-over never finds it.#[test]fn a_picture_with_its_real_id_takes_over_the_exports_media_line() { let file = TestFile::open(); import( &file, &batch(vec![ exported_media("[image omitted]", None, "2021-03-04T09:00:00.000Z", 0), exported_media("[attachment: VIDEO-2021-03-04-09-00-00.mp4]", Some("00000002-VIDEO-2021-03-04-09-00-00.mp4"), "2021-03-04T09:00:00.000Z", 1), exported_media("[<Media omitted>]", None, "2021-03-04T09:07:00.000Z", 0), ]), ); let report = import( &file, &batch(vec![ // Kinds out of the export's order: each still finds its own line. linked_media("3EB0V", "video", "Video", "2021-03-04T09:00:30.000Z"), EnvelopeMessage { media: Some(vec![EnvelopeMedia { key: "ws/messages/t/abc.jpg".to_string(), content_type: "image/jpeg".to_string(), name: None, size_bytes: None, width: None, height: None, contact: None, duration_ms: None, playback_key: None, playback_content_type: None, file_key: None, kind: None, waveform: None, preview: None, }]), ..linked_media("3EB0P", "image", "", "2021-03-04T09:00:10.000Z") }, // A bare <Media omitted> allows any kind. linked_media("3EB0S", "sticker", "Sticker", "2021-03-04T09:07:05.000Z"), // A second picture in the minute has no line left: a new row. linked_media("3EB0Q", "image", "Photo", "2021-03-04T09:00:50.000Z"), ]), ); assert_eq!(report.totals.inserted, 4); assert_eq!(file.rows("SELECT id FROM cotton_msg_messages").len(), 4, "three taken over, one new"); assert_eq!( column(&file, "SELECT external_id FROM cotton_msg_messages ORDER BY external_id", "external_id"), vec![Some("3EB0P".to_string()), Some("3EB0Q".to_string()), Some("3EB0S".to_string()), Some("3EB0V".to_string())], ); assert_eq!( one_text(&file, "SELECT body FROM cotton_msg_messages WHERE external_id = '3EB0V'", "body").as_deref(), Some("Video"), "the video took over the video line, not the image line" ); assert!( one_text(&file, "SELECT media FROM cotton_msg_messages WHERE external_id = '3EB0P'", "media") .is_some_and(|media| media.contains("abc.jpg")), "the picture's bytes came with it" ); // A re-read writes nothing. let again = import(&file, &batch(vec![linked_media("3EB0P", "image", "Photo", "2021-03-04T09:00:10.000Z")])); assert_eq!(again.totals.inserted, 0);}/// RULE: a picture never takes over a media line from the other side of the chat, nor one whose kind differs, nor a line with a caption.#[test]fn a_picture_leaves_another_sides_or_kinds_media_line_alone() { let file = TestFile::open(); let mut mine = exported_media("[image omitted]", None, "2021-03-04T09:00:00.000Z", 0); mine.direction = Direction::Out; let mut captioned = exported("look at this", "2021-03-04T09:00:00.000Z", 0); captioned.meta = exported_media("[image omitted]", None, "2021-03-04T09:00:00.000Z", 0).meta; import( &file, &batch(vec![mine, exported_media("[audio omitted]", None, "2021-03-04T09:00:00.000Z", 1), captioned]), ); import(&file, &batch(vec![linked_media("3EB0P", "image", "Photo", "2021-03-04T09:00:20.000Z")])); assert_eq!(file.rows("SELECT id FROM cotton_msg_messages").len(), 4, "nothing was taken over");}/// RULE: an export's media line the thread already holds as a picture-only message with WhatsApp's real id (same minute, side, kind) is skipped, never written twice.#[test]fn an_export_after_the_link_skips_the_pictures_it_already_holds() { let file = TestFile::open(); import( &file, &batch(vec![ linked_media("3EB0P", "image", "Photo", "2021-03-04T09:00:10.000Z"), linked_media("3EB0A", "voice", "Voice message", "2021-03-04T09:00:20.000Z"), ]), ); let report = import( &file, &batch(vec![ exported_media("[image omitted]", None, "2021-03-04T09:00:00.000Z", 0), exported_media("[audio omitted]", None, "2021-03-04T09:00:00.000Z", 1), exported_media("[image omitted]", None, "2021-03-04T09:00:00.000Z", 2), ]), ); assert_eq!(report.totals.inserted, 1, "the second image is new; the image and the voice note were held"); assert_eq!(file.rows("SELECT id FROM cotton_msg_messages").len(), 3);}/// RULE: a WhatsApp group is one thread whether its title-keyed export or its JID-keyed rows (linked device, backup) arrived first./// The JID batch takes over the export's thread and re-keys it; a later export joins the JID thread.#[test]fn a_group_is_one_thread_whether_the_export_or_the_link_came_first() { let jid_key = "wa:group:120363000000000001@g.us"; let file = TestFile::open(); import( &file, &ImportBatch { thread: Some(group_block("Weekend Plans", &group_external_key("Weekend Plans"), vec![participant("Asha", None)])), ..batch(vec![from_label("txt2:aaaa", "Asha")]) }, ); import( &file, &ImportBatch { thread: Some(group_block("Weekend Plans", jid_key, vec![participant("Asha", Some("15550001111"))])), ..batch(vec![from_label("3EB0C", "Asha")]) }, ); assert_eq!( column(&file, "SELECT external_key FROM cotton_msg_threads", "external_key"), vec![Some(jid_key.to_string())] ); assert_eq!(file.rows("SELECT id FROM cotton_msg_messages").len(), 2); let file = TestFile::open(); import( &file, &ImportBatch { thread: Some(group_block("Weekend Plans", jid_key, vec![participant("Asha", Some("15550001111"))])), ..batch(vec![from_label("3EB0C", "Asha")]) }, ); import( &file, &ImportBatch { thread: Some(group_block("Weekend plans", &group_external_key("Weekend plans"), vec![participant("Asha", None)])), ..batch(vec![from_label("txt2:aaaa", "Asha")]) }, ); assert_eq!(file.rows("SELECT id FROM cotton_msg_threads").len(), 1); assert_eq!( column(&file, "SELECT external_key FROM cotton_msg_threads", "external_key"), vec![Some(jid_key.to_string())] );}// Two JID groups with one title: an export cannot tell which it is, so it joins neither.#[test]fn an_export_never_guesses_between_two_groups_with_one_title() { let file = TestFile::open(); for (n, jid) in ["120363000000000001@g.us", "120363000000000002@g.us"].iter().enumerate() { import( &file, &ImportBatch { thread: Some(group_block("Family", &format!("wa:group:{jid}"), vec![participant("Asha", None)])), ..batch(vec![from_label(&format!("3EB0{n}"), "Asha")]) }, ); } import( &file, &ImportBatch { thread: Some(group_block("Family", &group_external_key("Family"), vec![participant("Asha", None)])), ..batch(vec![from_label("txt2:bbbb", "Asha")]) }, ); assert_eq!(file.rows("SELECT id FROM cotton_msg_threads").len(), 3);}// RULE: an edit, a delete for everyone or a reaction lands on the row its message id names; a change to a message the file lacks writes nothing.#[test]fn changes_land_on_the_message_their_id_names() { let file = TestFile::open(); import(&file, &batch(vec![envelope("D1"), envelope("D2")])); let thread = one_text(&file, "SELECT thread_id FROM cotton_msg_messages WHERE external_id = 'D1'", "thread_id") .expect("the message is in"); let at = "2021-03-04T10:00:00.000Z".to_string(); let changes = vec![ MessageChange::Edit { external_id: "D1".into(), body: "hello again".into(), at: at.clone() }, MessageChange::Reaction { external_id: "D1".into(), actor: "919999000011".into(), emoji: "👍".into(), at: at.clone() }, MessageChange::Reaction { external_id: "D1".into(), actor: "owner".into(), emoji: "❤️".into(), at: at.clone() }, MessageChange::Revoke { external_id: "D2".into(), at: at.clone() }, MessageChange::Edit { external_id: "NOT-HERE".into(), body: "x".into(), at: at.clone() }, ]; let (ops, report) = plan_message_changes(&file, WORKSPACE, "whatsapp", &changes).expect("plans"); file.apply(&ops).expect("applies"); assert_eq!( report, ChangesReport { edited: 1, revoked: 1, reacted: 2, unreacted: 0, voted: 0, missing: 1 } ); assert_eq!(one_text(&file, "SELECT body FROM cotton_msg_messages WHERE external_id = 'D1'", "body").as_deref(), Some("hello again")); assert_eq!(one_text(&file, "SELECT edited_at FROM cotton_msg_messages WHERE external_id = 'D1'", "edited_at"), Some(at.clone())); assert_eq!(one_text(&file, "SELECT body FROM cotton_msg_messages WHERE external_id = 'D2'", "body").as_deref(), Some("")); assert_eq!(one_text(&file, "SELECT deleted_at FROM cotton_msg_messages WHERE external_id = 'D2'", "deleted_at"), Some(at.clone())); assert_eq!(file.count("cotton_msg_messages"), 2, "no change becomes a message"); assert_eq!(file.count("cotton_msg_reactions"), 2); assert_eq!( one_text(&file, "SELECT DISTINCT thread_id FROM cotton_msg_reactions", "thread_id"), Some(thread) ); // Taking a reaction off removes its row; the other stays. let off = vec![MessageChange::Reaction { external_id: "D1".into(), actor: "owner".into(), emoji: String::new(), at }]; let (ops, report) = plan_message_changes(&file, WORKSPACE, "whatsapp", &off).expect("plans"); file.apply(&ops).expect("applies"); assert_eq!(report.unreacted, 1); assert_eq!(file.count("cotton_msg_reactions"), 1);}// RULE: A later change (an edit, a revoke, a reaction) finds the message it names through an index on its channel and external id, never by reading every message in the database.#[test]fn the_change_lookup_uses_the_channel_external_index() { let file = TestFile::open(); let plan = file .db .all( &format!("EXPLAIN QUERY PLAN {MESSAGE_BY_EXTERNAL_ID_SQL}"), &[text(WORKSPACE), text("whatsapp"), text("ABC")], ) .expect("a plan"); let detail = plan.iter().filter_map(|row| row.text("detail")).collect::<Vec<_>>().join(" | "); assert!( detail.contains("USING INDEX idx_cotton_msg_messages_channel_external"), "the change lookup does not use the channel/external index: {detail}" );}// RULE: An edit or a delete for everyone of a thread's newest message rewrites the thread's list line from the message as it now stands; a change to an older message leaves the line alone.#[test]fn the_thread_line_follows_an_edit_or_revoke_of_its_newest_message() { let file = TestFile::open(); let older = EnvelopeMessage { body: "first".into(), ..envelope("OLD") }; let newest = EnvelopeMessage { body: "last".into(), sent_at: "2021-03-04T09:05:00.000Z".into(), ..envelope("NEW") }; import(&file, &batch(vec![older, newest])); let line = |file: &TestFile| one_text(file, "SELECT last_message_preview FROM cotton_msg_threads", "last_message_preview"); let at_of = |file: &TestFile| one_text(file, "SELECT last_message_at FROM cotton_msg_threads", "last_message_at"); assert_eq!(line(&file).as_deref(), Some("last")); let at = "2021-03-04T10:00:00.000Z".to_string(); let edit_older = vec![MessageChange::Edit { external_id: "OLD".into(), body: "first, fixed".into(), at: at.clone() }]; let (ops, _) = plan_message_changes(&file, WORKSPACE, "whatsapp", &edit_older).expect("plans"); file.apply(&ops).expect("applies"); assert_eq!(line(&file).as_deref(), Some("last"), "an older message's edit is not the thread's line"); let edit_newest = vec![MessageChange::Edit { external_id: "NEW".into(), body: "last, fixed".into(), at: at.clone() }]; let (ops, _) = plan_message_changes(&file, WORKSPACE, "whatsapp", &edit_newest).expect("plans"); file.apply(&ops).expect("applies"); assert_eq!(line(&file).as_deref(), Some("last, fixed")); let revoke_newest = vec![MessageChange::Revoke { external_id: "NEW".into(), at }]; let (ops, _) = plan_message_changes(&file, WORKSPACE, "whatsapp", &revoke_newest).expect("plans"); file.apply(&ops).expect("applies"); assert_eq!(line(&file).as_deref(), Some("This message was deleted")); assert_eq!(at_of(&file).as_deref(), Some("2021-03-04T09:05:00.000Z"), "the thread does not move");}/// RULE: a message the thread already holds by its real id WITHOUT a picture (the linked device's history keeps pictures for 30 days only) takes the picture the iPhone backup brings onto the SAME row — one row, never a second — and a re-read of the backup changes nothing./// The left-behind label ("Photo") gives way to the backup's caption; a row that already holds media is never touched.#[test]fn a_held_message_without_its_picture_takes_the_backups_picture_on_the_same_row() { let file = TestFile::open(); import(&file, &batch(vec![linked_media("3EB0P", "image", "Photo", "2021-03-04T09:00:00.000Z")])); let id_before = one_text(&file, "SELECT id FROM cotton_msg_messages", "id"); let mut meta = Map::new(); meta.insert(MEDIA_ONLY_META.to_string(), Value::from("image")); let from_backup = EnvelopeMessage { body: String::new(), sent_at: "2021-03-04T09:00:00.000Z".to_string(), meta: Some(meta), media: Some(vec![EnvelopeMedia { key: "ws/messages/t/abc.jpg".to_string(), content_type: "image/jpeg".to_string(), name: None, size_bytes: Some(12.0), width: None, height: None, contact: None, duration_ms: None, playback_key: None, playback_content_type: None, file_key: None, kind: None, waveform: None, preview: None, }]), ..envelope("3EB0P") }; let report = import(&file, &batch(vec![from_backup.clone()])); assert_eq!(report.totals.inserted, 1, "the held row took its picture"); assert_eq!(file.rows("SELECT id FROM cotton_msg_messages").len(), 1, "one message, one row"); assert_eq!(one_text(&file, "SELECT id FROM cotton_msg_messages", "id"), id_before, "the same row"); assert_eq!( file.rows("SELECT id FROM cotton_msg_messages WHERE json_array_length(media) = 1").len(), 1 ); assert_eq!(one_text(&file, "SELECT body FROM cotton_msg_messages", "body").as_deref(), Some("")); let again = import(&file, &batch(vec![from_backup])); assert_eq!(again.totals.inserted, 0, "a row that holds media is never touched");}/// RULE: A site's handles identify speakers, never their display names; two people with the same displayed name retain separate contacts and message attribution, including on replay.#[test]fn site_handles_keep_same_named_speakers_separate() { let file=TestFile::open(); let batch:ImportBatch=serde_json::from_value(serde_json::json!({"workspaceId":WORKSPACE,"channel":"instagram","newThreadId":RESERVED, "thread":{"kind":"group","title":"Invented group","externalKey":"ig:thread:1122","participants":[ {"label":"Invented Speaker","handle":{"kind":"instagram","value":"@first.invented"}}, {"label":"Invented Speaker","handle":{"kind":"instagram","value":"second.invented"}} ]},"messages":[ {"direction":"in","senderLabel":"Invented Speaker","body":"First speaker","sentAt":NOW,"externalId":"ig:111","meta":{"source":{"senderHandle":{"kind":"instagram","value":"first.invented"}}}}, {"direction":"in","senderLabel":"Invented Speaker","body":"Second speaker","sentAt":NOW,"externalId":"ig:222","meta":{"source":{"senderHandle":{"kind":"instagram","value":"second.invented"}}}} ]})).unwrap(); assert_eq!(import(&file,&batch).totals.inserted,2); let sql="SELECT h.value FROM cotton_msg_messages m JOIN cotton_msg_thread_participants p ON p.id=m.sender_participant_id JOIN cotton_msg_contact_handles h ON h.contact_id=p.contact_id AND h.kind='instagram' WHERE m.external_id=?"; assert_eq!(file.db.get(sql,&[text("ig:111")]).unwrap().unwrap().text("value"),Some("first.invented")); assert_eq!(file.db.get(sql,&[text("ig:222")]).unwrap().unwrap().text("value"),Some("second.invented")); assert_eq!(import(&file,&batch).totals.inserted,0); assert_eq!(file.db.get("SELECT COUNT(*) AS n FROM cotton_msg_thread_participants WHERE thread_id=?",&[text(RESERVED)]).unwrap().unwrap().int("n"),Some(2)); assert_eq!(file.db.get("SELECT COUNT(DISTINCT sender_participant_id) AS n FROM cotton_msg_messages WHERE thread_id=?",&[text(RESERVED)]).unwrap().unwrap().int("n"),Some(2));}// ── the owner's region ──────────────────────────────────────────────────────fn seed_phone(file: &TestFile, id: &str, person: &str, normalised: &str) { file.seed( "cotton_person_handles", &[ ("id", text(id)), ("workspace_id", text(WORKSPACE)), ("person_id", text(person)), ("kind", text("phone")), ("value", text(normalised)), ("normalised", text(normalised)), ("source", text("contacts")), ("created_at", text(NOW)), ("updated_at", text(NOW)), ], );}/// RULE: a code-less number in a WhatsApp or iMessage batch is read in the/// country of the owner's own number — the same hint the tools' handle writes/// and the contacts import use (`phone_fold::region_hint`) — so "098123 45678"/// in an Indian owner's export is the contact, and the person, that/// "+91 98123 45678" already is. Read plainly, it would mint a second contact/// under 09812345678 and split the conversation.#[test]fn a_code_less_incoming_number_is_read_in_the_owners_country() { let file = TestFile::open(); seed_person(&file, "person-me", "Me"); seed_phone(&file, "handle-me", "person-me", "919876543210"); file.run( "UPDATE cotton_workspaces SET owner_person_id = 'person-me' WHERE id = ?", &[text(WORKSPACE)], ); seed_person(&file, "person-ravi", "Ravi"); seed_phone(&file, "handle-ravi", "person-ravi", "919812345678"); let report = import( &file, &batch(vec![EnvelopeMessage { phone: Some("098123 45678".to_string()), ..envelope("wa:region") }]), ); assert_eq!(report.chats[0].phone.as_deref(), Some("919812345678")); assert_eq!( column(&file, "SELECT phone_e164 FROM cotton_msg_contacts", "phone_e164"), vec![Some("919812345678".to_string())] ); assert_eq!( one_text(&file, "SELECT person_id FROM cotton_msg_contacts", "person_id").as_deref(), Some("person-ravi") );}/// With no owner number there is no region: the number stays as typed.#[test]fn with_no_owner_number_a_code_less_incoming_number_stays_as_typed() { let file = TestFile::open(); import( &file, &batch(vec![EnvelopeMessage { phone: Some("098123 45678".to_string()), ..envelope("wa:plain") }]), ); assert_eq!( column(&file, "SELECT phone_e164 FROM cotton_msg_contacts", "phone_e164"), vec![Some("09812345678".to_string())] );}fn picture_at(key: &str) -> Vec<EnvelopeMedia> { vec![EnvelopeMedia { key: key.to_string(), content_type: "image/jpeg".to_string(), name: None, size_bytes: Some(12.0), width: None, height: None, contact: None, duration_ms: None, playback_key: None, playback_content_type: None, file_key: None, kind: None, waveform: None, preview: None, }]}/// RULE: A media-only message lands with an empty body and its mark; the thread's line is the kit's word for the kind, never words written into the row.#[test]fn a_media_only_message_keeps_an_empty_body_and_its_mark() { let file = TestFile::open(); let message = EnvelopeMessage { media: Some(picture_at("ws/messages/t/m1.jpg")), ..linked_media("3EB0M", "image", "", "2021-03-04T09:00:00.000Z") }; import(&file, &batch(vec![message])); assert_eq!(one_text(&file, "SELECT body FROM cotton_msg_messages", "body").as_deref(), Some("")); assert_eq!( one_text(&file, "SELECT json_extract(meta, '$.mediaOnly') AS kind FROM cotton_msg_messages", "kind").as_deref(), Some("image") ); assert_eq!( one_text(&file, "SELECT last_message_preview FROM cotton_msg_threads", "last_message_preview"), Some(crate::messages::media_only::media_only_words("image")) );}/// RULE: A message with words and media keeps its words as the body.#[test]fn a_message_with_words_and_media_keeps_its_body() { let file = TestFile::open(); let message = EnvelopeMessage { body: "Invented caption".to_string(), media: Some(picture_at("ws/messages/t/m2.jpg")), ..envelope("3EB0W") }; import(&file, &batch(vec![message])); assert_eq!(one_text(&file, "SELECT body FROM cotton_msg_messages", "body").as_deref(), Some("Invented caption"));}// RULE (CONTRACT "Polls shown"): a vote lands on the poll its id names, as the voter's whole choice now: a second vote// from the same voter replaces their first, an empty one takes it back, the owner's is "me", each option's count is// the voters holding it; never a message of its own; a vote on a message that is no poll, or on none, changes nothing.#[test]fn a_vote_lands_on_its_poll_as_the_voters_whole_choice() { let file = TestFile::open(); let poll = serde_json::json!({ "poll": { "question": "Dinner on Friday?", "options": [{ "text": "Thai", "votes": 0 }, { "text": "Pizza", "votes": 0 }], "selectable": 0 } }); let mut asked = envelope("P1"); asked.body = "Dinner on Friday?".into(); asked.meta = poll.as_object().cloned(); import(&file, &batch(vec![asked, envelope("D1")])); let at = "2021-03-04T10:00:00.000Z".to_string(); let vote = |voter: &str, options: &[u32]| MessageChange::Vote { external_id: "P1".into(), voter: voter.into(), options: options.to_vec(), at: at.clone() }; let changes = vec![ vote("919999000011", &[0]), vote("owner", &[0, 1]), vote("919999000022", &[1, 9]), vote("919999000011", &[1]), MessageChange::Vote { external_id: "D1".into(), voter: "owner".into(), options: vec![0], at: at.clone() }, MessageChange::Vote { external_id: "NOT-HERE".into(), voter: "owner".into(), options: vec![0], at: at.clone() }, ]; let (ops, report) = plan_message_changes(&file, WORKSPACE, "whatsapp", &changes).expect("plans"); file.apply(&ops).expect("applies"); assert_eq!((report.voted, report.missing), (4, 2)); let meta: serde_json::Value = serde_json::from_str(&one_text(&file, "SELECT meta FROM cotton_msg_messages WHERE external_id = 'P1'", "meta").unwrap()).unwrap(); let poll = &meta["poll"]; assert_eq!(poll["options"][0]["votes"], 1.0, "{poll}"); assert_eq!(poll["options"][1]["votes"], 3.0, "{poll}"); let voters: Vec<(String, Vec<u64>)> = poll["voters"].as_array().unwrap().iter().map(|v| (v["who"].as_str().unwrap().to_string(), v["options"].as_array().unwrap().iter().map(|o| o.as_u64().unwrap()).collect())).collect(); assert_eq!(voters, vec![("me".into(), vec![0, 1]), ("919999000022".into(), vec![1]), ("919999000011".into(), vec![1])], "one entry a voter, their latest; an option past the end dropped"); assert_eq!(meta["poll"]["question"], "Dinner on Friday?"); assert_eq!(file.count("cotton_msg_messages"), 2, "a vote is never a message"); let back = vec![vote("owner", &[])]; let (ops, _) = plan_message_changes(&file, WORKSPACE, "whatsapp", &back).expect("plans"); file.apply(&ops).expect("applies"); let meta: serde_json::Value = serde_json::from_str(&one_text(&file, "SELECT meta FROM cotton_msg_messages WHERE external_id = 'P1'", "meta").unwrap()).unwrap(); assert_eq!((meta["poll"]["options"][0]["votes"].as_f64(), meta["poll"]["voters"].as_array().unwrap().len()), (Some(0.0), 2), "the owner took theirs back");}