opencode-statboard 2.0.10 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +3 -1
- package/README.md +3 -1
- package/package.json +2 -2
- package/public/index.html +79 -8
- package/server.js +44 -6
package/AGENTS.md
CHANGED
|
@@ -13,7 +13,7 @@ opencode-dashboard
|
|
|
13
13
|
## Architecture
|
|
14
14
|
|
|
15
15
|
- `server.js` — Node.js HTTP server (zero frameworks, pure `http` module)
|
|
16
|
-
- `public/index.html` — Single-file frontend (vanilla JS/CSS/HTML, no build step)
|
|
16
|
+
- `public/index.html` — Single-file frontend (vanilla JS/CSS/HTML, no build step). Report charts (`#speed-bars`, `#agent-bars`, `#session-bars`) render from `/api/report` data via `renderReportCharts`; `check-frontend-smoke.js` executes the page's real script against live API data with a stub DOM.
|
|
17
17
|
- `backups/` — Gzipped DB backups (auto-rotated, `OPENCODE_BACKUP_RETENTION`)
|
|
18
18
|
|
|
19
19
|
## Key Patterns
|
|
@@ -40,6 +40,8 @@ On a V1-only database every expression collapses to the plain V1 tables.
|
|
|
40
40
|
Token/cost attribution uses a hybrid model:
|
|
41
41
|
1. **Message-level** — Each assistant message's `tokens` and `cost` from `message.data` JSON are attributed to its `time_created` local day
|
|
42
42
|
2. **Session residual** — `session.tokens_* - sum(message.tokens_*)` is spread across the session's full local-day span, weighted by per-day message volume
|
|
43
|
+
3. **Speed (message-level only)** — Per-model `speed` (output tok/s) = Σ completed-assistant-message `tokens.output` ÷ Σ(`time.completed - time.created`). Session residuals carry no duration and are excluded; models without usable durations report `null` (shown as —). Tracked in the same message scan, no extra query.
|
|
44
|
+
4. **Period speed/active/wall (report)** — `buildReportFromDb` runs one extra `GROUP BY session_id` over the merged message view (scoped to `[periodStart, attrSnapshot)`), mapped onto the same session-meta buckets: providers/agents gain period `speed`; agents gain `wallMs` (Σ full session spans — same scope as their token columns) and `activeMs` (Σ in-period message durations); `report.sessions` lists the top 20 sessions by wall time with both durations. Wall includes idle; active counts only model-running time.
|
|
43
45
|
|
|
44
46
|
This ensures multi-day sessions (e.g. a session created Monday, updated Thursday) don't dump all tokens onto Thursday.
|
|
45
47
|
|
package/README.md
CHANGED
|
@@ -7,7 +7,9 @@ Real-time dashboard for your [opencode](https://opencode.ai) token usage and cos
|
|
|
7
7
|
- Live-updating overview: sessions, messages, total cost, tokens per session
|
|
8
8
|
- Token statistics: Input / Output / Reasoning / Cache Read / Cache Write
|
|
9
9
|
- Tool usage breakdown with percentage bars (collapsible)
|
|
10
|
-
- Per-model usage with cache read stats
|
|
10
|
+
- Per-model usage with cache read stats and generation speed (output tok/s)
|
|
11
|
+
- Usage reports: per-agent speed, wall/active time, and top-20 sessions by duration
|
|
12
|
+
- Visual charts for model speed, agent wall/active time, and longest sessions
|
|
11
13
|
- Daily trend chart (7D / 30D / 90D)
|
|
12
14
|
- Usage reports: Daily / Weekly / Monthly / All time
|
|
13
15
|
- i18n: English + Traditional Chinese, auto-detects browser language
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-statboard",
|
|
3
|
-
"version": "2.0
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"description": "Real-time dashboard for opencode token usage and cost statistics",
|
|
5
5
|
"main": "server.js",
|
|
6
6
|
"bin": {
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
},
|
|
9
9
|
"scripts": {
|
|
10
10
|
"start": "node server.js",
|
|
11
|
-
"test": "node --check server.js && node --check check-lib.js && node --check check-stats-verify.js && node --check check-trend-verify.js && node --check check-report-verify.js"
|
|
11
|
+
"test": "node --check server.js && node --check check-lib.js && node --check check-stats-verify.js && node --check check-trend-verify.js && node --check check-report-verify.js && node --check check-frontend-smoke.js"
|
|
12
12
|
},
|
|
13
13
|
"keywords": [
|
|
14
14
|
"opencode",
|
package/public/index.html
CHANGED
|
@@ -124,7 +124,7 @@
|
|
|
124
124
|
<h2 data-i18n="modelUsage">MODEL USAGE</h2>
|
|
125
125
|
<table>
|
|
126
126
|
<thead>
|
|
127
|
-
<tr><th data-i18n="thModel">Model</th><th data-i18n="thMsgs">Messages</th><th>Input</th><th>Output</th><th>Cache Read</th><th style="width:26%" data-i18n="thUsage">Usage</th><th data-i18n="thCost">Cost</th></tr>
|
|
127
|
+
<tr><th data-i18n="thModel">Model</th><th data-i18n="thMsgs">Messages</th><th>Input</th><th>Output</th><th>Cache Read</th><th data-i18n="thSpeed">Speed</th><th style="width:26%" data-i18n="thUsage">Usage</th><th data-i18n="thCost">Cost</th></tr>
|
|
128
128
|
</thead>
|
|
129
129
|
<tbody id="model-rows"></tbody>
|
|
130
130
|
</table>
|
|
@@ -173,6 +173,29 @@
|
|
|
173
173
|
<div id="reportContent" style="font-family:monospace;font-size:13px;line-height:1.6;white-space:pre;overflow-x:auto;color:var(--text)">Loading…</div>
|
|
174
174
|
</section>
|
|
175
175
|
|
|
176
|
+
<section>
|
|
177
|
+
<h2 data-i18n="modelSpeed">MODEL SPEED</h2>
|
|
178
|
+
<div id="speed-bars"></div>
|
|
179
|
+
</section>
|
|
180
|
+
|
|
181
|
+
<section>
|
|
182
|
+
<h2 data-i18n="agentTime">AGENT TIME</h2>
|
|
183
|
+
<div class="legend">
|
|
184
|
+
<span><i class="sw" style="background:var(--cache)"></i>wall</span>
|
|
185
|
+
<span><i class="sw" style="background:var(--out)"></i>active</span>
|
|
186
|
+
</div>
|
|
187
|
+
<div id="agent-bars"></div>
|
|
188
|
+
</section>
|
|
189
|
+
|
|
190
|
+
<section>
|
|
191
|
+
<h2 data-i18n="topSessions">TOP SESSIONS</h2>
|
|
192
|
+
<div class="legend">
|
|
193
|
+
<span><i class="sw" style="background:var(--cache)"></i>wall</span>
|
|
194
|
+
<span><i class="sw" style="background:var(--out)"></i>active</span>
|
|
195
|
+
</div>
|
|
196
|
+
<div id="session-bars"></div>
|
|
197
|
+
</section>
|
|
198
|
+
|
|
176
199
|
<script>
|
|
177
200
|
const STRINGS = {
|
|
178
201
|
en: {
|
|
@@ -182,10 +205,10 @@ const STRINGS = {
|
|
|
182
205
|
totalCost: 'Total Cost', avgCostDay: 'Avg Cost / Day',
|
|
183
206
|
avgTokensSession: 'Avg Tokens / Session', medianTokensSession: 'Median Tokens / Session',
|
|
184
207
|
tokenStats: 'TOKEN STATISTICS', toolUsage: 'TOOL USAGE', modelUsage: 'MODEL USAGE',
|
|
185
|
-
thModel: 'Model', thMsgs: 'Messages', thUsage: 'Usage', thCost: 'Cost',
|
|
208
|
+
thModel: 'Model', thMsgs: 'Messages', thSpeed: 'Speed', thUsage: 'Usage', thCost: 'Cost',
|
|
186
209
|
dailyTrend: 'DAILY TREND ({days} DAYS)',
|
|
187
210
|
inputDay: 'Input / Day', outputDay: 'Output / Day', cacheReadDay: 'Cache Read / Day', costDay: 'Cost / Day',
|
|
188
|
-
report: 'USAGE REPORT', all: 'All', daily: 'Daily', weekly: 'Weekly', monthly: 'Monthly',
|
|
211
|
+
report: 'USAGE REPORT', all: 'All', daily: 'Daily', weekly: 'Weekly', monthly: 'Monthly', modelSpeed: 'MODEL SPEED', agentTime: 'AGENT TIME', topSessions: 'TOP SESSIONS',
|
|
189
212
|
updating: 'updating…', generating: 'Generating trend data…', cachedAt: 'cached at', allFree: 'All models free — no cost recorded',
|
|
190
213
|
live: 'Live', loading: 'Loading…', lastUpdated: 'Last updated', dataAgo: 'data generated',
|
|
191
214
|
statsFail: 'Failed to read opencode stats', connFail: 'Connection failed',
|
|
@@ -199,10 +222,10 @@ const STRINGS = {
|
|
|
199
222
|
totalCost: '總費用', avgCostDay: '平均費用 / 天',
|
|
200
223
|
avgTokensSession: '平均 tokens / 場', medianTokensSession: '中位數 tokens / 場',
|
|
201
224
|
tokenStats: 'Tokens 統計', toolUsage: '工具使用', modelUsage: '模型使用',
|
|
202
|
-
thModel: '模型', thMsgs: '訊息', thUsage: '用量', thCost: '費用',
|
|
225
|
+
thModel: '模型', thMsgs: '訊息', thSpeed: '速度', thUsage: '用量', thCost: '費用',
|
|
203
226
|
dailyTrend: '近 {days} 天趨勢',
|
|
204
227
|
inputDay: 'Input / 天', outputDay: 'Output / 天', cacheReadDay: 'Cache Read / 天', costDay: '費用 / 天',
|
|
205
|
-
report: '用量報告', all: '全部', daily: '每日', weekly: '每週', monthly: '每月',
|
|
228
|
+
report: '用量報告', all: '全部', daily: '每日', weekly: '每週', monthly: '每月', modelSpeed: '模型速度', agentTime: '代理時間', topSessions: '最長場次',
|
|
206
229
|
updating: '更新中…', generating: '趨勢資料產生中…', cachedAt: '快取於', allFree: '全部使用免費模型,無費用紀錄',
|
|
207
230
|
live: '即時更新', loading: '載入中…', lastUpdated: '更新於', dataAgo: '數據產生於',
|
|
208
231
|
statsFail: 'opencode stats 讀取失敗', connFail: '連線失敗',
|
|
@@ -265,6 +288,9 @@ const fmt = (n) => {
|
|
|
265
288
|
return String(Math.round(n));
|
|
266
289
|
};
|
|
267
290
|
const fmtCost = (n) => (n == null || isNaN(n)) ? '—' : '$' + n.toFixed(2);
|
|
291
|
+
const fmtDur = (ms) => { const v = Math.round((ms || 0) / 1000); if (!isFinite(v) || v < 0) return '—'; const d = Math.floor(v / 86400), h = Math.floor(v % 86400 / 3600), m = Math.floor(v % 3600 / 60), s = v % 60; if (d > 0) return d + 'd' + h + 'h'; if (h > 0) return h + 'h' + String(m).padStart(2, '0') + 'm'; if (m > 0) return m + 'm' + String(s).padStart(2, '0') + 's'; return s + 's'; };
|
|
292
|
+
const esc = (s) => String(s == null ? '' : s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
293
|
+
const fmtSpeed = (n) => (n == null || isNaN(n) || !isFinite(n)) ? '—' : ((n >= 100 ? Math.round(n) : Math.round(n * 10) / 10) + ' tok/s');
|
|
268
294
|
|
|
269
295
|
function barRow(name, value, max, color) {
|
|
270
296
|
const pct = max > 0 ? Math.max(0.5, (value / max) * 100) : 0;
|
|
@@ -307,7 +333,7 @@ function render(d, models, trend) {
|
|
|
307
333
|
const cw = total > 0 ? (m.cacheRead / total) * 100 : 0;
|
|
308
334
|
const w = Math.max(iw + ow + cw, 1);
|
|
309
335
|
return `<tr><td>${m.name}</td><td>${fmt(m.messages)}</td><td>${fmt(m.input)}</td>
|
|
310
|
-
<td>${fmt(m.output)}</td><td>${fmt(m.cacheRead)}</td>
|
|
336
|
+
<td>${fmt(m.output)}</td><td>${fmt(m.cacheRead)}</td><td>${fmtSpeed(m.speed)}</td>
|
|
311
337
|
<td><div class="track" style="height:10px"><div class="stack">
|
|
312
338
|
<div style="width:${(iw / w) * 100}%;background:var(--in)"></div>
|
|
313
339
|
<div style="width:${(ow / w) * 100}%;background:var(--out)"></div>
|
|
@@ -445,6 +471,43 @@ let reportLoading = false;
|
|
|
445
471
|
let reportRetry = 0;
|
|
446
472
|
const MAX_REPORT_RETRIES = 12;
|
|
447
473
|
|
|
474
|
+
function twoBars(name, wallMs, activeMs, maxWall, valText, sub) {
|
|
475
|
+
const w = maxWall > 0 ? Math.max(0.5, (wallMs / maxWall) * 100) : 0;
|
|
476
|
+
const a = maxWall > 0 ? Math.max(0.5, (activeMs / maxWall) * 100) : 0;
|
|
477
|
+
return `<div class="bar-row"><div class="name" title="${esc(sub || '')}">${esc(name)}</div>
|
|
478
|
+
<div><div class="track" style="height:8px;margin-bottom:3px"><div class="fill" style="width:${w}%;background:var(--cache)"></div></div>
|
|
479
|
+
<div class="track" style="height:8px"><div class="fill" style="width:${a}%;background:var(--out)"></div></div></div>
|
|
480
|
+
<div class="val">${valText}</div></div>`;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function renderReportCharts(r) {
|
|
484
|
+
if (!r) return;
|
|
485
|
+
const spd = (r.providers || []).slice().sort((a, b) => (b.speed == null ? -1 : b.speed) - (a.speed == null ? -1 : a.speed));
|
|
486
|
+
const smax = Math.max(0, ...spd.map((p) => p.speed || 0));
|
|
487
|
+
const fullName = (p) => p.provider + '/' + p.model;
|
|
488
|
+
$('speed-bars').innerHTML = spd.length ? spd.map((p) => {
|
|
489
|
+
const pct = smax > 0 && p.speed != null ? Math.max(0.5, (p.speed / smax) * 100) : 0;
|
|
490
|
+
return `<div class="bar-row"><div class="name" title="${esc(fullName(p))}">${esc(fullName(p))}</div>
|
|
491
|
+
<div class="track"><div class="fill" style="width:${pct}%;background:var(--in)"></div></div>
|
|
492
|
+
<div class="val">${fmtSpeed(p.speed)}</div></div>`;
|
|
493
|
+
}).join('') : '<div class="val">—</div>';
|
|
494
|
+
|
|
495
|
+
const agents = r.agents || [];
|
|
496
|
+
const amax = Math.max(0, ...agents.map((a) => a.wallMs || 0));
|
|
497
|
+
$('agent-bars').innerHTML = agents.length ? agents.map((a) =>
|
|
498
|
+
twoBars(a.agent, a.wallMs || 0, a.activeMs || 0, amax,
|
|
499
|
+
fmtDur(a.wallMs) + ' / ' + fmtDur(a.activeMs), (a.sessions || 0) + ' sessions')
|
|
500
|
+
).join('') : '<div class="val">—</div>';
|
|
501
|
+
|
|
502
|
+
const sess = r.sessions || [];
|
|
503
|
+
const xmax = Math.max(0, ...sess.map((s) => s.wallMs || 0));
|
|
504
|
+
$('session-bars').innerHTML = sess.length ? sess.map((s) =>
|
|
505
|
+
twoBars(String(s.id).slice(0, 12), s.wallMs || 0, s.activeMs || 0, xmax,
|
|
506
|
+
fmtDur(s.wallMs) + ' · ' + fmtSpeed(s.speed),
|
|
507
|
+
(s.title || '') + ' · ' + s.agent + ' · ' + s.provider + '/' + s.model + ' · ' + (s.messages || 0) + ' msgs')
|
|
508
|
+
).join('') : '<div class="val">—</div>';
|
|
509
|
+
}
|
|
510
|
+
|
|
448
511
|
function formatReport(jr) {
|
|
449
512
|
const genTime = jr.generatedAt ? new Date(jr.generatedAt).toLocaleTimeString(lang === 'zh-TW' ? 'zh-TW' : 'en', { hour12: false }) : '?';
|
|
450
513
|
const cachedNote = jr.stale ? ' [⟳ ' + t('updating') + ']' : ' [' + t('cachedAt') + ' ' + genTime + ']';
|
|
@@ -473,16 +536,23 @@ function formatReport(jr) {
|
|
|
473
536
|
if (jr.providers && jr.providers.length) {
|
|
474
537
|
out += 'PROVIDERS & MODELS\n';
|
|
475
538
|
jr.providers.forEach((p) => {
|
|
476
|
-
out += ' ' + pad(p.provider + '/' + p.model, 45) + pad(p.sessions + ' sessions', 14) + ' ' + rpad(fmtCost(p.cost), 10) + ' ' + rpad(fmtT(p.tok_in), 8) + ' in / ' + rpad(fmtT(p.tok_out), 8) + ' out cache: ' + rpad(fmtT(p.cache_read), 8) + '\n';
|
|
539
|
+
out += ' ' + pad(p.provider + '/' + p.model, 45) + pad(p.sessions + ' sessions', 14) + ' ' + rpad(fmtCost(p.cost), 10) + ' ' + rpad(fmtT(p.tok_in), 8) + ' in / ' + rpad(fmtT(p.tok_out), 8) + ' out cache: ' + rpad(fmtT(p.cache_read), 8) + ' ' + rpad(fmtSpeed(p.speed), 11) + '\n';
|
|
477
540
|
});
|
|
478
541
|
out += '\n';
|
|
479
542
|
}
|
|
480
543
|
if (jr.agents && jr.agents.length) {
|
|
481
544
|
out += 'AGENTS\n';
|
|
482
545
|
jr.agents.forEach((a) => {
|
|
483
|
-
out += ' ' + pad(a.agent, 45) + pad(a.sessions + ' sessions', 14) + ' ' + rpad(fmtCost(a.cost), 10) + ' ' + rpad(fmtT(a.tok_in), 8) + ' in / ' + rpad(fmtT(a.tok_out), 8) + ' out cache: ' + rpad(fmtT(a.cache_read), 8) + '\n';
|
|
546
|
+
out += ' ' + pad(a.agent, 45) + pad(a.sessions + ' sessions', 14) + ' ' + rpad(fmtCost(a.cost), 10) + ' ' + rpad(fmtT(a.tok_in), 8) + ' in / ' + rpad(fmtT(a.tok_out), 8) + ' out cache: ' + rpad(fmtT(a.cache_read), 8) + ' ' + rpad(fmtSpeed(a.speed), 11) + ' wall:' + rpad(fmtDur(a.wallMs), 9) + 'act:' + rpad(fmtDur(a.activeMs), 9) + '\n';
|
|
484
547
|
});
|
|
485
548
|
}
|
|
549
|
+
if (jr.sessions && jr.sessions.length) {
|
|
550
|
+
out += 'SESSIONS (top ' + jr.sessions.length + ' by wall time)\n';
|
|
551
|
+
jr.sessions.forEach((s) => {
|
|
552
|
+
out += ' ' + pad(String(s.id).slice(0, 12), 13) + pad((s.title || '').slice(0, 28), 29) + pad(s.agent, 9) + pad((s.provider + '/' + s.model).slice(0, 30), 31) + 'wall:' + rpad(fmtDur(s.wallMs), 9) + 'act:' + rpad(fmtDur(s.activeMs), 9) + rpad(s.messages + 'msgs', 8) + rpad(fmtT(s.tok_in), 8) + ' in / ' + rpad(fmtT(s.tok_out), 8) + ' out ' + rpad(fmtSpeed(s.speed), 11) + ' ' + rpad(fmtCost(s.cost), 10) + '\n';
|
|
553
|
+
});
|
|
554
|
+
out += '\n';
|
|
555
|
+
}
|
|
486
556
|
return out || 'No data for this period.';
|
|
487
557
|
}
|
|
488
558
|
|
|
@@ -508,6 +578,7 @@ async function loadReport(days) {
|
|
|
508
578
|
}
|
|
509
579
|
reportRetry = 0;
|
|
510
580
|
$('reportContent').textContent = formatReport(j.report);
|
|
581
|
+
renderReportCharts(j.report);
|
|
511
582
|
} catch (e) {
|
|
512
583
|
$('reportContent').textContent = t('connFail') + ': ' + e.message;
|
|
513
584
|
}
|
package/server.js
CHANGED
|
@@ -96,6 +96,7 @@ function detectSchema(d) {
|
|
|
96
96
|
schema.embeddedTools = mV2;
|
|
97
97
|
schema.session = (sV2 && sV1)
|
|
98
98
|
? `(SELECT v.id AS id, v.agent AS agent, v.model AS model,
|
|
99
|
+
COALESCE(v.title, s.title, '') AS title,
|
|
99
100
|
v.time_created AS time_created,
|
|
100
101
|
MAX(v.time_updated, COALESCE(s.time_updated, 0)) AS time_updated,
|
|
101
102
|
MAX(v.tokens_input, COALESCE(s.tokens_input, 0)) AS tokens_input,
|
|
@@ -106,7 +107,7 @@ function detectSchema(d) {
|
|
|
106
107
|
MAX(v.cost, COALESCE(s.cost, 0)) AS cost
|
|
107
108
|
FROM session_v2 v LEFT JOIN session s ON s.id = v.id
|
|
108
109
|
UNION ALL
|
|
109
|
-
SELECT id, agent, model, time_created, time_updated, tokens_input, tokens_output,
|
|
110
|
+
SELECT id, agent, model, title, time_created, time_updated, tokens_input, tokens_output,
|
|
110
111
|
tokens_reasoning, tokens_cache_read, tokens_cache_write, cost
|
|
111
112
|
FROM session WHERE id NOT IN (SELECT id FROM session_v2))`
|
|
112
113
|
: sV2 ? 'session_v2' : 'session';
|
|
@@ -292,13 +293,13 @@ function attributeUsage(startMs, endMs) {
|
|
|
292
293
|
const perAgent = {};
|
|
293
294
|
const perSession = {};
|
|
294
295
|
const ensureDay = (key) => perDay[key] || (perDay[key] = { date: dateOfKey(key), sessions: new Set(), messages: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
|
|
295
|
-
const ensureModel = (n) => perModel[n] || (perModel[n] = { messages: 0, sessions: new Set(), input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
|
|
296
|
+
const ensureModel = (n) => perModel[n] || (perModel[n] = { messages: 0, sessions: new Set(), input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0, speedOut: 0, speedMs: 0 });
|
|
296
297
|
const ensureAgent = (a) => perAgent[a || 'unknown'] || (perAgent[a || 'unknown'] = { messages: 0, sessions: new Set(), input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
|
|
297
298
|
|
|
298
299
|
// 1. messages in period (exact timing)
|
|
299
300
|
const msgTok = {};
|
|
300
301
|
const msgW = {};
|
|
301
|
-
const mrows = dbQuery(`SELECT time_created AS t, session_id AS sid, COALESCE(json_extract(data, '$.agent'), 'unknown') AS agent, COALESCE(json_extract(data, '$.providerID'), json_extract(data, '$.model.providerID'), 'unknown') AS provider, COALESCE(json_extract(data, '$.modelID'), json_extract(data, '$.model.modelID'), json_extract(data, '$.model.id'), 'unknown') AS model, COALESCE(CAST(json_extract(data, '$.tokens.input') AS INTEGER), 0) AS input, COALESCE(CAST(json_extract(data, '$.tokens.output') AS INTEGER), 0) AS output, COALESCE(CAST(json_extract(data, '$.tokens.reasoning') AS INTEGER), 0) AS reasoning, COALESCE(CAST(json_extract(data, '$.tokens.cache.read') AS INTEGER), 0) AS cacheRead, COALESCE(CAST(json_extract(data, '$.tokens.cache.write') AS INTEGER), 0) AS cacheWrite, COALESCE(CAST(json_extract(data, '$.cost') AS REAL), 0) AS cost FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${endMs};`) || [];
|
|
302
|
+
const mrows = dbQuery(`SELECT time_created AS t, session_id AS sid, COALESCE(json_extract(data, '$.agent'), 'unknown') AS agent, COALESCE(json_extract(data, '$.providerID'), json_extract(data, '$.model.providerID'), 'unknown') AS provider, COALESCE(json_extract(data, '$.modelID'), json_extract(data, '$.model.modelID'), json_extract(data, '$.model.id'), 'unknown') AS model, COALESCE(CAST(json_extract(data, '$.tokens.input') AS INTEGER), 0) AS input, COALESCE(CAST(json_extract(data, '$.tokens.output') AS INTEGER), 0) AS output, COALESCE(CAST(json_extract(data, '$.tokens.reasoning') AS INTEGER), 0) AS reasoning, COALESCE(CAST(json_extract(data, '$.tokens.cache.read') AS INTEGER), 0) AS cacheRead, COALESCE(CAST(json_extract(data, '$.tokens.cache.write') AS INTEGER), 0) AS cacheWrite, COALESCE(CAST(json_extract(data, '$.cost') AS REAL), 0) AS cost, CAST(json_extract(data, '$.time.created') AS INTEGER) AS t0, CAST(json_extract(data, '$.time.completed') AS INTEGER) AS t1 FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${endMs};`) || [];
|
|
302
303
|
for (const r of mrows) {
|
|
303
304
|
const key = localDayKey(new Date(r.t));
|
|
304
305
|
const D = ensureDay(key);
|
|
@@ -311,6 +312,10 @@ function attributeUsage(startMs, endMs) {
|
|
|
311
312
|
M.messages++;
|
|
312
313
|
if (r.sid) M.sessions.add(r.sid);
|
|
313
314
|
M.input += iv; M.output += ov; M.reasoning += rv; M.cacheRead += crv; M.cacheWrite += cwv; M.cost += cv;
|
|
315
|
+
// Message-level generation speed only (session residuals have no
|
|
316
|
+
// duration): output tokens per active second over completed messages.
|
|
317
|
+
const t0 = +r.t0 || 0, t1 = +r.t1 || 0;
|
|
318
|
+
if (ov > 0 && t1 > t0) { M.speedOut += ov; M.speedMs += (t1 - t0); }
|
|
314
319
|
const A = ensureAgent(r.agent);
|
|
315
320
|
A.messages++;
|
|
316
321
|
if (r.sid) A.sessions.add(r.sid);
|
|
@@ -454,6 +459,7 @@ function getStatsFromDb(days) {
|
|
|
454
459
|
cacheRead: Math.round(m.cacheRead),
|
|
455
460
|
cacheWrite: Math.round(m.cacheWrite),
|
|
456
461
|
cost: m.cost,
|
|
462
|
+
speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
|
|
457
463
|
}))
|
|
458
464
|
.sort((a, b) => b.cost - a.cost);
|
|
459
465
|
|
|
@@ -510,6 +516,7 @@ function getModelsFromDb() {
|
|
|
510
516
|
cacheRead: Math.round(m.cacheRead),
|
|
511
517
|
cacheWrite: Math.round(m.cacheWrite),
|
|
512
518
|
cost: m.cost,
|
|
519
|
+
speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
|
|
513
520
|
}))
|
|
514
521
|
.sort((a, b) => b.cost - a.cost)
|
|
515
522
|
.slice(0, 10);
|
|
@@ -612,6 +619,14 @@ function buildReportFromDb(days) {
|
|
|
612
619
|
// requested period. This keeps per-day breakdown consistent with the
|
|
613
620
|
// trend chart (which also uses the same full attribution).
|
|
614
621
|
const a = getAttrAll();
|
|
622
|
+
const aNow = attrAllCache.at; // attribution snapshot time: scope message-level stats to it
|
|
623
|
+
// Message-level stats per session within the period (period speed + active
|
|
624
|
+
// time). One GROUP BY over the merged message view, mapped onto the same
|
|
625
|
+
// session-meta buckets as tokens so row sets stay identical.
|
|
626
|
+
const msgAgg = {};
|
|
627
|
+
for (const m of (dbQuery(`SELECT session_id AS sid, COUNT(*) AS n, COALESCE(SUM(CASE WHEN CAST(json_extract(data, '$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data, '$.time.completed') AS INTEGER) > CAST(json_extract(data, '$.time.created') AS INTEGER) THEN CAST(json_extract(data, '$.tokens.output') AS INTEGER) ELSE 0 END), 0) AS o, COALESCE(SUM(CASE WHEN CAST(json_extract(data, '$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data, '$.time.completed') AS INTEGER) > CAST(json_extract(data, '$.time.created') AS INTEGER) THEN CAST(json_extract(data, '$.time.completed') AS INTEGER) - CAST(json_extract(data, '$.time.created') AS INTEGER) ELSE 0 END), 0) AS ms FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${aNow} GROUP BY sid`) || [])) {
|
|
628
|
+
msgAgg[m.sid] = m;
|
|
629
|
+
}
|
|
615
630
|
const periodDays = {};
|
|
616
631
|
for (const [key, val] of Object.entries(a.perDay)) {
|
|
617
632
|
const dayMs = val.date.getTime();
|
|
@@ -658,28 +673,34 @@ function buildReportFromDb(days) {
|
|
|
658
673
|
// above for avg/median.
|
|
659
674
|
if (periodSessionIds.length) {
|
|
660
675
|
const placeholders = periodSessionIds.map(() => '?').join(',');
|
|
661
|
-
const sessMeta = dbQuery(`SELECT id, agent, COALESCE(json_extract(model,'$.providerID'),'unknown') AS provider, COALESCE(json_extract(model,'$.id'),'unknown') AS model FROM ${schema.session} WHERE id IN (${placeholders})`, periodSessionIds) || [];
|
|
676
|
+
const sessMeta = dbQuery(`SELECT id, agent, COALESCE(json_extract(model,'$.providerID'),'unknown') AS provider, COALESCE(json_extract(model,'$.id'),'unknown') AS model, title, time_created AS tc, time_updated AS tu FROM ${schema.session} WHERE id IN (${placeholders})`, periodSessionIds) || [];
|
|
662
677
|
const metaMap = {};
|
|
663
678
|
for (const s of sessMeta) metaMap[s.id] = s;
|
|
664
679
|
|
|
665
680
|
const agentAgg = {};
|
|
666
681
|
const modelAgg = {};
|
|
682
|
+
const sessRows = [];
|
|
667
683
|
for (const sid of periodSessionIds) {
|
|
668
684
|
const ps = a.perSession[sid];
|
|
669
685
|
if (!ps) continue;
|
|
670
686
|
const meta = metaMap[sid] || { agent: 'unknown', provider: 'unknown', model: 'unknown' };
|
|
671
687
|
const agent = meta.agent || 'unknown';
|
|
672
688
|
const modelName = `${meta.provider}/${meta.model}`;
|
|
673
|
-
if (!agentAgg[agent]) agentAgg[agent] = { sessions: new Set(), cost: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0 };
|
|
689
|
+
if (!agentAgg[agent]) agentAgg[agent] = { sessions: new Set(), cost: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, speedOut: 0, speedMs: 0, wallMs: 0, activeMs: 0 };
|
|
674
690
|
agentAgg[agent].sessions.add(sid);
|
|
675
691
|
agentAgg[agent].input += ps.input; agentAgg[agent].output += ps.output;
|
|
676
692
|
agentAgg[agent].reasoning += ps.reasoning; agentAgg[agent].cacheRead += ps.cacheRead;
|
|
677
693
|
agentAgg[agent].cost += ps.cost;
|
|
678
|
-
|
|
694
|
+
const mg = msgAgg[sid] || { n: 0, o: 0, ms: 0 };
|
|
695
|
+
agentAgg[agent].speedOut += mg.o; agentAgg[agent].speedMs += mg.ms; agentAgg[agent].activeMs += mg.ms;
|
|
696
|
+
agentAgg[agent].wallMs += Math.max(0, (meta.tu || 0) - (meta.tc || 0));
|
|
697
|
+
if (!modelAgg[modelName]) modelAgg[modelName] = { sessions: new Set(), cost: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, speedOut: 0, speedMs: 0 };
|
|
679
698
|
modelAgg[modelName].sessions.add(sid);
|
|
680
699
|
modelAgg[modelName].input += ps.input; modelAgg[modelName].output += ps.output;
|
|
681
700
|
modelAgg[modelName].reasoning += ps.reasoning; modelAgg[modelName].cacheRead += ps.cacheRead;
|
|
682
701
|
modelAgg[modelName].cost += ps.cost;
|
|
702
|
+
modelAgg[modelName].speedOut += mg.o; modelAgg[modelName].speedMs += mg.ms;
|
|
703
|
+
sessRows.push({ sid, meta, ps, mg });
|
|
683
704
|
}
|
|
684
705
|
|
|
685
706
|
var pAgentRows = Object.entries(agentAgg)
|
|
@@ -687,6 +708,8 @@ function buildReportFromDb(days) {
|
|
|
687
708
|
agent, sessions: m.sessions.size, cost: r4(m.cost),
|
|
688
709
|
tok_in: Math.round(m.input), tok_out: Math.round(m.output),
|
|
689
710
|
tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
|
|
711
|
+
speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
|
|
712
|
+
wallMs: Math.round(m.wallMs), activeMs: Math.round(m.activeMs),
|
|
690
713
|
}))
|
|
691
714
|
.sort((x, y) => y.cost - x.cost);
|
|
692
715
|
var pProviderRows = Object.entries(modelAgg)
|
|
@@ -696,12 +719,26 @@ function buildReportFromDb(days) {
|
|
|
696
719
|
provider, model, sessions: m.sessions.size, cost: r4(m.cost),
|
|
697
720
|
tok_in: Math.round(m.input), tok_out: Math.round(m.output),
|
|
698
721
|
tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
|
|
722
|
+
speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
|
|
699
723
|
};
|
|
700
724
|
})
|
|
701
725
|
.sort((x, y) => y.cost - x.cost);
|
|
726
|
+
var pSessionRows = sessRows
|
|
727
|
+
.map(({ sid, meta, ps, mg }) => ({
|
|
728
|
+
id: sid, title: (meta.title || '').slice(0, 40), agent: meta.agent || 'unknown',
|
|
729
|
+
provider: meta.provider || 'unknown', model: meta.model || 'unknown',
|
|
730
|
+
wallMs: Math.max(0, (meta.tu || 0) - (meta.tc || 0)),
|
|
731
|
+
activeMs: mg.ms || 0, messages: mg.n || 0,
|
|
732
|
+
tok_in: Math.round(ps.input), tok_out: Math.round(ps.output),
|
|
733
|
+
cost: r4(ps.cost),
|
|
734
|
+
speed: (mg.ms || 0) > 0 ? Math.round(((mg.o || 0) / (mg.ms / 1000)) * 10) / 10 : null,
|
|
735
|
+
}))
|
|
736
|
+
.sort((x, y) => y.wallMs - x.wallMs)
|
|
737
|
+
.slice(0, 20);
|
|
702
738
|
} else {
|
|
703
739
|
var pAgentRows = [];
|
|
704
740
|
var pProviderRows = [];
|
|
741
|
+
var pSessionRows = [];
|
|
705
742
|
}
|
|
706
743
|
|
|
707
744
|
return {
|
|
@@ -710,6 +747,7 @@ function buildReportFromDb(days) {
|
|
|
710
747
|
stats: statsR,
|
|
711
748
|
agents: pAgentRows,
|
|
712
749
|
providers: pProviderRows,
|
|
750
|
+
sessions: pSessionRows,
|
|
713
751
|
generatedAt: now,
|
|
714
752
|
};
|
|
715
753
|
}
|