Add a live statistics dashboard over persistent history

Replace the four-row stats modal with a real dashboard — our own angle on
the reference's ephemeral request monitor: because our context lives in
SQLite we can aggregate over ALL history, not just the last N requests.

Backend:
- Usage carries the engine's prompt_ms/decode_ms (from DONE); a token-
  weighted in-memory PerfMeter in ChatService records every served
  request (complete + stream) and exposes decode/prefill tok/s.
- store::Stats grows total_tokens, tool_calls (json_array_length over
  assistant tool_calls_json), a per-session breakdown (busiest first)
  and a per-UTC-day token series; all over existing columns, no schema
  change, still behind the Store trait.
- GET /api/stats returns the store aggregates flattened plus a live
  engine status (model, max_context, busy) and the perf gauge.

Frontend (mobile-first, vanilla, i18n catalog):
- Overview cards: engine state dot + model + context, decode speed
  (run average) + prefill, total/prompt/completion tokens, sessions +
  messages, tool calls, requests served.
- Daily stacked prompt/completion bar chart (continuous zero-filled
  UTC window, last 30 days) and per-session token-share bars.
- Polls every 2s while open, re-renders only on change; closes via
  button, backdrop or Escape.

Tests: new store breakdown test + extended stats integration assertions
(124 passed, 2 ignored). Verified live on the real engine: decode/prefill
gauge populated from DONE timings; dashboard renders on desktop.
This commit is contained in:
adm committed 2026-11-25 17:52:38 +01:00
1 parent e79ee0e20e
commit 765c197b95
11 files changed
+642 -42

No files matched your search

