//! Mail search that is true to twelve years — the mailsearch lane's guards.//!//! Each case runs the phone's own `/search` read (`read.find`) and its own//! thread read (`read.emailThread`) over a synthetic household, so what is//! held here is what the person's phone answers, not what one function says.//!//! EVERY FIXTURE HERE IS SYNTHETIC: animals writing to animals at//! `example.invalid` ([nothing-real-ever-goes-in-cotton-s-public-tree]).use rusqlite::types::ValueasSqlValue;use serde_json::{json, Map, Value};usecrate::shell::client::phone_tests::{args, attached};usecrate::shell::client::ClientController;const WS: &str = crate::fixture::WORKSPACE;const GARDEN: &str = "66666666-6666-4666-8666-666666666601";const DIGEST: &str = "66666666-6666-4666-8666-666666666602";const ORDER: &str = "66666666-6666-4666-8666-666666666603";const FENCE: &str = "66666666-6666-4666-8666-666666666604";fn read(client: &ClientController, name: &str, args: &Map<String, Value>) -> Value {let entry = super::reads::read_for(&format!("read.{name}")) .unwrap_or_else(|| panic!("read.{name} is declared"));super::answer_read(client, entry, args) .unwrap_or_else(|reason| panic!("read.{name} answered: {reason}"))}fn run(client: &ClientController, sql: &str, values: &[&str]) { client .with_writer(|replica| {let bound: Vec<SqlValue> = values .iter() .map(|value| SqlValue::Text((*value).to_string())) .collect(); replica .driver .run(sql, &bound) .map_err(|error| format!("{sql}: {error}")) }) .expect("the seed statement");}fn thread(client: &ClientController, id: &str, subject: &str, last_at: &str, kind: &str) { run( client,"INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, created_at, \ updated_at, last_at, sender_kind) VALUES (?,?,?,?,?,?,?,?)", &[id, WS, id, subject, last_at, last_at, last_at, kind], );}fn email(client: &ClientController, id: &str, thread: &str, from: &str, sent_at: &str, body: &str) { run( client,"INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, from_email, \ from_name, sent_at, body, created_at, in_inbox, subject) \ VALUES (?,?,?,?,?,?,?,?,?,0,(SELECT subject FROM cotton_email_threads WHERE id = ?))", &[id, WS, thread, id, from, "Synthetic Sender", sent_at, body, sent_at, thread], );}/// Four conversations that all say "trellis":/// - GARDEN (a person's): twice, its OLDER message is the one that says it;/// - DIGEST (junk): the newest of all;/// - ORDER (a service's): in its SUBJECT, the oldest of all;/// - FENCE (a person's): in a body, newer than GARDEN's.fn seed(client: &ClientController) { thread(client, GARDEN, "Garden plans", "2021-06-01T09:00:00.000Z", "person"); email(client, "garden-1", GARDEN, "mole@example.invalid", "2020-05-01T09:00:00.000Z","The trellis needs mending before the beans go in."); email(client, "garden-2", GARDEN, "vole@example.invalid", "2021-06-01T09:00:00.000Z","Bring seeds on Sunday."); thread(client, DIGEST, "Weekly digest", "2026-09-01T09:00:00.000Z", "junk"); email(client, "digest-1", DIGEST, "news@shop.example.invalid", "2026-09-01T09:00:00.000Z","Trellis sale this week only."); thread(client, ORDER, "Your trellis order", "2019-01-01T09:00:00.000Z", "service"); email(client, "order-1", ORDER, "orders@shop.example.invalid", "2019-01-01T09:00:00.000Z","Your order has shipped."); thread(client, FENCE, "The fence", "2026-08-01T09:00:00.000Z", "person"); email(client, "fence-1", FENCE, "stoat@example.invalid", "2026-08-01T09:00:00.000Z","The trellis is up at last.");}fn mail_hits(answer: &Value) -> Vec<Value> { answer["hits"] .as_array() .unwrap_or_else(|| panic!("hits: {answer}")) .iter() .filter(|hit| hit["kind"] == json!("email") || hit["kind"] == json!("email_thread")) .cloned() .collect()}fn find(client: &ClientController, query: &str) -> Value { read(client, "find", &args(&[("query", json!(query))]))}/// RULE: a word that is only in an email's BODY finds that email's thread —/// the owner kept twelve years of mail on the phone to search it, and a search/// that reads subjects and senders alone would find a fraction of it.#[test]fn a_word_only_in_a_body_is_found() {let (_dir, client) = attached(); seed(&client);let hits = mail_hits(&find(&client, "mending")); assert_eq!(hits.len(), 1, "one conversation says it: {hits:?}"); assert_eq!(hits[0]["threadId"], json!(GARDEN));}/// RULE: a Junk thread is FOUND but labelled with its stack, and comes after/// the mail that is not junk — junk is hidden from the list, never from/// search, and a person must be able to tell it apart at a glance.#[test]fn a_junk_thread_is_found_but_labelled() {let (_dir, client) = attached(); seed(&client);let hits = mail_hits(&find(&client, "trellis"));let digest = hits .iter() .find(|hit| hit["threadId"] == json!(DIGEST)) .unwrap_or_else(|| panic!("the junk thread is found: {hits:?}")); assert_eq!(digest["stack"], json!("junk")); assert_eq!(hits.last().map(|hit| hit["threadId"].clone()), Some(json!(DIGEST)));let garden = hits.iter().find(|hit| hit["threadId"] == json!(GARDEN)).expect("garden"); assert_eq!(garden["stack"], json!("people"));let order = hits.iter().find(|hit| hit["threadId"] == json!(ORDER)).expect("order"); assert_eq!(order["stack"], json!("records"));}/// RULE: one hit per CONVERSATION, ranked by where the words matched (subject/// or sender before body) and newest first within that — a twelve-year/// mailbox ranked by bm25 alone puts a 2014 newsletter above last week's/// letter, and a thread that says the word forty times is one result, not/// forty.#[test]fn mail_is_one_hit_per_thread_headers_first_then_newest_first() {let (_dir, client) = attached(); seed(&client);let answer = find(&client, "trellis");let order: Vec<Value> = mail_hits(&answer).iter().map(|hit| hit["threadId"].clone()).collect(); assert_eq!(order, vec![json!(ORDER), json!(FENCE), json!(GARDEN), json!(DIGEST)]); assert_eq!(answer["totals"]["email"], json!(4), "the total counts conversations: {answer}");}/// RULE: a result carries the MATCHING message and opens the thread at it —/// the reader is addressed by thread, so without the anchor a hit in a/// six-year-old reply opens at the newest message and the person scrolls for/// the line search already found.#[test]fn a_result_opens_the_thread_at_the_matching_message() {let (_dir, client) = attached(); seed(&client);let hits = mail_hits(&find(&client, "trellis"));let garden = hits.iter().find(|hit| hit["threadId"] == json!(GARDEN)).expect("garden"); assert_eq!(garden["id"], json!("garden-1"), "the message that says it, not the newest"); assert!( garden["snippet"].as_str().unwrap_or_default().contains("trellis"),"the slip shows the matching words: {garden}" );let opened = read( &client,"emailThread", &args(&[("threadId", json!(GARDEN)), ("at", garden["id"].clone())]), ); assert_eq!(opened["openAt"], json!("garden-1"));let ids: Vec<Value> = opened["emails"] .as_array() .expect("emails") .iter() .map(|email| email["id"].clone()) .collect(); assert!(ids.contains(&json!("garden-1")), "the anchor is drawn: {ids:?}");// An anchor that is not in this thread opens it at the newest, as before.let stray = read( &client,"emailThread", &args(&[("threadId", json!(GARDEN)), ("at", json!("fence-1"))]), ); assert_eq!(stray["openAt"], Value::Null);}/// RULE: the search inside Mail is scoped to mail — it answers mail and/// nothing else — while the global search still finds mail beside the rest.#[test]fn the_mail_scope_answers_mail_alone() {let (_dir, client) = attached(); seed(&client); run( &client,"INSERT INTO cotton_notes (id, workspace_id, title, body, created_at, updated_at) \ VALUES ('77777777-7777-4777-8777-777777777701', ?, 'Trellis sketch', 'trellis', \ '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z')", &[WS], );let scoped = read(&client, "find", &args(&[("query", json!("trellis")), ("scope", json!("mail"))]));let kinds: Vec<Value> = scoped["hits"] .as_array() .expect("hits") .iter() .map(|hit| hit["kind"].clone()) .collect(); assert!(!kinds.is_empty()); assert!(kinds.iter().all(|kind| kind == "email" || kind == "email_thread"), "{kinds:?}");let global = find(&client, "trellis");let global_kinds: Vec<Value> = global["hits"].as_array().expect("hits").iter().map(|hit| hit["kind"].clone()).collect(); assert!(global_kinds.contains(&json!("note")) && global_kinds.contains(&json!("email")), "{global_kinds:?}");}/// RULE: while the wide index fills in the background, search still answers/// from the index every file holds whole — the owner is never left without/// mail search for the hours a phone takes to index twelve years (coordinator,/// 12 Oct 2026) — and once it is whole, a sender's NAME finds their mail.#[test]fn search_answers_while_the_wide_index_fills_and_finds_senders_once_it_is_whole() {let (_dir, client) = attached(); seed(&client); run(&client, "UPDATE cotton_emails SET from_name = 'Mole Burrows' WHERE id = 'garden-1'", &[]);// As a v122 move leaves a file that held mail: the wide index empty, filling. client .with_writer(|replica| { replica .driver .exec("INSERT INTO fts_mail (fts_mail) VALUES ('delete-all')") .and_then(|()| cotton_store::fts_fill::begin(replica.driver, "fts_mail")) .map_err(|error| error.to_string()) }) .expect("filling");let during = mail_hits(&find(&client, "mending")); assert_eq!(during.len(), 1, "the old index answers during the fill: {during:?}"); assert!(mail_hits(&find(&client, "burrows")).is_empty(), "a sender's name is not in the old index"); client .with_writer(|replica| {while !cotton_store::fts_fill::step(replica.driver, "fts_mail", 2) .map_err(|error| error.to_string())? .is_some_and(|progress| progress.done) {}Ok::<(), String>(()) }) .expect("filled");let after = mail_hits(&find(&client, "burrows")); assert_eq!(after.len(), 1, "{after:?}"); assert_eq!(after[0]["id"], json!("garden-1")); assert_eq!(after[0]["threadId"], json!(GARDEN));}/// RULE: the device row's Sync section can say how far this device's mail/// index is filled — the owner is told why a sender's name does not find/// their mail yet, and when it will — and says nothing once it is whole.#[test]fn the_sync_status_counts_the_fill_and_falls_silent_when_it_is_whole() {let (_dir, client) = attached(); seed(&client); assert_eq!(client.sync_status()["searchIndex"], Value::Null); client .with_writer(|replica| { replica .driver .exec("INSERT INTO fts_mail (fts_mail) VALUES ('delete-all')") .and_then(|()| cotton_store::fts_fill::begin(replica.driver, "fts_mail")) .map_err(|error| error.to_string()) }) .expect("filling");let mail = client .with_writer(|replica| { replica .driver .get("SELECT count(*) AS n FROM cotton_emails", &[]) .map_err(|error| error.to_string()) }) .expect("counts") .and_then(|row| row.int("n")) .expect("a count"); assert_eq!(client.sync_status()["searchIndex"], json!({ "filled": 0, "total": mail }));// The background runner: one budgeted pass on this (phone) device.let done = super::mail_index::fill(&client, std::time::Duration::from_secs(5)).expect("fills"); assert!(done.is_some_and(|progress| progress.done)); assert_eq!(client.sync_status()["searchIndex"], Value::Null);}