opencode-statboard 2.0.9 → 2.1.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 CHANGED
@@ -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
 
@@ -115,8 +117,8 @@ npm install -g opencode-statboard # after the Actions run is green
115
117
  ## Known Constraints
116
118
 
117
119
  - `better-sqlite3` is a native addon; must match Node.js ABI
118
- - `attributeUsage` does a full DB scan (~31k messages); cached 300s via `getAttrAll()`
119
- - Trend and report share the same `getAttrAll()` cache so daily values are consistent
120
+ - `attributeUsage` does a full DB scan (~35k messages); cached 300s via `getAttrAll()`
121
+ - Trend buckets are sliced from the same `getAttrAll()` attribution the report uses — never a separate windowed call (windowed calls inflate in-window days via residual growth; fixed 2026-09-29 after measuring +0.25–1.7M input/day). Remaining panel differences are cache ages only (trend ≤60s, report ≤10min, both timestamps shown)
120
122
  - V2 tool counts use `json_each` over `session_message` content (~1.2s full scan) and run on every 15s refresh; legacy V1 DBs scan `part` instead (~0.8s)
121
123
  - OpenCode V2 writes `cost = 0` for free/subscription providers, so $ totals only reflect paid (per-token billed) usage — same field, not a schema issue
122
124
  - `gzip` compression on all `/api/` responses (>512B, level 1 for speed)
package/README.md CHANGED
@@ -7,7 +7,8 @@ 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
11
12
  - Daily trend chart (7D / 30D / 90D)
12
13
  - Usage reports: Daily / Weekly / Monthly / All time
13
14
  - 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.9",
3
+ "version": "2.1.0",
4
4
  "description": "Real-time dashboard for opencode token usage and cost statistics",
5
5
  "main": "server.js",
