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:
68
app/Cargo.lock
generated
68
app/Cargo.lock
generated
@@ -744,6 +744,18 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365"
|
||||
|
||||
[[package]]
|
||||
name = "fallible-iterator"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
|
||||
|
||||
[[package]]
|
||||
name = "fallible-streaming-iterator"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
@@ -816,6 +828,12 @@ version = "1.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.2"
|
||||
@@ -1024,12 +1042,30 @@ version = "0.14.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.15.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
|
||||
dependencies = [
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
|
||||
[[package]]
|
||||
name = "hashlink"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1"
|
||||
dependencies = [
|
||||
"hashbrown 0.15.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashmap_derive"
|
||||
version = "0.1.0"
|
||||
@@ -1497,6 +1533,7 @@ dependencies = [
|
||||
"opus2",
|
||||
"rand 0.9.5",
|
||||
"reqwest",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serenity",
|
||||
@@ -1786,6 +1823,17 @@ dependencies = [
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libsqlite3-sys"
|
||||
version = "0.35.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.12.1"
|
||||
@@ -2756,6 +2804,20 @@ dependencies = [
|
||||
"realfft",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rusqlite"
|
||||
version = "0.37.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"fallible-iterator",
|
||||
"fallible-streaming-iterator",
|
||||
"hashlink",
|
||||
"libsqlite3-sys",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "2.1.3"
|
||||
@@ -4108,6 +4170,12 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
|
||||
|
||||
[[package]]
|
||||
name = "vcpkg"
|
||||
version = "0.2.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
|
||||
@@ -35,6 +35,7 @@ chrono = { version = "0.4", default-features = false, features = ["clock", "std"
|
||||
zip = { version = "9", default-features = false, features = ["deflate"] }
|
||||
unicode-normalization = "0.1"
|
||||
jpeg-encoder = "0.6"
|
||||
rusqlite = { version = "0.37", features = ["bundled"] }
|
||||
|
||||
[dev-dependencies]
|
||||
jpeg-decoder = "0.3"
|
||||
|
||||
72
app/shell/Cargo.lock
generated
72
app/shell/Cargo.lock
generated
@@ -1059,7 +1059,7 @@ checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc"
|
||||
dependencies = [
|
||||
"bit-set 0.8.0",
|
||||
"cssparser 0.37.0",
|
||||
"foldhash",
|
||||
"foldhash 0.2.0",
|
||||
"html5ever 0.39.0",
|
||||
"precomputed-hash",
|
||||
"selectors 0.38.0",
|
||||
@@ -1074,7 +1074,7 @@ checksum = "498c698ac51127148a3984450e51fca7f01805a91d7a1f7a24af0a5f761e3385"
|
||||
dependencies = [
|
||||
"bit-set 0.11.1",
|
||||
"cssparser 0.38.0",
|
||||
"foldhash",
|
||||
"foldhash 0.2.0",
|
||||
"html5ever 0.40.1",
|
||||
"precomputed-hash",
|
||||
"selectors 0.41.0",
|
||||
@@ -1270,6 +1270,18 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365"
|
||||
|
||||
[[package]]
|
||||
name = "fallible-iterator"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
|
||||
|
||||
[[package]]
|
||||
name = "fallible-streaming-iterator"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
@@ -1361,6 +1373,12 @@ version = "1.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.2.0"
|
||||
@@ -1855,12 +1873,30 @@ version = "0.14.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.15.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
|
||||
dependencies = [
|
||||
"foldhash 0.1.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
|
||||
[[package]]
|
||||
name = "hashlink"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1"
|
||||
dependencies = [
|
||||
"hashbrown 0.15.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashmap_derive"
|
||||
version = "0.1.0"
|
||||
@@ -2392,6 +2428,7 @@ dependencies = [
|
||||
"opus2",
|
||||
"rand 0.9.5",
|
||||
"reqwest 0.12.28",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serenity",
|
||||
@@ -2886,6 +2923,17 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libsqlite3-sys"
|
||||
version = "0.35.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.12.1"
|
||||
@@ -4464,6 +4512,20 @@ dependencies = [
|
||||
"realfft",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rusqlite"
|
||||
version = "0.37.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"fallible-iterator",
|
||||
"fallible-streaming-iterator",
|
||||
"hashlink",
|
||||
"libsqlite3-sys",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "2.1.3"
|
||||
@@ -6573,6 +6635,12 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
|
||||
|
||||
[[package]]
|
||||
name = "vcpkg"
|
||||
version = "0.2.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||
|
||||
[[package]]
|
||||
name = "version-compare"
|
||||
version = "0.2.1"
|
||||
|
||||
@@ -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;
|
||||
|
||||
131
app/ui/app.js
131
app/ui/app.js
@@ -402,6 +402,136 @@ function activityScreen() {
|
||||
h("div", { class: "field" }, h("button", { class: "btn", onclick: load }, "새로 고침")), list));
|
||||
}
|
||||
|
||||
// ---- conversations ------------------------------------------------------------------------------
|
||||
|
||||
const VIA = { voice: "음성", chat: "채팅", task: "정기 작업" };
|
||||
const SKIPPED = { not_allowed: "허용되지 않은 도구라 부르지 않음", duplicate: "같은 호출을 되풀이해 부르지 않음" };
|
||||
const p2 = (n) => String(n).padStart(2, "0");
|
||||
const dayOf = (ts) => { const d = new Date(ts * 1000); return `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())}`; };
|
||||
const timeOf = (ts) => { const d = new Date(ts * 1000); return `${p2(d.getHours())}:${p2(d.getMinutes())}:${p2(d.getSeconds())}`; };
|
||||
const pre = (text) => h("pre", { class: "pre" }, text);
|
||||
|
||||
/** One step of how an answer was made (history.spec.md, "Traces"). */
|
||||
function traceStep(s) {
|
||||
if (s.kind === "records") {
|
||||
const lines = (title, xs) => xs.length ? h("details", {}, h("summary", { class: "small" }, `${title} ${xs.length}줄`), pre(xs.join("\n"))) : null;
|
||||
return h("div", { class: "step-row" }, h("div", { class: "k" }, "참고한 기록"),
|
||||
h("div", {}, (s.recent || []).length + (s.matches || []).length ? null : h("span", { class: "muted" }, "없음"),
|
||||
lines("최근 대화", s.recent || []), lines("관련 기록", s.matches || []),
|
||||
s.notes ? h("div", { class: "small muted" }, `사람별 지침 ${s.notes}개`) : null));
|
||||
}
|
||||
if (s.kind === "tools") return h("div", { class: "step-row" }, h("div", { class: "k" }, "쓸 수 있게 고른 도구"),
|
||||
h("div", { class: "row" }, (s.names || []).length ? s.names.map((n) => h("span", { class: "badge" }, n)) : h("span", { class: "muted" }, "없음")));
|
||||
if (s.kind === "plan") return h("div", { class: "step-row" }, h("div", { class: "k" }, "계획"), h("ol", { class: "plan" }, (s.steps || []).map((x) => h("li", {}, x))));
|
||||
if (s.kind === "think") return h("div", { class: "step-row" }, h("div", { class: "k" }, "모델 생각"), pre(s.text || ""));
|
||||
if (s.kind === "tool") {
|
||||
const state = s.skipped ? ["건너뜀", "warn"] : s.ok ? ["성공", "ok"] : ["실패", "bad"];
|
||||
return h("div", { class: "step-row" }, h("div", { class: "k" }, "도구 호출"),
|
||||
h("div", {}, h("div", { class: "row" }, h("b", {}, s.name), h("span", { class: "badge " + state[1] }, state[0])),
|
||||
Object.keys(s.args || {}).length ? pre(JSON.stringify(s.args, null, 2)) : null,
|
||||
s.skipped ? h("div", { class: "small muted" }, SKIPPED[s.skipped] || s.skipped) : null,
|
||||
s.result ? h("details", {}, h("summary", { class: "small" }, "결과"), pre(s.result)) : null));
|
||||
}
|
||||
return h("div", { class: "step-row" }, h("div", { class: "k" }, s.kind), pre(JSON.stringify(s, null, 2)));
|
||||
}
|
||||
|
||||
/** The 대화 screen (admin.spec.md, "Conversations"): what people said, what Jarvis answered, how. */
|
||||
function conversationScreen() {
|
||||
const chip = (label, on = true) => { const c = h("input", { type: "checkbox", checked: on }); return [c, h("label", { class: "chip" }, c, label)]; };
|
||||
const [said, saidChip] = chip("사람 말"), [answered, answeredChip] = chip("자비스 말"), [thought, thoughtChip] = chip("자비스 생각");
|
||||
const via = h("select", {}, h("option", { value: "" }, "모든 곳"), Object.entries(VIA).map(([v, t]) => h("option", { value: v }, t)));
|
||||
const person = h("select", {}, h("option", { value: "" }, "모든 사람"));
|
||||
const channel = h("select", {}, h("option", { value: "" }, "모든 채널"));
|
||||
const day = h("input", { type: "date" });
|
||||
const find = h("input", { type: "text", placeholder: "찾기 (말, 답, 생각)", style: "max-width:220px" });
|
||||
const live = h("input", { type: "checkbox", class: "switch", checked: true });
|
||||
const open = new Set(); // traces the user opened stay open across refreshes
|
||||
let expandAll = false, limit = 200, sig = null;
|
||||
const box = h("div", { class: "talk" });
|
||||
const summary = h("div", { class: "small muted" });
|
||||
const more = h("button", { class: "btn", hidden: true, onclick: () => { limit += 200; load(true); } }, "이전 기록 더 보기");
|
||||
|
||||
const fill = (sel, list, label) => {
|
||||
const key = JSON.stringify(list);
|
||||
if (sel.dataset.list === key) return; // an open picker is not rebuilt under the user
|
||||
sel.dataset.list = key;
|
||||
const keep = sel.value;
|
||||
sel.replaceChildren(sel.firstChild, ...list.map((x) => h("option", { value: x.id }, label(x))));
|
||||
sel.value = list.some((x) => x.id === keep) ? keep : "";
|
||||
};
|
||||
const channelLabel = (c) => c.name ? `${c.name} (${VIA[c.via]})` : `${VIA[c.via]} 채널 ${c.id}`;
|
||||
const channelName = (id) => { const c = (load.channels || []).find((x) => x.id === id); return c ? channelLabel(c) : id || ""; };
|
||||
const copy = (text) => async () => { try { await navigator.clipboard.writeText(text); toast("복사했습니다"); } catch (e) { fail(e); } };
|
||||
|
||||
function item(i) {
|
||||
const where = h("span", { class: "small muted" }, timeOf(i.at), " · ", VIA[i.via] || i.via, i.channel ? " · " + channelName(i.channel) : "");
|
||||
if (i.type === "thought") {
|
||||
const tools = (i.steps || []).filter((s) => s.kind === "tool" && !s.skipped).length;
|
||||
const d = h("details", { class: "msg thought", open: expandAll || open.has(i.key) },
|
||||
h("summary", {}, h("span", { class: "who" }, "자비스 생각"), " ",
|
||||
h("span", { class: "small muted" }, `${i.who.name || i.who.id}의 말에 답하며`, tools ? ` · 도구 ${tools}번` : "",
|
||||
` · ${(i.ms / 1000).toFixed(1)}초`, i.answer ? "" : " · 답 없음"), " ", where),
|
||||
h("div", { class: "steps" },
|
||||
h("div", { class: "step-row" }, h("div", { class: "k" }, "받은 말"), h("div", {}, i.question)),
|
||||
(i.steps || []).map(traceStep),
|
||||
h("div", { class: "step-row" }, h("div", { class: "k" }, "답"), i.answer ? h("div", {}, i.answer) : h("span", { class: "badge bad" }, "답하지 못함"))));
|
||||
d.addEventListener("toggle", () => (d.open ? open.add(i.key) : open.delete(i.key)));
|
||||
return d;
|
||||
}
|
||||
const mine = i.type === "answered";
|
||||
const who = mine ? (i.to ? `자비스 → ${i.to.name || i.to.id}` : "자비스") : (i.who.name || i.who.id);
|
||||
return h("div", { class: "msg " + (mine ? "answered" : "said") },
|
||||
h("div", { class: "row" }, h("span", { class: "who" }, who), where,
|
||||
h("button", { class: "linkbtn small", title: "글 복사", onclick: copy(i.text) }, "복사")),
|
||||
h("div", { class: "text" }, i.text));
|
||||
}
|
||||
|
||||
async function load(keepTop = false) {
|
||||
try {
|
||||
const since = day.value ? new Date(day.value + "T00:00:00").getTime() / 1000 : null;
|
||||
const r = await api("history_query", { said: said.checked, answered: answered.checked, thought: thought.checked,
|
||||
via: via.value || null, person: person.value || null, channel: channel.value || null, find: find.value || null,
|
||||
since, until: since == null ? null : since + 86400, limit });
|
||||
load.channels = r.channels;
|
||||
fill(person, r.people, (p) => `${p.name || p.id}`);
|
||||
fill(channel, r.channels, channelLabel);
|
||||
const s = JSON.stringify([r.items.map((i) => i.key + ":" + (i.text || i.answer || "").length), expandAll, r.more]);
|
||||
if (s === sig) return;
|
||||
sig = s;
|
||||
const stick = box.scrollTop + box.clientHeight >= box.scrollHeight - 30, fromBottom = box.scrollHeight - box.scrollTop;
|
||||
const kids = [];
|
||||
let lastDay = null;
|
||||
for (const i of r.items) {
|
||||
const d = dayOf(i.at);
|
||||
if (d !== lastDay) { kids.push(h("div", { class: "day" }, d)); lastDay = d; }
|
||||
kids.push(item(i));
|
||||
}
|
||||
box.replaceChildren(...(kids.length ? kids : [h("div", { class: "muted" },
|
||||
r.missing ? "아직 대화 기록이 없습니다. 서비스를 켜고 자비스와 이야기하면 여기에 나옵니다." : "조건에 맞는 기록이 없습니다.")]));
|
||||
more.hidden = !r.more;
|
||||
const n = (t) => r.items.filter((i) => i.type === t).length;
|
||||
summary.textContent = `사람 말 ${n("said")} · 자비스 말 ${n("answered")} · 생각 ${n("thought")}` + (r.more ? ` (최근 ${limit}개까지)` : "");
|
||||
if (keepTop) box.scrollTop = box.scrollHeight - fromBottom;
|
||||
else if (stick || !load.done) box.scrollTop = box.scrollHeight;
|
||||
load.done = true;
|
||||
} catch (e) { fail(e); }
|
||||
}
|
||||
const reload = () => { limit = 200; sig = null; load.done = false; load(); };
|
||||
for (const el of [said, answered, thought, via, person, channel, day]) el.addEventListener("change", reload);
|
||||
find.addEventListener("input", () => { clearTimeout(find.t); find.t = setTimeout(reload, 300); });
|
||||
const view = h("div", {}, h("h1", {}, "대화"),
|
||||
h("div", { class: "card filters" },
|
||||
h("div", { class: "row" }, saidChip, answeredChip, thoughtChip),
|
||||
h("div", { class: "row" }, via, person, channel, day, find),
|
||||
h("div", { class: "row" }, h("label", { class: "row small muted" }, live, "실시간"),
|
||||
h("button", { class: "btn", onclick: () => { expandAll = !expandAll; if (!expandAll) open.clear(); sig = null; load(); } }, "생각 모두 펼치기/접기"),
|
||||
h("button", { class: "btn", onclick: () => { sig = null; load(); } }, "새로 고침"), summary)),
|
||||
h("div", { class: "hint", style: "margin:8px 0" }, "사람이 한 말, 자비스의 답, 자비스가 답을 만든 과정(참고한 기록, 고른 도구, 계획, 도구 호출과 결과, 모델 생각)을 시간순으로 보여 줍니다. 모델 생각은 생각 모드가 켜진 답에만 있습니다. 생각 기록은 30일 동안 둡니다."),
|
||||
h("div", { class: "row", style: "justify-content:center" }, more), box);
|
||||
load();
|
||||
return { view, tick: () => live.checked && load() };
|
||||
}
|
||||
|
||||
async function settingsScreen(screen, title, extra) {
|
||||
const [all, view] = await Promise.all([fields(), api("settings_view")]);
|
||||
const list = all.filter((f) => f.screen === screen);
|
||||
@@ -719,6 +849,7 @@ async function show(name) {
|
||||
if (name === "dashboard") { screen.replaceChildren(); await refresh(); ticker = setInterval(refresh, 1000); return; }
|
||||
if (name === "logs") { const l = logsScreen(); screen.replaceChildren(l.view); ticker = setInterval(l.tick, 1000); return; }
|
||||
if (name === "activity") { screen.replaceChildren(activityScreen()); return; }
|
||||
if (name === "conversations") { const c = conversationScreen(); screen.replaceChildren(c.view); ticker = setInterval(c.tick, 3000); return; }
|
||||
if (name === "notes") { screen.replaceChildren(notesScreen()); return; }
|
||||
if (name === "update") { const u = updateScreen(); screen.replaceChildren(u.view); ticker = setInterval(u.tick, 1000); return; }
|
||||
const titles = { bot: "봇", channels: "채널·호출", chat: "채팅 채널", memory: "대화 기억", model: "모델", features: "기능",
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
<button data-screen="schedule" class="nav">예약</button>
|
||||
<button data-screen="pcControl" class="nav">PC 제어</button>
|
||||
<button data-screen="notes" class="nav">사람별 지침</button>
|
||||
<button data-screen="conversations" class="nav">대화</button>
|
||||
<button data-screen="activity" class="nav">한 일</button>
|
||||
<button data-screen="game" class="nav">게임 모드</button>
|
||||
<button data-screen="logs" class="nav">로그</button>
|
||||
|
||||
@@ -73,3 +73,23 @@ a { color: var(--accent2); }
|
||||
.row > select, .row > input[type=date] { width: auto; }
|
||||
input[type=date] { color-scheme: dark; }
|
||||
th, .btn { white-space: nowrap; }
|
||||
.filters { display: flex; flex-direction: column; gap: 10px; }
|
||||
.filters select, .filters input[type=date] { width: auto; }
|
||||
.chip { display: inline-flex; align-items: center; gap: 6px; border: 1px solid var(--line2); border-radius: 999px; padding: 4px 12px; cursor: pointer; color: var(--ink2); }
|
||||
.chip:has(input:checked) { border-color: var(--accent); color: var(--ink); background: var(--s3); }
|
||||
.talk { background: var(--s1); border: 1px solid var(--line); border-radius: 10px; height: 62vh; overflow: auto; padding: 10px 14px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.day { align-self: center; color: var(--ink4); font-size: 12px; border: 1px solid var(--line); border-radius: 999px; padding: 2px 12px; margin: 6px 0; }
|
||||
.msg { border: 1px solid var(--line); border-radius: 10px; padding: 8px 12px; max-width: 85%; background: var(--s2); }
|
||||
.msg.said { align-self: flex-start; }
|
||||
.msg.answered { align-self: flex-end; border-color: #2f3570; background: #12142a; }
|
||||
.msg.thought { align-self: stretch; max-width: none; border-style: dashed; background: var(--canvas); }
|
||||
.msg.thought > summary { cursor: pointer; }
|
||||
.msg .who { font-weight: 600; }
|
||||
.msg .text { white-space: pre-wrap; word-break: break-word; margin-top: 4px; line-height: 1.5; }
|
||||
.steps { display: flex; flex-direction: column; gap: 8px; margin-top: 10px; }
|
||||
.step-row { display: grid; grid-template-columns: 150px 1fr; gap: 12px; border-top: 1px solid var(--line); padding-top: 8px; }
|
||||
.step-row .k { color: var(--ink3); font-size: 12px; padding-top: 2px; }
|
||||
.pre { white-space: pre-wrap; word-break: break-word; font-family: ui-monospace, Consolas, monospace; font-size: 12px; background: var(--s1); border: 1px solid var(--line); border-radius: 6px; padding: 6px 8px; margin: 4px 0; max-height: 320px; overflow: auto; }
|
||||
.plan { margin: 0; padding-left: 18px; }
|
||||
.linkbtn { background: none; border: 0; color: var(--ink4); cursor: pointer; padding: 0 4px; margin-left: auto; }
|
||||
.linkbtn:hover { color: var(--ink2); }
|
||||
|
||||
Reference in New Issue
Block a user