opencode-statboard 2.8.4 → 2.9.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/attr-worker.js CHANGED
@@ -1,26 +1,25 @@
1
- // Stats worker: runs the heavy, SYNCHRONOUS database work off the request
2
- // thread. Scanning the message table (JSON.parse of ~1GB of content) plus the
3
- // embedded tool-part scan takes 3-29s against a live 2.7GB WAL DB while
4
- // opencode is writing; doing that inline froze the HTTP server for exactly as
5
- // long, which showed up as a slow cold start and stalled scope switches.
6
- //
7
- // It reuses server.js's own scan functions (no duplicated logic): requiring
8
- // server.js as a module skips every server-side side effect (see the
9
- // require.main guard near the bottom of that file).
10
1
  const { parentPort, workerData } = require('worker_threads');
2
+ const fs = require('fs');
11
3
  const srv = require('./server.js');
4
+ const dbg = (s) => fs.appendFileSync('C:\\Users\\CPXru\\Desktop\\thumb\\大拇哥實驗室\\Projects\\oc-stats\\worker-debug.txt', s + '\n');
5
+ dbg('WORKER STARTED; BACKUP_SRC=' + (srv.BACKUP_SRC || 'NOT EXPORTED') + ' env.OPENCODE_DATA=' + (process.env.OPENCODE_DATA || '(unset)'));
12
6
 