6
6
  "bin": {
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>
@@ -182,7 +182,7 @@ const STRINGS = {
182
182
  totalCost: 'Total Cost', avgCostDay: 'Avg Cost / Day',
183
183
  avgTokensSession: 'Avg Tokens / Session', medianTokensSession: 'Median Tokens / Session',
184
184
  tokenStats: 'TOKEN STATISTICS', toolUsage: 'TOOL USAGE', modelUsage: 'MODEL USAGE',
185
- thModel: 'Model', thMsgs: 'Messages', thUsage: 'Usage', thCost: 'Cost',
185
+ thModel: 'Model', thMsgs: 'Messages', thSpeed: 'Speed', thUsage: 'Usage', thCost: 'Cost',
186
186
  dailyTrend: 'DAILY TREND ({days} DAYS)',
187
187
  inputDay: 'Input / Day', outputDay: 'Output / Day', cacheReadDay: 'Cache Read / Day', costDay: 'Cost / Day',
188
188
  report: 'USAGE REPORT', all: 'All', daily: 'Daily', weekly: 'Weekly', monthly: 'Monthly',
@@ -199,7 +199,7 @@ const STRINGS = {
199
199
  totalCost: '總費用', avgCostDay: '平均費用 / 天',
200
200
  avgTokensSession: '平均 tokens / 場', medianTokensSession: '中位數 tokens / 場',
201
201
  tokenStats: 'Tokens 統計', toolUsage: '工具使用', modelUsage: '模型使用',
202
- thModel: '模型', thMsgs: '訊息', thUsage: '用量', thCost: '費用',
202
+ thModel: '模型', thMsgs: '訊息', thSpeed: '速度', thUsage: '用量', thCost: '費用',
203
203
  dailyTrend: '近 {days} 天趨勢',
204
204
  inputDay: 'Input / 天', outputDay: 'Output / 天', cacheReadDay: 'Cache Read / 天', costDay: '費用 / 天',
205
205
  report: '用量報告', all: '全部', daily: '每日', weekly: '每週', monthly: '每月',
@@ -265,6 +265,7 @@ const fmt = (n) => {
265
265
  return String(Math.round(n));
266
266
  };
267
267
  const fmtCost = (n) => (n == null || isNaN(n)) ? '—' : '$' + n.toFixed(2);
268
+ const fmtSpeed = (n) => (n == null || isNaN(n) || !isFinite(n)) ? '—' : ((n >= 100 ? Math.round(n) : Math.round(n * 10) / 10) + ' tok/s');
268
269
 
269
270
  function barRow(name, value, max, color) {
270
271
  const pct = max > 0 ? Math.max(0.5, (value / max) * 100) : 0;
@@ -307,7 +308,7 @@ function render(d, models, trend) {
307
308
  const cw = total > 0 ? (m.cacheRead / total) * 100 : 0;
308
309
  const w = Math.max(iw + ow + cw, 1);
309
310
  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>
311
+ <td>${fmt(m.output)}</td><td>${fmt(m.cacheRead)}</td><td>${fmtSpeed(m.speed)}</td>
311
312
  <td><div class="track" style="height:10px"><div class="stack">
312
313
  <div style="width:${(iw / w) * 100}%;background:var(--in)"></div>
313
314
  <div style="width:${(ow / w) * 100}%;background:var(--out)"></div>
@@ -338,12 +339,13 @@ function renderTrend(data) {
338
339
  const maxAll = Math.max(...data.input, ...data.output, ...(data.reasoning || []), ...data.cacheRead);
339
340
  const hasCost = data.cost.some((v) => v >= 0.0001);
340
341
 
342
+ const trendTime = data.generatedAt ? new Date(data.generatedAt).toLocaleTimeString(lang === 'zh-TW' ? 'zh-TW' : 'en', { hour12: false }) : '?';
341
343
  $('trend-tokens').innerHTML = data.labels.map((l, i) => {
342
344
  const hi = maxAll > 0 ? (data.input[i] / maxAll) * 100 : 0;
343
345
  const ho = maxAll > 0 ? (data.output[i] / maxAll) * 100 : 0;
344
346
  const hr = maxAll > 0 && data.reasoning ? (data.reasoning[i] / maxAll) * 100 : 0;
345
347
  const hc = maxAll > 0 ? (data.cacheRead[i] / maxAll) * 100 : 0;
346
- const tip = l + ': In ' + fmt(data.input[i]) + ' · Out ' + fmt(data.output[i]) + ' · Reas ' + fmt(data.reasoning ? data.reasoning[i] : 0) + ' · Cache ' + fmt(data.cacheRead[i]);
348
+ const tip = l + ': In ' + fmt(data.input[i]) + ' · Out ' + fmt(data.output[i]) + ' · Reas ' + fmt(data.reasoning ? data.reasoning[i] : 0) + ' · Cache ' + fmt(data.cacheRead[i]) + ' · ' + trendTime;
347
349
  return `<div class="col" title="${tip}">
348
350
  <div style="display:flex;gap:2px;align-items:flex-end;width:100%;height:170px;justify-content:center">
349
351
  <div style="position:relative;width:100%;height:100%">
@@ -449,6 +451,7 @@ function formatReport(jr) {
449
451
  const cachedNote = jr.stale ? ' [⟳ ' + t('updating') + ']' : ' [' + t('cachedAt') + ' ' + genTime + ']';
450
452
  const fmtCost = (n) => { const v = parseFloat(n); if (isNaN(v)) return '—'; return v === 0 ? '$0.00' : '$' + v.toFixed(4); };
451
453
  const fmtT = (n) => { const v = parseInt(n, 10); if (isNaN(v)) return '—'; if (v >= 1e9) return (v/1e9).toFixed(2)+'B'; if (v >= 1e6) return (v/1e6).toFixed(1)+'M'; if (v >= 1e3) return (v/1e3).toFixed(1)+'K'; return String(v); };
454
+ 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'; };
452
455
  const pad = (s, w) => { s = String(s); return s.length >= w ? s : s + ' '.repeat(w - s.length); };
453
456
  const rpad = (s, w) => { s = String(s); return s.length >= w ? s : ' '.repeat(w - s.length) + s; };
454
457
  let out = '';
@@ -472,16 +475,23 @@ function formatReport(jr) {
472
475
  if (jr.providers && jr.providers.length) {
473
476
  out += 'PROVIDERS & MODELS\n';
474
477
  jr.providers.forEach((p) => {
475
- 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';
478
+ 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';
476
479
  });
477
480
  out += '\n';
478
481
  }
479
482
  if (jr.agents && jr.agents.length) {
480
483
  out += 'AGENTS\n';
481
484
  jr.agents.forEach((a) => {
482
- 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';
485
+ 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';
483
486
  });
484
487
  }
488
+ if (jr.sessions && jr.sessions.length) {
489
+ out += 'SESSIONS (top ' + jr.sessions.length + ' by wall time)\n';
490
+ jr.sessions.forEach((s) => {
491
+ 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';
492
+ });
493
+ out += '\n';
494
+ }
485
495
  return out || 'No data for this period.';
486
496
  }
487
497
 
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';
@@ -207,12 +208,16 @@ function cleanExpiredCache(cache, ttl) {
207
208
  }
208
209
 
209
210
  async function generateTrend(days) {
210
- const now = Date.now();
211
-
212
211
  // Buckets: local midnights, today -> (days-1) days ago.
213
- // Values come from attributeUsage (hybrid message+session-residual
214
- // attribution), so multi-day sessions don't dump everything on one day
215
- // and pruned (message-less) history isn't lost either.
212
+ // Values are sliced from the SHARED all-time attribution (getAttrAll(),
213
+ // the same object the usage report uses) — never a separate windowed
214
+ // attributeUsage call. Windowed attribution inflates in-window days:
215
+ // messages before the window are excluded from msgTok, so the session
216
+ // residual grows and lands entirely on windowed days (measured
217
+ // +0.25–1.7M input/day on 2026-09-29). One shared attribution makes
218
+ // trend buckets and report periods structurally identical; any remaining
219
+ // panel difference is only cache age (trend ≤60s, report ≤10min, both
220
+ // timestamps shown in the UI).
216
221
  const buckets = [];
217
222
  const today = new Date();
218
223
  for (let i = 0; i < days; i++) {
@@ -221,7 +226,7 @@ async function generateTrend(days) {
221
226
  d.setHours(0, 0, 0, 0);
222
227
  buckets.push(d);
223
228
  }
224
- const a = attributeUsage(buckets[buckets.length - 1].getTime(), now);
229
+ const a = getAttrAll();
225
230
  const at = (b, f) => {
226
231
  const D = a.perDay[localDayKey(b)];
227
232
  return D ? D[f] : 0;
@@ -232,7 +237,7 @@ async function generateTrend(days) {
232
237
  };
233
238
 
234
239
  return {
235
- generatedAt: now,
240
+ generatedAt: attrAllCache.at, // attribution build time, not response time
236
241
  step: 1,
237
242
  labels: buckets.map((b) => (b.getMonth() + 1) + '/' + b.getDate()),
238
243
  sessions: buckets.map(sess),
@@ -288,13 +293,13 @@ function attributeUsage(startMs, endMs) {
288
293
  const perAgent = {};
289
294
  const perSession = {};
290
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 });
291
- 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 });
292
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 });
293
298
 
294
299
  // 1. messages in period (exact timing)
295
300
  const msgTok = {};
296
301
  const msgW = {};
297
- 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};`) || [];
298
303
  for (const r of mrows) {
299
304
  const key = localDayKey(new Date(r.t));
300
305
  const D = ensureDay(key);
@@ -307,6 +312,10 @@ function attributeUsage(startMs, endMs) {
307
312
  M.messages++;
308
313
  if (r.sid) M.sessions.add(r.sid);
309
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); }
310
319
  const A = ensureAgent(r.agent);
311
320
  A.messages++;
312
321
  if (r.sid) A.sessions.add(r.sid);
@@ -324,10 +333,9 @@ function attributeUsage(startMs, endMs) {
324
333
  // 2. sessions intersecting the period: spread residual
325
334
  const srows = dbQuery(`SELECT id, agent, COALESCE(json_extract(model, '$.providerID'), 'unknown') AS provider, COALESCE(json_extract(model, '$.id'), 'unknown') AS model, time_created AS tc, time_updated AS tu, tokens_input AS si, tokens_output AS so, tokens_reasoning AS sr, tokens_cache_read AS scr, tokens_cache_write AS scw, cost AS sc FROM ${schema.session} WHERE time_updated >= ${startMs} AND time_created < ${endMs};`) || [];
326
335
  for (const s of srows) {
327
- // Use the session's FULL span for residual distribution so that
328
- // trend (7d window) and report (1d window) distribute the same
329
- // residual across the same days. This keeps daily breakdown
330
- // consistent regardless of the caller's time window.
336
+ // Use the session's FULL span for residual distribution. All consumers
337
+ // share one all-time attribution (getAttrAll), so per-day values are
338
+ // identical whichever period slices them.
331
339
  const d0 = new Date(new Date(s.tc).setHours(0, 0, 0, 0));
332
340
  const d1 = new Date(new Date(s.tu).setHours(0, 0, 0, 0));
333
341
  const spanKeys = [];
@@ -451,6 +459,7 @@ function getStatsFromDb(days) {
451
459
  cacheRead: Math.round(m.cacheRead),
452
460
  cacheWrite: Math.round(m.cacheWrite),
453
461
  cost: m.cost,
462
+ speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
454
463
  }))
455
464
  .sort((a, b) => b.cost - a.cost);
456
465
 
@@ -507,6 +516,7 @@ function getModelsFromDb() {
507
516
  cacheRead: Math.round(m.cacheRead),
508
517
  cacheWrite: Math.round(m.cacheWrite),
509
518
  cost: m.cost,
519
+ speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
510
520
  }))
511
521
  .sort((a, b) => b.cost - a.cost)
512
522
  .slice(0, 10);
@@ -609,6 +619,14 @@ function buildReportFromDb(days) {
609
619
  // requested period. This keeps per-day breakdown consistent with the
610
620
  // trend chart (which also uses the same full attribution).
611
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
+ }
612
630
  const periodDays = {};
613
631
  for (const [key, val] of Object.entries(a.perDay)) {
614
632
  const dayMs = val.date.getTime();
@@ -655,28 +673,34 @@ function buildReportFromDb(days) {
655
673
  // above for avg/median.
656
674
  if (periodSessionIds.length) {
657
675
  const placeholders = periodSessionIds.map(() => '?').join(',');
658
- 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) || [];
659
677
  const metaMap = {};
660
678
  for (const s of sessMeta) metaMap[s.id] = s;
661
679
 
662
680
  const agentAgg = {};
663
681
  const modelAgg = {};
682
+ const sessRows = [];
664
683
  for (const sid of periodSessionIds) {
665
684
  const ps = a.perSession[sid];
666
685
  if (!ps) continue;
667
686
  const meta = metaMap[sid] || { agent: 'unknown', provider: 'unknown', model: 'unknown' };
668
687
  const agent = meta.agent || 'unknown';
669
688
  const modelName = `${meta.provider}/${meta.model}`;
670
- 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 };
671
690
  agentAgg[agent].sessions.add(sid);
672
691
  agentAgg[agent].input += ps.input; agentAgg[agent].output += ps.output;
673
692
  agentAgg[agent].reasoning += ps.reasoning; agentAgg[agent].cacheRead += ps.cacheRead;
674
693
  agentAgg[agent].cost += ps.cost;
675
- if (!modelAgg[modelName]) modelAgg[modelName] = { sessions: new Set(), cost: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0 };
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 };
676
698
  modelAgg[modelName].sessions.add(sid);
677
699
  modelAgg[modelName].input += ps.input; modelAgg[modelName].output += ps.output;
678
700
  modelAgg[modelName].reasoning += ps.reasoning; modelAgg[modelName].cacheRead += ps.cacheRead;
679
701
  modelAgg[modelName].cost += ps.cost;
702
+ modelAgg[modelName].speedOut += mg.o; modelAgg[modelName].speedMs += mg.ms;
703
+ sessRows.push({ sid, meta, ps, mg });
680
704
  }
681
705
 
682
706
  var pAgentRows = Object.entries(agentAgg)
@@ -684,6 +708,8 @@ function buildReportFromDb(days) {
684
708
  agent, sessions: m.sessions.size, cost: r4(m.cost),
685
709
  tok_in: Math.round(m.input), tok_out: Math.round(m.output),
686
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),
687
713
  }))
688
714
  .sort((x, y) => y.cost - x.cost);
689
715
  var pProviderRows = Object.entries(modelAgg)
@@ -693,12 +719,26 @@ function buildReportFromDb(days) {
693
719
  provider, model, sessions: m.sessions.size, cost: r4(m.cost),
694
720
  tok_in: Math.round(m.input), tok_out: Math.round(m.output),
695
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,
696
723
  };
697
724
  })
698
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);
699
738
  } else {
700
739
  var pAgentRows = [];
701
740
  var pProviderRows = [];
741
+ var pSessionRows = [];
702
742
  }
703
743
 
704
744
  return {
@@ -707,6 +747,7 @@ function buildReportFromDb(days) {
707
747
  stats: statsR,
708
748
  agents: pAgentRows,
709
749
  providers: pProviderRows,
750
+ sessions: pSessionRows,
710
751
  generatedAt: now,
711
752
  };
712
753
  }