//! Who said this? — the MCP message readers, driven through //! `dispatch::call_tool` over a fake `ToolServices` rather than the `/v1/mcp` //! endpoint. //! //! Since v5 a message attributes to a per-thread PARTICIPANT, not to a contact, //! and a participant may have no contact at all: the export wrote a name, //! nobody has said which person that is yet, and the archive imports anyway. So //! every reader has three answers to give for `from` — the contact's name for //! an identified participant, the raw label for an unidentified one, and //! `owner` for the user's own lines — plus a fourth for a dm whose counterpart //! is still nameless, where the thread's title is the best name anyone has. //! //! Seeded with SQL rather than through sync, exactly as the TypeScript seeds //! it: these rows stand in for what the importer wrote, and the point of the //! test is the READ. Every name, number and line of text is synthetic. mod support; use rusqlite::types::Value as SqlValue; use serde_json::{json, Value}; use support::harness::{synthetic_uuid, Harness}; use support::mcp::{call_tool, call_tool_raw, mint_token}; /// When every seeded row says it was written. const AT: &str = "2026-08-24T09:00:00.000Z"; // ── seeding ───────────────────────────────────────────────────────────────── /// One statement against the workspace's own file — what the importer wrote. fn run(h: &Harness, sql: &str, params: Vec) { h.run(sql, ¶ms); } fn t(value: &str) -> SqlValue { SqlValue::Text(value.to_string()) } fn null() -> SqlValue { SqlValue::Null } /// One group with a mixed roster and one dm nobody has identified yet. /// /// The group's two participants are the whole point: Priya's carries a contact /// (and the contact's display name, which is what a reader must see), Ravi's /// carries only the label the export wrote. struct Seeded { h: Harness, secret: String, group_id: String, dm_id: String, priya_contact: String, } fn seeded() -> Seeded { let mut h = Harness::new(); let ws = h.workspace_id.clone(); let priya_contact = synthetic_uuid("contact-priya"); run( &h, "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, created_at, updated_at) VALUES (?, ?, '919876543210', 'Priya Nair', ?, ?)", vec![t(&priya_contact), t(&ws), t(AT), t(AT)], ); let group_id = synthetic_uuid("thread-group"); run( &h, "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, last_message_at, created_at, updated_at) VALUES (?, ?, 'group', 'Kitchen rebuild', ?, ?, ?)", vec![t(&group_id), t(&ws), t(AT), t(AT), t(AT)], ); // A titled dm with NO contact: the counterpart is unidentified, which v5 // allows and v4 did not. let dm_id = synthetic_uuid("thread-dm"); run( &h, "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, last_message_at, created_at, updated_at) VALUES (?, ?, 'dm', 'Wrenna', '2026-08-24T08:00:00.000Z', ?, ?)", vec![t(&dm_id), t(&ws), t(AT), t(AT)], ); let identified = synthetic_uuid("participant-identified"); let unidentified = synthetic_uuid("participant-unidentified"); run( &h, "INSERT INTO cotton_msg_thread_participants (id, thread_id, workspace_id, contact_id, display_name, created_at) VALUES (?, ?, ?, ?, 'Priya', ?)", vec![ t(&identified), t(&group_id), t(&ws), t(&priya_contact), t(AT), ], ); run( &h, "INSERT INTO cotton_msg_thread_participants (id, thread_id, workspace_id, contact_id, display_name, created_at) VALUES (?, ?, ?, NULL, 'Ravi Kumar', ?)", vec![t(&unidentified), t(&group_id), t(&ws), t(AT)], ); let line = |thread_id: &str, direction: &str, body: &str, sent_at: &str, seat: Option<&str>| { let id = synthetic_uuid("message"); let external = format!("txt2:{}", synthetic_uuid("fingerprint")); run( &h, "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, media, external_id, sent_at, created_at, reactions, meta, sender_participant_id) VALUES (?, ?, ?, ?, 'whatsapp', 'imported', ?, '[]', ?, ?, ?, '[]', '{}', ?)", vec![ t(&id), t(thread_id), t(&ws), t(direction), t(body), t(&external), t(sent_at), t(sent_at), seat.map_or_else(null, t), ], ); }; line( &group_id, "in", "cardamom shelf goes above the hob", "2026-08-24T09:00:00.000Z", Some(&identified), ); line( &group_id, "in", "cardamom is the wrong height there", "2026-08-24T09:01:00.000Z", Some(&unidentified), ); line( &group_id, "out", "cardamom it is then", "2026-08-24T09:02:00.000Z", None, ); // A dm inbound line carries no participant at all — the thread IS the // counterpart. line( &dm_id, "in", "cardamom for the payasam?", "2026-08-24T08:00:00.000Z", None, ); let secret = mint_token(&mut h, &["read", "write"], "Claude"); Seeded { h, secret, group_id, dm_id, priya_contact, } } /// One more line in the dm, written the way a LIVE Cotton message is. struct LivePatch<'a> { body: Option<&'a str>, media: Value, seq: Option, sent_at: &'a str, /// Written as a file that held it before mint refused it ([`Harness::run_held`]). held: bool, } impl Default for LivePatch<'_> { fn default() -> Self { LivePatch { body: Some("hello"), media: json!([]), seq: None, sent_at: "2026-08-24T08:05:00.000Z", held: false, } } } fn live_line(h: &Harness, thread_id: &str, patch: LivePatch<'_>) -> String { let id = synthetic_uuid("message-live"); let write = if patch.held { Harness::run_held } else { Harness::run }; write( h, "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, media, sent_at, created_at, reactions, meta, seq) VALUES (?, ?, ?, 'in', 'cotton', 'live', ?, ?, ?, ?, '[]', '{}', ?)", &[ t(&id), t(thread_id), t(&h.workspace_id), patch.body.map_or_else(null, t), t(&patch.media.to_string()), t(patch.sent_at), t(patch.sent_at), patch.seq.map_or_else(null, SqlValue::Integer), ], ); id } fn strings(value: &Value, key: &str) -> Vec { value .as_array() .expect("an array") .iter() .map(|item| item[key].clone()) .collect() } fn message_with<'a>(result: &'a Value, id: &str) -> &'a Value { result["messages"] .as_array() .expect("messages") .iter() .find(|message| message["id"] == id) .expect("the message is on the page") } // ── read_message_thread ───────────────────────────────────────────────────── #[test] fn names_a_groups_senders_through_their_participants_contact_label_owner() { let s = seeded(); let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "threadId": s.group_id }), ); assert_eq!( strings(&result["messages"], "from"), vec![json!("Priya Nair"), json!("Ravi Kumar"), json!("owner")] ); // The contact's display name wins over the participant's own label: // identifying someone, then renaming them, has to rename every bubble. assert_ne!(result["messages"][0]["from"], json!("Priya")); assert_eq!(result["thread"]["id"], json!(s.group_id)); assert_eq!(result["thread"]["kind"], json!("group")); assert_eq!(result["thread"]["name"], json!("Kitchen rebuild")); } #[test] fn reads_an_unidentified_dms_inbound_lines_as_its_title() { let s = seeded(); let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "threadId": s.dm_id }), ); assert_eq!(result["thread"]["kind"], json!("dm")); assert_eq!(result["thread"]["name"], json!("Wrenna")); assert_eq!(strings(&result["messages"], "from"), vec![json!("Wrenna")]); } #[test] fn prefers_a_dms_contact_over_its_imported_title_once_someone_is_identified() { let s = seeded(); let contact_id = synthetic_uuid("contact-wrenna"); run( &s.h, "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, created_at, updated_at) VALUES (?, ?, '919000000001', 'Wrenna Rao', ?, ?)", vec![t(&contact_id), t(&s.h.workspace_id), t(AT), t(AT)], ); run( &s.h, "UPDATE cotton_msg_threads SET contact_id = ? WHERE id = ?", vec![t(&contact_id), t(&s.dm_id)], ); let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "threadId": s.dm_id }), ); assert_eq!(result["thread"]["name"], json!("Wrenna Rao")); assert_eq!( strings(&result["messages"], "from"), vec![json!("Wrenna Rao")] ); } // ── read_message_thread — the summary in the header ───────────────────────── // // Schema v15: a chat carries the owner's paragraph about the conversation, with // its provenance and how much has been said since. It rides the HEADER, beside // the name — it is about the conversation, not any line in it — and it is the // owner's alone: never relayed, never mirrored. // // Every instant here is seeded explicitly, so nothing on the read path asks the // clock and no fake timer is needed. const SUMMARY_AT: &str = "2026-08-24T09:00:30.000Z"; const SUMMARY_TEXT: &str = "The kitchen rebuild group: shelf heights, then who buys what."; fn write_summary(h: &Harness, thread_id: &str, at: &str) { run( h, "UPDATE cotton_msg_threads SET summary = ?, summary_by = ?, summary_updated_at = ? \ WHERE id = ?", vec![t(SUMMARY_TEXT), t("Claude Code"), t(at), t(thread_id)], ); } #[test] fn carries_the_summary_who_wrote_it_and_what_has_arrived_since() { let s = seeded(); // The group's three lines are 09:00, 09:01 and 09:02; the summary was // written at 09:00:30, so two of them arrived after it. write_summary(&s.h, &s.group_id, SUMMARY_AT); let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "threadId": s.group_id }), ); assert_eq!(result["thread"]["id"], json!(s.group_id)); assert_eq!(result["thread"]["name"], json!("Kitchen rebuild")); assert_eq!( result["thread"]["summary"], json!({ "text": SUMMARY_TEXT, "by": "Claude Code", "updatedAt": SUMMARY_AT, "since": { "count": 2, "noun": "message" }, }) ); } #[test] fn omits_the_summary_key_entirely_when_there_is_none() { let s = seeded(); let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "threadId": s.group_id }), ); assert!(result["thread"].get("summary").is_none()); } #[test] fn omits_since_when_nothing_has_arrived() { let s = seeded(); write_summary(&s.h, &s.group_id, "2026-08-24T23:00:00.000Z"); // after every line let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "threadId": s.group_id }), ); let keys: Vec<&String> = result["thread"]["summary"] .as_object() .expect("a summary") .keys() .collect(); assert_eq!(keys, vec!["text", "by", "updatedAt"]); } /// `mcpSummary.test.ts`'s parameterised case, the `thread` instance. /// /// The `person`, `email_thread` and `project` instances read through /// `get_record`, `read_email_thread` and `get_project` and belong to the groups /// that own those tools. #[test] fn thread_the_read_carries_the_summary_and_its_provenance() { let s = seeded(); write_summary(&s.h, &s.group_id, "2026-08-24T23:00:00.000Z"); let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "threadId": s.group_id }), ); assert_eq!( result["thread"]["summary"], json!({ "text": SUMMARY_TEXT, "by": "Claude Code", "updatedAt": "2026-08-24T23:00:00.000Z" }) ); } // ── search_messages ───────────────────────────────────────────────────────── #[test] fn carries_the_same_participant_names_into_every_match() { let s = seeded(); let result = call_tool( &s.h, &s.secret, "search_messages", json!({ "query": "cardamom" }), ); // Newest first, so the group's three lines then the dm's. assert_eq!( strings(&result["matches"], "from"), vec![ json!("owner"), json!("Ravi Kumar"), json!("Priya Nair"), json!("Wrenna") ] ); assert_eq!( strings(&result["matches"], "threadName"), vec![ json!("Kitchen rebuild"), json!("Kitchen rebuild"), json!("Kitchen rebuild"), json!("Wrenna") ] ); let mut thread_ids: Vec = strings(&result["matches"], "threadId") .into_iter() .map(|id| id.as_str().unwrap_or_default().to_string()) .collect(); thread_ids.sort(); thread_ids.dedup(); let mut expected = vec![s.group_id.clone(), s.dm_id.clone()]; expected.sort(); assert_eq!(thread_ids, expected); } #[test] fn says_unknown_rather_than_inventing_a_name_when_a_participant_is_gone() { let s = seeded(); // Removing a participant sets its messages' reference to NULL (the FK's ON // DELETE SET NULL). A seatless inbound line in a GROUP has nobody to name — // and the reader has to say so rather than fall back to the group's own // name. run( &s.h, "DELETE FROM cotton_msg_thread_participants WHERE thread_id = ?", vec![t(&s.group_id)], ); let result = call_tool( &s.h, &s.secret, "search_messages", json!({ "query": "cardamom", "threadId": s.group_id }), ); assert_eq!( strings(&result["matches"], "from"), vec![json!("owner"), json!("(unknown)"), json!("(unknown)")] ); } // ── list_message_threads ──────────────────────────────────────────────────── #[test] fn lists_an_unidentified_dm_under_its_title_and_counts_every_participant() { let s = seeded(); let result = call_tool(&s.h, &s.secret, "list_message_threads", json!({})); let threads = result["threads"].as_array().expect("threads").clone(); let group = threads .iter() .find(|row| row["id"] == json!(s.group_id)) .expect("the group"); let dm = threads .iter() .find(|row| row["id"] == json!(s.dm_id)) .expect("the dm"); assert_eq!(group["kind"], json!("group")); assert_eq!(group["name"], json!("Kitchen rebuild")); assert_eq!(group["participantCount"], json!(2)); assert_eq!(dm["kind"], json!("dm")); assert_eq!(dm["name"], json!("Wrenna")); // A dm has no roster to count. assert!(dm.get("participantCount").is_none()); } // ── read_message_thread — what schema v9 added ────────────────────────────── /// The wall is asked of the ROW's own file: a key under another file's prefix /// is never signed, however the row got there. #[test] fn an_attachment_keyed_under_another_files_prefix_is_never_signed() { let s = seeded(); let other = synthetic_uuid("another-file"); let key = format!("{other}/messages/{}/abc123.jpg", s.dm_id); let id = live_line( &s.h, &s.dm_id, LivePatch { body: Some("look"), media: json!([{ "key": key, "contentType": "image/jpeg", "name": "beach.jpg" }]), held: true, ..Default::default() }, ); let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "threadId": s.dm_id }), ); let media = message_with(&result, &id)["media"] .as_array() .expect("the attachments"); assert_eq!(media.len(), 1); assert_eq!(media[0]["key"], json!(key)); assert!( media[0].get("url").is_none(), "no link for a key outside the row's file: {}", media[0] ); assert!(!s .h .services .media .calls() .iter() .any(|(what, asked)| what == "presign" && asked == &key)); } #[test] fn presigns_an_attachment_stored_as_a_key_and_passes_an_old_url_row_through() { let s = seeded(); let key = format!("{}/messages/{}/abc123.jpg", s.h.workspace_id, s.dm_id); let id = live_line( &s.h, &s.dm_id, LivePatch { body: Some("look"), media: json!([ { "key": key, "contentType": "image/jpeg", "name": "beach.jpg" }, { "url": "https://old.example/x.pdf", "contentType": "application/pdf" }, ]), ..Default::default() }, ); let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "threadId": s.dm_id }), ); // The blocking signer IS on `ToolServices` here, so the keyed attachment // really is signed — asserted through the store's own ledger rather than by // re-deriving the fake's URL shape. `expiresAt` is the one field of the // TypeScript's four that Rust does not answer: `presign` hands back a URL // and nothing else, so there is no instant to echo. let media = message_with(&result, &id)["media"] .as_array() .expect("the attachments") .clone(); assert_eq!(media.len(), 2); assert_eq!(media[0]["key"], json!(key)); assert_eq!(media[0]["contentType"], json!("image/jpeg")); assert_eq!(media[0]["name"], json!("beach.jpg")); assert!( media[0]["url"].as_str().is_some_and(|url| !url.is_empty()), "the keyed attachment was not signed: {}", media[0] ); assert!(s .h .services .media .calls() .iter() .any(|(what, asked)| what == "presign" && asked == &key)); // An imported row predates content-addressing: it has a url and no key, and // it passes through untouched. assert_eq!( media[1], json!({ "url": "https://old.example/x.pdf", "contentType": "application/pdf" }) ); } #[test] fn an_attachment_keeps_the_fields_a_bubble_draws_with() { // What the phone's composer wrote when it attached a picture (4q): the // renderer's own half — what it IS, how big it is — travels with the key, // because a conversation that learns a picture's size only when the bytes // land is one that jumps as each of them arrives. let s = seeded(); let key = format!("{}/messages/{}/abc123.jpg", s.h.workspace_id, s.dm_id); let id = live_line( &s.h, &s.dm_id, LivePatch { body: Some("look"), media: json!([{ "key": key, "contentType": "image/jpeg", "kind": "image", "width": 1200, "height": 900, "sizeBytes": 51200, "preview": "/9j/synthetic", }]), ..Default::default() }, ); let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "threadId": s.dm_id }), ); let entry = message_with(&result, &id)["media"][0].clone(); assert_eq!(entry["kind"], json!("image")); assert_eq!(entry["width"], json!(1200)); assert_eq!(entry["height"], json!(900)); assert_eq!(entry["sizeBytes"], json!(51200)); // AND NOT THE PREVIEW. It is four kilobytes of base64 pixels whose only // use is to be drawn blurred; an assistant cannot see it and a window of // fifty messages would carry a couple of hundred kilobytes of them. assert!( entry.get("preview").is_none(), "an assistant was sent a blur placeholder: {entry}" ); } #[test] fn the_owner_s_own_app_gets_the_blur_placeholder_an_assistant_does_not() { let s = seeded(); let key = format!("{}/messages/{}/abc123.jpg", s.h.workspace_id, s.dm_id); let id = live_line( &s.h, &s.dm_id, LivePatch { body: Some("look"), media: json!([{ "key": key, "contentType": "image/jpeg", "preview": "/9j/synthetic" }]), ..Default::default() }, ); let answer = support::mcp::call_tool_as_owner( &s.h, "device:00000000000000000000000000", "read_message_thread", json!({ "threadId": s.dm_id }), ); assert!(!answer.is_error, "the owner's app was refused: {}", answer.text); let entry = message_with(&answer.json(), &id)["media"][0].clone(); assert_eq!(entry["preview"], json!("/9j/synthetic")); } #[test] fn a_voice_note_s_waveform_reaches_the_owner_s_app_and_no_assistant() { // The paper chat draws a voice note as its waveform. Sixty-four numbers are // a drawing and nothing else, so they travel the preview's road: to the // owner's own app, and to no assistant. let s = seeded(); let key = format!("{}/messages/{}/voice.m4a", s.h.workspace_id, s.dm_id); let id = live_line( &s.h, &s.dm_id, LivePatch { body: None, media: json!([{ "key": key, "contentType": "audio/mp4", "kind": "voice", "durationMs": 15000, "waveform": [0.1, 0.8, 0.4], }]), ..Default::default() }, ); let owner = support::mcp::call_tool_as_owner( &s.h, "device:00000000000000000000000000", "read_message_thread", json!({ "threadId": s.dm_id }), ); assert!(!owner.is_error, "the owner's app was refused: {}", owner.text); let entry = message_with(&owner.json(), &id)["media"][0].clone(); assert_eq!(entry["waveform"], json!([0.1, 0.8, 0.4])); assert_eq!(entry["durationMs"], json!(15000)); let assistant = call_tool(&s.h, &s.secret, "read_message_thread", json!({ "threadId": s.dm_id })); let entry = message_with(&assistant, &id)["media"][0].clone(); assert!(entry.get("waveform").is_none(), "an assistant was sent a waveform: {entry}"); } /// RULE: a recording's playable rendition and a shared card's readable part travel with the message on every read — the stored entry is the writer's answer, and a read that drops `playbackKey` leaves a WhatsApp voice note (Ogg/Opus, which the phone cannot play) silent behind its AAC copy. #[test] fn a_voice_note_s_playable_copy_and_a_contact_card_reach_the_thread() { let s = seeded(); let ogg = format!("{}/messages/{}/voice.ogg", s.h.workspace_id, s.dm_id); let m4a = format!("{}/messages/{}/voice.m4a", s.h.workspace_id, s.dm_id); let vcf = format!("{}/messages/{}/card.vcf", s.h.workspace_id, s.dm_id); let id = live_line( &s.h, &s.dm_id, LivePatch { body: None, media: json!([ { "key": ogg, "contentType": "audio/ogg; codecs=opus", "kind": "voice", "durationMs": 4000, "playbackKey": m4a, "playbackContentType": "audio/mp4", }, { "key": vcf, "contentType": "text/vcard", "kind": "contact", "contact": { "name": "Ada Example", "phones": ["+15550100"], "emails": [] }, }, ]), ..Default::default() }, ); let owner = support::mcp::call_tool_as_owner( &s.h, "device:00000000000000000000000000", "read_message_thread", json!({ "threadId": s.dm_id }), ); assert!(!owner.is_error, "the owner's app was refused: {}", owner.text); let media = message_with(&owner.json(), &id)["media"].clone(); assert_eq!(media[0]["playbackKey"], json!(m4a)); assert_eq!(media[0]["playbackContentType"], json!("audio/mp4")); assert_eq!(media[1]["contact"]["name"], json!("Ada Example")); assert_eq!(media[1]["contact"]["phones"], json!(["+15550100"])); } #[test] fn never_mints_a_link_for_a_key_belonging_to_another_workspace() { let s = seeded(); // A relay bug, a hand-edited file, an attacker — it does not matter which. let foreign = "00000000-0000-4000-8000-0000000000ff/messages/t/abc.jpg"; let id = live_line( &s.h, &s.dm_id, LivePatch { body: Some("nope"), media: json!([{ "key": foreign, "contentType": "image/jpeg" }]), held: true, ..Default::default() }, ); let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "threadId": s.dm_id }), ); // The attachment survives as a fact; the LINK does not exist. assert_eq!( message_with(&result, &id)["media"], json!([{ "key": foreign, "contentType": "image/jpeg" }]) ); assert!(!s .h .services .media .calls() .iter() .any(|(what, key)| what == "presign" && key == foreign)); } #[test] fn carries_seq_edited_at_and_reactions() { let s = seeded(); let id = live_line( &s.h, &s.dm_id, LivePatch { body: Some("hi"), seq: Some(7), ..Default::default() }, ); run( &s.h, "UPDATE cotton_msg_messages SET edited_at = ? WHERE id = ?", vec![t(AT), t(&id)], ); run( &s.h, "INSERT INTO cotton_msg_reactions (id, workspace_id, thread_id, message_id, actor, emoji, created_at) VALUES ('r1', ?, ?, ?, '919876543210', '👍', ?)", vec![t(&s.h.workspace_id), t(&s.dm_id), t(&id), t(AT)], ); let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "threadId": s.dm_id }), ); let message = message_with(&result, &id); assert_eq!(message["seq"], json!(7)); assert_eq!(message["editedAt"], json!(AT)); assert_eq!(message["edited"], json!(true)); // The contact seeded by `seeded()` owns 919876543210 and is named // "Priya Nair" — an assistant should read a name, not a number. assert_eq!( message["reactions"], json!([{ "emoji": "👍", "by": "Priya Nair" }]) ); assert_eq!(s.priya_contact.len(), 36); } #[test] fn names_the_owners_own_reaction_owner_rather_than_showing_self() { let s = seeded(); let id = live_line( &s.h, &s.dm_id, LivePatch { body: Some("hi"), seq: Some(1), ..Default::default() }, ); run( &s.h, "INSERT INTO cotton_msg_reactions (id, workspace_id, thread_id, message_id, actor, emoji, created_at) VALUES ('r-self', ?, ?, ?, 'self', '❤️', ?)", vec![t(&s.h.workspace_id), t(&s.dm_id), t(&id), t(AT)], ); let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "threadId": s.dm_id }), ); assert_eq!( message_with(&result, &id)["reactions"], json!([{ "emoji": "❤️", "by": "owner" }]) ); } #[test] fn withholds_a_deleted_messages_body_and_attachments_and_says_so() { let s = seeded(); let key = format!("{}/messages/{}/x.jpg", s.h.workspace_id, s.dm_id); let id = live_line( &s.h, &s.dm_id, LivePatch { body: Some("the thing I regret"), media: json!([{ "key": key, "contentType": "image/jpeg" }]), ..Default::default() }, ); run( &s.h, "UPDATE cotton_msg_messages SET deleted_at = ? WHERE id = ?", vec![t(AT), t(&id)], ); let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "threadId": s.dm_id }), ); let message = message_with(&result, &id); // "Delete for everyone" has to mean it for the assistant too, or the // product's most sensitive promise is one a model can read straight past. assert_eq!(message["deleted"], json!(true)); assert_eq!(message["body"], Value::Null); assert_eq!(message["media"], json!([])); } #[test] fn reports_how_far_each_person_has_read() { let s = seeded(); live_line( &s.h, &s.dm_id, LivePatch { body: Some("hi"), seq: Some(3), ..Default::default() }, ); run( &s.h, "INSERT INTO cotton_msg_receipts (id, workspace_id, thread_id, phone, delivered_seq, read_seq, updated_at) VALUES (?, ?, ?, '919876543210', 3, 2, ?)", vec![ t(&format!("receipt:{}:919876543210", s.dm_id)), t(&s.h.workspace_id), t(&s.dm_id), t(AT), ], ); let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "threadId": s.dm_id }), ); assert_eq!( result["receipts"], json!([{ "name": "Priya Nair", "deliveredSeq": 3, "readSeq": 2 }]) ); } // ── search_messages — the index, not a table scan ─────────────────────────── #[test] fn finds_a_word_through_fts5_rather_than_a_substring() { let s = seeded(); live_line( &s.h, &s.dm_id, LivePatch { body: Some("The invoice is attached"), seq: Some(1), ..Default::default() }, ); let result = call_tool( &s.h, &s.secret, "search_messages", json!({ "query": "invoice" }), ); assert_eq!(result["matches"].as_array().expect("matches").len(), 1); assert_eq!( result["matches"][0]["body"], json!("The invoice is attached") ); } #[test] fn ands_two_words_anywhere_in_a_message_a_substring_scan_cannot() { let s = seeded(); live_line( &s.h, &s.dm_id, LivePatch { body: Some("the invoice arrives on Tuesday"), seq: Some(1), ..Default::default() }, ); live_line( &s.h, &s.dm_id, LivePatch { body: Some("Tuesday is fine"), seq: Some(2), sent_at: "2026-08-24T08:06:00.000Z", ..Default::default() }, ); // `ilike '%invoice Tuesday%'` finds NEITHER: the words are not adjacent. // The index is the whole reason two words can mean "both, anywhere". let result = call_tool( &s.h, &s.secret, "search_messages", json!({ "query": "invoice Tuesday" }), ); assert_eq!(result["matches"].as_array().expect("matches").len(), 1); assert_eq!( result["matches"][0]["body"], json!("the invoice arrives on Tuesday") ); } #[test] fn matches_whole_words_not_fragments_inside_longer_ones() { let s = seeded(); live_line( &s.h, &s.dm_id, LivePatch { body: Some("the invoicing system is down"), seq: Some(1), ..Default::default() }, ); // `%invoice%` matches "invoicing" and puts a false hit in front of a person. // The index tokenises, so it does not. (`unicode61` does not stem either — // the server holds no porter tokenizer, and adding one is a schema change // with a full reindex behind it.) let result = call_tool( &s.h, &s.secret, "search_messages", json!({ "query": "invoice" }), ); assert_eq!(result["matches"], json!([])); } #[test] fn treats_a_punctuation_only_query_as_no_query_rather_than_a_syntax_error() { let s = seeded(); live_line( &s.h, &s.dm_id, LivePatch { body: Some("hello"), seq: Some(1), ..Default::default() }, ); // Raw, this is an FTS5 MATCH syntax error and the whole call would fail. let result = call_tool( &s.h, &s.secret, "search_messages", json!({ "query": "\"\" AND" }), ); assert_eq!(result["matches"], json!([])); } #[test] fn never_returns_a_deleted_message() { let s = seeded(); let id = live_line( &s.h, &s.dm_id, LivePatch { body: Some("invoice"), seq: Some(1), ..Default::default() }, ); run( &s.h, "UPDATE cotton_msg_messages SET deleted_at = ? WHERE id = ?", vec![t(AT), t(&id)], ); let result = call_tool( &s.h, &s.secret, "search_messages", json!({ "query": "invoice" }), ); assert_eq!(result["matches"], json!([])); } // ── One conversation per person (schema v38, spec §D4) ────────────────────── // // Storage keeps a DM thread per counterpart CONTACT, and a person reachable // from two numbers has two contacts and two threads. The merge is a READ: every // reader groups DM threads by the person their contact resolves to and // interleaves the messages by when they were sent, each carrying its channel. // These tests are that read, over MCP — the same core functions the app calls, // so the phone and an assistant cannot describe one conversation two ways. struct SeededPerson { h: Harness, secret: String, ravi: String, imessage_thread: String, sms_thread: String, group_id: String, } /// Ravi, reachable from two numbers: an iMessage thread on one and an SMS /// thread on the other. Plus a group, which never merges into anything. fn seeded_person() -> SeededPerson { let mut h = Harness::new(); let ws = h.workspace_id.clone(); let ravi = synthetic_uuid("person-ravi"); run( &h, "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES (?, ?, 'Ravi Kumar', ?, ?)", vec![t(&ravi), t(&ws), t(AT), t(AT)], ); let contact = |phone: &str, name: &str, person_id: Option<&str>| -> String { let id = synthetic_uuid("contact"); run( &h, "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, person_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)", vec![ t(&id), t(&ws), t(phone), t(name), person_id.map_or_else(null, t), t(AT), t(AT), ], ); id }; let thread = |contact_id: Option<&str>, kind: &str, title: Option<&str>, last: &str| -> String { let id = synthetic_uuid("thread"); run( &h, "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, contact_id, last_message_at, last_message_preview, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 'the last thing said', ?, ?)", vec![ t(&id), t(&ws), t(kind), title.map_or_else(null, t), contact_id.map_or_else(null, t), t(last), t(AT), t(AT), ], ); id }; let line = |thread_id: &str, channel: &str, body: &str, sent_at: &str, source: Value| { let id = synthetic_uuid("message"); let external = format!("txt2:{}", synthetic_uuid("fingerprint")); let meta = if source.is_null() { json!({}) } else { json!({ "source": source }) }; run( &h, "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, media, external_id, sent_at, created_at, reactions, meta, sender_participant_id) VALUES (?, ?, ?, 'in', ?, 'imported', ?, '[]', ?, ?, ?, '[]', ?, NULL)", vec![ t(&id), t(thread_id), t(&ws), t(channel), t(body), t(&external), t(sent_at), t(sent_at), t(&meta.to_string()), ], ); }; let first = contact("919000000001", "Ravi", Some(&ravi)); let second = contact("919000000002", "Ravi (work)", Some(&ravi)); let imessage_thread = thread(Some(&first), "dm", None, "2026-09-01T10:02:00.000Z"); let sms_thread = thread(Some(&second), "dm", None, "2026-09-01T10:01:00.000Z"); let group_id = thread( None, "group", Some("Kitchen rebuild"), "2026-09-01T09:00:00.000Z", ); line( &imessage_thread, "imessage", "on the blue one", "2026-09-01T10:00:00.000Z", json!({ "service": "iMessage", "device": "mac-a", "externalId": "guid-1" }), ); line( &sms_thread, "sms", "and on the green one", "2026-09-01T10:01:00.000Z", json!({ "service": "SMS", "device": "mac-a", "externalId": "guid-2" }), ); line( &imessage_thread, "imessage", "blue again", "2026-09-01T10:02:00.000Z", Value::Null, ); line( &group_id, "whatsapp", "shelf heights", "2026-09-01T09:00:00.000Z", Value::Null, ); let secret = mint_token(&mut h, &["read", "write"], "Claude"); SeededPerson { h, secret, ravi, imessage_thread, sms_thread, group_id, } } // ── list_message_threads — grouped by person ──────────────────────────────── #[test] fn folds_a_persons_two_dm_threads_into_one_conversation_and_leaves_the_group_alone() { let s = seeded_person(); let result = call_tool(&s.h, &s.secret, "list_message_threads", json!({})); let rows = result["threads"].as_array().expect("threads").clone(); let merged = rows .iter() .find(|row| row["personId"] == json!(s.ravi)) .expect("the merged conversation"); assert_eq!(merged["name"], json!("Ravi Kumar")); let mut thread_ids: Vec = merged["threadIds"] .as_array() .expect("threadIds") .iter() .map(|id| id.as_str().unwrap_or_default().to_string()) .collect(); thread_ids.sort(); let mut expected = vec![s.imessage_thread.clone(), s.sms_thread.clone()]; expected.sort(); assert_eq!(thread_ids, expected); // No `id`: a merged conversation is not one thread, so handing back an id // somebody could pass to read_message_thread would be handing back half the // conversation. assert!(merged.get("id").is_none()); // Channels in vocabulary order, so the same pair of badges always draws the // same way. assert_eq!(merged["channels"], json!(["imessage", "sms"])); assert_eq!(merged["lastMessageAt"], json!("2026-09-01T10:02:00.000Z")); // A group is always its own conversation — a WhatsApp group and an iMessage // group with the same people are different groups. let group = rows .iter() .find(|row| row["id"] == json!(s.group_id)) .expect("the group"); assert_eq!(group["kind"], json!("group")); assert_eq!(group["name"], json!("Kitchen rebuild")); assert_eq!(group["channels"], json!(["whatsapp"])); assert!(group.get("personId").is_none()); assert_eq!(rows.len(), 2); } #[test] fn group_by_thread_answers_the_raw_threads_one_row_each() { let s = seeded_person(); let result = call_tool( &s.h, &s.secret, "list_message_threads", json!({ "groupBy": "thread" }), ); let rows = result["threads"].as_array().expect("threads").clone(); let mut ids: Vec = rows .iter() .map(|row| row["id"].as_str().unwrap_or_default().to_string()) .collect(); ids.sort(); let mut expected = vec![ s.imessage_thread.clone(), s.sms_thread.clone(), s.group_id.clone(), ]; expected.sort(); assert_eq!(ids, expected); for row in &rows { assert!(row.get("personId").is_none()); } } #[test] fn refuses_a_group_by_nobody_has() { let s = seeded_person(); let answer = call_tool_raw( &s.h, &s.secret, "list_message_threads", json!({ "groupBy": "channel" }), ); assert!(answer.is_error); assert!(answer.text.contains("groupBy"), "{}", answer.text); } // ── read_message_thread — by person ───────────────────────────────────────── #[test] fn interleaves_both_threads_by_when_each_line_was_sent_with_a_channel_on_every_one() { let s = seeded_person(); let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "personId": s.ravi }), ); assert_eq!( strings(&result["messages"], "body"), vec![ json!("on the blue one"), json!("and on the green one"), json!("blue again") ] ); assert_eq!( strings(&result["messages"], "channel"), vec![json!("imessage"), json!("sms"), json!("imessage")] ); assert_eq!( strings(&result["messages"], "threadId"), vec![ json!(s.imessage_thread), json!(s.sms_thread), json!(s.imessage_thread) ] ); assert_eq!(result["thread"]["personId"], json!(s.ravi)); assert_eq!(result["thread"]["name"], json!("Ravi Kumar")); assert_eq!(result["thread"]["kind"], json!("dm")); let mut thread_ids: Vec = result["thread"]["threadIds"] .as_array() .expect("threadIds") .iter() .map(|id| id.as_str().unwrap_or_default().to_string()) .collect(); thread_ids.sort(); let mut expected = vec![s.imessage_thread.clone(), s.sms_thread.clone()]; expected.sort(); assert_eq!(thread_ids, expected); } #[test] fn carries_each_messages_provenance_where_it_came_from_and_what_read_it() { let s = seeded_person(); let result = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "personId": s.ravi }), ); let messages = result["messages"].as_array().expect("messages"); assert_eq!( messages[0]["source"], json!({ "service": "iMessage", "device": "mac-a", "externalId": "guid-1" }) ); assert_eq!( messages[1]["source"], json!({ "service": "SMS", "device": "mac-a", "externalId": "guid-2" }) ); // A message nobody imported has no provenance, and the key is absent rather // than null. assert!(messages[2].get("source").is_none()); } #[test] fn pages_a_merged_conversation_the_same_way_it_pages_one_thread() { let s = seeded_person(); let page = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "personId": s.ravi, "limit": 2 }), ); // The NEWEST two, chronological — the same semantics as one thread. assert_eq!( strings(&page["messages"], "body"), vec![json!("and on the green one"), json!("blue again")] ); assert_eq!(page["nextBefore"], json!("2026-09-01T10:01:00.000Z")); let older = call_tool( &s.h, &s.secret, "read_message_thread", json!({ "personId": s.ravi, "before": page["nextBefore"] }), ); assert_eq!( strings(&older["messages"], "body"), vec![json!("on the blue one")] ); } #[test] fn refuses_both_ids_at_once_and_neither() { let s = seeded_person(); let both = call_tool_raw( &s.h, &s.secret, "read_message_thread", json!({ "personId": s.ravi, "threadId": s.imessage_thread }), ); assert!(both.is_error); assert!(both.text.contains("threadId or personId"), "{}", both.text); let neither = call_tool_raw(&s.h, &s.secret, "read_message_thread", json!({})); assert!(neither.is_error); } #[test] fn refuses_a_person_with_no_conversation_rather_than_answering_an_empty_one() { let s = seeded_person(); let answer = call_tool_raw( &s.h, &s.secret, "read_message_thread", json!({ "personId": synthetic_uuid("nobody") }), ); assert!(answer.is_error); assert!( answer.text.to_lowercase().contains("no conversation"), "{}", answer.text ); } // ── search_messages — which transport a line arrived over ─────────────────── #[test] fn puts_the_channel_on_every_match() { let s = seeded_person(); let result = call_tool( &s.h, &s.secret, "search_messages", json!({ "query": "one" }), ); assert_eq!( strings(&result["matches"], "body"), vec![json!("and on the green one"), json!("on the blue one")] ); assert_eq!( strings(&result["matches"], "channel"), vec![json!("sms"), json!("imessage")] ); }