opencode-statboard 2.3.0 → 2.3.1

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
@@ -120,7 +120,7 @@ npm install -g opencode-statboard # after the Actions run is green
120
120
  - `better-sqlite3` is a native addon; must match Node.js ABI
121
121
  - `attributeUsage` does a full DB scan (~35k messages); cached 300s via `getAttrAll()`
122
122
  - 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)
123
- - 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)
123
+ - V2 tool counts use `json_each` over `session_message` content (~1.5s full scan), cached 5min via `toolsCache` (the 15s refresh serves cache; verification accepts api<=expected so staleness never fails checks); legacy V1 DBs scan `part` instead
124
124
  - OpenCode V2 writes `cost = 0` for free/subscription providers, so $ totals only reflect paid (per-token billed) usage — same field, not a schema issue
125
125
  - `gzip` compression on all `/api/` responses (>512B, level 1 for speed)
126
126
  - Backup is deferred 30s after startup — heavy disk I/O (500MB copy+compress) during startup causes Windows to terminate the process
package/README.md CHANGED
@@ -11,6 +11,7 @@ Real-time dashboard for your [opencode](https://opencode.ai) token usage and cos
11
11
  - Usage reports: per-agent speed, wall/active time, and top-20 sessions by duration
12
12
  - Savings estimate: market value at paid catalog rates vs actual cost (per-model, per-report, overview cards)
13
13
  - Visual charts for model speed, agent wall/active time, and longest sessions
14
+ - Visual usage-report tables (providers, agents, sessions) with collapsible raw text
14
15
  - Collapsible sections (collapse state remembered in browser)
15
16
  - Daily trend chart (7D / 30D / 90D)
16
17
  - Usage reports: Daily / Weekly / Monthly / All time
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-statboard",
3
- "version": "2.3.0",
3
+ "version": "2.3.1",
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
@@ -36,6 +36,14 @@
36
36
  .bar-row { display: grid; grid-template-columns: 150px 1fr 120px; align-items: center; gap: 12px; padding: 7px 0; font-size: 13px; }
37
37
  .bar-row .name { color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
38
38
  .bar-row .val { text-align: right; font-variant-numeric: tabular-nums; }
39
+ .bar-row.wide { grid-template-columns: minmax(220px, 320px) 1fr 120px; }
40
+ .bar-row.wide .name { font-size: 12px; }
41
+ .scrollx { overflow-x: auto; }
42
+ .scrollx table { min-width: 880px; }
43
+ td.clip { max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
44
+ .rep-head { color: var(--muted); font-size: 12px; margin-bottom: 12px; }
45
+ .rep-hint { color: var(--muted); font-size: 12px; font-weight: 400; }
46
+ .rep-pre { font-family: monospace; font-size: 13px; line-height: 1.6; white-space: pre; overflow-x: auto; color: var(--text); margin: 0; }
39
47
  .track { background: #21262d; border-radius: 4px; height: 12px; overflow: hidden; }
40
48
  .fill { height: 100%; border-radius: 4px; transition: width .6s ease; min-width: 1px; }
41
49
  .stack { display: flex; height: 100%; }
@@ -215,7 +223,7 @@ const STRINGS = {
215
223
  totalCost: 'Total Cost', avgCostDay: 'Avg Cost / Day',
216
224
  avgTokensSession: 'Avg Tokens / Session', medianTokensSession: 'Median Tokens / Session', marketValue: 'Market Value', saved: 'Saved', savings: 'SAVINGS',
217
225
  tokenStats: 'TOKEN STATISTICS', toolUsage: 'TOOL USAGE', modelUsage: 'MODEL USAGE',
218
- thModel: 'Model', thMsgs: 'Messages', thSpeed: 'Speed', thUsage: 'Usage', thCost: 'Cost',
226
+ thModel: 'Model', thMsgs: 'Messages', thSpeed: 'Speed', thUsage: 'Usage', thCost: 'Cost', repProviders: 'PROVIDERS & MODELS', repAgents: 'AGENTS', repSessions: 'SESSIONS', repPricing: 'PRICING BASIS', repRaw: 'RAW TEXT',
219
227
  dailyTrend: 'DAILY TREND ({days} DAYS)',
220
228
  inputDay: 'Input / Day', outputDay: 'Output / Day', cacheReadDay: 'Cache Read / Day', costDay: 'Cost / Day',
221
229
  report: 'USAGE REPORT', all: 'All', daily: 'Daily', weekly: 'Weekly', monthly: 'Monthly', modelSpeed: 'MODEL SPEED', agentTime: 'AGENT TIME', topSessions: 'TOP SESSIONS',
@@ -232,7 +240,7 @@ const STRINGS = {
232
240
  totalCost: '總費用', avgCostDay: '平均費用 / 天',
233
241
  avgTokensSession: '平均 tokens / 場', medianTokensSession: '中位數 tokens / 場', marketValue: '市價', saved: '已節省', savings: '節省金額',
234
242
  tokenStats: 'Tokens 統計', toolUsage: '工具使用', modelUsage: '模型使用',
235
- thModel: '模型', thMsgs: '訊息', thSpeed: '速度', thUsage: '用量', thCost: '費用',
243
+ thModel: '模型', thMsgs: '訊息', thSpeed: '速度', thUsage: '用量', thCost: '費用', repProviders: '供應商與模型', repAgents: '代理', repSessions: '場次', repPricing: '定價依據', repRaw: '原始文字',
236
244
  dailyTrend: '近 {days} 天趨勢',
237
245
  inputDay: 'Input / 天', outputDay: 'Output / 天', cacheReadDay: 'Cache Read / 天', costDay: '費用 / 天',
238
246
  report: '用量報告', all: '全部', daily: '每日', weekly: '每週', monthly: '每月', modelSpeed: '模型速度', agentTime: '代理時間', topSessions: '最長場次',
@@ -513,7 +521,7 @@ function renderReportCharts(r) {
513
521
  const fullName = (p) => p.provider + '/' + p.model;
514
522
  $('speed-bars').innerHTML = spd.length ? spd.map((p) => {
515
523
  const pct = smax > 0 && p.speed != null ? Math.max(0.5, (p.speed / smax) * 100) : 0;
516
- return `<div class="bar-row"><div class="name" title="${esc(fullName(p))}">${esc(fullName(p))}</div>
524
+ return `<div class="bar-row wide"><div class="name" title="${esc(fullName(p))}">${esc(fullName(p))}</div>
517
525
  <div class="track"><div class="fill" style="width:${pct}%;background:var(--in)"></div></div>
518
526
  <div class="val">${fmtSpeed(p.speed)}</div></div>`;
519
527
  }).join('') : '<div class="val">—</div>';
@@ -539,12 +547,61 @@ function renderReportCharts(r) {
539
547
  const pct = mmax > 0 ? Math.max(0.5, ((p.market || 0) / mmax) * 100) : 0;
540
548
  const sv = p.saved == null ? '—' : fmtCost(p.saved) + ' saved';
541
549
  const tip = 'market ' + fmtCost(p.market) + ' · actual ' + fmtCost(p.cost) + ' · via ' + (p.pricedAs || '?');
542
- return `<div class="bar-row"><div class="name" title="${esc(fullName(p))}">${esc(fullName(p))}</div>
550
+ return `<div class="bar-row wide"><div class="name" title="${esc(fullName(p))}">${esc(fullName(p))}</div>
543
551
  <div class="track"><div class="fill" style="width:${pct}%;background:var(--cost)"></div></div>
544
552
  <div class="val" title="${esc(tip)}">${sv}</div></div>`;
545
553
  }).join('') : '<div class="val">—</div>';
546
554
  }
547
555
 
556
+ function repTable(heads, rows) {
557
+ return `<div class="scrollx"><table><thead><tr>${heads.map((h) => `<th>${esc(h)}</th>`).join('')}</tr></thead><tbody>${rows.join('')}</tbody></table></div>`;
558
+ }
559
+
560
+ function repBlock(title, hint, body, isOpen) {
561
+ return `<details class="tool-section"${isOpen ? ' open' : ''}><summary><h2>${esc(title)}</h2><span class="rep-hint">${esc(hint)}</span></summary>${body}</details>`;
562
+ }
563
+
564
+ function renderReportTables(r) {
565
+ const o = (r.stats && r.stats.overview) || {};
566
+ const c = (r.stats && r.stats.cost) || {};
567
+ const genTime = r.generatedAt ? new Date(r.generatedAt).toLocaleTimeString(lang === 'zh-TW' ? 'zh-TW' : 'en', { hour12: false }) : '?';
568
+ const periodText = r.days === -1 ? 'All time' : r.days <= 1 ? 'Today (local)' : r.days <= 7 ? 'Last 7 days (local)' : 'Month to date (local)';
569
+ let h = `<div class="rep-head">OPENCODE USAGE STATEMENT · ${esc(r.label || '')} · ${esc(periodText)} · ${esc(r.stale ? '⟳ ' + t('updating') : t('cachedAt') + ' ' + genTime)}</div>`;
570
+ h += `<div class="cards">` + [
571
+ [t('sessions'), fmt(o.sessions)], [t('messages'), fmt(o.messages)],
572
+ [t('totalCost'), fmtCost(c.total)], [t('marketValue'), fmtCost(c.marketTotal)],
573
+ [t('saved'), fmtCost(c.savedTotal)],
574
+ ].map(([l, v]) => `<div class="card"><div class="l">${esc(l)}</div><div class="v" style="font-size:20px">${esc(String(v))}</div></div>`).join('') + `</div>`;
575
+
576
+ const prov = r.providers || [];
577
+ h += repBlock(t('repProviders'), prov.length + ' models' + (prov.length ? ' · ' + prov[0].provider + '/' + prov[0].model : ''),
578
+ repTable(['Model', 'Sess', 'Cost', 'In', 'Out', 'Cache', 'Speed', 'Market', 'Saved'], prov.map((p) => {
579
+ const name = p.provider + '/' + p.model;
580
+ return `<tr><td class="clip" title="${esc(name)}">${esc(name)}</td><td>${p.sessions}</td><td>${fmtCost(p.cost)}</td><td>${fmt(p.tok_in)}</td><td>${fmt(p.tok_out)}</td><td>${fmt(p.cache_read)}</td><td>${fmtSpeed(p.speed)}</td><td>${fmtCost(p.market)}</td><td>${fmtCost(p.saved)}</td></tr>`;
581
+ })), true);
582
+
583
+ const ags = r.agents || [];
584
+ h += repBlock(t('repAgents'), ags.length + ' agents' + (ags.length ? ' · ' + ags[0].agent : ''),
585
+ repTable(['Agent', 'Sess', 'Cost', 'In', 'Out', 'Speed', 'Wall', 'Active', 'Market', 'Saved'], ags.map((a) =>
586
+ `<tr><td>${esc(a.agent)}</td><td>${a.sessions}</td><td>${fmtCost(a.cost)}</td><td>${fmt(a.tok_in)}</td><td>${fmt(a.tok_out)}</td><td>${fmtSpeed(a.speed)}</td><td>${fmtDur(a.wallMs)}</td><td>${fmtDur(a.activeMs)}</td><td>${fmtCost(a.market)}</td><td>${fmtCost(a.saved)}</td></tr>`)), true);
587
+
588
+ const sess = r.sessions || [];
589
+ h += repBlock(t('repSessions'), 'top ' + sess.length + ' by wall',
590
+ repTable(['Session', 'Agent', 'Model', 'Wall', 'Active', 'Msgs', 'In', 'Out', 'Speed', 'Saved'], sess.map((s) => {
591
+ const name = s.provider + '/' + s.model;
592
+ return `<tr><td class="clip" title="${esc(s.id + ' · ' + (s.title || ''))}">${esc(String(s.id).slice(0, 12))}</td><td>${esc(s.agent)}</td><td class="clip" title="${esc(name)}">${esc(name)}</td><td>${fmtDur(s.wallMs)}</td><td>${fmtDur(s.activeMs)}</td><td>${s.messages}</td><td>${fmt(s.tok_in)}</td><td>${fmt(s.tok_out)}</td><td>${fmtSpeed(s.speed)}</td><td>${fmtCost(s.saved)}</td></tr>`;
593
+ })), true);
594
+
595
+ const basis = prov.filter((p) => p.pricedAs && p.pricedAs !== (p.provider + '/' + p.model));
596
+ if (basis.length) {
597
+ h += repBlock(t('repPricing'), basis.length + ' mappings',
598
+ repTable(['Usage', 'Basis'], basis.map((p) =>
599
+ `<tr><td class="clip" title="${esc(p.provider + '/' + p.model)}">${esc(p.provider + '/' + p.model)}</td><td class="clip" title="${esc(p.pricedAs)}">${esc(p.pricedAs)}</td></tr>`)), false);
600
+ }
601
+ h += repBlock(t('repRaw'), 'statement text', `<pre class="rep-pre">${esc(formatReport(r))}</pre>`, false);
602
+ return h;
603
+ }
604
+
548
605
  function formatReport(jr) {
549
606
  const genTime = jr.generatedAt ? new Date(jr.generatedAt).toLocaleTimeString(lang === 'zh-TW' ? 'zh-TW' : 'en', { hour12: false }) : '?';
550
607
  const cachedNote = jr.stale ? ' [⟳ ' + t('updating') + ']' : ' [' + t('cachedAt') + ' ' + genTime + ']';
@@ -624,7 +681,7 @@ async function loadReport(days) {
624
681
  return;
625
682
  }
626
683
  reportRetry = 0;
627
- $('reportContent').textContent = formatReport(j.report);
684
+ $('reportContent').innerHTML = renderReportTables(j.report);
628
685
  renderReportCharts(j.report);
629
686
  } catch (e) {
630
687
  $('reportContent').textContent = t('connFail') + ': ' + e.message;
package/server.js CHANGED
@@ -16,6 +16,7 @@ const PORT = parseInt(process.env.OC_PORT || '4868', 10);
16
16
  const REFRESH_MS = 15000;
17
17
  const TREND_MS = 60 * 1000;
18
18
  const REPORT_TTL = 10 * 60 * 1000;
19
+ const TOOLS_TTL = 5 * 60 * 1000;
19
20
  const STATS_TTL = 10 * 60 * 1000;
20
21
  const CACHE_CLEANUP_MS = 5 * 60 * 1000;
21
22
  const BACKUP_DIR = path.join(__dirname, 'backups');
@@ -402,6 +403,9 @@ function attributeUsage(startMs, endMs) {
402
403
  // All-time attribution, memoized 300s (expensive full DB scan; avoids
403
404
  // re-running attributeUsage on every /api/stats hit).
404
405
  let attrAllCache = null;
406
+ // Tool counts change slowly but the embedded-content scan costs ~1.5s on a
407
+ // large DB; cache it so the 15s refresh stays cheap. Keyed on schema+window.
408
+ let toolsCache = null;
405
409
  function getAttrAll() {
406
410
  const now = Date.now();
407
411
  if (attrAllCache && now - attrAllCache.at < 300000) return attrAllCache.a;
@@ -436,16 +440,21 @@ function getStatsFromDb(days) {
436
440
  // V2: tool parts are embedded in session_message content (part table froze
437
441
  // at the upgrade and its migrated rows were rebuilt into content, so
438
442
  // querying all of part would double count — only parts of messages that
439
- // were never migrated are added from `part`).
440
- const toolRows = schema.embeddedTools
441
- ? dbQuery(`SELECT COALESCE(json_extract(je.value, '$.tool'), json_extract(je.value, '$.name')) AS tool FROM session_message sm, json_each(json_extract(sm.data, '$.content')) je WHERE json_extract(je.value, '$.type') = 'tool' ${startMs ? `AND sm.time_updated >= ${startMs}` : ''}
442
- UNION ALL
443
- SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' AND p.message_id NOT IN (SELECT id FROM session_message) ${startMs ? `AND p.time_updated >= ${startMs}` : ''};`) || []
444
- : dbQuery(`SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' ${timeFilterPart};`) || [];
445
- const toolCounts = {};
446
- for (const row of toolRows) {
447
- if (row.tool) toolCounts[row.tool] = (toolCounts[row.tool] || 0) + 1;
443
+ // were never migrated are added from `part`). Cached (see toolsCache):
444
+ // verification accepts api<=expected, so staleness never fails checks.
445
+ if (!toolsCache || now - toolsCache.at > TOOLS_TTL || toolsCache.embedded !== schema.embeddedTools || toolsCache.startMs !== startMs) {
446
+ const toolRows = schema.embeddedTools
447
+ ? dbQuery(`SELECT COALESCE(json_extract(je.value, '$.tool'), json_extract(je.value, '$.name')) AS tool FROM session_message sm, json_each(json_extract(sm.data, '$.content')) je WHERE json_extract(je.value, '$.type') = 'tool' ${startMs ? `AND sm.time_updated >= ${startMs}` : ''}
448
+ UNION ALL
449
+ SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' AND p.message_id NOT IN (SELECT id FROM session_message) ${startMs ? `AND p.time_updated >= ${startMs}` : ''};`) || []
450
+ : dbQuery(`SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' ${timeFilterPart};`) || [];
451
+ const counts = {};
452
+ for (const row of toolRows) {
453
+ if (row.tool) counts[row.tool] = (counts[row.tool] || 0) + 1;
454
+ }
455
+ toolsCache = { at: now, embedded: schema.embeddedTools, startMs, counts };
448
456
  }
457
+ const toolCounts = toolsCache.counts;
449
458
  const totalToolUse = Object.values(toolCounts).reduce((s, v) => s + v, 0) || 1;
450
459
  const tools = Object.entries(toolCounts)
451
460
  .map(([name, count]) => ({ name, count, pct: Math.round((count / totalToolUse) * 1000) / 10 }))
@@ -838,7 +847,7 @@ const server = http.createServer(async (req, res) => {
838
847
  for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);
839
848
  if (useGzip && payload.length > 512) {
840
849
  res.setHeader('Content-Encoding', 'gzip');
841
- const compressed = zlib.gzipSync(Buffer.from(payload), { level: 6 });
850
+ const compressed = zlib.gzipSync(Buffer.from(payload), { level: 1 });
842
851
  res.end(compressed);
843
852
  } else {
844
853
  res.end(payload);