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

+92 -8
View File
@@ -8,6 +8,7 @@
//! while the HTTP handler just forwards what the task puts on the channel.
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use futures::Stream;
use tokio::sync::mpsc::UnboundedSender;
@@ -27,11 +28,58 @@ use super::types::{
pub struct ChatService {
engine: Arc<Engine>,
fmt: Arc<dyn Formatter>,
perf: Arc<StdMutex<PerfMeter>>,
}
/// A running, token-weighted performance gauge over the requests served since
/// startup (in-memory, like the reference monitor's retained requests). Powers
/// the "average decode speed" headline without per-message schema churn.
#[derive(Debug, Default, Clone, Copy, serde::Serialize)]
pub struct PerfSnapshot {
pub requests: u64,
pub decode_tps: Option<f64>,
pub prefill_tps: Option<f64>,
}
#[derive(Default)]
struct PerfMeter {
requests: u64,
decode_tokens: u64,
decode_ms: f64,
prompt_tokens: u64,
prompt_ms: f64,
}
impl PerfMeter {
fn record(&mut self, u: &Usage) {
self.requests += 1;
if let Some(d) = u.decode_ms.filter(|d| *d > 0.0) {
self.decode_tokens += u.completion_tokens as u64;
self.decode_ms += d;
}
if let Some(p) = u.prompt_ms.filter(|p| *p > 0.0) {
self.prompt_tokens += u.prompt_tokens as u64;
self.prompt_ms += p;
}
}
fn snapshot(&self) -> PerfSnapshot {
PerfSnapshot {
requests: self.requests,
decode_tps: (self.decode_ms > 0.0)
.then(|| self.decode_tokens as f64 / (self.decode_ms / 1000.0)),
prefill_tps: (self.prompt_ms > 0.0)
.then(|| self.prompt_tokens as f64 / (self.prompt_ms / 1000.0)),
}
}
}
impl ChatService {
pub fn new(engine: Arc<Engine>, fmt: Arc<dyn Formatter>) -> Self {
Self { engine, fmt }
Self {
engine,
fmt,
perf: Arc::new(StdMutex::new(PerfMeter::default())),
}
}
pub fn model_name(&self) -> &str {
@@ -43,6 +91,24 @@ impl ChatService {
self.fmt.count_tokens(text)
}
/// Running performance gauge (average decode/prefill speed since startup).
pub fn perf(&self) -> PerfSnapshot {
self.perf
.lock()
.unwrap_or_else(|e| e.into_inner())
.snapshot()
}
/// The engine's context window (tokens).
pub fn max_context(&self) -> u32 {
self.engine.ready().max_context
}
/// True when no request holds the engine wires.
pub fn is_idle(&self) -> bool {
self.engine.is_idle()
}
/// One-shot completion.
pub async fn complete(&self, req: &ChatRequest) -> Result<ChatResponse, ApiErrorEnvelope> {
let mut prompt = self.build_prompt_blocking(req).await?;
@@ -84,6 +150,16 @@ impl ChatService {
finish_reason(&outcome, prompt.max_new)
};
let usage = usage_of(
&outcome,
prompt.ids.len() as u32,
outcome.tokens.len() as u32,
);
self.perf
.lock()
.unwrap_or_else(|e| e.into_inner())
.record(&usage);
Ok(ChatResponse {
id: completion_id(),
object: "chat.completion",
@@ -101,11 +177,7 @@ impl ChatService {
},
finish_reason: finish,
}],
usage: usage_of(
&outcome,
prompt.ids.len() as u32,
outcome.tokens.len() as u32,
),
usage,
})
}
@@ -128,6 +200,7 @@ impl ChatService {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<ChatChunk>();
let engine = self.engine.clone();
let fmt = self.fmt.clone();
let perf = self.perf.clone();
let (p_ids, p_max, p_sampling, p_temp) = (
prompt.ids,
@@ -229,6 +302,16 @@ impl ChatService {
.unwrap_or(out.tokens.len() as u32),
Err(_) => 0,
};
let (pms, dms) = gen
.as_ref()
.ok()
.and_then(|o| o.done.as_ref())
.map(|d| (Some(d.prompt_ms), Some(d.decode_ms)))
.unwrap_or((None, None));
let usage = Usage::new(prompt_len, completion).with_timings(pms, dms);
perf.lock()
.unwrap_or_else(|e| e.into_inner())
.record(&usage);
send(
&tx,
&id,
@@ -236,7 +319,7 @@ impl ChatService {
&model,
Delta::default(),
Some(finish),
Some(Usage::new(prompt_len, completion)),
Some(usage),
);
if let Err(e) = gen {
@@ -378,7 +461,8 @@ fn finish_reason(outcome: &Outcome, max_new: u32) -> FinishReason {
fn usage_of(outcome: &Outcome, prompt_len: u32, completion: u32) -> Usage {
match &outcome.done {
Some(d) => Usage::new(d.prompt_tokens.max(prompt_len), d.generated.max(completion)),
Some(d) => Usage::new(d.prompt_tokens.max(prompt_len), d.generated.max(completion))
.with_timings(Some(d.prompt_ms), Some(d.decode_ms)),
None => Usage::new(prompt_len, completion),
}
}
+32 -3
View File
@@ -13,9 +13,10 @@ use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{sse::Event, sse::Sse, IntoResponse, Json};
use futures::StreamExt;
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use super::routes::{AppState, Error};
use super::service::PerfSnapshot;
use super::types::{
completion_id, now_unix, ChatChunk, ChatMessage, ChatRequest, ChatResponse, Choice,
FinishReason, FunctionCall, Role, ToolCall, Usage,
@@ -189,8 +190,36 @@ pub(crate) async fn get_messages(
Ok(Json(with_store(&st, move |s| s.messages(&id)).await?))
}
pub(crate) async fn stats(State(st): State<AppState>) -> Result<Json<Stats>, Error> {
Ok(Json(with_store(&st, |s| s.stats()).await?))
/// The stats dashboard payload: persistent history aggregates (from the store)
/// plus a live engine status and the since-startup performance gauge, in one
/// JSON object so the GUI renders the whole view from a single poll.
#[derive(Serialize)]
pub(crate) struct StatsResponse {
#[serde(flatten)]
totals: Stats,
engine: EngineStatus,
perf: PerfSnapshot,
}
#[derive(Serialize)]
struct EngineStatus {
model: String,
max_context: u32,
busy: bool,
}
pub(crate) async fn stats(State(st): State<AppState>) -> Result<Json<StatsResponse>, Error> {
let totals = with_store(&st, |s| s.stats()).await?;
let engine = EngineStatus {
model: st.service.model_name().to_string(),
max_context: st.service.max_context(),
busy: !st.service.is_idle(),
};
Ok(Json(StatsResponse {
totals,
engine,
perf: st.service.perf(),
}))
}
fn role_of(s: &str) -> Role {
+16
View File
@@ -150,6 +150,13 @@ pub struct Usage {
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub total_tokens: u32,
/// Engine prefill time (ms), when reported. Non-standard extras; OpenAI
/// clients ignore them, the GUI uses them for performance stats.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub prompt_ms: Option<f64>,
/// Engine decode time (ms), when reported.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub decode_ms: Option<f64>,
}
impl Usage {
@@ -158,8 +165,17 @@ impl Usage {
prompt_tokens,
completion_tokens,
total_tokens: prompt_tokens + completion_tokens,
prompt_ms: None,
decode_ms: None,
}
}
/// Attach engine timings (prefill/decode ms) for performance statistics.
pub fn with_timings(mut self, prompt_ms: Option<f64>, decode_ms: Option<f64>) -> Self {
self.prompt_ms = prompt_ms.filter(|v| *v > 0.0);
self.decode_ms = decode_ms.filter(|v| *v > 0.0);
self
}
}
/// Why generation stopped (OpenAI spelling).
+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();