//! `chat.search`: Chat's search, answered from the phone's own copy //! (chat-search, 21 Nov 2026). The rules — what a search is, where a match //! stands, a result's line — are `cotton_core::messages::app::find`. //! //! Messages are sealed on the server, so the server is never asked: the //! copy's `fts_chat` (v149, any three characters in a row) finds a search of //! three characters or more in a millisecond or so on 200,000 messages. Two //! cases read the messages themselves, newest first, and stop at a page: //! a shorter search (one or two characters: "कल" is a word), and the rows //! below the index's floor while this phone still fills it in the background //! (`mail_index::fill_chat`); the answer then says `older`. //! //! Newest first means newest landed: the order of the copy's rows, which the //! index keeps and can page without sorting every match. use cotton_core::messages::app::find; use cotton_core::messages::app::shapes::{FoundMessage, InChatAnswer, InChatWords, SearchAnswer, SearchWords, StarredAnswer}; use super::*; /// Messages one page of results holds. const PAGE: usize = 40; /// How many rows one statement reads before the hits are judged in Rust. const BATCH: i64 = 400; pub(super) fn answer(client: &ClientController, request: &Value) -> Result { let typed = request.get("text").and_then(Value::as_str).unwrap_or_default(); let query = find::query_of(typed).ok_or_else(|| bad("text", "what to search for"))?; let answer = match request.get("thread").and_then(Value::as_str).filter(|t| !t.is_empty()) { Some(thread) => serde_json::to_value(in_chat(client, &query, thread)?), None => serde_json::to_value(everywhere(client, &query, request.get("after").and_then(Value::as_str).and_then(|a| a.parse::().ok()))?), }; answer.map_err(|e| MethodError::new("unanswerable", e.to_string())) } /// Where the index stands: the floor below which it holds nothing yet (0 once whole). fn floor_of(client: &ClientController) -> i64 { client .with_writer(|replica| { let row = replica .driver .get("SELECT floor FROM _fts_fill WHERE fts = ?", &[SqlValue::Text(super::super::mail_index::CHAT_INDEX.into())]) .map_err(|e| e.to_string())?; Ok(row.and_then(|r| r.int("floor")).unwrap_or(0)) }) .unwrap_or(0) } /// One message row as the search reads it. const FOUND_COLUMNS: &str = "m.rowid AS _row, m.id, m.thread_id, m.direction, m.body, m.meta, m.sent_at, m.sender_participant_id"; /// What a search never finds: trashed, deleted or hidden messages, and a /// group's event lines. const LIVE: &str = "m.workspace_id = ? AND m.trashed_at IS NULL AND m.deleted_at IS NULL AND m.hidden_at IS NULL AND m.body IS NOT NULL AND m.body <> ''"; /// Up to `want` matching rows below `before` (a row; none: from the newest), /// newest landed first, in `thread` alone when given. Each one's words hold /// the search (the index's and LIKE's candidates are judged by `find::marks`). fn matching(ctx: &mut Ctx<'_>, query: &str, thread: Option<&str>, before: Option, want: usize, floor: i64) -> Result>, String> { let mut out = Vec::new(); let phrase = find::fts_phrase(query); let like = find::like_pattern(query); let mut below = before.unwrap_or(i64::MAX); let in_thread = if thread.is_some() { " AND m.thread_id = ?" } else { "" }; // The index holds every row at or above its floor; LIKE reads the rest. // CROSS JOIN keeps the index first: SQLite never drives from the // messages (by thread) and asks the index once a row. let mut indexed = phrase.is_some(); // A blocked sender's messages are found nowhere but Blocked (SENDERS.md). let hidden = super::senders::hidden_threads(ctx)?; loop { let mut params = vec![ws(ctx)]; let sql = if indexed { params.insert(0, text(phrase.clone().unwrap_or_default())); format!( "SELECT {FOUND_COLUMNS} FROM fts_chat f CROSS JOIN {MESSAGES} m ON m.rowid = f.rowid WHERE fts_chat MATCH ? AND {LIVE}{in_thread} AND f.rowid < ? ORDER BY f.rowid DESC LIMIT {BATCH}" ) } else { params.push(text(like.clone())); format!( "SELECT {FOUND_COLUMNS} FROM {MESSAGES} m WHERE {LIVE} AND m.body LIKE ? ESCAPE '\\'{in_thread} AND m.rowid < ? ORDER BY m.rowid DESC LIMIT {BATCH}" ) }; if let Some(thread) = thread { params.push(text(thread.to_string())); } params.push(SqlValue::Integer(if indexed { below } else { below.min(if phrase.is_some() { floor } else { i64::MAX }) })); let got = rows(ctx, &sql, ¶ms)?; let full = got.len() as i64 == BATCH; for row in got { below = n(&row, "_row"); let body = s(&row, "body").unwrap_or_default(); let event = meta_value_of(&row).get("system").is_some_and(|v| v.is_object() || v == &Value::Bool(true)); let blocked = s(&row, "thread_id").is_some_and(|t| hidden.contains(&t)); if !event && !blocked && !find::marks(&body, query).is_empty() { out.push(row); if out.len() >= want { return Ok(out); } } } if full { continue; } // The index is read through; below its floor, LIKE reads on. if indexed && floor > 0 { indexed = false; below = below.min(floor); continue; } return Ok(out); } } fn meta_value_of(row: &Map) -> Value { super::super::cotton_chat::meta_value(row.get("meta").unwrap_or(&Value::Null)) } fn everywhere(client: &ClientController, query: &str, after: Option) -> Result { let lines = list::lines(); let clock = Clock::of(client); let you = say(&lines, "app.list.you", &[]); let floor = floor_of(client); let folded = query.to_lowercase(); let (chats, found, more) = read(client, "chat.search", |ctx| { let all: Vec = summaries(ctx, None)?; let every: Vec<&Summary> = all.iter().collect(); let named = names(ctx, &every, &you)?; // Chats by name, on the first page only: a chat deleted from the list // is still one the person can find by its name, as a new chat would be. let mut chats = Vec::new(); if after.is_none() { let mut hits: Vec = all.iter().filter(|t| named.get(&t.id).is_some_and(|n| n.name.to_lowercase().contains(&folded))).cloned().collect(); hits.sort_by_key(|t| t.order()); for t in &mut hits { count_unread(ctx, t)?; } for t in &hits { let last = last_message(ctx, t)?; chats.push(row_of(&lines, &clock, t, named.get(&t.id).unwrap_or(&Named::default()), last.as_ref())); } } // Messages: one more than a page says whether there is a next one. let by_id: HashMap<&str, &Summary> = all.iter().map(|t| (t.id.as_str(), t)).collect(); let mut kept = Vec::new(); let mut before = after; loop { let got = matching(ctx, query, None, before, PAGE + 1 - kept.len(), floor)?; let exhausted = got.len() < PAGE + 1 - kept.len(); for row in got { before = Some(n(&row, "_row")); let thread = s(&row, "thread_id").unwrap_or_default(); // A message the person deleted their chat over stays gone (`deleteChat`). let Some(t) = by_id.get(thread.as_str()) else { continue }; if t.cleared_before.as_deref().is_some_and(|cut| ms(&s(&row, "sent_at").unwrap_or_default()) <= ms(cut)) { continue; } kept.push(row); } if exhausted || kept.len() > PAGE { break; } } let more = kept.len() > PAGE; kept.truncate(PAGE); let found: Vec = kept .iter() .filter_map(|row| { let thread = s(row, "thread_id")?; let t = by_id.get(thread.as_str())?; let (line, marks) = find::snippet(&s(row, "body").unwrap_or_default(), query)?; found_of(&lines, &clock, row, t, named.get(&thread).unwrap_or(&Named::default()), line, marks) }) .collect(); let more = more.then(|| found.last().and_then(|f| kept.iter().find(|r| s(r, "id").as_deref() == Some(f.message.as_str()))).map(|r| n(r, "_row").to_string())).flatten(); Ok((chats, found, more)) })?; let empty = (chats.is_empty() && found.is_empty()).then(|| say(&lines, "app.search.none", &[("text", query)])); Ok(SearchAnswer { text: query.to_string(), chats, messages: found, after: more, older: (floor > 0).then(|| say(&lines, "app.search.older", &[])), empty, words: SearchWords { hint: say(&lines, "app.search.hint", &[]), chats: say(&lines, "app.search.chats", &[]), messages: say(&lines, "app.search.messages", &[]), more: say(&lines, "app.search.more", &[]), }, }) } fn in_chat(client: &ClientController, query: &str, thread: &str) -> Result { let lines = list::lines(); let floor = floor_of(client); let hits = read(client, "chat.search", |ctx| { let Some(t) = summaries(ctx, Some(thread))?.into_iter().next() else { return Ok(None) }; let got = matching(ctx, query, Some(thread), None, COUNT_CEILING as usize, floor)?; // Newest first by the moment it was sent, as the thread is laid. let mut kept: Vec<(String, i64, String)> = got .into_iter() .filter(|row| !t.cleared_before.as_deref().is_some_and(|cut| ms(&s(row, "sent_at").unwrap_or_default()) <= ms(cut))) .map(|row| (s(&row, "sent_at").unwrap_or_default(), n(&row, "_row"), s(&row, "id").unwrap_or_default())) .collect(); kept.sort_by(|a, b| (&b.0, a.1).cmp(&(&a.0, b.1))); Ok(Some(kept.into_iter().map(|(_, _, id)| id).collect::>())) })? .ok_or_else(|| MethodError::new("not_found", say(&lines, "app.refused.no_message", &[])))?; let count = badge(hits.len() as u32); let places = (1..=hits.len()).map(|i| say(&lines, "app.search.of", &[("i", &i.to_string()), ("n", &count)])).collect(); Ok(InChatAnswer { text: query.to_string(), thread: thread.to_string(), empty: hits.is_empty().then(|| say(&lines, "app.search.none_here", &[])), count, places, hits, older: (floor > 0).then(|| say(&lines, "app.search.older", &[])), words: InChatWords { hint: say(&lines, "app.search.in_chat", &[]), earlier: say(&lines, "app.search.earlier", &[]), later: say(&lines, "app.search.later", &[]), }, }) } /// One message as a result draws it: its chat, who wrote it, its line. fn found_of(lines: &LineSet, clock: &Clock, row: &Map, t: &Summary, named: &Named, line: String, marks: Vec<[u32; 2]>) -> Option { let thread = s(row, "thread_id")?; let mine = s(row, "direction").as_deref() == Some("out"); let from = if mine { Some(say(lines, "app.thread.you", &[])) } else if t.group { Some(s(row, "sender_participant_id").and_then(|seat| named.seats.get(&seat).map(|(name, _)| name.clone())).unwrap_or_else(|| cotton_core::messages::display::UNKNOWN_NAME.to_string())) } else { None }; Some(FoundMessage { message: s(row, "id")?, picture: picture(&thread, &named.name, named.photo.clone()), name: named.name.clone(), thread, group: t.group, from, mine, line, marks, when: s(row, "sent_at").and_then(|at| clock.recent(&at)), }) } /// `chat.starred { after? }`: the person's starred messages, newest starred /// first, forty a page; `after` is the last one's place. pub(super) fn starred(client: &ClientController, request: &Value) -> Result { let after = request.get("after").and_then(Value::as_str).and_then(|a| a.split_once('\u{1f}')).map(|(at, id)| (at.to_string(), id.to_string())); let lines = list::lines(); let clock = Clock::of(client); let you = say(&lines, "app.list.you", &[]); let (found, more) = read(client, "chat.starred", |ctx| { let mut params = vec![ws(ctx)]; let mut sql = format!("SELECT {FOUND_COLUMNS}, m.media, m.starred_at FROM {MESSAGES} m WHERE m.workspace_id = ? AND m.starred_at IS NOT NULL AND m.trashed_at IS NULL AND m.deleted_at IS NULL AND m.hidden_at IS NULL"); if let Some((at, id)) = &after { sql.push_str(" AND (m.starred_at < ? OR (m.starred_at = ? AND m.id < ?))"); params.extend([text(at.clone()), text(at.clone()), text(id.clone())]); } sql.push_str(&format!(" ORDER BY m.starred_at DESC, m.id DESC LIMIT {}", PAGE + 1)); let mut got = rows(ctx, &sql, ¶ms)?; let more = got.len() > PAGE; got.truncate(PAGE); let all: Vec = summaries(ctx, None)?; let every: Vec<&Summary> = all.iter().collect(); let named = names(ctx, &every, &you)?; let by_id: HashMap<&str, &Summary> = all.iter().map(|t| (t.id.as_str(), t)).collect(); let found: Vec = got .iter() .filter_map(|row| { let thread = s(row, "thread_id")?; let t = by_id.get(thread.as_str())?; let media = media_of(row); let meta = meta_of(row); let r = Row { body: row.get("body").and_then(Value::as_str), media: &media, meta: meta.as_ref(), deleted_at: None }; found_of(&lines, &clock, row, t, named.get(&thread).unwrap_or(&Named::default()), bubble::line_of(&r), Vec::new()) }) .collect(); let more = more.then(|| got.last().map(|r| format!("{}\u{1f}{}", s(r, "starred_at").unwrap_or_default(), s(r, "id").unwrap_or_default()))).flatten(); Ok((found, more)) })?; let answer = StarredAnswer { title: say(&lines, "app.starred.title", &[]), empty: (found.is_empty() && after.is_none()).then(|| say(&lines, "app.starred.empty", &[])), messages: found, after: more, }; serde_json::to_value(answer).map_err(|e| MethodError::new("unanswerable", e.to_string())) }