//! `chat.search` over a phone's own copy (chat-search, 21 Nov 2026). Every //! name, number and line is invented. use super::*; fn search(handle: &CottonHandle, request: Value) -> Value { answer(handle, "chat.search", request) } fn found_ids(answer: &Value) -> Vec { answer["messages"].as_array().unwrap().iter().map(|m| m["message"].as_str().unwrap().to_string()).collect() } fn cut(text: &str, mark: &Value) -> String { let units: Vec = text.encode_utf16().collect(); let (a, b) = (mark[0].as_u64().unwrap() as usize, mark[1].as_u64().unwrap() as usize); String::from_utf16(&units[a..b]).unwrap() } fn indian_chats(handle: &CottonHandle) { three_chats(handle); message(handle, "m-h1", ASHA, false, "cotton", "live", "कल शाम को मिलते हैं", &iso(4), 4, None); message(handle, "m-h2", ASHA, true, "cotton", "live", "ठीक है, मिलते हैं", &iso(3), 5, None); message(handle, "m-t1", WEEKEND, false, "whatsapp", "imported", "நாளை சந்திப்போம்", &iso(59), 0, Some("s-chitra")); } // RULE: A search across every chat finds message text inside a word in any script, newest first, each with its chat, who wrote it and where the match stands; chats whose name holds it come first. #[test] fn a_search_finds_words_inside_words_in_any_script() { let (_dir, handle) = phone(); indian_chats(&handle); let hindi = search(&handle, json!({ "text": "िलत" })); assert_eq!(found_ids(&hindi), ["m-h2", "m-h1"], "newest first, inside a word"); let first = &hindi["messages"][0]; assert_eq!(first["name"], "Asha Example"); assert_eq!(first["mine"], true); assert_eq!(first["from"], "You"); assert_eq!(cut(first["line"].as_str().unwrap(), &first["marks"][0]), "िलत"); assert!(hindi["messages"][1].get("from").is_none(), "the other person of a one-to-one is the chat's name"); assert!(hindi.get("older").is_none() && hindi.get("empty").is_none()); let tamil = search(&handle, json!({ "text": "சந்தி" })); assert_eq!(found_ids(&tamil), ["m-t1"]); assert_eq!(tamil["messages"][0]["from"], "Chitra Example", "a group's writer"); assert_eq!(tamil["messages"][0]["group"], true); // Case folded, and a chat by its name before the messages. let named = search(&handle, json!({ "text": "WEEKEND" })); assert_eq!(named["chats"].as_array().unwrap().iter().map(|c| c["name"].as_str().unwrap()).collect::>(), ["Weekend plans"]); let kite = search(&handle, json!({ "text": "KITE" })); assert_eq!(found_ids(&kite), ["m-a3"]); assert_eq!(cut(kite["messages"][0]["line"].as_str().unwrap(), &kite["messages"][0]["marks"][0]), "kite"); // Two characters (a whole word in Hindi) are read from the messages themselves. let short = search(&handle, json!({ "text": "कल" })); assert_eq!(found_ids(&short), ["m-h1"]); let none = search(&handle, json!({ "text": "absent words" })); assert_eq!(none["empty"], "Nothing found for “absent words”."); assert_eq!(refused(&handle, "chat.search", json!({ "text": " " })), "invalid_request"); } // RULE: A search never finds a deleted, trashed or hidden message, a group's event line, or what a chat deleted from the list held. #[test] fn a_search_finds_only_what_the_person_can_see() { let (_dir, handle) = phone(); three_chats(&handle); message(&handle, "m-gone", ASHA, false, "cotton", "live", "the secret picnic", &iso(4), 4, None); message(&handle, "m-bin", ASHA, false, "cotton", "live", "the secret picnic again", &iso(4), 5, None); message(&handle, "m-veil", ASHA, false, "cotton", "live", "the secret picnic hidden", &iso(4), 6, None); message(&handle, "m-event", WEEKEND, false, "cotton", "live", "Bimal named the group secret picnic", &iso(4), 0, None); message(&handle, "m-keep", WEEKEND, false, "whatsapp", "imported", "a secret picnic it is", &iso(3), 0, Some("s-bimal")); sql(&handle, "UPDATE cotton_msg_messages SET deleted_at = ? WHERE id = 'm-gone'", &[t(&iso(1))]); sql(&handle, "UPDATE cotton_msg_messages SET trashed_at = ? WHERE id = 'm-bin'", &[t(&iso(1))]); sql(&handle, "UPDATE cotton_msg_messages SET hidden_at = ? WHERE id = 'm-veil'", &[t(&iso(1))]); sql(&handle, "UPDATE cotton_msg_messages SET meta = '{\"system\":{\"kind\":\"renamed\"}}' WHERE id = 'm-event'", &[]); assert_eq!(found_ids(&search(&handle, json!({ "text": "secret picnic" }))), ["m-keep"]); // Deleted from the list: what it held stays unfound. sql(&handle, "UPDATE cotton_msg_threads SET cleared_before = ? WHERE id = ?", &[t(&iso(0)), t(WEEKEND)]); assert!(found_ids(&search(&handle, json!({ "text": "secret picnic" }))).is_empty()); } // RULE: Inside one chat a search answers every match newest first with its place ("1 of 3"), and the thread opened around a match marks it in the bubble's words. #[test] fn inside_a_chat_a_search_steps_through_its_matches() { let (_dir, handle) = phone(); indian_chats(&handle); message(&handle, "m-x", WEEKEND, false, "whatsapp", "imported", "मिलते हैं फिर", &iso(58), 0, Some("s-bimal")); let here = search(&handle, json!({ "text": "मिलते", "thread": ASHA })); assert_eq!(here["hits"], json!(["m-h2", "m-h1"]), "this chat's alone, newest first"); assert_eq!(here["count"], "2"); assert_eq!(here["places"], json!(["1 of 2", "2 of 2"])); assert_eq!(here["words"]["earlier"], "Earlier"); let page = answer(&handle, "chat.thread", json!({ "thread": ASHA, "around": "m-h1", "find": "मिलते" })); assert_eq!(page["focus"], "m-h1"); let bubbles: Vec<&Value> = page["items"].as_array().unwrap().iter().filter(|i| i["item"] == "bubble").collect(); let hit = bubbles.iter().find(|b| b["message"] == "m-h1").unwrap(); assert_eq!(cut(hit["text"].as_str().unwrap(), &hit["marks"][0]), "मिलते"); assert!(bubbles.iter().filter(|b| b["message"] == "m-a3").all(|b| b.get("marks").is_none()), "no match, no mark"); let none = search(&handle, json!({ "text": "tent", "thread": ASHA })); assert_eq!(none["hits"], json!([])); assert_eq!(none["empty"], "Not in this chat."); } // RULE: While the index still fills, a search finds the older messages by reading them, and says more may appear; once whole it says nothing. #[test] fn a_search_finds_older_messages_while_the_index_fills() { let (_dir, handle) = phone(); indian_chats(&handle); handle .client() .with_writer(|replica| { replica.driver.exec("INSERT INTO fts_chat (fts_chat) VALUES ('delete-all')").map_err(|e| e.to_string())?; cotton_store::fts_fill::begin(replica.driver, "fts_chat").map_err(|e| e.to_string()) }) .unwrap(); message(&handle, "m-new", ASHA, false, "cotton", "live", "मिलते रहना", &iso(1), 9, None); let filling = search(&handle, json!({ "text": "मिलते" })); assert_eq!(found_ids(&filling), ["m-new", "m-h2", "m-h1"], "the index's rows, then the older ones read"); assert_eq!(filling["older"], "Still reading older messages. More may appear."); crate::phone::mail_index::fill_chat(&handle.client(), std::time::Duration::from_secs(5)).unwrap(); let whole = search(&handle, json!({ "text": "मिलते" })); assert_eq!(found_ids(&whole), ["m-new", "m-h2", "m-h1"]); assert!(whole.get("older").is_none()); } // RULE: Search is fast on 200,000 messages: a page of results across every chat, and every match inside one chat, each well under a tenth of a second here. #[test] fn a_search_is_fast_on_two_hundred_thousand_messages() { let (_dir, handle) = phone(); three_chats(&handle); let ws = workspace(&handle); // 200,000 invented messages over the three chats, a few words each, in four scripts. sql( &handle, "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 200000) INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at) SELECT 'bulk-' || i, CASE i % 3 WHEN 0 THEN ? WHEN 1 THEN ? ELSE ? END, ?, CASE i % 2 WHEN 0 THEN 'in' ELSE 'out' END, 'cotton', 'live', CASE i % 4 WHEN 0 THEN 'see you tomorrow at the station ' || i WHEN 1 THEN 'कल शाम को मिलते हैं ' || i WHEN 2 THEN 'நாளை சந்திப்போம் ' || i ELSE 'พรุ่งนี้เจอกัน ' || i END, strftime('%Y-%m-%dT%H:%M:%fZ', '2026-01-01', '+' || i || ' seconds'), '2026-01-01' FROM n", &[t(ASHA), t(WEEKEND), t(OLD_SMS), t(&ws)], ); let _ = search(&handle, json!({ "text": "station" })); for (text, thread) in [("station", None), ("िलत", None), ("सलाम नहीं", None), ("சந்தி", Some(ASHA)), ("เจอกัน 1999", None)] { let started = std::time::Instant::now(); let got = match thread { Some(thread) => search(&handle, json!({ "text": text, "thread": thread })), None => search(&handle, json!({ "text": text })), }; let took = started.elapsed(); eprintln!("search {text:?} in {thread:?}: {took:?}"); assert!(took < std::time::Duration::from_millis(if cfg!(debug_assertions) { 400 } else { 100 }), "{text}: {took:?}"); if thread.is_some() { assert_eq!(got["count"], "999+", "every match counted to the ceiling"); } else if text == "सलाम नहीं" { assert!(found_ids(&got).is_empty()); } else { assert!(!found_ids(&got).is_empty() && got["after"].is_string() || text.contains("1999"), "{text}"); } } // The next page follows on from the first, with nothing twice. let first = search(&handle, json!({ "text": "station" })); let second = search(&handle, json!({ "text": "station", "after": first["after"] })); let (a, b) = (found_ids(&first), found_ids(&second)); assert_eq!((a.len(), b.len()), (40, 40)); assert!(a.iter().all(|id| !b.contains(id))); }