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:
1 parent
e79ee0e20e
commit
765c197b95
11 files changed
+642
-42
No files matched your search
+181
-14
@@ -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"));
|
||||
|
||||
Reference in new issue
Block a user