//! The 대화 screen's reads (`app/src/admin.spec.md`, "Conversations"): what people said, what Jarvis //! answered and how each answer was made, from the worker's history store //! (`memory/history.sqlite`, schema owned by `src/jarvis/memory/history.py`). Read only; the //! screen is the only reader, and nothing it reads goes to a log. use std::collections::HashMap; use std::path::Path; use rusqlite::{params_from_iter, types::Value as Sql, Connection, OpenFlags}; use serde_json::{json, Value}; use unicode_normalization::UnicodeNormalization; pub const DEFAULT_LIMIT: usize = 200; pub const MAX_LIMIT: usize = 2000; /// What the screen asks for. `None` filters match everything. #[derive(Debug, Clone)] pub struct Query { /// People's words (voice transcripts and chat messages). pub said: bool, /// Jarvis's answers and its own chat messages. pub answered: bool, /// How each answer was made (the traces). pub thought: bool, /// `voice`, `chat` or `task` (a task has traces only; its answer is a chat message). pub via: Option, /// A person's records: written by them or answers to them. pub person: Option, pub channel: Option, /// Text the record (or the trace's question, answer or steps) contains, case folded. pub find: Option, /// Unix seconds, inclusive / exclusive. pub since: Option, pub until: Option, /// Only items older than this one (paging back) / this one and newer (the window shown). pub before: Option, pub from: Option, pub limit: usize, } /// An item's place in the order: time, then records before traces, then id. Items are ordered by /// it, so paging by it never skips or repeats one, even when two share a time. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Cursor { pub at: f64, /// 0: a record (`h`), 1: a trace (`t`). pub src: u8, pub id: i64, } impl Cursor { /// From `{at, key}`, as the screen sends an item back. pub fn of(v: &Value) -> Option { let at = v.get("at")?.as_f64()?; let key = v.get("key")?.as_str()?; let src = match key.get(..1)? { "h" => 0, "t" => 1, _ => return None }; Some(Self { at, src, id: key[1..].parse().ok()? }) } /// SQL for "a row of table `src` comes before this cursor", over columns `{p}ts` and `{p}id`. fn before_sql(&self, src: u8, p: &str) -> (String, Vec) { use std::cmp::Ordering::*; match src.cmp(&self.src) { Less => (format!("{p}ts <= ?"), vec![Sql::Real(self.at)]), Greater => (format!("{p}ts < ?"), vec![Sql::Real(self.at)]), Equal => (format!("({p}ts < ? OR ({p}ts = ? AND {p}id < ?))"), vec![Sql::Real(self.at), Sql::Real(self.at), Sql::Integer(self.id)]), } } } /// The cursor conditions of `q` for table `src`, appended to `sql` and `args`. fn cursor_sql(q: &Query, src: u8, p: &str, sql: &mut String, args: &mut Vec) { if let Some(c) = &q.before { let (cond, a) = c.before_sql(src, p); *sql += &format!(" AND {cond}"); args.extend(a); } if let Some(c) = &q.from { let (cond, a) = c.before_sql(src, p); *sql += &format!(" AND NOT {cond}"); args.extend(a); } } impl Default for Query { fn default() -> Self { Self { said: true, answered: true, thought: true, via: None, person: None, channel: None, find: None, since: None, until: None, before: None, from: None, limit: DEFAULT_LIMIT } } } /// Jarvis's Discord user id, from its bot token: the token's first part is the id in base64. pub fn bot_id_of_token(token: &str) -> Option { use base64::Engine; let first = token.trim().split('.').next()?.trim_end_matches('='); let raw = base64::engine::general_purpose::STANDARD_NO_PAD.decode(first) .or_else(|_| base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(first)).ok()?; let id = String::from_utf8(raw).ok()?; (!id.is_empty() && id.len() <= 20 && id.bytes().all(|b| b.is_ascii_digit())).then_some(id) } /// The history store's own text folding (`history.py`, `_fold`): NFKC, then lower case. fn fold(text: &str) -> String { text.nfkc().collect::().to_lowercase() } fn like(text: &str) -> String { let escaped = text.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_"); format!("%{escaped}%") } fn open(path: &Path) -> Result { // Read-write without create: a WAL database needs its shared-memory file, which a read-only // connection may not make. Only SELECTs run (query_only). let c = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX) .map_err(|e| format!("대화 기록을 열 수 없습니다: {e}"))?; c.busy_timeout(std::time::Duration::from_secs(3)).map_err(|e| e.to_string())?; c.pragma_update(None, "query_only", true).map_err(|e| e.to_string())?; Ok(c) } fn has_traces(c: &Connection) -> bool { c.query_row("SELECT 1 FROM sqlite_master WHERE type='table' AND name='traces'", [], |_| Ok(())).is_ok() } /// The records and traces `q` asks for, newest `q.limit` of them in time order, with the people /// and channels the filters can pick from. `bot`: Jarvis's Discord user id, when known (its chat /// messages count as answers; without it only those that answer someone do, and the authors of those). pub fn query(path: &Path, bot: Option<&str>, q: &Query) -> Result { if !path.is_file() { return Ok(json!({"items": [], "more": false, "people": [], "channels": [], "missing": true})); } let c = open(path)?; let limit = q.limit.clamp(1, MAX_LIMIT); let bot = bot.unwrap_or(""); let is_bot = "(h.to_id IS NOT NULL OR h.author_id = ?1 OR h.author_id IN \ (SELECT author_id FROM history WHERE kind = 'chat' AND to_id IS NOT NULL))"; let err = |e: rusqlite::Error| format!("대화 기록을 읽지 못했습니다: {e}"); let names: HashMap = { let mut st = c.prepare("SELECT author_id, author_name, MAX(ts) FROM history \ WHERE kind IN ('voice', 'chat') AND author_id != '' GROUP BY author_id").map_err(err)?; let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(err)?; rows.collect::>().map_err(err)? }; let name_of = |id: &str| names.get(id).cloned().unwrap_or_default(); let mut items: Vec<((f64, u8, i64), Value)> = Vec::new(); let mut more = false; if q.said || q.answered { let mut sql = format!("SELECT h.id, h.ts, h.kind, h.channel_id, h.author_id, h.author_name, h.to_id, h.text, \ ({is_bot} AND h.kind = 'chat') OR h.kind = 'reply' FROM history h WHERE 1"); let mut args: Vec = vec![Sql::Text(bot.into())]; match (q.said, q.answered) { (true, false) => sql += &format!(" AND (h.kind = 'voice' OR (h.kind = 'chat' AND NOT {is_bot}))"), (false, true) => sql += &format!(" AND (h.kind = 'reply' OR (h.kind = 'chat' AND {is_bot}))"), _ => {} } match q.via.as_deref() { Some("voice") => sql += " AND h.kind IN ('voice', 'reply')", Some("chat") => sql += " AND h.kind = 'chat'", Some(_) => sql += " AND 0", None => {} } if let Some(p) = &q.person { sql += " AND (h.author_id = ? OR h.to_id = ?)"; args.extend([Sql::Text(p.clone()), Sql::Text(p.clone())]); } if let Some(ch) = &q.channel { sql += " AND h.channel_id = ?"; args.push(Sql::Text(ch.clone())); } if let Some(f) = q.find.as_deref().map(str::trim).filter(|f| !f.is_empty()) { sql += " AND h.norm LIKE ? ESCAPE '\\'"; args.push(Sql::Text(like(&fold(f)))); } if let Some(t) = q.since { sql += " AND h.ts >= ?"; args.push(Sql::Real(t)); } if let Some(t) = q.until { sql += " AND h.ts < ?"; args.push(Sql::Real(t)); } cursor_sql(q, 0, "h.", &mut sql, &mut args); sql += &format!(" ORDER BY h.ts DESC, h.id DESC LIMIT {}", limit + 1); let mut st = c.prepare(&sql).map_err(err)?; let rows = st.query_map(params_from_iter(args), |r| { let (id, ts, kind): (i64, f64, String) = (r.get(0)?, r.get(1)?, r.get(2)?); let (author, author_name, to): (String, String, Option) = (r.get(4)?, r.get(5)?, r.get(6)?); let answer: bool = r.get(8)?; Ok(((ts, 0, id), json!({ "key": format!("h{id}"), "type": if answer { "answered" } else { "said" }, "at": ts, "via": if kind == "chat" { "chat" } else { "voice" }, "channel": r.get::<_, String>(3)?, "who": {"id": author, "name": author_name}, "to": to.map(|t| json!({"id": t, "name": name_of(&t)})), "text": r.get::<_, String>(7)?, }))) }).map_err(err)?; let got = rows.collect::, _>>().map_err(err)?; more |= got.len() > limit; items.extend(got.into_iter().take(limit)); } if q.thought && has_traces(&c) { let mut sql = String::from("SELECT id, ts, via, channel_id, user_id, question, answer, ms, steps FROM traces WHERE 1"); let mut args: Vec = Vec::new(); if let Some(v) = &q.via { sql += " AND via = ?"; args.push(Sql::Text(v.clone())); } if let Some(p) = &q.person { sql += " AND user_id = ?"; args.push(Sql::Text(p.clone())); } if let Some(ch) = &q.channel { sql += " AND channel_id = ?"; args.push(Sql::Text(ch.clone())); } if let Some(f) = q.find.as_deref().map(str::trim).filter(|f| !f.is_empty()) { sql += " AND (question LIKE ? ESCAPE '\\' OR answer LIKE ? ESCAPE '\\' OR steps LIKE ? ESCAPE '\\')"; args.extend(std::iter::repeat_n(Sql::Text(like(f)), 3)); } if let Some(t) = q.since { sql += " AND ts >= ?"; args.push(Sql::Real(t)); } if let Some(t) = q.until { sql += " AND ts < ?"; args.push(Sql::Real(t)); } cursor_sql(q, 1, "", &mut sql, &mut args); let sql = format!("{sql} ORDER BY ts DESC, id DESC LIMIT {}", limit + 1); let mut st = c.prepare(&sql).map_err(err)?; let rows = st.query_map(params_from_iter(args), |r| { let (id, ts): (i64, f64) = (r.get(0)?, r.get(1)?); let user: String = r.get(4)?; let steps: String = r.get(8)?; let ms: i64 = r.get(7)?; Ok(((ts, 1, id), json!({ "key": format!("t{id}"), "type": "thought", "at": ts, "via": r.get::<_, String>(2)?, "channel": r.get::<_, Option>(3)?, "who": {"id": user.clone(), "name": name_of(&user)}, "question": r.get::<_, String>(5)?, "answer": r.get::<_, String>(6)?, "ms": ms.max(0), "pending": ms < 0, "steps": serde_json::from_str::(&steps).unwrap_or(json!([])), }))) }).map_err(err)?; let got = rows.collect::, _>>().map_err(err)?; more |= got.len() > limit; items.extend(got.into_iter().take(limit)); } items.sort_by(|a, b| b.0.0.total_cmp(&a.0.0).then(b.0.1.cmp(&a.0.1)).then(b.0.2.cmp(&a.0.2))); more |= items.len() > limit; items.truncate(limit); items.reverse(); let mut people: Vec = { let mut st = c.prepare(&format!("SELECT h.author_id, h.author_name, MAX(h.ts) FROM history h \ WHERE (h.kind = 'voice' OR (h.kind = 'chat' AND NOT {is_bot})) AND h.author_id != '' GROUP BY h.author_id")) .map_err(err)?; let rows = st.query_map([bot], |r| Ok(json!({"id": r.get::<_, String>(0)?, "name": r.get::<_, String>(1)?}))) .map_err(err)?; rows.collect::>().map_err(err)? }; people.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str())); let channels: Vec = { let mut st = c.prepare("SELECT channel_id, MAX(kind = 'chat'), MAX(ts) FROM history GROUP BY channel_id \ ORDER BY MAX(ts) DESC").map_err(err)?; let rows = st.query_map([], |r| Ok(json!({"id": r.get::<_, String>(0)?, "via": if r.get::<_, bool>(1)? { "chat" } else { "voice" }}))).map_err(err)?; rows.collect::>().map_err(err)? }; Ok(json!({"items": items.into_iter().map(|(_, v)| v).collect::>(), "more": more, "people": people, "channels": channels})) } /// Every item between `since` (inclusive) and `until` (exclusive) as plain text, in time order: /// what people said, Jarvis's answers, and each trace in full (the records and notes it was given, /// the tools offered, the plan, the model's thinking, every tool call with its arguments and result, /// the answer), for the 로그 screen's 대화 export. `names`: chat channel id to the name given it. /// Returns the text and how many items it holds. pub fn export_text(path: &Path, bot: Option<&str>, since: f64, until: f64, names: &HashMap) -> Result<(String, usize), String> { let mut pages: Vec> = vec![]; let mut before = None; loop { let q = Query { since: Some(since), until: Some(until), before, limit: MAX_LIMIT, ..Query::default() }; let v = query(path, bot, &q)?; let items = v["items"].as_array().cloned().unwrap_or_default(); before = items.first().and_then(Cursor::of); let more = v["more"].as_bool().unwrap_or(false); pages.push(items); if !more || before.is_none() { break; } } let items: Vec = pages.into_iter().rev().flatten().collect(); let mut out = String::new(); for i in &items { export_item(&mut out, i, names); } Ok((out, items.len())) } fn export_item(out: &mut String, i: &Value, names: &HashMap) { use std::fmt::Write; let s = |v: &Value| v.as_str().unwrap_or("").to_string(); let at = chrono::DateTime::from_timestamp_millis((i["at"].as_f64().unwrap_or(0.0) * 1000.0) as i64) .map(|t| t.with_timezone(&chrono::Local).format("%Y-%m-%d %H:%M:%S").to_string()).unwrap_or_default(); let via = match i["via"].as_str() { Some("voice") => "음성", Some("chat") => "채팅", Some("task") => "정기 작업", _ => "" }; let channel = match i["channel"].as_str() { Some(id) if !id.is_empty() => match names.get(id) { Some(n) => format!(" · {n}"), None => format!(" · {via} 채널 {id}"), }, _ => String::new(), }; let person = |w: &Value| { let (id, name) = (s(&w["id"]), s(&w["name"])); if name.is_empty() { id } else if id.is_empty() { name } else { format!("{name}({id})") } }; let indent = |text: &str, pad: &str| text.lines().map(|l| format!("{pad}{l}\n")).collect::(); match i["type"].as_str() { Some("thought") => { let tools = i["steps"].as_array().map_or(0, |st| st.iter() .filter(|x| x["kind"] == "tool" && x.get("skipped").is_none_or(Value::is_null)).count()); let took = if i["pending"].as_bool() == Some(true) { "답을 만드는 중".to_string() } else { format!("{:.1}초", i["ms"].as_f64().unwrap_or(0.0) / 1000.0) }; let _ = writeln!(out, "[{at}] 자비스 생각 · {}의 말에 답하며 · 도구 {tools}번 · {took} · {via}{channel}", person(&i["who"])); let _ = writeln!(out, " 받은 말: {}", s(&i["question"])); for st in i["steps"].as_array().into_iter().flatten() { export_step(out, st, &indent); } let answer = s(&i["answer"]); let _ = writeln!(out, " 답: {}", if i["pending"].as_bool() == Some(true) { "(만드는 중)".into() } else if answer.is_empty() { "(답하지 못함)".into() } else { answer }); } Some(kind) => { let who = if kind == "answered" { match i.get("to").filter(|t| !t.is_null()) { Some(t) => format!("자비스 → {}", person(t)), None => "자비스".into() } } else { person(&i["who"]) }; let _ = writeln!(out, "[{at}] {who} · {via}{channel}"); out.push_str(&indent(&s(&i["text"]), " ")); } None => {} } out.push('\n'); } fn export_step(out: &mut String, st: &Value, indent: &dyn Fn(&str, &str) -> String) { use std::fmt::Write; let list = |k: &str| st[k].as_array().map(|a| a.iter().filter_map(Value::as_str).map(String::from).collect::>()) .unwrap_or_default(); match st["kind"].as_str() { Some("records") => { let (recent, matches) = (list("recent"), list("matches")); let notes = st["notes"].as_u64().unwrap_or(0); let _ = writeln!(out, " 참고한 기록: 최근 대화 {}줄 · 관련 기록 {}줄 · 사람별 지침 {notes}개", recent.len(), matches.len()); for (title, xs) in [("최근 대화", recent), ("관련 기록", matches)] { if !xs.is_empty() { let _ = writeln!(out, " {title}:"); out.push_str(&indent(&xs.join("\n"), " ")); } } } Some("tools") => { let _ = writeln!(out, " 쓸 수 있게 고른 도구: {}", list("names").join(", ")); } Some("plan") => { let _ = writeln!(out, " 계획:"); for (n, x) in list("steps").iter().enumerate() { let _ = writeln!(out, " {}. {x}", n + 1); } } Some("think") => { let _ = writeln!(out, " 모델 생각:"); out.push_str(&indent(st["text"].as_str().unwrap_or(""), " ")); } Some("tool") => { let state = match st["skipped"].as_str() { Some("duplicate") => "건너뜀: 같은 호출을 되풀이해 부르지 않음".to_string(), Some("not_allowed") => "건너뜀: 허용되지 않은 도구라 부르지 않음".to_string(), Some(other) => format!("건너뜀: {other}"), None => (if st["ok"].as_bool() == Some(true) { "성공" } else { "실패" }).to_string(), }; let _ = writeln!(out, " 도구 호출: {} ({state})", st["name"].as_str().unwrap_or("")); if st["args"].as_object().is_some_and(|a| !a.is_empty()) { let _ = writeln!(out, " 인자:"); out.push_str(&indent(&serde_json::to_string_pretty(&st["args"]).unwrap_or_default(), " ")); } if let Some(r) = st["result"].as_str().filter(|r| !r.is_empty()) { let _ = writeln!(out, " 결과:"); out.push_str(&indent(r, " ")); } } other => { let _ = writeln!(out, " {}: {st}", other.unwrap_or("?")); } } } /// A cheap mark of what the 대화 screen shows that changes when something is said or a question /// arrives (the newest record and trace), and as an answer is made (its steps) and ends, so the /// screen can poll it often and read the items again only when it changed. pub fn stamp(path: &Path) -> Result { if !path.is_file() { return Ok("missing".into()); } let c = open(path)?; let err = |e: rusqlite::Error| format!("대화 기록을 읽지 못했습니다: {e}"); let said: Option = c.query_row("SELECT MAX(id) FROM history", [], |r| r.get(0)).map_err(err)?; let thought: (Option, i64, Option) = if has_traces(&c) { c.query_row("SELECT MAX(id), (SELECT COUNT(*) FROM traces WHERE ms < 0), \ (SELECT SUM(LENGTH(steps)) FROM traces WHERE ms < 0) FROM traces", [], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))) .map_err(err)? } else { (None, 0, None) }; Ok(format!("{said:?}/{thought:?}")) } /// The history store's tables as `src/jarvis/memory/history.py` makes them, for tests. #[cfg(test)] pub(crate) const TEST_SCHEMA: &str = " CREATE TABLE history (id INTEGER PRIMARY KEY, ts REAL NOT NULL, kind TEXT NOT NULL, channel_id TEXT NOT NULL, author_id TEXT NOT NULL, author_name TEXT NOT NULL, to_id TEXT, message_id TEXT, text TEXT NOT NULL, norm TEXT NOT NULL); CREATE TABLE traces (id INTEGER PRIMARY KEY, ts REAL NOT NULL, via TEXT NOT NULL, channel_id TEXT, user_id TEXT NOT NULL, question TEXT NOT NULL, answer TEXT NOT NULL, ms INTEGER NOT NULL, steps TEXT NOT NULL);"; #[cfg(test)] mod tests { use super::*; use std::path::PathBuf; fn db(tag: &str) -> (PathBuf, Connection) { let dir = std::env::temp_dir().join(format!("jarvis-history-view-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("history.sqlite"); let c = Connection::open(&path).unwrap(); c.pragma_update(None, "journal_mode", "WAL").unwrap(); c.execute_batch(TEST_SCHEMA).unwrap(); (path, c) } fn rec(c: &Connection, ts: f64, kind: &str, ch: &str, author: &str, name: &str, to: Option<&str>, text: &str) { c.execute("INSERT INTO history(ts, kind, channel_id, author_id, author_name, to_id, text, norm) VALUES (?,?,?,?,?,?,?,?)", rusqlite::params![ts, kind, ch, author, name, to, text, fold(text)]).unwrap(); } fn trace(c: &Connection, ts: f64, via: &str, ch: Option<&str>, user: &str, q: &str, a: &str, steps: &str) { c.execute("INSERT INTO traces(ts, via, channel_id, user_id, question, answer, ms, steps) VALUES (?,?,?,?,?,?,?,?)", rusqlite::params![ts, via, ch, user, q, a, 900, steps]).unwrap(); } /// Alice speaks and Jarvis answers by voice; Bob writes in chat and Jarvis (bot 900) answers there /// and also posts a reminder of its own. fn sample(tag: &str) -> PathBuf { let (path, c) = db(tag); rec(&c, 10.0, "voice", "vc", "1", "Alice", None, "서울 날씨 어때"); trace(&c, 11.0, "voice", Some("vc"), "1", "서울 날씨 어때", "맑습니다", r#"[{"kind":"tools","names":["getWeather"]},{"kind":"think","text":"날씨 도구를 쓰자"}]"#); rec(&c, 12.0, "reply", "vc", "", "Jarvis", Some("1"), "맑습니다"); rec(&c, 20.0, "chat", "ch", "2", "Bob", None, "Hello THERE"); trace(&c, 21.0, "chat", Some("ch"), "2", "Hello THERE", "안녕하세요", "[]"); rec(&c, 22.0, "chat", "ch", "900", "Jarvis", Some("2"), "안녕하세요"); rec(&c, 30.0, "chat", "ch", "900", "Jarvis", None, "약속 알림"); path } fn kinds(v: &Value) -> Vec<(String, String)> { v["items"].as_array().unwrap().iter() .map(|i| (i["type"].as_str().unwrap().into(), i["text"].as_str().or(i["question"].as_str()).unwrap().into())) .collect() } #[test] fn everything_comes_in_time_order_with_who_said_it() { let path = sample("all"); let v = query(&path, None, &Query::default()).unwrap(); let k = kinds(&v); assert_eq!(k.iter().map(|(t, _)| t.as_str()).collect::>(), ["said", "thought", "answered", "said", "thought", "answered", "answered"]); let items = v["items"].as_array().unwrap(); assert_eq!(items[2]["to"], json!({"id": "1", "name": "Alice"})); assert_eq!(items[1]["who"]["name"], "Alice"); assert_eq!(items[1]["steps"][1]["text"], "날씨 도구를 쓰자"); assert_eq!(items[1]["ms"], 900); // Jarvis's reminder counts as its own words because it answered in chat before. assert_eq!(k[6], ("answered".into(), "약속 알림".into())); assert_eq!(v["people"], json!([{"id": "1", "name": "Alice"}, {"id": "2", "name": "Bob"}])); assert_eq!(v["channels"], json!([{"id": "ch", "via": "chat"}, {"id": "vc", "via": "voice"}])); assert_eq!(v["more"], false); } #[test] fn the_filters_pick_kinds_people_places_text_and_time() { let path = sample("filters"); let only = |q: Query| kinds(&query(&path, Some("900"), &q).unwrap()); assert_eq!(only(Query { answered: false, thought: false, ..Query::default() }), [("said".into(), "서울 날씨 어때".into()), ("said".into(), "Hello THERE".into())]); assert_eq!(only(Query { said: false, answered: false, ..Query::default() }).len(), 2); assert_eq!(only(Query { via: Some("voice".into()), ..Query::default() }).len(), 3); assert_eq!(only(Query { via: Some("task".into()), ..Query::default() }), Vec::<(String, String)>::new()); assert_eq!(only(Query { person: Some("2".into()), ..Query::default() }).len(), 3); assert_eq!(only(Query { channel: Some("vc".into()), ..Query::default() }).len(), 3); // Text search ignores case, and finds a trace by what it thought. assert_eq!(only(Query { find: Some("hello there".into()), thought: false, ..Query::default() }), [("said".into(), "Hello THERE".into())]); assert_eq!(only(Query { find: Some("도구를".into()), ..Query::default() }), [("thought".into(), "서울 날씨 어때".into())]); assert_eq!(only(Query { find: Some("100%".into()), ..Query::default() }).len(), 0); assert_eq!(only(Query { since: Some(20.0), until: Some(30.0), ..Query::default() }).len(), 3); } #[test] fn the_newest_come_first_when_there_are_more_than_asked() { let path = sample("limit"); let v = query(&path, None, &Query { limit: 2, ..Query::default() }).unwrap(); assert_eq!(kinds(&v), [("answered".into(), "안녕하세요".into()), ("answered".into(), "약속 알림".into())]); assert_eq!(v["more"], true); } /// Every item, walking back page by page with the cursor of the oldest one shown. #[test] fn pages_walk_back_through_everything_past_any_limit_even_at_equal_times() { let (path, c) = db("pages"); for i in 0..7 { // Records and traces at the same moments, so a page edge falls inside equal times. rec(&c, (i / 2) as f64, "voice", "vc", "1", "Alice", None, &format!("말 {i}")); trace(&c, (i / 2) as f64, "voice", Some("vc"), "1", &format!("생각 {i}"), "", "[]"); } let all = query(&path, None, &Query { limit: MAX_LIMIT, ..Query::default() }).unwrap()["items"].clone(); let all: Vec = all.as_array().unwrap().clone(); assert_eq!(all.len(), 14); let cursor = |i: &Value| Cursor::of(&json!({"at": i["at"], "key": i["key"]})).unwrap(); let mut got: Vec = Vec::new(); let mut before = None; loop { let v = query(&path, None, &Query { limit: 3, before, ..Query::default() }).unwrap(); let page = v["items"].as_array().unwrap().clone(); before = page.first().map(cursor); got.splice(0..0, page); if v["more"] == false { break; } } assert_eq!(got, all); // From a cursor on: that item and everything newer, whatever the limit was before. let from = query(&path, None, &Query { limit: MAX_LIMIT, from: Some(cursor(&all[5])), ..Query::default() }).unwrap(); assert_eq!(from["items"].as_array().unwrap()[..], all[5..]); assert!(Cursor::of(&json!({"at": 1.0, "key": "x1"})).is_none()); } #[test] fn a_trace_still_being_made_reads_as_pending_with_its_steps_so_far() { let (path, c) = db("pending"); rec(&c, 10.0, "voice", "vc", "1", "Alice", None, "서울 날씨 어때"); c.execute("INSERT INTO traces(ts, via, channel_id, user_id, question, answer, ms, steps) VALUES (?,?,?,?,?,?,?,?)", rusqlite::params![10.5, "voice", "vc", "1", "서울 날씨 어때", "", -1, r#"[{"kind":"tools","names":["getWeather"]}]"#]) .unwrap(); let v = query(&path, None, &Query::default()).unwrap(); let t = &v["items"][1]; assert_eq!((t["type"].as_str(), t["pending"].as_bool()), (Some("thought"), Some(true))); assert_eq!(t["steps"][0]["names"], json!(["getWeather"])); let done = query(&sample("pending-done"), None, &Query::default()).unwrap(); assert_eq!(done["items"][1]["pending"], false); } #[test] fn the_stamp_changes_when_a_question_is_answered_step_by_step_and_only_then() { let (path, c) = db("stamp"); let now = || stamp(&path).unwrap(); let empty = now(); assert_eq!(now(), empty, "nothing changed"); rec(&c, 10.0, "voice", "vc", "1", "Alice", None, "서울 날씨 어때"); let said = now(); assert_ne!(said, empty); c.execute("INSERT INTO traces(ts, via, channel_id, user_id, question, answer, ms, steps) \ VALUES (10.5, 'voice', 'vc', '1', '서울 날씨 어때', '', -1, '[]')", []).unwrap(); let asked = now(); assert_ne!(asked, said, "a trace still being made"); c.execute("UPDATE traces SET steps = '[{\"kind\":\"tools\",\"names\":[\"getWeather\"]}]'", []).unwrap(); let step = now(); assert_ne!(step, asked, "a step added"); c.execute("UPDATE traces SET answer = '맑습니다', ms = 900", []).unwrap(); assert_ne!(now(), step, "the answer"); let dir = std::env::temp_dir().join(format!("jarvis-history-view-nostamp-{}", std::process::id())); assert!(stamp(&dir.join("history.sqlite")).is_ok()); } #[test] fn the_export_holds_every_item_of_the_days_in_order_with_each_trace_in_full() { let path = sample("export"); let c = Connection::open(&path).unwrap(); trace(&c, 25.0, "voice", Some("vc"), "1", "아이유 신곡 틀어 줘", "", r#"[{"kind":"records","recent":["[14:44] Alice: 안녕"],"matches":[],"notes":2}, {"kind":"plan","steps":["botBrowser open"]}, {"kind":"tool","name":"botBrowser","args":{"action":"open","url":"https://youtube.com"},"ok":true,"result":"Title: YouTube\nMedia: paused"}, {"kind":"tool","name":"webSearch","args":{"q":"x"},"ok":false,"skipped":"duplicate"}]"#); drop(c); let names = HashMap::from([("ch".to_string(), "잡담".to_string())]); let (text, n) = export_text(&path, Some("900"), 0.0, 100.0, &names).unwrap(); assert_eq!(n, 8); let order: Vec = ["서울 날씨 어때", " 답: 맑습니다", "자비스 → Alice(1) · 음성", "Bob(2) · 채팅 · 잡담", "아이유 신곡 틀어 줘", "약속 알림"].iter().map(|x| text.find(x).unwrap_or_else(|| panic!("{x} in\n{text}"))).collect(); assert!(order.windows(2).all(|w| w[0] < w[1]), "time order:\n{text}"); for want in ["쓸 수 있게 고른 도구: getWeather", "모델 생각:\n 날씨 도구를 쓰자", " [14:44] Alice: 안녕", "사람별 지침 2개", " 1. botBrowser open", "도구 호출: botBrowser (성공)", "\"url\": \"https://youtube.com\"", " 결과:\n Title: YouTube\n Media: paused", "도구 호출: webSearch (건너뜀: 같은 호출을 되풀이해 부르지 않음)", "도구 1번", " 답: (답하지 못함)"] { assert!(text.contains(want), "{want:?} in\n{text}"); } // Only the days asked for. let (text, n) = export_text(&path, Some("900"), 20.0, 23.0, &names).unwrap(); assert_eq!(n, 3); assert!(!text.contains("서울 날씨")); } #[test] fn the_bot_id_comes_from_its_token() { assert_eq!(bot_id_of_token("MTIzNDU2Nzg5MDEyMzQ1Njc4.GxYzAb.abcdef").as_deref(), Some("123456789012345678")); assert_eq!(bot_id_of_token("bm90IGFuIGlk.x.y"), None); assert_eq!(bot_id_of_token(""), None); } #[test] fn a_missing_store_or_one_without_traces_reads_as_empty() { let dir = std::env::temp_dir().join(format!("jarvis-history-view-none-{}", std::process::id())); let v = query(&dir.join("history.sqlite"), None, &Query::default()).unwrap(); assert_eq!((v["items"].clone(), v["missing"].clone()), (json!([]), json!(true))); let (path, c) = db("old"); c.execute_batch("DROP TABLE traces").unwrap(); rec(&c, 1.0, "voice", "vc", "1", "Alice", None, "안녕"); assert_eq!(kinds(&query(&path, None, &Query::default()).unwrap()), [("said".into(), "안녕".into())]); } }