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

+77 -3
View File
@@ -210,9 +210,83 @@ details.thinking .reasoning {
padding: 20px; max-width: 420px; width: 100%;
}
.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-body dd { margin: 0; font-variant-numeric: tabular-nums; }
/* ---- Stats dashboard ---- */
.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-input {
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() {
const s = await getJSON("/api/stats");
const body = $("#stats-body");
body.textContent = "";
const rows = [
["Sessioni", s.sessions],
["Messaggi", s.messages],
["Token prompt", s.prompt_tokens],
["Token completati", s.completion_tokens],
];
for (const [k, v] of rows) {
body.appendChild(el("dt", null, k));
body.appendChild(el("dd", null, String(v)));
// ---- Stats dashboard ------------------------------------------------------
// Our angle vs the reference's ephemeral request monitor: a dashboard over the
// PERSISTENT history (overview cards, daily token chart, per-session share) plus
// a live engine/perf gauge. Polls every 2s while open; re-renders only on change.
let statsTimer = null;
let statsStamp = "";
let _nf = null, _nfLang = null;
function nf() {
if (_nfLang !== I18N.lang) { _nf = new Intl.NumberFormat(I18N.lang); _nfLang = I18N.lang; }
return _nf;
}
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;
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) -------------------
@@ -705,7 +869,10 @@ function wire() {
ab.classList.toggle("active", state.agent);
ab.setAttribute("aria-pressed", String(state.agent));
$("#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"));
$("#set-scope-session").addEventListener("click", () => openSettings("session"));
$("#set-scope-general").addEventListener("click", () => openSettings("general"));
+31 -1
View File
@@ -20,5 +20,35 @@
"settings.error": "Error: {msg}",
"attach.title": "Attach files or images",
"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}",
"attach.title": "Allega file o immagini",
"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": "—"
}