feat(app): 대화 screen to read what people said, Jarvis's answers and how each answer was made
The management app reads the worker's history store (read only) and shows people's words, Jarvis's answers and the answer traces in time order, with filters for kind, place, person, channel, day and text, live follow, older items on demand and expandable traces (records given, tools offered, plan, model thinking, tool calls and results). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -221,6 +221,26 @@ editable on the 사람별 지침 screen.
|
||||
- `notes_list` (everyone's, by person, IDs as strings), `note_update` `{id, text}` and `note_delete`
|
||||
`{id}` serve the screen. Logs carry note ids only, never their text.
|
||||
|
||||
## Conversations (`app/src/history_view.rs`)
|
||||
|
||||
What people said, what Jarvis answered and how it made each answer, for the 대화 screen. Read
|
||||
only, from the worker's history store `memory/history.sqlite` (`src/jarvis/memory/history.spec.md`,
|
||||
records and "Traces"), so it works while the services are stopped. Nothing it reads goes to a log.
|
||||
|
||||
- Each item is `said` (a voice transcript, or a chat message by someone other than Jarvis),
|
||||
`answered` (a spoken answer, or Jarvis's own chat message; to whom, when it answers someone) or
|
||||
`thought` (a trace: the question, the answer or none, how long it took and its steps). Jarvis's
|
||||
chat messages are known by the bot's user id (the first part of the stored token is that id in
|
||||
base64) and by the author of any chat answer to someone.
|
||||
- `history_query` `{said, answered, thought, via, person, channel, find, since, until, limit}`: the
|
||||
three kinds (each on unless false), where (`voice`, `chat`, `task`; a task has traces only), a
|
||||
person (their records, answers to them and traces of their questions), a channel, text the record
|
||||
or the trace's question, answer or steps contains (records folded like the store: NFKC, lower
|
||||
case), Unix seconds from (inclusive) and to (exclusive), and `limit` (1-2000, default 200). Answers
|
||||
`{items, more, people, channels}`: the newest `limit` items in time order, whether older ones
|
||||
were left out, the people who spoke (their latest name) and the channels with records (with the
|
||||
name given a chat channel in the settings). Without the file: no items and `missing: true`.
|
||||
|
||||
## Activity (`app/src/activity.rs`)
|
||||
|
||||
`docs/v2/proactive.md` (제안 5). What Jarvis did outside its answers, for the 한 일 screen: each chat
|
||||
@@ -664,6 +684,7 @@ back as Korean messages for the screen. The Tauri shell passes the screens' `inv
|
||||
| `service_start` / `service_stop` / `service_restart` / `dashboard` | the controller and its snapshot; start and restart run in the background, stop also cancels a start |
|
||||
| `discord_channel_info` `{id}` / `channel_sync_status` | a channel's Discord name and topic / each synced chat channel's last result (above) |
|
||||
| `notes_list` / `note_update` `{id, text}` / `note_delete` `{id}` | everyone's personal notes (above) / change one's text / delete one |
|
||||
| `history_query` `{said, answered, thought, via, person, channel, find, since, until, limit}` | the 대화 screen's records and answer traces (above, "Conversations") |
|
||||
| `activity_list` `{limit}` | what Jarvis did (above, "Activity"), newest first |
|
||||
| `schedules_list` / `schedule_delete` `{id}` | every person's schedules (above), soonest first, with IDs as strings / delete one |
|
||||
| `collect_results` `{target, limit}` | `{targets, items}`: every target folder with results, and the collected items newest first (`target` null: every target; `limit` 1-500, default 100) |
|
||||
@@ -708,6 +729,16 @@ Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. A
|
||||
or "다시 울리지 않음", repeat, who and how they asked, kind and text as plain text, the last
|
||||
outcome, delete).
|
||||
- **사람별 지침**: every person's notes (name and ID, the text in a box, save and delete).
|
||||
- **대화**: what people said, Jarvis's answers and how each answer was made, in time order with a
|
||||
date line between days; people's words on the left, Jarvis's on the right with whom it answered,
|
||||
each with its time, voice or chat and channel, and a copy button. A trace is a closed card (whose
|
||||
question, how many tool calls, seconds, no answer) that opens to the question, the records and
|
||||
notes it was given, the tools offered, the plan, the model's thinking, each tool call (name,
|
||||
arguments, success, failure or skipped and why, its result) and the answer. Filters: the three
|
||||
kinds as chips, where (음성, 채팅, 정기 작업), person, channel, one day and text; "실시간" (on by
|
||||
default) refreshes every 3 seconds and redraws only when something changed, keeping the cards the
|
||||
user opened open and the scroll where it was unless it was at the end; "이전 기록 더 보기" adds 200
|
||||
older items; "생각 모두 펼치기/접기"; a count of each kind shown.
|
||||
- **한 일**: the activity (time, kind, target, who asked, outcome and why it failed), newest 200,
|
||||
with a refresh button.
|
||||
- **업데이트**: the version here, the state, "다시 확인", "받기" (with its percentage) and "설치하고
|
||||
|
||||
@@ -396,6 +396,29 @@ impl AdminApi {
|
||||
crate::info_log!("admin", "note {id} deleted");
|
||||
Ok(json!({"deleted": id.to_string()}))
|
||||
}
|
||||
// The 대화 screen (admin.spec.md, "Conversations"): records and answer traces.
|
||||
"history_query" => {
|
||||
let dir = self.dir()?;
|
||||
let text = |k: &str| args.get(k).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(String::from);
|
||||
let flag = |k: &str| args.get(k).and_then(Value::as_bool).unwrap_or(true);
|
||||
let q = crate::history_view::Query {
|
||||
said: flag("said"), answered: flag("answered"), thought: flag("thought"),
|
||||
via: text("via"), person: text("person"), channel: text("channel"), find: text("find"),
|
||||
since: args.get("since").and_then(Value::as_f64), until: args.get("until").and_then(Value::as_f64),
|
||||
limit: args.get("limit").and_then(Value::as_u64).map_or(crate::history_view::DEFAULT_LIMIT, |n| n as usize),
|
||||
};
|
||||
let bot = self.secrets()?.get(DISCORD_TOKEN).ok().flatten().and_then(|t| crate::history_view::bot_id_of_token(&t));
|
||||
let path = dir.path().join("memory").join("history.sqlite");
|
||||
let mut v = tokio::task::spawn_blocking(move || crate::history_view::query(&path, bot.as_deref(), &q))
|
||||
.await.map_err(|e| e.to_string())??;
|
||||
// Chat channels by the names given them in the settings.
|
||||
let named = crate::settings::load_settings(&dir.settings_file()).map(|s| s.chat_channels).unwrap_or_default();
|
||||
for ch in v["channels"].as_array_mut().into_iter().flatten() {
|
||||
let name = named.iter().find(|c| Some(c.id.to_string().as_str()) == ch["id"].as_str()).map(|c| c.name.clone());
|
||||
ch["name"] = json!(name.unwrap_or_default());
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
"activity_list" => {
|
||||
let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(200).clamp(1, 1000) as usize;
|
||||
Ok(json!({"items": crate::activity::Activity::new(self.dir()?.path()).recent(limit)}))
|
||||
@@ -541,6 +564,28 @@ mod tests {
|
||||
assert!(store.all().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_conversation_screen_reads_records_and_traces_with_channel_names() {
|
||||
let (a, base) = api("api-history");
|
||||
let data = base.join("d");
|
||||
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
|
||||
assert_eq!(a.call("history_query", json!({})).await.unwrap()["missing"], true);
|
||||
std::fs::create_dir_all(data.join("memory")).unwrap();
|
||||
let c = rusqlite::Connection::open(data.join("memory").join("history.sqlite")).unwrap();
|
||||
c.execute_batch(crate::history_view::TEST_SCHEMA).unwrap();
|
||||
c.execute_batch("INSERT INTO history(ts, kind, channel_id, author_id, author_name, text, norm)
|
||||
VALUES (1, 'chat', '123456789012345678', '1', 'Alice', '안녕', '안녕');
|
||||
INSERT INTO traces(ts, via, channel_id, user_id, question, answer, ms, steps)
|
||||
VALUES (2, 'chat', '123456789012345678', '1', '안녕', '반가워요', 5, '[]');").unwrap();
|
||||
a.call("settings_apply", json!({"changes": {"chatChannels": [{"id": "123456789012345678", "name": "잡담"}]}})).await.unwrap();
|
||||
let v = a.call("history_query", json!({"thought": false})).await.unwrap();
|
||||
assert_eq!(v["items"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(v["items"][0]["who"]["name"], "Alice");
|
||||
assert_eq!(v["channels"][0]["name"], "잡담");
|
||||
let v = a.call("history_query", json!({"said": false, "find": "반가"})).await.unwrap();
|
||||
assert_eq!(v["items"][0]["type"], "thought");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_activity_screen_reads_the_newest_entries() {
|
||||
let (a, base) = api("api-activity");
|
||||
|
||||
325
app/src/history_view.rs
Normal file
325
app/src/history_view.rs
Normal file
@@ -0,0 +1,325 @@
|
||||
//! 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<String>,
|
||||
/// A person's records: written by them or answers to them.
|
||||
pub person: Option<String>,
|
||||
pub channel: Option<String>,
|
||||
/// Text the record (or the trace's question, answer or steps) contains, case folded.
|
||||
pub find: Option<String>,
|
||||
/// Unix seconds, inclusive / exclusive.
|
||||
pub since: Option<f64>,
|
||||
pub until: Option<f64>,
|
||||
pub limit: usize,
|
||||
}
|
||||
|
||||
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, 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<String> {
|
||||
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::<String>().to_lowercase()
|
||||
}
|
||||
|
||||
fn like(text: &str) -> String {
|
||||
let escaped = text.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_");
|
||||
format!("%{escaped}%")
|
||||
}
|
||||
|
||||
fn open(path: &Path) -> Result<Connection, String> {
|
||||
// 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<Value, String> {
|
||||
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<String, String> = {
|
||||
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::<Result<_, _>>().map_err(err)?
|
||||
};
|
||||
let name_of = |id: &str| names.get(id).cloned().unwrap_or_default();
|
||||
|
||||
let mut items: Vec<(f64, 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<Sql> = 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)); }
|
||||
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<String>) = (r.get(4)?, r.get(5)?, r.get(6)?);
|
||||
let answer: bool = r.get(8)?;
|
||||
Ok((ts, 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::<Result<Vec<_>, _>>().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<Sql> = 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)); }
|
||||
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)?;
|
||||
Ok((ts, json!({
|
||||
"key": format!("t{id}"), "type": "thought", "at": ts, "via": r.get::<_, String>(2)?,
|
||||
"channel": r.get::<_, Option<String>>(3)?,
|
||||
"who": {"id": user.clone(), "name": name_of(&user)},
|
||||
"question": r.get::<_, String>(5)?, "answer": r.get::<_, String>(6)?, "ms": r.get::<_, i64>(7)?,
|
||||
"steps": serde_json::from_str::<Value>(&steps).unwrap_or(json!([])),
|
||||
})))
|
||||
}).map_err(err)?;
|
||||
let got = rows.collect::<Result<Vec<_>, _>>().map_err(err)?;
|
||||
more |= got.len() > limit;
|
||||
items.extend(got.into_iter().take(limit));
|
||||
}
|
||||
items.sort_by(|a, b| b.0.total_cmp(&a.0));
|
||||
more |= items.len() > limit;
|
||||
items.truncate(limit);
|
||||
items.reverse();
|
||||
|
||||
let mut people: Vec<Value> = {
|
||||
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::<Result<_, _>>().map_err(err)?
|
||||
};
|
||||
people.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str()));
|
||||
let channels: Vec<Value> = {
|
||||
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::<Result<_, _>>().map_err(err)?
|
||||
};
|
||||
Ok(json!({"items": items.into_iter().map(|(_, v)| v).collect::<Vec<_>>(), "more": more,
|
||||
"people": people, "channels": channels}))
|
||||
}
|
||||
|
||||
/// 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::<Vec<_>>(),
|
||||
["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);
|
||||
}
|
||||
|
||||
#[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())]);
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ pub mod discord_setup;
|
||||
pub mod download;
|
||||
pub mod earcon;
|
||||
pub mod features;
|
||||
pub mod history_view;
|
||||
pub mod game;
|
||||
pub mod frames;
|
||||
pub mod install;
|
||||
|
||||
Reference in New Issue
Block a user