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

+15 -2
View File
@@ -100,7 +100,9 @@ offline, same-origin so no CORS). It is a thin client over a **session-aware API
- `POST /api/sessions/{id}/chat` — append a turn; the server loads the stored - `POST /api/sessions/{id}/chat` — append a turn; the server loads the stored
context, runs inference (streaming SSE or not) and persists the new turns with context, runs inference (streaming SSE or not) and persists the new turns with
their token usage. their token usage.
- `GET /api/stats` — aggregate counters (sessions, messages, prompt/completion tokens). - `GET /api/stats` — the stats dashboard payload: persistent totals (sessions,
messages, prompt/completion/total tokens, tool calls), per-session and per-day
breakdowns, plus live engine status and a since-startup decode/prefill speed gauge.
- `GET/PUT /api/settings/defaults` — the global default settings template. - `GET/PUT /api/settings/defaults` — the global default settings template.
- `POST /api/uploads` — store an uploaded file (base64) in the shared upload dir; - `POST /api/uploads` — store an uploaded file (base64) in the shared upload dir;
returns metadata (kind, token count, path). Attach the returned id to a chat turn. returns metadata (kind, token count, path). Attach the returned id to a chat turn.
@@ -128,6 +130,17 @@ tokenizer) is inlined; **large text and binaries** are handed to the agent as a
with a reminder to inspect them selectively via `shell_exec` — binaries never enter with a reminder to inspect them selectively via `shell_exec` — binaries never enter
the context directly. The `shell_exec` output cap is a second safety net. the context directly. The `shell_exec` output cap is a second safety net.
**Statistics.** The "Statistiche" button opens a live dashboard over the
*persistent* history — our angle on the reference's ephemeral request monitor:
overview cards (engine model / context window / idle-busy, token-weighted **decode
speed** and prefill speed since startup, total/prompt/completion tokens, sessions,
messages, tool calls), a **daily token chart** (stacked prompt/completion per UTC
day) and a **per-session breakdown** with relative token-share bars. `GET /api/stats`
returns the store aggregates plus a live engine status and an in-memory performance
gauge (token-weighted over the requests served since startup, from the engine's
`DONE` timings); the view polls every 2s while open. History totals survive
restarts; the speed gauge resets with the process.
The standard `/v1` API stays **stateless**; conversation context lives server-side The standard `/v1` API stays **stateless**; conversation context lives server-side
in an embedded **SQLite** database (default `~/.strata-ctl/data/sessions.db`, in an embedded **SQLite** database (default `~/.strata-ctl/data/sessions.db`,
override with `db_path`). Storage sits behind a `Store` trait so it can be swapped override with `db_path`). Storage sits behind a `Store` trait so it can be swapped
@@ -232,7 +245,7 @@ later adaptation round.
## Status ## Status
Working and tested (123 tests, plus 2 real-file tests run on demand). Text, images, Working and tested (124 tests, plus 2 real-file tests run on demand). Text, images,
the full client-side tool loop, the Anthropic endpoint, the web GUI (session the full client-side tool loop, the Anthropic endpoint, the web GUI (session
context, streaming, stats, **file/image upload**) and **agent mode** (the model context, streaming, stats, **file/image upload**) and **agent mode** (the model
using `shell_exec` on the host) have been validated live against the real Inkling using `shell_exec` on the host) have been validated live against the real Inkling
+92 -8
View File
@@ -8,6 +8,7 @@
//! while the HTTP handler just forwards what the task puts on the channel. //! while the HTTP handler just forwards what the task puts on the channel.
use std::sync::Arc; use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use futures::Stream; use futures::Stream;
use tokio::sync::mpsc::UnboundedSender; use tokio::sync::mpsc::UnboundedSender;
@@ -27,11 +28,58 @@ use super::types::{
pub struct ChatService { pub struct ChatService {
engine: Arc<Engine>, engine: Arc<Engine>,
fmt: Arc<dyn Formatter>, 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 { impl ChatService {
pub fn new(engine: Arc<Engine>, fmt: Arc<dyn Formatter>) -> Self { 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 { pub fn model_name(&self) -> &str {
@@ -43,6 +91,24 @@ impl ChatService {
self.fmt.count_tokens(text) 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. /// One-shot completion.
pub async fn complete(&self, req: &ChatRequest) -> Result<ChatResponse, ApiErrorEnvelope> { pub async fn complete(&self, req: &ChatRequest) -> Result<ChatResponse, ApiErrorEnvelope> {
let mut prompt = self.build_prompt_blocking(req).await?; let mut prompt = self.build_prompt_blocking(req).await?;
@@ -84,6 +150,16 @@ impl ChatService {
finish_reason(&outcome, prompt.max_new) 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 { Ok(ChatResponse {
id: completion_id(), id: completion_id(),
object: "chat.completion", object: "chat.completion",
@@ -101,11 +177,7 @@ impl ChatService {
}, },
finish_reason: finish, finish_reason: finish,
}], }],
usage: usage_of( usage,
&outcome,
prompt.ids.len() as u32,
outcome.tokens.len() as u32,
),
}) })
} }
@@ -128,6 +200,7 @@ impl ChatService {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<ChatChunk>(); let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<ChatChunk>();
let engine = self.engine.clone(); let engine = self.engine.clone();
let fmt = self.fmt.clone(); let fmt = self.fmt.clone();
let perf = self.perf.clone();
let (p_ids, p_max, p_sampling, p_temp) = ( let (p_ids, p_max, p_sampling, p_temp) = (
prompt.ids, prompt.ids,
@@ -229,6 +302,16 @@ impl ChatService {
.unwrap_or(out.tokens.len() as u32), .unwrap_or(out.tokens.len() as u32),
Err(_) => 0, 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( send(
&tx, &tx,
&id, &id,
@@ -236,7 +319,7 @@ impl ChatService {
&model, &model,
Delta::default(), Delta::default(),
Some(finish), Some(finish),
Some(Usage::new(prompt_len, completion)), Some(usage),
); );
if let Err(e) = gen { 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 { fn usage_of(outcome: &Outcome, prompt_len: u32, completion: u32) -> Usage {
match &outcome.done { 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), 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::http::StatusCode;
use axum::response::{sse::Event, sse::Sse, IntoResponse, Json}; use axum::response::{sse::Event, sse::Sse, IntoResponse, Json};
use futures::StreamExt; use futures::StreamExt;
use serde::Deserialize; use serde::{Deserialize, Serialize};
use super::routes::{AppState, Error}; use super::routes::{AppState, Error};
use super::service::PerfSnapshot;
use super::types::{ use super::types::{
completion_id, now_unix, ChatChunk, ChatMessage, ChatRequest, ChatResponse, Choice, completion_id, now_unix, ChatChunk, ChatMessage, ChatRequest, ChatResponse, Choice,
FinishReason, FunctionCall, Role, ToolCall, Usage, 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?)) Ok(Json(with_store(&st, move |s| s.messages(&id)).await?))
} }
pub(crate) async fn stats(State(st): State<AppState>) -> Result<Json<Stats>, Error> { /// The stats dashboard payload: persistent history aggregates (from the store)
Ok(Json(with_store(&st, |s| s.stats()).await?)) /// 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 { fn role_of(s: &str) -> Role {
+16
View File
@@ -150,6 +150,13 @@ pub struct Usage {
pub prompt_tokens: u32, pub prompt_tokens: u32,
pub completion_tokens: u32, pub completion_tokens: u32,
pub total_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 { impl Usage {
@@ -158,8 +165,17 @@ impl Usage {
prompt_tokens, prompt_tokens,
completion_tokens, completion_tokens,
total_tokens: 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). /// Why generation stopped (OpenAI spelling).
+141 -4
View File
@@ -111,13 +111,42 @@ pub struct NewMessage<'a> {
pub completion_tokens: u32, 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)] #[derive(Debug, Clone, Default, Serialize)]
pub struct Stats { pub struct Stats {
pub sessions: u64, pub sessions: u64,
pub messages: u64, pub messages: u64,
pub prompt_tokens: u64, pub prompt_tokens: u64,
pub completion_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). /// 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> { fn stats(&self) -> Result<Stats> {
let conn = self.lock(); let conn = self.lock();
let sessions: i64 = conn.query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))?; let sessions: i64 = conn.query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))?;
let (messages, prompt, completion): (i64, i64, i64) = conn.query_row( // Totals + tool-call count in one pass. tool_calls_json is always a JSON
"SELECT COUNT(*), COALESCE(SUM(prompt_tokens),0), COALESCE(SUM(completion_tokens),0) FROM messages", // 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 { Ok(Stats {
sessions: sessions as u64, sessions: sessions as u64,
messages: messages as u64, messages: messages as u64,
prompt_tokens: prompt as u64, prompt_tokens: prompt as u64,
completion_tokens: completion 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); 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] #[test]
fn settings_instance_and_name_lock() { fn settings_instance_and_name_lock() {
let s = store(); let s = store();
+17
View File
@@ -178,6 +178,23 @@ async fn session_holds_context_and_persists_usage() {
assert_eq!(s["sessions"], 1); assert_eq!(s["sessions"], 1);
assert_eq!(s["messages"], 4); assert_eq!(s["messages"], 4);
assert_eq!(s["completion_tokens"], 10); assert_eq!(s["completion_tokens"], 10);
// Expanded dashboard payload: totals, per-session/daily breakdown, and the
// live engine status + since-startup performance gauge layered on top.
assert_eq!(
s["total_tokens"],
s["prompt_tokens"].as_u64().unwrap() + s["completion_tokens"].as_u64().unwrap()
);
assert_eq!(s["tool_calls"], 0);
assert_eq!(s["by_session"].as_array().unwrap().len(), 1);
assert_eq!(s["by_session"][0]["messages"], 4);
assert_eq!(s["daily"].as_array().unwrap().len(), 1);
assert_eq!(s["engine"]["model"], "test-model");
assert_eq!(s["engine"]["max_context"], 8192);
assert_eq!(s["engine"]["busy"], false);
// Two non-stream completions were served and recorded by the perf meter,
// whose token-weighted decode speed comes from the mock's DONE timings.
assert_eq!(s["perf"]["requests"], 2);
assert!(s["perf"]["decode_tps"].as_f64().unwrap() > 0.0);
} }
#[tokio::test] #[tokio::test]
+77 -3
View File
@@ -210,9 +210,83 @@ details.thinking .reasoning {
padding: 20px; max-width: 420px; width: 100%; padding: 20px; max-width: 420px; width: 100%;
} }
.modal-card h2 { margin: 0 0 12px; font-size: 1.1rem; } .modal-card h2 { margin: 0 0 12px; font-size: 1.1rem; }
#stats-body { display: grid; grid-template-columns: 1fr auto; gap: 6px 16px; margin: 0 0 16px; }
#stats-body dt { color: var(--muted); } /* ---- Stats dashboard ---- */
#stats-body dd { margin: 0; font-variant-numeric: tabular-nums; } .stats-card {
width: min(940px, 100%); max-width: 940px; max-height: 88dvh;
display: flex; flex-direction: column; padding: 0; overflow: hidden;
}
.stats-head {
display: flex; align-items: center; gap: 12px;
padding: 14px 18px; border-bottom: 1px solid var(--border);
background: var(--panel); flex: 0 0 auto;
}
.stats-head h2 { margin: 0; font-size: 1.15rem; }
.stats-live { flex: 1; font-size: 0.72rem; text-align: right; font-variant-numeric: tabular-nums; }
.stats-head .btn.icon { min-height: 36px; padding: 6px 10px; font-size: 1rem; }
.stats-content { padding: 18px; overflow-y: auto; display: flex; flex-direction: column; gap: 22px; }
/* Overview cards: 2-up on phones, 3-up from 700px. */
.stat-cards { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; }
.stat-card {
background: var(--panel-2); border: 1px solid var(--border);
border-radius: 12px; padding: 12px 14px; min-width: 0;
}
.stat-card .label {
font-size: 0.66rem; text-transform: uppercase; letter-spacing: 0.7px; color: var(--muted);
}
.stat-card .value {
font-size: 1.5rem; font-weight: 600; line-height: 1.25; margin-top: 4px;
font-variant-numeric: tabular-nums; overflow-wrap: anywhere;
}
.stat-card .sub { font-size: 0.73rem; color: var(--muted); margin-top: 3px; overflow-wrap: anywhere; }
.stat-card.engine .value { display: flex; align-items: center; gap: 8px; font-size: 1.1rem; }
.stat-card .model {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.72rem; color: var(--muted); margin-top: 5px; overflow-wrap: anywhere;
}
.dot { width: 9px; height: 9px; border-radius: 50%; background: var(--muted); flex: 0 0 auto; }
.dot.idle { background: #3fb950; }
.dot.busy { background: #d29922; }
/* Section headings inside the dashboard. */
.stat-section > h3 { margin: 0; font-size: 0.95rem; }
.stat-section > .sub { font-size: 0.73rem; color: var(--muted); margin: 2px 0 12px; }
.stat-empty { color: var(--muted); font-size: 0.85rem; padding: 10px 0; }
/* Daily activity chart: stacked prompt/completion bars (pure CSS, responsive). */
.chart-bars { display: flex; align-items: flex-end; gap: 3px; height: 132px; }
.chart-bars .bar {
flex: 1 1 0; min-width: 0; height: 100%;
display: flex; flex-direction: column; justify-content: flex-end;
}
.chart-bars .bar i { display: block; width: 100%; }
.chart-bars .bar i.prompt { background: var(--accent-press); }
.chart-bars .bar i.completion { background: var(--accent); border-radius: 3px 3px 0 0; }
.chart-bars .bar:hover i { filter: brightness(1.18); }
.chart-x { display: flex; justify-content: space-between; gap: 8px; font-size: 0.66rem; color: var(--muted); margin-top: 6px; }
.chart-legend { display: flex; gap: 14px; margin-top: 10px; font-size: 0.72rem; color: var(--muted); }
.chart-legend span { display: inline-flex; align-items: center; gap: 6px; }
.swatch { width: 10px; height: 10px; border-radius: 3px; display: inline-block; }
.swatch.prompt { background: var(--accent-press); }
.swatch.completion { background: var(--accent); }
/* Per-session breakdown: relative token-share bars, busiest first. */
.sess-stats { display: flex; flex-direction: column; gap: 12px; }
.sess-stat { min-width: 0; }
.sess-stat.current .name { color: var(--accent); }
.sess-stat-top { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; }
.sess-stat-top .name { font-size: 0.9rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.sess-stat-top .tok { font-size: 0.8rem; color: var(--muted); font-variant-numeric: tabular-nums; flex: 0 0 auto; }
.sess-bar { display: flex; height: 8px; border-radius: 5px; overflow: hidden; background: var(--bg); margin: 5px 0 4px; }
.sess-bar i { display: block; height: 100%; }
.sess-bar i.prompt { background: var(--accent-press); }
.sess-bar i.completion { background: var(--accent); }
.sess-stat-sub { font-size: 0.7rem; color: var(--muted); }
@media (min-width: 700px) {
.stat-cards { grid-template-columns: repeat(3, 1fr); }
}
#dialog-msg { margin: 0 0 16px; } #dialog-msg { margin: 0 0 16px; }
#dialog-input { #dialog-input {
width: 100%; background: var(--panel-2); color: var(--text); width: 100%; background: var(--panel-2); color: var(--text);
+181 -14
View File
@@ -486,21 +486,185 @@ async function agentTurn(content, t, attachments) {
} }
} }
async function showStats() { // ---- Stats dashboard ------------------------------------------------------
const s = await getJSON("/api/stats"); // Our angle vs the reference's ephemeral request monitor: a dashboard over the
const body = $("#stats-body"); // PERSISTENT history (overview cards, daily token chart, per-session share) plus
body.textContent = ""; // a live engine/perf gauge. Polls every 2s while open; re-renders only on change.
const rows = [ let statsTimer = null;
["Sessioni", s.sessions], let statsStamp = "";
["Messaggi", s.messages], let _nf = null, _nfLang = null;
["Token prompt", s.prompt_tokens], function nf() {
["Token completati", s.completion_tokens], if (_nfLang !== I18N.lang) { _nf = new Intl.NumberFormat(I18N.lang); _nfLang = I18N.lang; }
]; return _nf;
for (const [k, v] of rows) {
body.appendChild(el("dt", null, k));
body.appendChild(el("dd", null, String(v)));
} }
function fmtInt(n) { return nf().format(Math.round(Number(n) || 0)); }
function fmt1(n) { return (Number(n) || 0).toFixed(1); }
function fmtCompact(n) {
n = Number(n) || 0;
if (n >= 1e6) return (n / 1e6).toFixed(n >= 1e7 ? 0 : 1) + "M";
if (n >= 1e3) return (n / 1e3).toFixed(n >= 1e4 ? 0 : 1) + "k";
return String(n);
}
function dayLabel(secs) {
return new Date(secs * 1000).toLocaleDateString(I18N.lang, { day: "2-digit", month: "short", timeZone: "UTC" });
}
function whenLabel(secs) {
if (!secs) return t("stats.na");
return new Date(secs * 1000).toLocaleString(I18N.lang, { day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" });
}
// One overview card; `value` is a string or a Node (the engine status dot).
function statCard(label, value, sub, cls) {
const card = el("div", "stat-card" + (cls ? " " + cls : ""));
card.appendChild(el("div", "label", label));
const v = el("div", "value");
if (value instanceof Node) v.appendChild(value); else v.textContent = value;
card.appendChild(v);
if (sub) card.appendChild(el("div", "sub", sub));
return card;
}
function engineCard(engine) {
const card = el("div", "stat-card engine");
card.appendChild(el("div", "label", t("stats.engine")));
const v = el("div", "value");
v.appendChild(el("span", "dot " + (engine.busy ? "busy" : "idle")));
v.appendChild(el("span", null, engine.busy ? t("stats.engine.busy") : t("stats.engine.idle")));
card.appendChild(v);
card.appendChild(el("div", "model", engine.model || t("stats.na")));
card.appendChild(el("div", "sub", t("stats.context", { n: fmtInt(engine.max_context) })));
return card;
}
function renderStats(s) {
const root = $("#stats-content");
root.textContent = "";
const perf = s.perf || {};
const cards = el("div", "stat-cards");
cards.appendChild(engineCard(s.engine || {}));
const decode = perf.decode_tps != null ? t("stats.tps", { n: fmt1(perf.decode_tps) }) : t("stats.na");
const decodeSub = perf.prefill_tps != null
? t("stats.decode.sub") + " · " + t("stats.prefill", { n: fmt1(perf.prefill_tps) })
: t("stats.decode.sub");
cards.appendChild(statCard(t("stats.decode"), decode, decodeSub));
cards.appendChild(statCard(t("stats.tokens"), fmtInt(s.total_tokens),
t("stats.tokens.sub", { p: fmtInt(s.prompt_tokens), c: fmtInt(s.completion_tokens) })));
cards.appendChild(statCard(t("stats.sessions"), fmtInt(s.sessions),
t("stats.messages.sub", { n: fmtInt(s.messages) })));
cards.appendChild(statCard(t("stats.tools"), fmtInt(s.tool_calls), t("stats.tools.sub")));
cards.appendChild(statCard(t("stats.requests"), fmtInt(perf.requests), t("stats.requests.sub")));
root.appendChild(cards);
root.appendChild(dailySection(s.daily || []));
root.appendChild(sessionSection(s.by_session || []));
}
// Daily token chart: a continuous, zero-filled UTC-day window (last 30 bars),
// each bar stacked prompt (bottom) + completion (top), scaled to the peak day.
function dailySection(daily) {
const sec = el("div", "stat-section");
sec.appendChild(el("h3", null, t("stats.daily")));
sec.appendChild(el("div", "sub", t("stats.daily.sub")));
if (!daily.length) {
sec.appendChild(el("div", "stat-empty", t("stats.daily.empty")));
return sec;
}
const byDay = new Map(daily.map((d) => [d.day, d]));
const last = daily[daily.length - 1].day;
const span = Math.round((last - daily[0].day) / 86400) + 1;
const count = Math.min(span, 30);
const start = last - (count - 1) * 86400;
const days = [];
let max = 1;
for (let i = 0; i < count; i++) {
const day = start + i * 86400;
const d = byDay.get(day) || { day, prompt_tokens: 0, completion_tokens: 0 };
const total = (d.prompt_tokens || 0) + (d.completion_tokens || 0);
if (total > max) max = total;
days.push({ day, prompt_tokens: d.prompt_tokens || 0, completion_tokens: d.completion_tokens || 0, total });
}
const bars = el("div", "chart-bars");
for (const d of days) {
const bar = el("div", "bar");
bar.title = dayLabel(d.day) + " · " + t("stats.tokens.sub", { p: fmtInt(d.prompt_tokens), c: fmtInt(d.completion_tokens) });
const c = el("i", "completion"); c.style.height = (d.completion_tokens / max * 100) + "%";
const p = el("i", "prompt"); p.style.height = (d.prompt_tokens / max * 100) + "%";
bar.appendChild(c); bar.appendChild(p);
bars.appendChild(bar);
}
sec.appendChild(bars);
const x = el("div", "chart-x");
x.appendChild(el("span", null, dayLabel(days[0].day)));
if (days.length > 2) x.appendChild(el("span", null, dayLabel(days[Math.floor(days.length / 2)].day)));
x.appendChild(el("span", null, dayLabel(days[days.length - 1].day)));
sec.appendChild(x);
const legend = el("div", "chart-legend");
for (const [cls, key] of [["prompt", "stats.legend.prompt"], ["completion", "stats.legend.completion"]]) {
const item = el("span");
item.appendChild(el("i", "swatch " + cls));
item.appendChild(document.createTextNode(t(key)));
legend.appendChild(item);
}
sec.appendChild(legend);
return sec;
}
// Per-session share bars (relative to the busiest session), busiest first.
function sessionSection(rows) {
const sec = el("div", "stat-section");
sec.appendChild(el("h3", null, t("stats.perSession")));
sec.appendChild(el("div", "sub", t("stats.perSession.sub")));
if (!rows.length) {
sec.appendChild(el("div", "stat-empty", t("stats.perSession.empty")));
return sec;
}
const total = (r) => (r.prompt_tokens || 0) + (r.completion_tokens || 0);
const max = Math.max(1, ...rows.map(total));
const list = el("div", "sess-stats");
for (const r of rows) {
const row = el("div", "sess-stat" + (r.id === state.current ? " current" : ""));
const top = el("div", "sess-stat-top");
top.appendChild(el("span", "name", r.title || r.id));
top.appendChild(el("span", "tok", fmtCompact(total(r))));
row.appendChild(top);
const bar = el("div", "sess-bar");
const p = el("i", "prompt"); p.style.width = ((r.prompt_tokens || 0) / max * 100) + "%";
const c = el("i", "completion"); c.style.width = ((r.completion_tokens || 0) / max * 100) + "%";
bar.appendChild(p); bar.appendChild(c);
row.appendChild(bar);
row.appendChild(el("div", "sess-stat-sub",
t("stats.messages.sub", { n: fmtInt(r.messages) }) + " · " + t("stats.session.updated", { when: whenLabel(r.updated_at) })));
list.appendChild(row);
}
sec.appendChild(list);
return sec;
}
async function refreshStats() {
try {
const s = await getJSON("/api/stats");
$("#stats-live").textContent = t("stats.updated", { time: new Date().toLocaleTimeString(I18N.lang) });
const stamp = JSON.stringify(s);
if (stamp === statsStamp) return;
statsStamp = stamp;
renderStats(s);
} catch (e) {
$("#stats-live").textContent = t("stats.disconnected");
}
}
async function showStats() {
$("#stats-modal").hidden = false; $("#stats-modal").hidden = false;
statsStamp = "";
$("#stats-content").textContent = "";
await refreshStats();
clearInterval(statsTimer);
statsTimer = setInterval(refreshStats, 2000);
}
function closeStats() {
$("#stats-modal").hidden = true;
clearInterval(statsTimer);
statsTimer = null;
} }
// ---- Settings (per-session instance or global defaults) ------------------- // ---- Settings (per-session instance or global defaults) -------------------
@@ -705,7 +869,10 @@ function wire() {
ab.classList.toggle("active", state.agent); ab.classList.toggle("active", state.agent);
ab.setAttribute("aria-pressed", String(state.agent)); ab.setAttribute("aria-pressed", String(state.agent));
$("#show-stats").addEventListener("click", showStats); $("#show-stats").addEventListener("click", showStats);
$("#close-stats").addEventListener("click", () => { $("#stats-modal").hidden = true; }); $("#close-stats").setAttribute("aria-label", t("stats.close"));
$("#close-stats").addEventListener("click", closeStats);
$("#stats-modal").addEventListener("click", (e) => { if (e.target.id === "stats-modal") closeStats(); });
document.addEventListener("keydown", (e) => { if (e.key === "Escape" && !$("#stats-modal").hidden) closeStats(); });
$("#show-settings").addEventListener("click", () => openSettings("session")); $("#show-settings").addEventListener("click", () => openSettings("session"));
$("#set-scope-session").addEventListener("click", () => openSettings("session")); $("#set-scope-session").addEventListener("click", () => openSettings("session"));
$("#set-scope-general").addEventListener("click", () => openSettings("general")); $("#set-scope-general").addEventListener("click", () => openSettings("general"));
+31 -1
View File
@@ -20,5 +20,35 @@
"settings.error": "Error: {msg}", "settings.error": "Error: {msg}",
"attach.title": "Attach files or images", "attach.title": "Attach files or images",
"attach.remove": "Remove attachment", "attach.remove": "Remove attachment",
"attach.error": "Upload failed: {msg}" "attach.error": "Upload failed: {msg}",
"stats.title": "Statistics",
"stats.close": "Close",
"stats.updated": "Updated {time}",
"stats.disconnected": "Disconnected · retrying",
"stats.engine": "Engine",
"stats.engine.idle": "Idle",
"stats.engine.busy": "In use",
"stats.context": "{n} token context",
"stats.decode": "Decode speed",
"stats.decode.sub": "run average",
"stats.prefill": "prefill {n} tok/s",
"stats.tokens": "Total tokens",
"stats.tokens.sub": "{p} prompt · {c} completion",
"stats.sessions": "Sessions",
"stats.messages.sub": "{n} messages",
"stats.tools": "Tool calls",
"stats.tools.sub": "across history",
"stats.requests": "Requests served",
"stats.requests.sub": "since startup",
"stats.daily": "Daily activity",
"stats.daily.sub": "tokens per day (UTC)",
"stats.daily.empty": "No activity recorded yet.",
"stats.legend.prompt": "Prompt",
"stats.legend.completion": "Completion",
"stats.perSession": "Per session",
"stats.perSession.sub": "token share per chat",
"stats.perSession.empty": "No sessions yet.",
"stats.session.updated": "updated {when}",
"stats.tps": "{n} tok/s",
"stats.na": "—"
} }
+31 -1
View File
@@ -20,5 +20,35 @@
"settings.error": "Errore: {msg}", "settings.error": "Errore: {msg}",
"attach.title": "Allega file o immagini", "attach.title": "Allega file o immagini",
"attach.remove": "Rimuovi allegato", "attach.remove": "Rimuovi allegato",
"attach.error": "Caricamento fallito: {msg}" "attach.error": "Caricamento fallito: {msg}",
"stats.title": "Statistiche",
"stats.close": "Chiudi",
"stats.updated": "Aggiornato {time}",
"stats.disconnected": "Disconnesso · riprovo",
"stats.engine": "Motore",
"stats.engine.idle": "Inattivo",
"stats.engine.busy": "In uso",
"stats.context": "{n} token di contesto",
"stats.decode": "Velocità decode",
"stats.decode.sub": "media dall'avvio",
"stats.prefill": "prefill {n} tok/s",
"stats.tokens": "Token totali",
"stats.tokens.sub": "{p} prompt · {c} completati",
"stats.sessions": "Sessioni",
"stats.messages.sub": "{n} messaggi",
"stats.tools": "Chiamate tool",
"stats.tools.sub": "nella cronologia",
"stats.requests": "Richieste servite",
"stats.requests.sub": "dall'avvio",
"stats.daily": "Attività giornaliera",
"stats.daily.sub": "token per giorno (UTC)",
"stats.daily.empty": "Nessuna attività registrata.",
"stats.legend.prompt": "Prompt",
"stats.legend.completion": "Completati",
"stats.perSession": "Per sessione",
"stats.perSession.sub": "quota di token per chat",
"stats.perSession.empty": "Nessuna sessione.",
"stats.session.updated": "aggiornato {when}",
"stats.tps": "{n} tok/s",
"stats.na": "—"
} }
+9 -6
View File
@@ -18,7 +18,7 @@
</div> </div>
<ul id="session-list"></ul> <ul id="session-list"></ul>
<div class="drawer-foot"> <div class="drawer-foot">
<button id="show-stats" class="btn ghost">Statistiche</button> <button id="show-stats" class="btn ghost" data-i18n="stats.title">Statistiche</button>
</div> </div>
</aside> </aside>
<div id="splitter" role="separator" aria-orientation="vertical" aria-label="Ridimensiona l'elenco delle discussioni" aria-valuemin="200" aria-valuemax="480" aria-valuenow="280" tabindex="0"></div> <div id="splitter" role="separator" aria-orientation="vertical" aria-label="Ridimensiona l'elenco delle discussioni" aria-valuemin="200" aria-valuemax="480" aria-valuenow="280" tabindex="0"></div>
@@ -49,12 +49,15 @@
</main> </main>
</div> </div>
<!-- Stats modal --> <!-- Stats dashboard -->
<div id="stats-modal" hidden> <div id="stats-modal" hidden>
<div class="modal-card"> <div class="modal-card stats-card">
<h2>Statistiche</h2> <div class="stats-head">
<dl id="stats-body"></dl> <h2 data-i18n="stats.title">Statistiche</h2>
<button id="close-stats" class="btn">Chiudi</button> <span id="stats-live" class="stats-live muted"></span>
<button id="close-stats" class="btn icon" aria-label="Chiudi">&#10005;</button>
</div>
<div id="stats-content" class="stats-content"></div>
</div> </div>
</div> </div>