// 搜尋所有聊天: the words of every chat — the open conversation of each bot and its past ones — // and the names of the files in them. What the person and the bots said is searched; the // results of tools are not (a page read once would drown the rest). // // Newest first. A hit knows where it is (bot, conversation, message), so a click opens it there. use crate::model::{Bot, Message, Role}; /// The most that is shown; `search` says whether there was more. pub const LIMIT: usize = 40; /// A snippet: this much before the match, and this much in all. const BEFORE: usize = 12; const SNIPPET: usize = 70; #[derive(Clone, Debug, PartialEq)] pub struct Hit { pub bot: u64, /// None: the open conversation; Some(i): 過去的對話 number i. pub thread: Option, /// Where in that conversation, and when it was said (0 for old messages without a time). pub index: usize, pub at: i64, pub mine: bool, /// The match is a file's name. pub file: bool, pub snippet: String, } /// One line around the match, with … where it was cut. fn snippet(text: &str, lower_at: usize, lower: &str) -> String { // (Lower-casing can change a string's length, so the place is counted in characters.) let at = lower[..lower_at].chars().count(); let chars: Vec = text.chars().map(|c| if c.is_whitespace() { ' ' } else { c }).collect(); let from = at.saturating_sub(BEFORE).min(chars.len()); let to = (from + SNIPPET).min(chars.len()); let mut s: String = chars[from..to].iter().collect::().split(' ').filter(|w| !w.is_empty()).collect::>().join(" "); if from > 0 { s.insert(0, '…'); } if to < chars.len() { s.push('…'); } s } fn in_messages(bot: u64, thread: Option, msgs: &[Message], q: &str, out: &mut Vec) { for (index, m) in msgs.iter().enumerate() { if !matches!(m.role, Role::User | Role::Assistant) || m.summary { continue; } let mine = m.role == Role::User; let lower = m.text.to_lowercase(); if let Some(at) = lower.find(q) { out.push(Hit { bot, thread, index, at: m.at, mine, file: false, snippet: snippet(&m.text, at, &lower) }); continue; } if let Some(a) = m.attachments.iter().find(|a| a.name.to_lowercase().contains(q)) { out.push(Hit { bot, thread, index, at: m.at, mine, file: true, snippet: a.name.clone() }); } } } /// Every message that has `query` in it, newest first, and whether there were more than LIMIT. pub fn search(bots: &[Bot], query: &str) -> (Vec, bool) { let q = query.trim().to_lowercase(); if q.is_empty() { return (vec![], false); } let mut out = vec![]; for b in bots { in_messages(b.id, None, &b.messages, &q, &mut out); for (i, (_, msgs)) in b.threads.iter().enumerate() { in_messages(b.id, Some(i), msgs, &q, &mut out); } } // Newest first; messages without a time keep their order, after the dated ones. out.sort_by_key(|a| std::cmp::Reverse(a.at)); let more = out.len() > LIMIT; out.truncate(LIMIT); (out, more) } /// What the chats amount to, cheaply: a search is done again only when this or the query changes. /// (How many messages, the newest one's time, and which conversations are the open ones.) pub fn stamp(bots: &[Bot]) -> (usize, i64, i64) { let (mut n, mut newest, mut open) = (0, 0, 0i64); for b in bots { n += b.messages.len() + b.threads.iter().map(|t| t.1.len()).sum::() + b.threads.len(); newest = newest.max(b.messages.last().map(|m| m.at).unwrap_or(0)); open = open.wrapping_mul(31).wrapping_add(b.messages.first().map(|m| m.at).unwrap_or(0)); } (n, newest, open) } /// 搜尋 → 那則訊息: the message a click on a hit goes to (the chat scrolls there and lights it /// for a moment). #[derive(Clone, Copy, Debug)] pub struct Goto { pub bot: u64, pub index: usize, pub at: i64, pub since: std::time::Instant, } /// How long the chat keeps scrolling to it (the layout settles over a few frames), and how long /// the light stays. pub const GOTO_SCROLL_SECS: f32 = 0.35; pub const GOTO_LIGHT_SECS: f32 = 1.8; impl Goto { /// Is it this message? By its time; by its place for old messages that have none. pub fn is(&self, bot: u64, index: usize, at: i64) -> bool { self.bot == bot && if self.at != 0 { self.at == at } else { self.index == index } } } #[cfg(test)] mod tests { use super::*; fn bot(id: u64, msgs: Vec, threads: Vec<(String, Vec)>) -> Bot { let mut b = crate::model::State::demo().bots[0].clone(); b.id = id; b.messages = msgs; b.threads = threads; b } #[test] fn every_chat_is_searched_newest_first() { let file: crate::attach::Attachment = serde_json::from_value(serde_json::json!({"name": "Q3 報價單.xlsx", "path": "/x"})).unwrap(); let bots = vec![ bot(1, vec![Message { at: 10, ..Message::user("幫我查台北到東京的機票") }, Message { at: 20, ..Message::assistant("最便宜的是飛東京 Tokyo 成田,NT$ 8,200", "m") }, Message { at: 25, ..Message::tool_result("c", "web_fetch", "tokyo tokyo tokyo") }], vec![]), bot(2, vec![Message { at: 30, attachments: vec![file], ..Message::user("看這個") }], vec![("舊的".into(), vec![Message { at: 5, ..Message::user("東京天氣") }, Message { at: 6, summary: true, ..Message::assistant("摘要:東京", "m") }])]), ]; let (hits, more) = search(&bots, " TOKYO "); assert!(!more); // Not the tool's result, and whatever the letters' case. assert_eq!(hits.len(), 1); assert_eq!((hits[0].bot, hits[0].thread, hits[0].index, hits[0].mine), (1, None, 1, false)); assert!(hits[0].snippet.contains("Tokyo 成田")); let (hits, _) = search(&bots, "東京"); // The open chats and the past one, newest first; the summary isn't something anyone said. assert_eq!(hits.iter().map(|h| (h.bot, h.thread, h.index)).collect::>(), vec![(1, None, 1), (1, None, 0), (2, Some(0), 0)]); let (hits, _) = search(&bots, "報價"); assert_eq!(hits.len(), 1); assert!(hits[0].file && hits[0].snippet == "Q3 報價單.xlsx" && hits[0].bot == 2); assert!(search(&bots, " ").0.is_empty()); assert!(search(&bots, "沒有這個字").0.is_empty()); } #[test] fn a_snippet_is_one_line_around_the_match() { let text = format!("{}\n第二行說到 重點在這裡,後面還有很多很多字{}", "前".repeat(40), "後".repeat(100)); let bots = vec![bot(1, vec![Message::user(&text)], vec![])]; let (hits, _) = search(&bots, "重點"); let s = &hits[0].snippet; assert!(s.starts_with('…') && s.ends_with('…'), "{s}"); assert!(s.contains("第二行說到 重點在這裡") && !s.contains('\n'), "{s}"); assert!(s.chars().count() <= SNIPPET + 2); // More than can be shown: the newest LIMIT, and it says so. let many: Vec = (0..LIMIT as i64 + 5).map(|i| Message { at: i + 1, ..Message::user("重複的話") }).collect(); let (hits, more) = search(&[bot(1, many, vec![])], "重複"); assert!(more); assert_eq!(hits.len(), LIMIT); assert_eq!(hits[0].at, LIMIT as i64 + 5); } }