Cotton code
605 lines · 28.6 KB · RustRaw
//! `import.whatsappExport` over the attached test controller.//!//! Every transcript here is invented — names, numbers and every line of text//! ([nothing-real-ever-goes-in-cotton-s-public-tree]). The format is the one//! WhatsApp for iOS writes: a LEFT-TO-RIGHT MARK, the bracketed stamp, the//! sender, the body.use std::path::{Path, PathBuf};use serde_json::json;use super::{run, validate, ImportArgs, METHOD};use crate::methods::CLIENT_METHODS;use crate::shell::client::phone_tests::attached as attached_open;use crate::shell::client::ClientController;/// The kit seals the messages tables, so an import keys its ids under the/// database's data key: every test here holds a synthetic one.fn attached() -> (tempfile::TempDir, std::sync::Arc<ClientController>) {    let (dir, client) = attached_open();    client.data_keys().hold(&client.current_database().expect("attached"), &cotton_core::seal::DataKey::from_bytes([7; 32]));    (dir, client)}const LRM: &str = "\u{200e}";fn line(stamp: &str, sender: &str, body: &str) -> String {    format!("{LRM}[{stamp}] {sender}: {body}\n")}/// A 1:1 chat between the owner and one other person: a greeting, a poll, an/// omitted picture and an attached one.fn dm_transcript() -> String {    let mut text = String::new();    text.push_str(&format!(        "{LRM}[26/07/2025, 10:00:00 AM] Messages and calls are end-to-end encrypted. No one outside of this chat, not even WhatsApp, can read or listen to them.\n"    ));    text.push_str(&line("26/07/2025, 10:12:45 AM", "Tarun Bose", "Are we still on for the trek?"));    text.push_str(&line("26/07/2025, 10:13:02 AM", "Priya Vend", "Yes! Bringing the map."));    text.push_str(&line(        "26/07/2025, 10:14:00 AM",        "Priya Vend",        "POLL:\nWhich trail?\nOPTION: Ridge (2 votes)\nOPTION: River (1 vote)",    ));    text.push_str(&line("26/07/2025, 10:15:00 AM", "Priya Vend", "image omitted"));    text.push_str(&line(        "26/07/2025, 10:16:00 AM",        "Tarun Bose",        &format!("{LRM}<attached: 00000005-PHOTO-2025-07-26-10-16-00.jpg>"),    ));    text.push_str(&line("26/07/2025, 10:17:00 AM", "Tarun Bose", "See you at six."));    text}/// A group of three, created in the transcript, where nothing names the owner.fn group_transcript() -> String {    let mut text = String::new();    text.push_str(&format!(        "{LRM}[01/08/2025, 09:00:00 AM] Priya Vend created group \"Weekend Trek\"\n"    ));    text.push_str(&line("01/08/2025, 09:01:00 AM", "Priya Vend", "Welcome all."));    text.push_str(&line("01/08/2025, 09:02:00 AM", "Tarun Bose", "Saturday works for me."));    text.push_str(&line("01/08/2025, 09:03:00 AM", "Meera Iyer", "Same here."));    text.push_str(&line("01/08/2025, 09:04:00 AM", "Priya Vend", "Saturday it is."));    text}/// A minimal STORED zip — local headers, a central directory and the end/// record — which is all the reader needs and what WhatsApp writes for media.fn stored_zip(entries: &[(&str, &[u8])]) -> Vec<u8> {    let mut out: Vec<u8> = Vec::new();    let mut central: Vec<u8> = Vec::new();    for (name, data) in entries {        let offset = out.len() as u32;        let name_bytes = name.as_bytes();        // Local file header.        out.extend_from_slice(&0x0403_4b50u32.to_le_bytes());        out.extend_from_slice(&20u16.to_le_bytes()); // version needed        out.extend_from_slice(&0u16.to_le_bytes()); // flags        out.extend_from_slice(&0u16.to_le_bytes()); // method: stored        out.extend_from_slice(&0u16.to_le_bytes()); // time        out.extend_from_slice(&0u16.to_le_bytes()); // date        out.extend_from_slice(&0u32.to_le_bytes()); // crc (the reader does not check)        out.extend_from_slice(&(data.len() as u32).to_le_bytes());        out.extend_from_slice(&(data.len() as u32).to_le_bytes());        out.extend_from_slice(&(name_bytes.len() as u16).to_le_bytes());        out.extend_from_slice(&0u16.to_le_bytes()); // extra        out.extend_from_slice(name_bytes);        out.extend_from_slice(data);        // Central directory entry.        central.extend_from_slice(&0x0201_4b50u32.to_le_bytes());        central.extend_from_slice(&20u16.to_le_bytes()); // made by        central.extend_from_slice(&20u16.to_le_bytes()); // needed        central.extend_from_slice(&0u16.to_le_bytes());        central.extend_from_slice(&0u16.to_le_bytes());        central.extend_from_slice(&0u16.to_le_bytes());        central.extend_from_slice(&0u16.to_le_bytes());        central.extend_from_slice(&0u32.to_le_bytes());        central.extend_from_slice(&(data.len() as u32).to_le_bytes());        central.extend_from_slice(&(data.len() as u32).to_le_bytes());        central.extend_from_slice(&(name_bytes.len() as u16).to_le_bytes());        central.extend_from_slice(&0u16.to_le_bytes()); // extra        central.extend_from_slice(&0u16.to_le_bytes()); // comment        central.extend_from_slice(&0u16.to_le_bytes()); // disk        central.extend_from_slice(&0u16.to_le_bytes()); // internal attrs        central.extend_from_slice(&0u32.to_le_bytes()); // external attrs        central.extend_from_slice(&offset.to_le_bytes());        central.extend_from_slice(name_bytes);    }    let central_offset = out.len() as u32;    let central_size = central.len() as u32;    out.extend_from_slice(&central);    out.extend_from_slice(&0x0605_4b50u32.to_le_bytes());    out.extend_from_slice(&0u16.to_le_bytes());    out.extend_from_slice(&0u16.to_le_bytes());    out.extend_from_slice(&(entries.len() as u16).to_le_bytes());    out.extend_from_slice(&(entries.len() as u16).to_le_bytes());    out.extend_from_slice(&central_size.to_le_bytes());    out.extend_from_slice(&central_offset.to_le_bytes());    out.extend_from_slice(&0u16.to_le_bytes());    out}fn args(path: &Path, owner: Option<&str>) -> ImportArgs {    ImportArgs {        path: path.to_path_buf(),        file_name: None,        owner_name: owner.map(str::to_string),        tz_offset: "+05:30".to_string(),        country_code: "91".to_string(),    }}/// The same, for a file the SHARE EXTENSION staged: the path is a UUID copy in/// the app group and the name the export actually came under rides beside it.fn shared_args(path: &Path, file_name: &str, owner: Option<&str>) -> ImportArgs {    ImportArgs {        file_name: Some(file_name.to_string()),        ..args(path, owner)    }}fn write(dir: &Path, name: &str, bytes: &[u8]) -> PathBuf {    let path = dir.join(name);    std::fs::write(&path, bytes).expect("the export file");    path}fn count(client: &ClientController, sql: &str) -> i64 {    client        .with_writer(|file| {            file.driver                .get(sql, &[])                .map_err(|error| error.to_string())?                .and_then(|row| row.int("n"))                .ok_or_else(|| "no count".to_string())        })        .expect("a count")}fn text(client: &ClientController, sql: &str) -> Option<String> {    client        .with_writer(|file| {            Ok(file                .driver                .get(sql, &[])                .map_err(|error| error.to_string())?                .and_then(|row| row.text("v").map(str::to_string)))        })        .expect("a read")}#[test]fn the_verb_is_in_the_client_partition() {    assert!(CLIENT_METHODS.contains(&METHOD), "{METHOD} is a phone verb");}#[test]fn validate_refuses_what_it_should_before_a_byte_moves() {    let dir = tempfile::tempdir().expect("a temp dir");    let missing = dir.path().join("nothing.txt");    let error = validate(&json!({"path": missing.to_string_lossy()})).expect_err("no file");    assert_eq!(error.code, "bad_request");    let wrong = write(dir.path(), "notes.pdf", b"%PDF");    let error = validate(&json!({"path": wrong.to_string_lossy()})).expect_err("not an export");    assert!(error.message.contains("not a WhatsApp export"), "{}", error.message);    let error = validate(&json!({"bytes": "…"})).expect_err("bytes");    assert!(error.message.contains("never cross"), "{}", error.message);    let error = validate(&json!({})).expect_err("no path");    assert!(error.message.contains("`path` is required"), "{}", error.message);    let ok = write(dir.path(), "_chat.txt", b"x");    let parsed = validate(&json!({"args": {"path": ok.to_string_lossy(), "ownerName": " Priya Vend "}}))        .expect("a valid request");    assert_eq!(parsed.owner_name.as_deref(), Some("Priya Vend"));    assert_eq!(parsed.tz_offset, "+05:30");    assert_eq!(parsed.country_code, "91");}#[test]fn a_dm_export_lands_as_one_thread_with_its_poll_and_its_omitted_picture_and_a_rerun_adds_nothing() {    let (dir, client) = attached();    // The file is named the way WhatsApp names a 1:1 export: after the other    // person. That is how the owner is decided without asking.    let path = write(        dir.path(),        "WhatsApp Chat - Tarun Bose.txt",        dm_transcript().as_bytes(),    );    let answer = run(&client, &args(&path, None)).expect("an import");    assert_eq!(answer["kind"], json!("dm"));    assert_eq!(answer["ownerName"], json!("Priya Vend"), "the other sender is you");    assert_eq!(answer["imported"], json!(6), "{answer}");    assert_eq!(answer["skipped"], json!(0));    assert_eq!(answer["method"], json!(METHOD));    let thread = answer["thread"].as_str().expect("a thread id").to_string();    assert!(!thread.is_empty());    // A `.txt` carries no bytes: the attached picture is counted absent, the    // omitted one omitted, and nothing is copied.    assert_eq!(answer["media"]["copied"], json!(0));    assert_eq!(answer["media"]["omitted"], json!(2), "{answer}");    assert_eq!(count(&client, "SELECT COUNT(*) AS n FROM cotton_msg_threads"), 1);    assert_eq!(        count(&client, &format!("SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = '{thread}'")),        6    );    assert_eq!(        text(&client, &format!("SELECT DISTINCT origin AS v FROM cotton_msg_messages WHERE thread_id = '{thread}'")).as_deref(),        Some("imported"),        "an imported row is never relayed"    );    assert_eq!(        text(&client, &format!("SELECT json_extract(meta, '$.poll.question') AS v FROM cotton_msg_messages WHERE thread_id = '{thread}' AND json_extract(meta, '$.poll') IS NOT NULL")).as_deref(),        Some("Which trail?"),        "the poll is read beside the words"    );    assert_eq!(        count(&client, &format!("SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = '{thread}' AND json_extract(meta, '$.attachment.omitted') = 1")),        1,        "the omitted picture is a row with its words and no bytes"    );    assert_eq!(count(&client, "SELECT COUNT(*) AS n FROM _media"), 0);    let ops = count(&client, "SELECT COUNT(*) AS n FROM _outbox");    assert!(ops > 0, "the rows went through the outbox");    assert_eq!(        text(&client, "SELECT json_extract(msg_import_self_names, '$.whatsapp[0]') AS v FROM cotton_workspaces").as_deref(),        Some("Priya Vend"),        "the owner's name is remembered for the next export"    );    // The same file again: nothing twice.    let again = run(&client, &args(&path, None)).expect("a re-run");    assert_eq!(again["imported"], json!(0), "{again}");    assert_eq!(again["skipped"], json!(6));    assert_eq!(again["thread"], json!(thread));    assert_eq!(count(&client, "SELECT COUNT(*) AS n FROM cotton_msg_threads"), 1);    assert_eq!(count(&client, &format!("SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = '{thread}'")), 6);    // A re-run queues no message, only its own line in the Imports history.    assert_eq!(count(&client, "SELECT COUNT(*) AS n FROM _outbox"), ops + 1, "a re-run queues its run's line alone");    assert_eq!(count(&client, "SELECT COUNT(*) AS n FROM cotton_imports WHERE source = 'chat_export'"), 2);    assert_eq!(        count(&client, "SELECT COUNT(*) AS n FROM cotton_imports WHERE added = 6 AND skipped = 0"),        1,        "the first run's line counts what it added"    );    assert_eq!(count(&client, "SELECT COUNT(*) AS n FROM cotton_imports WHERE added = 0 AND skipped = 6"), 1);    assert_eq!(        text(&client, "SELECT DISTINCT title AS v FROM cotton_imports").as_deref(),        Some("WhatsApp chat with Tarun Bose"),        "the run is named by the chat, never by the file's path"    );}#[test]fn a_zip_export_copies_its_picture_into_the_store_and_queues_the_upload_once() {    let (dir, client) = attached();    let picture = b"\xff\xd8\xff\xe0 not really a jpeg but bytes all the same".to_vec();    let archive = stored_zip(&[        ("_chat.txt", dm_transcript().as_bytes()),        ("00000005-PHOTO-2025-07-26-10-16-00.jpg", &picture),    ]);    let path = write(dir.path(), "WhatsApp Chat - Tarun Bose.zip", &archive);    let answer = run(&client, &args(&path, None)).expect("an import");    assert_eq!(answer["imported"], json!(6), "{answer}");    assert_eq!(answer["media"]["copied"], json!(1), "{answer}");    assert_eq!(answer["media"]["omitted"], json!(1), "the `image omitted` line");    let thread = answer["thread"].as_str().expect("a thread").to_string();    assert_eq!(count(&client, "SELECT COUNT(*) AS n FROM _media WHERE state = 'pending'"), 1);    let key = text(&client, "SELECT key AS v FROM _media").expect("a key");    assert!(        key.starts_with(&format!("{}/messages/{thread}/", crate::fixture::WORKSPACE)),        "the key carries the workspace and the thread: {key}"    );    // RULE: an imported picture is this phone's to give until it uploads, so    // the phone says so — the hold is how the serving Mac tells "on its way"    // from "on no machine", and how its media-index sweep knows the photo row    // has bytes behind it (todo 5365af8f: 3,348 rows that never did).    assert_eq!(        text(&client, "SELECT object_key AS v FROM cotton_media_holdings WHERE tier = 'original' AND dropped_at IS NULL"),        Some(key.clone()),        "the phone holds the imported original"    );    let local = text(&client, "SELECT local_path AS v FROM _media").expect("a local path");    assert_eq!(std::fs::read(&local).expect("the stored bytes"), picture, "content-addressed copy");    assert_eq!(        count(&client, &format!("SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = '{thread}' AND json_array_length(media) = 1")),        1,        "the row carries the object key"    );    // The scratch folder is gone.    assert!(!client.layout().client_dir().join("import-scratch").exists() || std::fs::read_dir(client.layout().client_dir().join("import-scratch")).map(|d| d.count() == 0).unwrap_or(true));    let again = run(&client, &args(&path, None)).expect("a re-run");    assert_eq!(again["imported"], json!(0));    assert_eq!(again["media"]["copied"], json!(0), "a re-run copies nothing: {again}");    assert_eq!(count(&client, "SELECT COUNT(*) AS n FROM _media"), 1);    assert_eq!(count(&client, "SELECT COUNT(*) AS n FROM cotton_media_holdings"), 1, "a re-run holds nothing new");}#[test]fn a_group_nobody_names_the_owner_in_asks_once_and_remembers() {    let (dir, client) = attached();    let path = write(dir.path(), "WhatsApp Chat - Weekend Trek.txt", group_transcript().as_bytes());    // Nothing decides: no remembered name, no `You`, three senders.    let asked = run(&client, &args(&path, None)).expect("a question, not a refusal");    assert_eq!(asked["needs"], json!("ownerName"), "{asked}");    let senders: Vec<String> = serde_json::from_value(asked["senders"].clone()).expect("senders");    assert_eq!(senders, ["Priya Vend", "Tarun Bose", "Meera Iyer"]);    assert_eq!(count(&client, "SELECT COUNT(*) AS n FROM cotton_msg_threads"), 0, "asking writes nothing");    let answer = run(&client, &args(&path, Some("Tarun Bose"))).expect("an import");    assert_eq!(answer["kind"], json!("group"));    assert_eq!(answer["title"], json!("Weekend Trek"));    // Four lines and the creation event, which a group keeps as a row.    assert_eq!(answer["imported"], json!(5), "{answer}");    let thread = answer["thread"].as_str().expect("a thread").to_string();    assert_eq!(        count(&client, &format!("SELECT COUNT(*) AS n FROM cotton_msg_thread_participants WHERE thread_id = '{thread}'")),        2,        "the two OTHER people are seats — the owner is the workspace, not a participant — and no number was invented for either"    );    assert_eq!(        count(&client, &format!("SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = '{thread}' AND direction = 'out'")),        1,        "the one line the owner wrote"    );    // Third time, no name given: remembered, and nothing added.    let again = run(&client, &args(&path, None)).expect("remembered");    assert_eq!(again["ownerName"], json!("Tarun Bose"));    assert_eq!(again["imported"], json!(0));    assert_eq!(again["thread"], json!(thread));}#[test]fn a_file_that_is_not_a_transcript_is_refused_by_name() {    let (dir, client) = attached();    let path = write(dir.path(), "_chat.txt", b"just some words\nwith no stamps at all\n");    let error = run(&client, &args(&path, None)).expect_err("not an export");    assert_eq!(error.code, "bad_request");    assert!(error.message.contains("no messages at all"), "{}", error.message);    let archive = stored_zip(&[("README.md", b"hello")]);    let path = write(dir.path(), "something.zip", &archive);    let error = run(&client, &args(&path, None)).expect_err("no transcript");    assert!(error.message.contains("holds no _chat.txt"), "{}", error.message);    assert!(!error.message.contains('`'), "a refusal is a sentence, not markup: {}", error.message);}// ── what the file is CALLED, not where it is staged ─────────────────────────/// **Finding a of the 15 Sep 2026 walk.** A 1:1 export names the OTHER party on/// the file, so the owner is the sender who is not in it — and the share/// extension's copy is a UUID, which carries none of that. With the name passed/// beside the path, the question is not asked.#[test]fn a_staged_copy_decides_the_owner_from_the_name_the_export_came_under() {    let (dir, client) = attached();    // What the share extension writes: a UUID in the app group's inbox.    let staged = write(        dir.path(),        "9F3C1A22-0000-4000-8000-00000000A1B2.txt",        dm_transcript().as_bytes(),    );    // Without the name, the path says nothing and the screen has to ask.    let asked = run(&client, &args(&staged, None)).expect("a question, not a refusal");    assert_eq!(asked["needs"], json!("ownerName"), "{asked}");    // With it, the other sender is you and nothing is asked.    let answer = run(        &client,        &shared_args(&staged, "WhatsApp Chat - Tarun Bose.txt", None),    )    .expect("an import");    assert_eq!(answer["ownerName"], json!("Priya Vend"));    assert_eq!(answer["imported"], json!(6), "{answer}");}/// **Finding b.** A refusal is read by a person who shared a file, and a/// sandbox path is neither actionable nor theirs. Every message names the/// DISPLAY name and no message carries a path.////// It carries no BACKTICKS either (the walk of 15 Sep 2026, on/// `/messages/import`): the screen drew the crate's sentence verbatim, so/// ``like this`` arrived on the page as grave accents around the person's own/// file name. A refusal is a sentence, not markup.#[test]fn no_refusal_ever_names_a_path() {    // Every assertion below also holds this, so it is said once.    fn plain(message: &str) {        assert!(!message.contains('/'), "a path reached a person: {message}");        assert!(!message.contains('`'), "a refusal is a sentence, not markup: {message}");        assert!(!message.contains("os error"), "the OS reached a person: {message}");    }    let (dir, client) = attached();    let staged = write(dir.path(), "3B7E0000-0000-4000-8000-000000000001.txt", b"no stamps here\n");    let error = run(        &client,        &shared_args(&staged, "WhatsApp Chat - Asha Rao.txt", None),    )    .expect_err("not an export");    assert!(error.message.contains("WhatsApp Chat - Asha Rao.txt"), "{}", error.message);    plain(&error.message);    let archive = stored_zip(&[("README.md", b"hello")]);    let staged = write(dir.path(), "3B7E0000-0000-4000-8000-000000000002.zip", &archive);    let error = run(&client, &shared_args(&staged, "WhatsApp Chat - Asha Rao.zip", None))        .expect_err("no transcript");    assert!(error.message.contains("WhatsApp Chat - Asha Rao.zip"), "{}", error.message);    plain(&error.message);    // And the two refusals `validate` makes, before a byte moves.    let wrong = write(dir.path(), "3B7E0000-0000-4000-8000-000000000003.pdf", b"%PDF");    let error = validate(&json!({        "path": wrong.to_string_lossy(),        "fileName": "Statement April.pdf",    }))    .expect_err("not an export");    assert!(error.message.contains("Statement April.pdf"), "{}", error.message);    plain(&error.message);    let missing = dir.path().join("3B7E0000-0000-4000-8000-000000000004.txt");    let error = validate(&json!({        "path": missing.to_string_lossy(),        "fileName": "WhatsApp Chat - Asha Rao.txt",    }))    .expect_err("no file");    assert!(error.message.contains("WhatsApp Chat - Asha Rao.txt"), "{}", error.message);    // A missing file is `NotFound`, so the person is told that in words —    // never as `No such file or directory (os error 2)`.    assert!(error.message.contains("the file is no longer there"), "{}", error.message);    plain(&error.message);}/// A caller-supplied name is a stranger's text: the leaf survives and anything/// that could read as a path does not.#[test]fn a_supplied_file_name_is_reduced_to_a_leaf() {    let dir = tempfile::tempdir().expect("a temp dir");    let ok = write(dir.path(), "_chat.txt", b"x");    let path = ok.to_string_lossy().to_string();    let parsed = validate(&json!({"path": path, "fileName": "/var/mobile/…/WhatsApp Chat - Asha Rao.txt"}))        .expect("a valid request");    assert_eq!(parsed.file_name.as_deref(), Some("WhatsApp Chat - Asha Rao.txt"));    for blank in ["", "   ", ".", "..", "some/dir/"] {        let parsed = validate(&json!({"path": path, "fileName": blank})).expect("a valid request");        assert_eq!(parsed.file_name, None, "{blank:?}");    }}/// A 1:1 transcript between two named people, both of whom speak. Unattributed/// notice, so nothing but the file name could name the chat — which is what a/// staged copy does not have.fn dm_between(one: &str, two: &str) -> String {    let mut text = String::new();    text.push_str(&format!(        "{LRM}[03/08/2025, 09:00:00 AM] Messages and calls are end-to-end encrypted. No one outside of this chat, not even WhatsApp, can read or listen to them.\n"    ));    text.push_str(&line("03/08/2025, 09:01:00 AM", one, "Are you coming?"));    text.push_str(&line("03/08/2025, 09:02:00 AM", two, "On my way."));    text.push_str(&line("03/08/2025, 09:03:00 AM", one, "See you there."));    text}/// **Finding d.** The owner answers once per SPELLING, never once per export./// Two exports naming the owner differently, then a re-import of the FIRST:/// two questions in all, because every answered name is remembered. Before the/// fix only the latest was kept, so step 3 asked a third time.#[test]fn the_owner_is_asked_once_per_spelling_and_never_again() {    let (dir, client) = attached();    // Staged copies: a UUID name, so nothing outside the transcript names the    // chat and the owner cannot be read off the file (which is the ordinary    // share-sheet case, and what makes the memory load-bearing).    let first = write(        dir.path(),        "9F3C1A22-0000-4000-8000-0000000000A1.txt",        dm_between("Priya Vend", "Tarun Bose").as_bytes(),    );    let second = write(        dir.path(),        "9F3C1A22-0000-4000-8000-0000000000A2.txt",        dm_between("+91 98765 43210", "Meera Iyer").as_bytes(),    );    // 1. The first export asks, and is answered.    assert_eq!(        run(&client, &args(&first, None)).expect("a question")["needs"],        json!("ownerName")    );    let answer = run(&client, &args(&first, Some("Priya Vend"))).expect("an import");    assert_eq!(answer["ownerName"], json!("Priya Vend"));    // 2. A second export whose senders name the owner by a number instead. It    //    asks, because nothing remembered is in it.    assert_eq!(        run(&client, &args(&second, None)).expect("a question")["needs"],        json!("ownerName"),        "a spelling nobody has answered with yet is a question"    );    let answer = run(&client, &args(&second, Some("+91 98765 43210"))).expect("an import");    assert_eq!(answer["ownerName"], json!("+91 98765 43210"));    // 3. THE FIRST EXPORT AGAIN, with no name given. This is the regression:    //    with only the latest answer kept, "Priya Vend" was forgotten the    //    moment the second export was answered.    let again = run(&client, &args(&first, None)).expect("remembered");    assert_eq!(again["ownerName"], json!("Priya Vend"), "{again}");    assert_eq!(again["imported"], json!(0), "and it adds nothing twice");    // 4. And the second, likewise.    let again = run(&client, &args(&second, None)).expect("remembered");    assert_eq!(again["ownerName"], json!("+91 98765 43210"), "{again}");    // Both spellings are on the workspace row, most recent first.    assert_eq!(        text(&client, "SELECT msg_import_self_names AS v FROM cotton_workspaces").as_deref(),        Some(r#"{"whatsapp":["+91 98765 43210","Priya Vend"]}"#),        "every answered name is kept"    );}/// RULE: once the kit seals the messages tables, a/// phone's export import makes its contacts and threads under the keyed/// namespace only the data key makes (the Mac's import makes the same), so/// no derived id is a hash of the database id and a phone number; with no/// data key held it is refused by name and writes nothing.#[test]fn a_sealed_chat_import_keys_its_ids_and_refuses_without_the_data_key() {    let (dir, client) = attached_open();    let path = write(dir.path(), "WhatsApp Chat - Tarun Bose.txt", dm_transcript().as_bytes());    let refused = run(&client, &args(&path, None)).expect_err("no data key");    assert_eq!(refused.code, cotton_client::seal::SEAL_KEY_MISSING, "{refused:?}");    assert_eq!(count(&client, "SELECT count(*) AS n FROM cotton_msg_messages"), 0, "nothing was written");    let database = client.current_database().expect("attached");    let dk = cotton_core::seal::DataKey::from_bytes([7; 32]);    client.data_keys().hold(&database, &dk);    let answer = run(&client, &args(&path, None)).expect("an import");    assert_eq!(answer["imported"], json!(6), "{answer}");    let plain = text(&client, "SELECT coalesce(namespace, id) AS v FROM cotton_workspaces LIMIT 1").expect("the file's namespace");    let keyed = cotton_client::seal::keyed_namespace(&dk, &database, &plain).expect("keyed");    assert_ne!(keyed, plain);    // Every contact the export made is derived under the keyed namespace, none under the plain one.    let handles = text(&client, "SELECT group_concat(contact_id || '|' || kind || '|' || value, char(10)) AS v FROM cotton_msg_contact_handles").unwrap_or_default();    let mut checked = 0;    for line in handles.lines() {        let [contact, kind, value] = line.splitn(3, '|').collect::<Vec<_>>()[..] else { continue };        let derived = |ns: &str| [cotton_core::cotton_rules::ids::msg_contact_handle_id(ns, kind, value), cotton_core::cotton_rules::ids::contact_handle_id(ns, kind, value)];        assert!(!derived(&plain).iter().any(|id| id == contact), "{kind} contact made under the plain namespace");        checked += 1;    }    // A name-only export makes no contact to check; every handle it does make is checked above.    let _ = checked;    let again = run(&client, &args(&path, None)).expect("a rerun");    assert_eq!(again["imported"], json!(0), "a rerun under the same key adds nothing: {again}");}// RULE: an imported chat in front is named as the stream names it (the thread's// own name, else its title), never left blank: it has no Cotton number and no// contact of its own.#[test]fn an_imported_chat_in_front_is_named_after_the_other_person() {    let (dir, client) = attached();    let path = write(dir.path(), "WhatsApp Chat - Tarun Bose.txt", dm_transcript().as_bytes());    let thread = run(&client, &args(&path, None)).expect("an import")["thread"].as_str().expect("a thread").to_string();    let front = crate::phone::chat_face::slips(&client, &json!({ "thread": thread })).expect("chat.slips");    assert_eq!(front["name"], json!("Tarun Bose"), "{front}");    assert_eq!(front["cotton"], json!(false));    assert!(front.get("number").is_none(), "an archive says no number");    assert!(!front["slips"].as_array().expect("slips").is_empty());}