From b2b6f9294317e2eee484d7cb7d0edb02932e56b9 Mon Sep 17 00:00:00 2001 From: javis-bot Date: Mon, 16 Nov 2026 12:33:38 +0900 Subject: [PATCH] =?UTF-8?q?fix(app):=20=EB=8C=80=ED=99=94=20shows=20a=20tr?= =?UTF-8?q?ace=20before=20a=20quick=20answer=20ends?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The screen re-read its window every 3 seconds unless a trace was already shown as being made, so an answer that ended between two reads came with its trace. It now asks twice a second for history_stamp (the newest record and trace ids and the steps of the traces being made, cheap and not logged) and reads the window again as soon as it changes. Co-Authored-By: Claude Opus 5.5 --- app/src/admin.spec.md | 8 +++++++- app/src/admin_api.rs | 17 ++++++++++++++++- app/src/history_view.rs | 42 +++++++++++++++++++++++++++++++++++++++++ app/ui/app.js | 20 ++++++++++++++------ 4 files changed, 79 insertions(+), 8 deletions(-) diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index 4627caf..63624c7 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -246,6 +246,9 @@ records and "Traces"), so it works while the services are stopped. Nothing it re 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), and `session`, when the latest start began (Unix seconds, null before the first). Without the file: no items and `missing: true`. +- `history_stamp`: `{stamp}`, a string that changes when a record or trace is added and as a trace + still being made gets a step or ends (the newest ids, and the number and length of the steps of + the traces being made), cheap enough to ask twice a second; not logged. ## Activity (`app/src/activity.rs`) @@ -691,6 +694,7 @@ back as Korean messages for the screen. The Tauri shell passes the screens' `inv | `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, session, before, from, limit}` | the 대화 screen's records and answer traces (above, "Conversations") | +| `history_stamp` | `{stamp}`: changes when what the 대화 screen shows may have changed (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) | @@ -752,7 +756,9 @@ are on the 앱 screen) and no separate 한 일 screen (it is a view of the 로 the count line starts with that start's date and time, and with no start yet in this app run the list says so; a new start while it is on starts the list over from that start), where (음성, 채팅, 정기 작업), person, channel, one day and text; "실시간" (on by - default) re-reads the live window every second while a trace in it is being made, else every 3 seconds: every item from its first one on (`from`, up to + default) asks for `history_stamp` twice a second and re-reads the live window at once when it + changed (so a trace shows from its question on, before a quick answer ends), and every 3 seconds + anyway: every item from its first one on (`from`, up to 2,000). Only items in that window change on screen, an edited message included; items paged back past it stay as they were loaded (edits and deletes there show after a reload of the screen). The screen redraws only when an item changed, keeping the cards the user opened open and the scroll diff --git a/app/src/admin_api.rs b/app/src/admin_api.rs index 0e7f790..68e2f9f 100644 --- a/app/src/admin_api.rs +++ b/app/src/admin_api.rs @@ -189,7 +189,10 @@ impl AdminApi { } pub async fn call(&self, command: &str, args: Value) -> Result { - crate::debug_log!("admin", "command {command}"); + // The 대화 screen asks for the stamp twice a second: a line each time would bury the log. + if command != "history_stamp" { + crate::debug_log!("admin", "command {command}"); + } match command { "app_status" => { let dir = self.dir.lock().unwrap().clone(); @@ -405,6 +408,13 @@ impl AdminApi { crate::info_log!("admin", "note {id} deleted"); Ok(json!({"deleted": id.to_string()})) } + // The 대화 screen (admin.spec.md, "Conversations"): whether what it shows changed. + "history_stamp" => { + let path = self.dir()?.path().join("memory").join("history.sqlite"); + let stamp = tokio::task::spawn_blocking(move || crate::history_view::stamp(&path)) + .await.map_err(|e| e.to_string())??; + Ok(json!({"stamp": stamp})) + } // The 대화 screen (admin.spec.md, "Conversations"): records and answer traces. "history_query" => { let dir = self.dir()?; @@ -603,6 +613,7 @@ mod tests { 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); + let before = a.call("history_stamp", json!({})).await.unwrap(); 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(); @@ -617,6 +628,10 @@ mod tests { 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"); + // The screen polls the stamp and reads again only when it changed. + let now = a.call("history_stamp", json!({})).await.unwrap(); + assert_ne!(now["stamp"], before["stamp"]); + assert_eq!(a.call("history_stamp", json!({})).await.unwrap(), now); } #[tokio::test] diff --git a/app/src/history_view.rs b/app/src/history_view.rs index 5256d4a..3e2f08b 100644 --- a/app/src/history_view.rs +++ b/app/src/history_view.rs @@ -254,6 +254,26 @@ pub fn query(path: &Path, bot: Option<&str>, q: &Query) -> Result "people": people, "channels": channels})) } +/// 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 = " @@ -401,6 +421,28 @@ mod tests { 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_bot_id_comes_from_its_token() { assert_eq!(bot_id_of_token("MTIzNDU2Nzg5MDEyMzQ1Njc4.GxYzAb.abcdef").as_deref(), Some("123456789012345678")); diff --git a/app/ui/app.js b/app/ui/app.js index f2d61ec..1e40a9f 100644 --- a/app/ui/app.js +++ b/app/ui/app.js @@ -589,11 +589,19 @@ function conversationScreen() { h("div", { class: "hint", style: "margin:8px 0" }, "사람이 한 말, 자비스의 답, 자비스가 답을 만든 과정(참고한 기록, 고른 도구, 계획, 도구 호출과 결과, 모델 생각)을 시간순으로 보여 줍니다. 자비스가 말을 알아들은 순간 생각이 나타나고, 답을 만드는 동안 단계가 하나씩 채워집니다. 모델 생각은 생각 모드가 켜진 답에만 있습니다. 생각 기록은 30일 동안 둡니다. 실시간으로 다시 읽는 것은 최근 2,000개까지이고, 그보다 앞서 불러온 기록의 수정과 삭제는 화면을 다시 열면 보입니다."), h("div", { class: "row", style: "justify-content:center" }, more), box); load(); - // Every second while an answer is being made, so its trace fills in as it goes; else every 3 seconds. - let ticks = 0; - const tick = () => { - const making = page.shown.some((i) => i.pending); - if (live.checked && (making || ++ticks % 3 === 0)) load(); + // Twice a second the store's stamp (cheap): when something was said, a question arrived or an + // answer moved on, the window is read again at once, so a trace shows from its question on and + // fills in as it goes. Every 3 seconds it is read anyway (an edited message changes no stamp). + let ticks = 0, stamp = null, asking = false; + const tick = async () => { + if (!live.checked) return; + if (++ticks % 6 === 0) return load(); + if (asking) return; + asking = true; + try { + const s = (await api("history_stamp")).stamp; + if (s !== stamp) { stamp = s; load(); } + } catch (e) { /* the next tick tries again */ } finally { asking = false; } }; return { view, tick }; } @@ -925,7 +933,7 @@ async function show(name) { try { 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 === "conversations") { const c = conversationScreen(); screen.replaceChildren(c.view); ticker = setInterval(c.tick, 1000); return; } + if (name === "conversations") { const c = conversationScreen(); screen.replaceChildren(c.view); ticker = setInterval(c.tick, 500); return; } if (name === "notes") { screen.replaceChildren(notesScreen()); return; } const titles = { bot: "봇", channels: "채널·호출", chat: "채팅 채널", memory: "대화 기억", model: "모델", features: "기능", collect: "백그라운드 수집", game: "게임 모드", schedule: "예약", pcControl: "PC 제어", app: "앱" };