13
7
  (async () => {
14
- const now = workerData.now || Date.now();
15
- const bundle = await srv.buildAttrBundle(now);
16
- bundle.builtAt = now;
8
+ dbg('calling buildAttrBundle...');
9
+ const bundle = await srv.buildAttrBundle(workerData.now || Date.now());
10
+ dbg('bundle done: messages=' + bundle.totals.messages + ' input=' + bundle.totals.input);
11
+ bundle.builtAt = workerData.now || Date.now();
17
12
  const counts = srv.scanToolCounts(workerData.toolsStartMs || 0);
13
+ dbg('tools done: ' + Object.keys(counts).length);
18
14
  parentPort.postMessage({
19
15
  ok: true,
20
- builtAt: now,
16
+ builtAt: bundle.builtAt,
17
+ dbRevision: srv.dbRevision(),
21
18
  json: srv.serializeBundle(bundle, { embedded: srv.getEmbeddedToolsFlag(), startMs: workerData.toolsStartMs || 0, counts }),
22
19
  tools: { embedded: srv.getEmbeddedToolsFlag(), startMs: workerData.toolsStartMs || 0, counts },
23
20
  });
21
+ dbg('posted');
24
22
  })().catch((e) => {
23
+ dbg('CATCH: ' + (e && e.stack ? e.stack : e));
25
24
  parentPort.postMessage({ ok: false, error: (e && e.message) || String(e) });
26
25
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-statboard",
3
- "version": "2.8.4",
3
+ "version": "2.9.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
@@ -91,6 +91,19 @@
91
91
  .trend-wrap { display: flex; gap: 24px; flex-wrap: wrap; }
92
92
  .trend-wrap > div { flex: 1; min-width: 300px; }
93
93
  .trend-wrap #costSection { min-width: 240px; }
94
+ .heatmap-wrap { display: flex; flex-direction: column; gap: 8px; }
95
+ .heatmap-months { display: flex; gap: 2px; padding-left: 22px; font-size: 10px; color: var(--muted); }
96
+ .heatmap-months span { flex: 1; text-align: left; overflow: visible; white-space: nowrap; }
97
+ .heatmap-grid { display: flex; gap: 2px; }
98
+ .heatmap-grid .hm-week { display: flex; flex-direction: column; gap: 2px; }
99
+ .hm-cell { width: 11px; height: 11px; border-radius: 2px; background: var(--card2); border: 1px solid var(--border); box-sizing: border-box; }
100
+ .hm-cell.hm-0 { background: var(--card2); }
101
+ .hm-cell.hm-1 { background: color-mix(in srgb, var(--in) 22%, var(--card2)); }
102
+ .hm-cell.hm-2 { background: color-mix(in srgb, var(--in) 45%, var(--card2)); }
103
+ .hm-cell.hm-3 { background: color-mix(in srgb, var(--in) 70%, var(--card2)); }
104
+ .hm-cell.hm-4 { background: var(--in); }
105
+ .heatmap-legend { display: flex; gap: 6px; align-items: center; font-size: 11px; color: var(--muted); }
106
+ .heatmap-legend .hm-cell { width: 10px; height: 10px; }
94
107
  .legend { display: flex; gap: 16px; font-size: 12px; color: var(--muted); margin-bottom: 12px; flex-wrap: wrap; }
95
108
  .legend span { display: flex; align-items: center; gap: 6px; }
96
109
  .sw { width: 12px; height: 12px; border-radius: 3px; display: inline-block; }
@@ -222,6 +235,24 @@
222
235
  </details>
223
236
 
224
237
  <!-- 3. BREAKDOWN — one table, three sub-tabs, sorted by tokens -->
238
+ <!-- 2b. HEATMAP — daily token intensity, last 90 days -->
239
+ <details class="tool-section" open id="sec-heatmap">
240
+ <summary><h2 data-i18n="heatmap">HEATMAP</h2><span class="scope-tag" id="tag-heatmap"></span></summary>
241
+ <div class="heatmap-wrap">
242
+ <div class="heatmap-months" id="heatmap-months"></div>
243
+ <div class="heatmap-grid" id="heatmap-grid"></div>
244
+ <div class="heatmap-legend">
245
+ <span data-i18n="less">Less</span>
246
+ <span class="hm-cell hm-0"></span>
247
+ <span class="hm-cell hm-1"></span>
248
+ <span class="hm-cell hm-2"></span>
249
+ <span class="hm-cell hm-3"></span>
250
+ <span class="hm-cell hm-4"></span>
251
+ <span data-i18n="more">More</span>
252
+ </div>
253
+ </div>
254
+ </details>
255
+
225
256
  <details class="tool-section" open id="sec-breakdown">
226
257
  <summary><h2 data-i18n="breakdown">BREAKDOWN</h2><span class="scope-tag" id="tag-breakdown"></span></summary>
227
258
  <div class="subtabs" id="bdTabs">
@@ -303,9 +334,9 @@ const STRINGS = {
303
334
  scopeSuffix: { '-1': 'All time', '1': 'Today (local)', '7': 'Last 7 days (local)', '30': 'Month to date (local)' },
304
335
  trendScope: '{n}-day buckets · today leftmost',
305
336
  toolsOther: '{n} more tools',
306
- allTimeTrend: 'All time · 90-day buckets · today leftmost',
337
+ allTimeTrend: 'All time · 90-day buckets · today leftmost', less: 'Less', more: 'More',
307
338
  toolsScope: '{scope} · tool counts are all-time',
308
- headline: 'HEADLINE', trend: 'TREND', breakdown: 'BREAKDOWN', toolUsage: 'TOOLS',
339
+ headline: 'HEADLINE', trend: 'TREND', heatmap: 'HEATMAP', breakdown: 'BREAKDOWN', toolUsage: 'TOOLS', heatmapScope: '90 days',
309
340
  pricingBasis: 'PRICING BASIS', rawText: 'RAW TEXT',
310
341
  rawHint: 'Plain-text statement, same numbers as the tables above.',
311
342
  tokens: 'Tokens', tIn: 'in', tOut: 'out', tReasoning: 'reasoning', tCache: 'cache re-reads', tokensExclCache: 'new tokens (excl. cache re-reads): {v}',
@@ -349,9 +380,9 @@ const STRINGS = {
349
380
  scopeSuffix: { '-1': '全期', '1': '今天(本地)', '7': '近 7 天(本地)', '30': '本月至今(本地)' },
350
381
  trendScope: '{n} 天分桶 · 今天在最左',
351
382
  toolsOther: '其他 {n} 個工具',
352
- allTimeTrend: '全期 · 90 天分桶 · 今天在最左',
383
+ allTimeTrend: '全部 · 90 天桶 · 今天在左', less: '較少', more: '較多',
353
384
  toolsScope: '{scope} · 工具統計一律為全期',
354
- headline: '重點指標', trend: '趨勢', breakdown: '明細', toolUsage: '工具',
385
+ headline: '重點指標', trend: '趨勢', heatmap: '熱力圖', breakdown: '明細', toolUsage: '工具', heatmapScope: '90 天',
355
386
  pricingBasis: '定價依據', rawText: '原始文字',
356
387
  rawHint: '純文字報表,數字與上方表格一致。',
357
388
  tokens: 'Tokens', tIn: '輸入', tOut: '輸出', tReasoning: '推理', tCache: '快取重讀', tokensExclCache: '新 token(不含快取重讀):{v}',
@@ -485,6 +516,7 @@ function applyScopeTags() {
485
516
  $('tag-pricing').textContent = sl;
486
517
  $('tag-raw').textContent = sl;
487
518
  $('tag-trend').textContent = scopeDays === -1 ? t('allTimeTrend') : fmtLang('trendScope', { n: trendDays(scopeDays) });
519
+ $('tag-heatmap').textContent = t('heatmapScope');
488
520
  $('tag-tools').textContent = fmtLang('toolsScope', { scope: sl });
489
521
  $('scopeNow').textContent = sl;
490
522
  $('updated').textContent = lastUpdatedText || t('loading');
@@ -743,6 +775,76 @@ function renderTrend(data) {
743
775
  `<span style="${i % labelStep === 0 ? '' : 'visibility:hidden'}">${esc(l)}</span>`).join('');
744
776
  }
745
777
 
778
+ // ---- heatmap (daily token intensity, last 90 days) ---------------------
779
+ // GitHub-style calendar: one cell per day, colored by how many tokens the
780
+ // models processed that day (input + cache re-reads). Always shows the
781
+ // 90-day window so it stays useful regardless of the global scope.
782
+ let heatmapTrend = null;
783
+ async function loadHeatmap() {
784
+ if (heatmapTrend) return heatmapTrend;
785
+ try {
786
+ const r = await fetch('/api/stats?days=90&_=' + Date.now(), { cache: 'no-store' });
787
+ const j = await r.json();
788
+ if (j && j.trend && j.trend.labels && j.trend.labels.length) {
789
+ heatmapTrend = j.trend;
790
+ return heatmapTrend;
791
+ }
792
+ } catch (_) {}
793
+ return null;
794
+ }
795
+ function renderHeatmap(data) {
796
+ const grid = $('heatmap-grid');
797
+ const months = $('heatmap-months');
798
+ if (!grid) return;
799
+ if (!data || !data.dates || !data.dates.length) {
800
+ grid.innerHTML = ''; months.innerHTML = '';
801
+ return;
802
+ }
803
+ const dates = data.dates;
804
+ const input = data.input || [];
805
+ const cache = data.cacheRead || [];
806
+ const vals = dates.map((d, i) => (input[i] || 0) + (cache[i] || 0));
807
+ const max = Math.max(1, ...vals);
808
+ // Pad leading days so the first date lands on its real weekday (Sun=0).
809
+ const first = new Date(dates[0] + 'T00:00:00');
810
+ const lead = first.getDay(); // 0 Sun .. 6 Sat
811
+ const cells = [];
812
+ for (let i = 0; i < lead; i++) cells.push(null);
813
+ dates.forEach((d, i) => cells.push({ d, v: vals[i] }));
814
+ // Group into weeks of 7 (Sunday-first).
815
+ const weeks = [];
816
+ for (let i = 0; i < cells.length; i += 7) weeks.push(cells.slice(i, i + 7));
817
+ // Pad the last week to 7.
818
+ const last = weeks[weeks.length - 1];
819
+ while (last.length < 7) last.push(null);
820
+
821
+ const levelOf = (v) => {
822
+ if (!v || v <= 0) return 0;
823
+ const r = v / max;
824
+ if (r >= 0.75) return 4;
825
+ if (r >= 0.5) return 3;
826
+ if (r >= 0.25) return 2;
827
+ return 1;
828
+ };
829
+ grid.innerHTML = weeks.map((w) => '<div class="hm-week">' +
830
+ w.map((c) => c
831
+ ? `<div class="hm-cell hm-${levelOf(c.v)}" title="${esc(c.d)} · ${fmt(c.v)}"></div>`
832
+ : '<div class="hm-cell" style="border-color:transparent;background:transparent"></div>').join('') +
833
+ '</div>').join('');
834
+
835
+ // Month labels: one per week-column where the month changes.
836
+ const monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
837
+ let lastMonth = -1;
838
+ months.innerHTML = weeks.map((w) => {
839
+ const firstCell = w.find((c) => c);
840
+ if (!firstCell) return '<span></span>';
841
+ const m = new Date(firstCell.d + 'T00:00:00').getMonth();
842
+ if (m === lastMonth) return '<span></span>';
843
+ lastMonth = m;
844
+ return '<span>' + monthNames[m] + '</span>';
845
+ }).join('');
846
+ }
847
+
746
848
  // ---- tools (all-time; the API cannot slice them) -----------------------
747
849
  // Long tail (48 tools, most under 0.1%) is folded into one "other" row:
748
850
  // a 48-row list of near-empty bars is visual noise, not information.
@@ -781,6 +883,7 @@ function renderAll() {
781
883
  if (window.__lastReport) renderReport(window.__lastReport);
782
884
  const tr = trendCache[trendDays(scopeDays)];
783
885
  renderTrend(tr || null);
886
+ renderHeatmap(heatmapTrend);
784
887
  renderTools(lastTools);
785
888
  }
786
889
 
@@ -977,6 +1080,7 @@ renderAll();
977
1080
  poll();
978
1081
  setInterval(poll, 15000);
979
1082
  loadReport(scopeDays);
1083
+ loadHeatmap().then(renderHeatmap);
980
1084
  </script>
981
1085
  </body>
982
- </html>
1086
+ </html>
package/server.js CHANGED
@@ -244,6 +244,7 @@ async function generateTrend(days) {
244
244
  generatedAt: attrAllCache.at, // attribution build time, not response time
245
245
  step: 1,
246
246
  labels: buckets.map((b) => (b.getMonth() + 1) + '/' + b.getDate()),
247
+ dates: buckets.map((b) => b.toISOString().slice(0, 10)),
247
248
  sessions: buckets.map(sess),
248
249
  input: buckets.map((b) => at(b, 'input')),
249
250
  output: buckets.map((b) => at(b, 'output')),
@@ -602,6 +603,16 @@ const BUNDLE_SAVE_MS = 60000; // don't hammer the disk while chatting
602
603
  function dbFingerprint() {
603
604
  return BACKUP_SRC;
604
605
  }
606
+ // Cheap revision check for the REBUILD decision (distinct from the cache
607
+ // fingerprint above, which is intentionally path-only). Two servers pointed at
608
+ // the same DB see the same revision, so a DB that has not changed since the
609
+ // last scan is never scanned again.
610
+ function dbRevision() {
611
+ try {
612
+ const st = fs.statSync(BACKUP_SRC);
613
+ return `${BACKUP_SRC}|${st.size}|${Math.round(st.mtimeMs)}`;
614
+ } catch (_) { return BACKUP_SRC; }
615
+ }
605
616
  function serializeBundle(a, tools) {
606
617
  // MUST NOT mutate: the caller serializes the LIVE bundle, and swapping a
607
618
  // bucket's `sessions` Set for an array in place would break every later
@@ -623,7 +634,7 @@ function serializeBundle(a, tools) {
623
634
  perAgentPeriod: setToArr(sl.perAgentPeriod),
624
635
  };
625
636
  return JSON.stringify({
626
- v: 2, builtAt: a.builtAt, db: dbFingerprint(), byPeriodStart: a.byPeriodStart,
637
+ v: 2, builtAt: a.builtAt, db: dbFingerprint(), dbRevision: dbRevision(), byPeriodStart: a.byPeriodStart,
627
638
  tools: tools ? { embedded: tools.embedded, startMs: tools.startMs, counts: tools.counts } : null,
628
639
  perDay: days,
629
640
  perModel: setToArr(a.perModel), perAgent: setToArr(a.perAgent),
@@ -711,9 +722,17 @@ function refreshAttrBundle() {
711
722
  if (attrBundlePending) return attrAllCache ? attrAllCache.a : null;
712
723
  const now = Date.now();
713
724
  if (attrAllCache && now - attrAllCache.at < ATTR_TTL) return attrAllCache.a;
725
+ const rev = dbRevision();
726
+ // DB hasn't changed since the last scan: just extend the TTL, no scan.
727
+ // This is the common case on a machine where opencode is idle (which is most
728
+ // of the time), and it turns a 30-60s rebuild into a stat() call.
729
+ if (attrAllCache && rev && attrAllCache.dbRevision === rev) {
730
+ attrAllCache.at = now;
731
+ return attrAllCache.a;
732
+ }
714
733
  attrBundlePending = true;
715
734
  attrWorkerActive = true;
716
- spawnAttrWorker(now);
735
+ spawnAttrWorker(now, rev);
717
736
  return attrAllCache ? attrAllCache.a : null;
718
737
  }
719
738
 
@@ -728,7 +747,7 @@ function waitForBundle(timeoutMs) {
728
747
  });
729
748
  }
730
749
 
731
- function spawnAttrWorker(now) {
750
+ function spawnAttrWorker(now, rev) {
732
751
  // Failure path: unblock waiters and, on a truly cold start, build inline so
733
752
  // the dashboard still shows numbers.
734
753
  function failBundle(msg) {
@@ -748,7 +767,7 @@ function spawnAttrWorker(now) {
748
767
  }
749
768
  let w;
750
769
  try {
751
- w = new Worker(ATTR_WORKER, { workerData: { now, toolsStartMs: 0 } });
770
+ w = new Worker(ATTR_WORKER, { workerData: { now, toolsStartMs: 0, dbRevision: rev } });
752
771
  } catch (e) {
753
772
  // Worker unavailable (very old Node / restricted env): build inline.
754
773
  console.error('attr worker spawn failed, building inline:', e.message);
@@ -764,7 +783,8 @@ function spawnAttrWorker(now) {
764
783
  try {
765
784
  const a = reviveBundle(JSON.parse(m.json));
766
785
  a.builtAt = m.builtAt;
767
- attrAllCache = { at: m.builtAt, a };
786
+ a.dbRevision = m.dbRevision || rev;
787
+ attrAllCache = { at: m.builtAt, a, dbRevision: a.dbRevision };
768
788
  if (m.tools) {
769
789
  toolsCache = { at: m.builtAt, embedded: m.tools.embedded, startMs: 0, counts: m.tools.counts, fromWorker: true };
770
790
  }
@@ -1448,6 +1468,8 @@ if (require.main !== module) {
1448
1468
  serializeBundle,
1449
1469
  reviveBundle,
1450
1470
  scanToolCounts,
1471
+ dbRevision,
1472
+ BACKUP_SRC,
1451
1473
  getEmbeddedToolsFlag: () => schema.embeddedTools,
1452
1474
  };
1453
1475
  return;
@@ -0,0 +1,20 @@
1
+ WORKER STARTED; BACKUP_SRC=C:\Users\CPXru\AppData\Local\Temp\opencode\snap-v28\opencode.db env.OPENCODE_DATA=C:\Users\CPXru\AppData\Local\Temp\opencode\snap-v28
2
+ calling buildAttrBundle...
3
+ bundle done: messages=0 input=0
4
+ tools done: 0
5
+ posted
6
+ WORKER STARTED; BACKUP_SRC=C:\Users\CPXru\AppData\Local\Temp\opencode\snap-v28\opencode.db env.OPENCODE_DATA=C:\Users\CPXru\AppData\Local\Temp\opencode\snap-v28
7
+ calling buildAttrBundle...
8
+ bundle done: messages=0 input=0
9
+ tools done: 0
10
+ posted
11
+ WORKER STARTED; BACKUP_SRC=C:\Users\CPXru\AppData\Local\Temp\opencode\snap-v28\opencode.db env.OPENCODE_DATA=C:\Users\CPXru\AppData\Local\Temp\opencode\snap-v28
12
+ calling buildAttrBundle...
13
+ bundle done: messages=0 input=0
14
+ tools done: 0
15
+ posted
16
+ WORKER STARTED; BACKUP_SRC=C:\Users\CPXru\AppData\Local\Temp\opencode\snap-v30\opencode.db env.OPENCODE_DATA=C:\Users\CPXru\AppData\Local\Temp\opencode\snap-v30
17
+ calling buildAttrBundle...
18
+ bundle done: messages=98508 input=1041461624.0000005
19
+ tools done: 52
20
+ posted