+141 -4
View File
@@ -111,13 +111,42 @@ pub struct NewMessage<'a> {
pub completion_tokens: u32,
}
/// Aggregate counters for the stats view.
/// Aggregate counters for the stats view, computed over the whole persistent
/// history (the advantage over an in-memory request monitor). The live engine
/// gauge is layered on top by the API handler, not stored here.
#[derive(Debug, Clone, Default, Serialize)]
pub struct Stats {
pub sessions: u64,
pub messages: u64,
pub prompt_tokens: u64,
pub completion_tokens: u64,
pub total_tokens: u64,
/// Tool calls requested across all assistant turns (agent activity).
pub tool_calls: u64,
/// Per-session breakdown, busiest (most tokens) first.
pub by_session: Vec<SessionStat>,
/// Token activity per UTC day, oldest first (bounded to recent days).
pub daily: Vec<DailyStat>,
}
/// One session's share of the persistent totals.
#[derive(Debug, Clone, Serialize)]
pub struct SessionStat {
pub id: String,
pub title: String,
pub messages: u64,
pub prompt_tokens: u64,
pub completion_tokens: u64,
pub updated_at: i64,
}
/// One UTC day's activity (`day` = unix seconds at midnight).
#[derive(Debug, Clone, Serialize)]
pub struct DailyStat {
pub day: i64,
pub messages: u64,
pub prompt_tokens: u64,
pub completion_tokens: u64,
}
/// Metadata for an uploaded file (bytes live on disk under the shared upload dir).
@@ -464,16 +493,69 @@ impl Store for SqliteStore {
fn stats(&self) -> Result<Stats> {
let conn = self.lock();
let sessions: i64 = conn.query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))?;
let (messages, prompt, completion): (i64, i64, i64) = conn.query_row(
"SELECT COUNT(*), COALESCE(SUM(prompt_tokens),0), COALESCE(SUM(completion_tokens),0) FROM messages",
// Totals + tool-call count in one pass. tool_calls_json is always a JSON
// array of calls (or NULL); json_array_length counts the calls themselves.
let (messages, prompt, completion, tool_calls): (i64, i64, i64, i64) = conn.query_row(
"SELECT COUNT(*),
COALESCE(SUM(prompt_tokens),0),
COALESCE(SUM(completion_tokens),0),
COALESCE(SUM(CASE WHEN tool_calls_json IS NOT NULL
THEN json_array_length(tool_calls_json) ELSE 0 END),0)
FROM messages",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
)?;
// Per-session breakdown (LEFT JOIN keeps empty sessions visible), busiest first.
let mut stmt = conn.prepare(
"SELECT s.id, s.title, COUNT(m.id),
COALESCE(SUM(m.prompt_tokens),0), COALESCE(SUM(m.completion_tokens),0),
s.updated_at
FROM sessions s LEFT JOIN messages m ON m.session_id = s.id
GROUP BY s.id
ORDER BY (COALESCE(SUM(m.prompt_tokens),0)+COALESCE(SUM(m.completion_tokens),0)) DESC,
s.updated_at DESC",
)?;
let by_session = stmt
.query_map([], |r| {
Ok(SessionStat {
id: r.get(0)?,
title: r.get(1)?,
messages: r.get::<_, i64>(2)? as u64,
prompt_tokens: r.get::<_, i64>(3)? as u64,
completion_tokens: r.get::<_, i64>(4)? as u64,
updated_at: r.get(5)?,
})
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
// Daily activity (UTC day buckets): the 30 most recent active days, oldest first.
let mut stmt = conn.prepare(
"SELECT (created_at/86400)*86400 AS day, COUNT(*),
COALESCE(SUM(prompt_tokens),0), COALESCE(SUM(completion_tokens),0)
FROM messages GROUP BY day ORDER BY day DESC LIMIT 30",
)?;
let mut daily = stmt
.query_map([], |r| {
Ok(DailyStat {
day: r.get(0)?,
messages: r.get::<_, i64>(1)? as u64,
prompt_tokens: r.get::<_, i64>(2)? as u64,
completion_tokens: r.get::<_, i64>(3)? as u64,
})
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
daily.reverse();
Ok(Stats {
sessions: sessions as u64,
messages: messages as u64,
prompt_tokens: prompt as u64,
completion_tokens: completion as u64,
total_tokens: (prompt + completion) as u64,
tool_calls: tool_calls as u64,
by_session,
daily,
})
}
@@ -607,6 +689,61 @@ mod tests {
assert_eq!(s.list_sessions().unwrap().len(), 0);
}
#[test]
fn stats_breakdown_counts_tools_and_orders_sessions() {
let s = store();
let a = s
.create_session("Alpha", "m", &SessionSettings::default())
.unwrap();
let b = s
.create_session("Beta", "m", &SessionSettings::default())
.unwrap();
let add = |sid: &str, role: &'static str, tc: Option<&'static str>, pt: u32, ct: u32| {
s.append_message(
sid,
NewMessage {
role,
content: "x",
reasoning_content: None,
tool_calls_json: tc,
tool_call_id: None,
prompt_tokens: pt,
completion_tokens: ct,
},
)
.unwrap();
};
// Alpha: a user turn + an assistant turn requesting TWO tool calls.
add(&a.id, "user", None, 10, 0);
add(
&a.id,
"assistant",
Some(r#"[{"id":"1"},{"id":"2"}]"#),
10,
4,
);
// Beta: a smaller plain exchange.
add(&b.id, "user", None, 2, 0);
add(&b.id, "assistant", None, 2, 1);
let st = s.stats().unwrap();
assert_eq!(st.sessions, 2);
assert_eq!(st.messages, 4);
assert_eq!(st.prompt_tokens, 24);
assert_eq!(st.completion_tokens, 5);
assert_eq!(st.total_tokens, 29);
assert_eq!(st.tool_calls, 2); // two calls inside Alpha's single turn
// Busiest first: Alpha (24 tokens) ahead of Beta (5).
assert_eq!(st.by_session.len(), 2);
assert_eq!(st.by_session[0].id, a.id);
assert_eq!(st.by_session[0].messages, 2);
assert_eq!(st.by_session[1].id, b.id);
// All four messages fall in today's UTC bucket.
assert_eq!(st.daily.len(), 1);
assert_eq!(st.daily[0].messages, 4);
assert_eq!(st.daily[0].completion_tokens, 5);
}
#[test]
fn settings_instance_and_name_lock() {
let s = store();