Cotton code
263 lines · 14.4 KB · RustRaw
//! The generic record verbs over the messages archive: what a chat and a//! message answer beyond their stored columns (`tables::chat_views`), driven//! through the dispatcher as an assistant's connection. Every value is//! invented ([nothing-real-ever-goes-in-cotton-s-public-tree]).mod support;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::Harness;use support::mcp::{call_tool, mint_token};const NOW: &str = "2026-09-10T08:00:00.000Z";const NAMED_DM: &str = "c0000000-0000-4000-8000-000000000001";const BARE_DM: &str = "c0000000-0000-4000-8000-000000000002";const GROUP: &str = "c0000000-0000-4000-8000-000000000003";const SEAT: &str = "c0000000-0000-4000-8000-0000000000a1";fn t(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}fn opt(value: Option<&str>) -> SqlValue {    value.map_or(SqlValue::Null, t)}/// Two direct chats that store no title — one whose contact is named and/// whose stored last line is an importer's marker, one that is a bare number/// with nothing in it — and a group holding every shape a message takes.fn archive() -> (Harness, String) {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Claude");    let w = h.workspace_id.clone();    for (id, phone, name) in [("contact-named", "15550101", Some("Example Asha")), ("contact-bare", "15550102", None)] {        h.run(            "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, created_at, updated_at) \             VALUES (?, ?, ?, ?, ?, ?)",            &[t(id), t(&w), t(phone), opt(name), t(NOW), t(NOW)],        );    }    for (id, kind, contact, title, last_at, line) in [        (NAMED_DM, "dm", Some("contact-named"), None, Some("2026-09-01T10:00:00.000Z"), Some("[unsupported message]")),        (BARE_DM, "dm", Some("contact-bare"), None, None, None),        (GROUP, "group", None, Some("Example club"), Some("2026-09-05T10:04:00.000Z"), None),    ] {        h.run(            "INSERT INTO cotton_msg_threads (id, workspace_id, kind, contact_id, title, last_message_at, \             last_message_preview, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",            &[t(id), t(&w), t(kind), opt(contact), opt(title), opt(last_at), opt(line), t(NOW), t(NOW)],        );    }    for (id, name, own) in [(SEAT, "Example Ben", 0), ("c0000000-0000-4000-8000-0000000000a2", "Owner", 1)] {        h.run(            "INSERT INTO cotton_msg_thread_participants (id, thread_id, workspace_id, display_name, is_self, created_at) \             VALUES (?, ?, ?, ?, ?, ?)",            &[t(id), t(GROUP), t(&w), t(name), SqlValue::Integer(own), t(NOW)],        );    }    let picture = format!(r#"[{{"key":"{w}/messages/group/a.jpg","contentType":"image/jpeg"}}]"#);    let picture = picture.as_str();    // (id, direction, seat, body, media, reply, deleted, starred, minute)    let lines: [(&str, &str, Option<&str>, Option<&str>, Option<&str>, Option<&str>, bool, bool, u8); 5] = [        ("m1", "in", Some(SEAT), Some("who is driving?"), None, None, false, false, 0),        ("m2", "out", None, Some("I can"), None, Some("m1"), false, false, 1),        ("m3", "in", Some(SEAT), None, Some(picture), None, false, false, 2),        ("m4", "in", Some(SEAT), Some("[attachment: Example Chen.vcf]"), None, None, false, false, 3),        ("m5", "in", Some(SEAT), Some("wrong chat"), Some(picture), None, true, true, 4),    ];    for (id, direction, seat, body, media, reply, deleted, starred, minute) in lines {        let sent = format!("2026-09-05T10:0{minute}:00.000Z");        h.run(            "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, media, \             reply_to_id, sender_participant_id, deleted_at, starred_at, sent_at, created_at) \             VALUES (?, ?, ?, ?, 'whatsapp', 'imported', ?, ?, ?, ?, ?, ?, ?, ?)",            &[                t(id), t(GROUP), t(&w), t(direction), opt(body), t(media.unwrap_or("[]")), opt(reply), opt(seat),                opt(deleted.then_some(NOW)), opt(starred.then_some(NOW)), t(&sent), t(NOW),            ],        );    }    for (id, actor) in [("r1", "self"), ("r2", "15550101")] {        h.run(            "INSERT INTO cotton_msg_reactions (id, workspace_id, thread_id, message_id, actor, emoji, created_at) \             VALUES (?, ?, ?, 'm1', ?, '❤️', ?)",            &[t(id), t(&w), t(GROUP), t(actor), t(NOW)],        );    }    (h, secret)}fn listed(h: &Harness, secret: &str, args: Value) -> Vec<Value> {    call_tool(h, secret, "list_records", args)["records"].as_array().expect("records").clone()}fn by_id<'a>(records: &'a [Value], id: &str) -> &'a Value {    &records.iter().find(|record| record["id"] == id).unwrap_or_else(|| panic!("no record {id}"))["data"]}/// RULE: A chat's members are one list holding everyone: the owner first, each member with a person record as that person, and every other member by name; nobody its members line names is missing.#[test]fn a_chats_members_are_one_list_holding_everyone() {    let (h, secret) = archive();    let chats = listed(&h, &secret, json!({ "table": "thread" }));    let group = by_id(&chats, GROUP);    assert_eq!(group["member_self"], "You");    for chat in &chats {        let data = &chat["data"];        let lines = |key: &str| data[key].as_str().map(|names| names.lines().count()).unwrap_or(0);        let people = data["member_people"].as_array().map(Vec::len).unwrap_or(0);        let owner = usize::from(data["member_self"] == "You");        assert!(lines("members") <= owner + people + lines("members_unmatched"), "somebody is missing: {data}");        if let Some(unmatched) = data["members_unmatched"].as_str() {            assert!(!unmatched.lines().any(|name| name == "You"), "the owner is said once, first: {data}");        }    }}/// RULE: A chat is in a channel's view when a message came into it by that channel — Messages' WhatsApp, SMS and Instagram views read `where channels` — and a chat no message of that channel came into is in none (owner, 27 Oct 2026).#[test]fn a_chat_is_read_by_the_channels_its_messages_came_by() {    let (h, secret) = archive();    h.run(        "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at) \         VALUES ('s1', ?, ?, 'in', 'sms', 'imported', 'your code is 0000', '2026-09-01T10:00:00.000Z', ?)",        &[t(NAMED_DM), t(&h.workspace_id), t(NOW)],    );    let ids = |where_: Value| {        let mut ids: Vec<String> = listed(&h, &secret, json!({ "table": "thread", "where": where_ }))            .iter()            .map(|record| record["id"].as_str().unwrap().to_string())            .collect();        ids.sort();        ids    };    assert_eq!(ids(json!({ "channels": "whatsapp" })), [GROUP]);    assert_eq!(ids(json!({ "channels": "sms" })), [NAMED_DM]);    assert_eq!(ids(json!({ "channels": "instagram" })), Vec::<String>::new());    assert_eq!(ids(json!({ "channels": ["sms", "whatsapp"] })), [NAMED_DM, GROUP]);}/// RULE: Generic chats preserve contact identity and search their own contacts and messages; transport markers never become the imported content.#[test]fn chat_reads_preserve_contact_identity_and_search_its_own_data() {    let (h, secret) = archive();    let chats = listed(&h, &secret, json!({ "table": "thread" }));    let named = by_id(&chats, NAMED_DM);    assert_eq!(named["name"], "Example Asha");    assert!(!named["last_message_preview"].as_str().unwrap().contains("[unsupported message]"));    assert_eq!(named["member_people"], Value::Null);    let bare = by_id(&chats, BARE_DM);    assert!(!bare["name"].as_str().unwrap().trim().is_empty());    let group = by_id(&chats, GROUP);    assert_eq!(group["name"], "Example club");    // A search reads the contact's name, which the chat's own row never held.    let found = listed(&h, &secret, json!({ "table": "thread", "query": "asha" }));    assert_eq!(found.iter().map(|record| record["id"].as_str().unwrap()).collect::<Vec<_>>(), [NAMED_DM]);    // And what a message in it says, which no column of the chat holds.    let found = listed(&h, &secret, json!({ "table": "thread", "query": "driving" }));    assert_eq!(found.iter().map(|record| record["id"].as_str().unwrap()).collect::<Vec<_>>(), [GROUP]);}/// RULE: Generic message reads retain authorship, replies and typed attachments; deleting a message removes its original content and media from the read.#[test]fn message_reads_preserve_authorship_attachments_and_deletion_privacy() {    let (h, secret) = archive();    let lines = listed(&h, &secret, json!({ "table": "message", "where": { "thread_id": GROUP } }));    let first = by_id(&lines, "m1");    assert_eq!(first["display_body"], "who is driving?");    assert_eq!(first["sender_label"], "Example Ben");    assert_eq!(first["paper_sender"], "Example Ben");    assert_eq!(first["reactions"], "❤️ 2");    assert_eq!(first["is_system"], false);    let mine = by_id(&lines, "m2");    assert_eq!(mine["sender_name"], "You");    assert_eq!(mine["sender_label"], Value::Null);    assert!(mine["reply_preview"].as_str().unwrap().contains("who is driving?"));    let picture = by_id(&lines, "m3");    assert_eq!(picture["display_body"], Value::Null, "a picture alone has no words");    assert_eq!(picture["media"][0]["contentType"], "image/jpeg");    let card = by_id(&lines, "m4");    // A shared contact is its card — a media entry by name — and its note says nothing.    assert_eq!(card["display_body"], Value::Null);    assert_eq!(card["media"], json!([{ "kind": "contact", "name": "Example Chen" }]));    let deleted = by_id(&lines, "m5");    assert_ne!(deleted["display_body"], "wrong chat");    assert_eq!(deleted["media"], Value::Null);    // A deleted line is a line about the chat: drawn as a system line.    assert_eq!(deleted["is_system"], true);    assert_eq!(deleted["kept"], true);    let kept = listed(&h, &secret, json!({ "table": "message", "where": { "kept": true } }));    assert_eq!(kept.iter().map(|record| record["id"].as_str().unwrap()).collect::<Vec<_>>(), ["m5"]);}/// RULE: The owner is a member of every group in their archive unless their own seat says they left — an import that wrote no seat for the owner still lists You first, on the chat and on its Members list.#[test]fn the_owner_is_in_every_group_they_did_not_leave() {    let (h, secret) = archive();    let w = h.workspace_id.clone();    let seatless = "c0000000-0000-4000-8000-0000000000b1";    let left = "c0000000-0000-4000-8000-0000000000b2";    for (id, title) in [(seatless, "Example walkers"), (left, "Example old club")] {        h.run(            "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, created_at, updated_at) \             VALUES (?, ?, 'group', ?, ?, ?)",            &[t(id), t(&w), t(title), t(NOW), t(NOW)],        );    }    h.run(        "INSERT INTO cotton_msg_thread_participants (id, thread_id, workspace_id, display_name, is_self, left_at, created_at) \         VALUES ('c0000000-0000-4000-8000-0000000000b3', ?, ?, 'Owner', 1, ?, ?)",        &[t(left), t(&w), t(NOW), t(NOW)],    );    let chats = listed(&h, &secret, json!({ "table": "thread" }));    assert_eq!(by_id(&chats, seatless)["member_self"], "You", "no seat for the owner, still a member");    assert!(by_id(&chats, left)["member_self"].is_null(), "the owner's seat says they left");    // The Members screen reads `thread_member`: You first there too.    let members = listed(&h, &secret, json!({ "table": "thread_member", "where": { "thread_id": seatless } }));    assert_eq!(members.first().map(|member| member["data"]["name"].clone()), Some(json!("You")), "{members:?}");    let seated = listed(&h, &secret, json!({ "table": "thread_member", "where": { "thread_id": GROUP } }));    assert_eq!(seated.first().map(|member| member["data"]["name"].clone()), Some(json!("Owner")), "the owner's own seat leads: {seated:?}");    assert_eq!(seated.iter().filter(|member| member["data"]["name"] == "You").count(), 0, "never a second You beside a seat");}/// RULE: A chat says whether it can be filed and whether it is: `fileable` is true for a chat of the personal Messages and absent in a shared database, and `filed` is `one` or `several` for a chat with live filings and absent for a chat filed nowhere or unfiled.////// These two are what the chat's File and Unfile commands are offered by. A/// filed chat's copy in a shared database keeps the chat's own id, so a File/// offered there would file the PERSONAL chat of that id somewhere the owner/// was not looking; and an Unfile offered on a chat that is not filed has/// nothing to stop.#[test]fn a_chat_says_whether_it_can_be_filed_and_whether_it_is() {    let (h, secret) = archive();    let chat = |h: &Harness| by_id(&listed(h, &secret, json!({ "table": "thread" })), GROUP).clone();    assert_eq!(chat(&h)["fileable"], true);    assert_eq!(chat(&h)["filed_copy"], Value::Null, "a chat of the personal Messages is no copy");    assert_eq!(chat(&h)["filed"], Value::Null, "filed nowhere, it says nothing");    let files = |id: &str, database: &str, state: &str| {        h.run(            "INSERT INTO cotton_msg_thread_filings (id, workspace_id, thread_id, database_id, state, filed_at, created_at, updated_at) \             VALUES (?, ?, ?, ?, ?, ?, ?, ?)",            &[t(id), t(&h.workspace_id), t(GROUP), t(database), t(state), t(NOW), t(NOW), t(NOW)],        );    };    files("filing-1", "database-one", "paused");    assert_eq!(chat(&h)["filed"], "one", "a paused filing is still a filing");    files("filing-2", "database-two", "unfiled");    assert_eq!(chat(&h)["filed"], "one", "an unfiled one is not");    files("filing-3", "database-three", "filed");    assert_eq!(chat(&h)["filed"], "several");    // The same rows read in a shared database: a chat there is a filed copy.    h.run("UPDATE cotton_workspaces SET kind = 'shared' WHERE id = ?", &[t(&h.workspace_id)]);    assert_eq!(chat(&h)["fileable"], Value::Null);    assert_eq!(chat(&h)["filed"], Value::Null);    // And it says so: Clear chat asks in the copy's own words there, nobody    // is "You" in a chat everybody reads, and nobody sends into a copy.    assert_eq!(chat(&h)["filed_copy"], true);    assert_eq!(chat(&h)["member_self"], Value::Null);    assert_eq!(chat(&h)["sendable"], false);    assert_eq!(chat(&h)["send_blocked_reason"], "A filed chat is read here. Reply from your own Messages.");}