opencode-statboard 2.9.2 → 2.9.6

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,6 +1,17 @@
1
1
  const { parentPort, workerData } = require('worker_threads');
2
2
  const srv = require('./server.js');
3
3
 
4
+ // I/O throttling parameters (from env, with defaults)
5
+ const ITHROTTLE_BATCH = parseInt(process.env.OPENCODE_ITHROTTLE_BATCH || '1000', 10);
6
+ const ITHROTTLE_DELAY_MS = parseInt(process.env.OPENCODE_ITHROTTLE_DELAY_MS || '5', 10);
7
+
8
+ function throttle(iteration) {
9
+ if (iteration % ITHROTTLE_BATCH === 0) {
10
+ return new Promise((r) => setTimeout(r, ITHROTTLE_DELAY_MS));
11
+ }
12
+ return Promise.resolve();
13
+ }
14
+
4
15
  (async () => {
5
16
  const bundle = await srv.buildAttrBundle(workerData.now || Date.now());
6
17
  bundle.builtAt = workerData.now || Date.now();
package/fix-catch.js ADDED
@@ -0,0 +1,49 @@
1
+ const fs = require('fs');
2
+ const content = fs.readFileSync('server.js', 'utf8');
3
+
4
+ // Find the catch block in the refresh function
5
+ const lines = content.split('\n');
6
+ let inRefresh = false;
7
+ let inCatch = false;
8
+ let catchStart = -1;
9
+ let finallyStart = -1;
10
+
11
+ for (let i = 0; i < lines.length; i++) {
12
+ const line = lines[i];
13
+
14
+ if (line.includes('async function refresh()')) {
15
+ inRefresh = true;
16
+ }
17
+
18
+ if (inRefresh && line.trim() === '} catch (e) {') {
19
+ catchStart = i;
20
+ }
21
+
22
+ if (inRefresh && line.trim() === '} finally {') {
23
+ finallyStart = i;
24
+ break;
25
+ }
26
+ }
27
+
28
+ if (catchStart >= 0 && finallyStart >= 0) {
29
+ // Replace the catch block (from catchStart to finallyStart - 1)
30
+ const newCatchBlock = [
31
+ ' } catch (e) {',
32
+ ' console.error("refresh error:", e);',
33
+ ' state.error = e.message;',
34
+ ' state.loading = false;',
35
+ ' } finally {'
36
+ ];
37
+
38
+ const newLines = [
39
+ ...lines.slice(0, catchStart),
40
+ ...newCatchBlock,
41
+ ...lines.slice(finallyStart + 1)
42
+ ];
43
+
44
+ const newContent = newLines.join('\n');
45
+ fs.writeFileSync('server.js', newContent, 'utf8');
46
+ console.log('Done');
47
+ } else {
48
+ console.log('Could not find catch/finally blocks');
49
+ }
package/fix-refresh.js ADDED
@@ -0,0 +1,8 @@
1
+ const fs = require('fs');
2
+ const content = fs.readFileSync('server.js', 'utf8');
3
+ const newContent = content.replace(
4
+ '} catch (e) {\n state.error = e.message;\n } finally {\n state.busy = false;\n }',
5
+ '} catch (e) {\n console.error("refresh error:", e);\n state.error = e.message;\n state.loading = false;\n } finally {\n state.busy = false;\n }'
6
+ );
7
+ fs.writeFileSync('server.js', newContent, 'utf8');
8
+ console.log('Done');
@@ -0,0 +1,8 @@
1
+ const fs = require('fs');
2
+ const content = fs.readFileSync('server.js', 'utf8');
3
+ const newContent = content.replace(
4
+ '} catch (e) {\n state.error = e.message;\n } finally {\n state.busy = false;\n }',
5
+ '} catch (e) {\n console.error("refresh error:", e);\n state.error = e.message;\n state.loading = false;\n } finally {\n state.busy = false;\n }'
6
+ );
7
+ fs.writeFileSync('server.js', newContent, 'utf8');
8
+ console.log('Done');
@@ -0,0 +1,8 @@
1
+ const fs = require('fs');
2
+ const content = fs.readFileSync('server.js', 'utf8');
3
+ const newContent = content.replace(
4
+ '} catch (e) {\n state.error = e.message;\n } finally {\n state.busy = false;\n }',
5
+ '} catch (e) {\n console.error("refresh error:", e);\n state.error = e.message;\n state.loading = false;\n } finally {\n state.busy = false;\n }'
6
+ );
7
+ fs.writeFileSync('server.js', newContent, 'utf8');
8
+ console.log('Done');
@@ -0,0 +1,65 @@
1
+ const fs = require('fs');
2
+ const content = fs.readFileSync('server.js', 'utf8');
3
+ const oldFunc = `async function refresh() {
4
+ if (state.busy) return;
5
+ state.busy = true;
6
+ try {
7
+ // No bundle yet (first run on this machine, or right after \`npm i -g\`
8
+ // wiped the package dir): the worker is still scanning \uFEFFX which can take
9
+ // 30-60s on a 3GB DB. Publish "loading" instead of an all-zero payload
10
+ // the UI cannot tell apart from real numbers.
11
+ if (!attrAllCache) {
12
+ refreshAttrBundle();
13
+ state.loading = true;
14
+ return;
15
+ }
16
+ const p = getStatsFromDb(0);
17
+ if (p && p.ok) {
18
+ state.data = p;
19
+ state.error = null;
20
+ state.updatedAt = Date.now();
21
+ state.loading = false;
22
+ } else {
23
+ state.error = state.error || 'failed to read database';
24
+ }
25
+ } catch (e) {
26
+ state.error = e.message;
27
+ } finally {
28
+ state.busy = false;
29
+ }
30
+ }`;
31
+ const newFunc = `async function refresh() {
32
+ if (state.busy) return;
33
+ state.busy = true;
34
+ try {
35
+ // No bundle yet (first run on this machine, or right after \`npm i -g\`
36
+ // wiped the package dir): the worker is still scanning \uFEFFX which can take
37
+ // 30-60s on a 3GB DB. Publish "loading" instead of an all-zero payload
38
+ // the UI cannot tell apart from real numbers.
39
+ if (!attrAllCache) {
40
+ refreshAttrBundle();
41
+ state.loading = true;
42
+ return;
43
+ }
44
+ const p = getStatsFromDb(0);
45
+ if (p && p.ok) {
46
+ state.data = p;
47
+ state.error = null;
48
+ state.updatedAt = Date.now();
49
+ state.loading = false;
50
+ } else {
51
+ state.error = state.error || 'failed to read database';
52
+ state.loading = false;
53
+ }
54
+ } catch (e) {
55
+ console.error("refresh error:", e);
56
+ state.error = e.message;
57
+ state.loading = false;
58
+ } finally {
59
+ state.busy = false;
60
+ }
61
+ }`;
62
+ const content = fs.readFileSync('server.js', 'utf8');
63
+ const newContent = content.replace(oldFunc, newFunc);
64
+ fs.writeFileSync('server.js', newContent, 'utf8');
65
+ console.log('Done');
@@ -0,0 +1,64 @@
1
+ const fs = require('fs');
2
+ const oldFunc = `async function refresh() {
3
+ if (state.busy) return;
4
+ state.busy = true;
5
+ try {
6
+ // No bundle yet (first run on this machine, or right after \`npm i -g\`
7
+ // wiped the package dir): the worker is still scanning \uFEFFX which can take
8
+ // 30-60s on a 3GB DB. Publish "loading" instead of an all-zero payload
9
+ // the UI cannot tell apart from real numbers.
10
+ if (!attrAllCache) {
11
+ refreshAttrBundle();
12
+ state.loading = true;
13
+ return;
14
+ }
15
+ const p = getStatsFromDb(0);
16
+ if (p && p.ok) {
17
+ state.data = p;
18
+ state.error = null;
19
+ state.updatedAt = Date.now();
20
+ state.loading = false;
21
+ } else {
22
+ state.error = state.error || 'failed to read database';
23
+ }
24
+ } catch (e) {
25
+ state.error = e.message;
26
+ } finally {
27
+ state.busy = false;
28
+ }
29
+ }`;
30
+ const newFunc = `async function refresh() {
31
+ if (state.busy) return;
32
+ state.busy = true;
33
+ try {
34
+ // No bundle yet (first run on this machine, or right after \`npm i -g\`
35
+ // wiped the package dir): the worker is still scanning \uFEFFX which can take
36
+ // 30-60s on a 3GB DB. Publish "loading" instead of an all-zero payload
37
+ // the UI cannot tell apart from real numbers.
38
+ if (!attrAllCache) {
39
+ refreshAttrBundle();
40
+ state.loading = true;
41
+ return;
42
+ }
43
+ const p = getStatsFromDb(0);
44
+ if (p && p.ok) {
45
+ state.data = p;
46
+ state.error = null;
47
+ state.updatedAt = Date.now();
48
+ state.loading = false;
49
+ } else {
50
+ state.error = state.error || 'failed to read database';
51
+ state.loading = false;
52
+ }
53
+ } catch (e) {
54
+ console.error("refresh error:", e);
55
+ state.error = e.message;
56
+ state.loading = false;
57
+ } finally {
58
+ state.busy = false;
59
+ }
60
+ }`;
61
+ const content = fs.readFileSync('server.js', 'utf8');
62
+ const newContent = content.replace(oldFunc, newFunc);
63
+ fs.writeFileSync('server.js', newContent, 'utf8');
64
+ console.log('Done');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-statboard",
3
- "version": "2.9.2",
3
+ "version": "2.9.6",
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
@@ -92,18 +92,37 @@
92
92
  .trend-wrap > div { flex: 1; min-width: 300px; }
93
93
  .trend-wrap #costSection { min-width: 240px; }
94
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); }
95
+ .heatmap-months { display: flex; gap: 2px; padding-left: 28px; font-size: 11px; color: var(--muted); }
96
96
  .heatmap-months span { flex: 1; text-align: left; overflow: visible; white-space: nowrap; }
97
97
  .heatmap-grid { display: flex; gap: 2px; }
98
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; }
99
+ .hm-cell { width: 14px; height: 14px; border-radius: 2px; background: var(--card2); border: 1px solid var(--border); box-sizing: border-box; }
100
+ /* Heatmap color scale: 10 levels from cool to hot */
100
101
  .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; }
102
+ .hm-cell.hm-1 { background: #0d47a1; } /* Deep blue */
103
+ .hm-cell.hm-2 { background: #1565c0; }
104
+ .hm-cell.hm-2 { background: #1976d2; }
105
+ .hm-cell.hm-3 { background: #1e88e5; }
106
+ .hm-cell.hm-4 { background: #2196f3; }
107
+ .hm-cell.hm-5 { background: #64b5f6; }
108
+ .hm-cell.hm-6 { background: #90caf9; }
109
+ .hm-cell.hm-7 { background: #bbdefb; }
110
+ .hm-cell.hm-8 { background: #e3f2fd; }
111
+ .hm-cell.hm-9 { background: #fff3e0; }
112
+ .hm-cell.hm-10 { background: #ffe0b2; }
113
+ .hm-cell.hm-11 { background: #ffcc80; }
114
+ .hm-cell.hm-12 { background: #ffb74d; }
115
+ .hm-cell.hm-13 { background: #ffa726; }
116
+ .hm-cell.hm-14 { background: #ff9800; }
117
+ .hm-cell.hm-15 { background: #fb8c00; }
118
+ .hm-cell.hm-16 { background: #f57c00; }
119
+ .hm-cell.hm-17 { background: #ef6c00; }
120
+ .hm-cell.hm-18 { background: #e65100; }
121
+ .hm-cell.hm-19 { background: #d84315; }
122
+ .hm-cell.hm-20 { background: #c62828; }
123
+ .hm-cell.hm-21 { background: #b71c1c; }
124
+ .heatmap-legend { display: flex; gap: 4px; align-items: center; font-size: 11px; color: var(--muted); flex-wrap: wrap; }
125
+ .heatmap-legend .hm-cell { width: 12px; height: 12px; }
107
126
  .legend { display: flex; gap: 16px; font-size: 12px; color: var(--muted); margin-bottom: 12px; flex-wrap: wrap; }
108
127
  .legend span { display: flex; align-items: center; gap: 6px; }
109
128
  .sw { width: 12px; height: 12px; border-radius: 3px; display: inline-block; }
@@ -244,10 +263,16 @@
244
263
  <div class="heatmap-legend">
245
264
  <span data-i18n="less">Less</span>
246
265
  <span class="hm-cell hm-0"></span>
247
- <span class="hm-cell hm-1"></span>
248
266
  <span class="hm-cell hm-2"></span>
249
- <span class="hm-cell hm-3"></span>
250
267
  <span class="hm-cell hm-4"></span>
268
+ <span class="hm-cell hm-6"></span>
269
+ <span class="hm-cell hm-8"></span>
270
+ <span class="hm-cell hm-10"></span>
271
+ <span class="hm-cell hm-12"></span>
272
+ <span class="hm-cell hm-14"></span>
273
+ <span class="hm-cell hm-16"></span>
274
+ <span class="hm-cell hm-18"></span>
275
+ <span class="hm-cell hm-20"></span>
251
276
  <span data-i18n="more">More</span>
252
277
  </div>
253
278
  </div>
@@ -821,9 +846,27 @@ function renderHeatmap(data) {
821
846
  const levelOf = (v) => {
822
847
  if (!v || v <= 0) return 0;
823
848
  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;
849
+ // 20 levels for smooth gradient
850
+ if (r >= 0.95) return 20;
851
+ if (r >= 0.90) return 19;
852
+ if (r >= 0.85) return 18;
853
+ if (r >= 0.80) return 17;
854
+ if (r >= 0.75) return 16;
855
+ if (r >= 0.70) return 15;
856
+ if (r >= 0.65) return 14;
857
+ if (r >= 0.60) return 13;
858
+ if (r >= 0.55) return 12;
859
+ if (r >= 0.50) return 11;
860
+ if (r >= 0.45) return 10;
861
+ if (r >= 0.40) return 9;
862
+ if (r >= 0.35) return 9;
863
+ if (r >= 0.30) return 8;
864
+ if (r >= 0.25) return 7;
865
+ if (r >= 0.20) return 6;
866
+ if (r >= 0.15) return 5;
867
+ if (r >= 0.10) return 4;
868
+ if (r >= 0.05) return 3;
869
+ if (r >= 0.02) return 2;
827
870
  return 1;
828
871
  };
829
872
  grid.innerHTML = weeks.map((w) => '<div class="hm-week">' +
@@ -924,6 +967,7 @@ async function poll() {
924
967
  const time = new Date().toLocaleTimeString(lang === 'zh-TW' ? 'zh-TW' : 'en', { hour12: false });
925
968
  lastUpdatedText = t('lastUpdated') + ' ' + time + ' (' + t('dataAgo') + ' ' + ago + 's)';
926
969
  $('updated').textContent = lastUpdatedText;
970
+ refreshCurrentReport(); // auto-refresh report panels
927
971
  return j;
928
972
  } catch (e) {
929
973
  $('updated').textContent = t('connFail') + ': ' + e.message;
@@ -932,6 +976,21 @@ async function poll() {
932
976
  }
933
977
  }
934
978
 
979
+ // Auto-refresh the current scope report when poll succeeds (so all panels stay fresh)
980
+ // Debounced to avoid hammering the API if poll runs frequently
981
+ let reportRefreshDebounce = null;
982
+ async function refreshCurrentReport() {
983
+ if (reportRefreshDebounce) clearTimeout(reportRefreshDebounce);
984
+ reportRefreshDebounce = setTimeout(async () => {
985
+ if (window.__lastReport) {
986
+ try {
987
+ const r = await loadReport(scopeDays);
988
+ if (r) renderReport(r);
989
+ } catch (_) {}
990
+ }
991
+ }, 500); // debounce 500ms
992
+ }
993
+
935
994
  let reportLoading = false;
936
995
  let reportRetry = 0;
937
996
  const MAX_REPORT_RETRIES = 12;
package/server.js CHANGED
@@ -343,8 +343,13 @@ const ATTR_TTL = 300000;
343
343
  // Minimum interval between full scans, regardless of DB revision changes.
344
344
  // Prevents excessive scanning when opencode is actively writing (WAL checkpoints
345
345
  // change DB mtime/size constantly, making revision appear changed every time).
346
- // Default 15 minutes — configurable via OPENCODE_MIN_SCAN_INTERVAL_MS.
347
- const MIN_SCAN_INTERVAL = parseInt(process.env.OPENCODE_MIN_SCAN_INTERVAL_MS || String(15 * 60 * 1000), 10);
346
+ // Default 30 minutes — configurable via OPENCODE_MIN_SCAN_INTERVAL_MS.
347
+ const MIN_SCAN_INTERVAL = parseInt(process.env.OPENCODE_MIN_SCAN_INTERVAL_MS || String(30 * 60 * 1000), 10);
348
+
349
+ // I/O throttling for the attr worker: process N rows, then yield for M ms.
350
+ // Prevents the worker from saturating the disk. Configurable via env vars.
351
+ const ITHROTTLE_BATCH = parseInt(process.env.OPENCODE_ITHROTTLE_BATCH || '1000', 10); // rows per yield
352
+ const ITHROTTLE_DELAY_MS = parseInt(process.env.OPENCODE_ITHROTTLE_DELAY_MS || '5', 10); // ms to sleep
348
353
  // Tool counts change slowly but the embedded-content scan costs ~2.8s on a
349
354
  // 2.7GB live DB, so it is computed by the stats WORKER (see spawnAttrWorker)
350
355
  // and only ever READ here. `fromWorker` marks worker-supplied data, which is
@@ -403,13 +408,14 @@ async function attributeUsage(startMs, endMs, periodStartsMs) {
403
408
  };
404
409
  });
405
410
 
406
- const rows = dbQuery(`SELECT time_created AS t, session_id AS sid, data FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${endMs};`) || [];
411
+ // STREAMING iteration with throttling: use .iterate() instead of .all()
412
+ // to avoid loading all rows into memory at once. Throttle every ITHROTTLE_BATCH rows.
413
+ const stmt = db.prepare(`SELECT time_created AS t, session_id AS sid, data FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${endMs};`);
407
414
  let processed = 0;
408
- for (const row of rows) {
415
+ for (const row of stmt.iterate()) {
409
416
  let d = null;
410
417
  try { d = JSON.parse(row.data); } catch (_) { d = null; }
411
- processed++;
412
- if (!d) continue;
418
+ if (!d) { processed++; continue; }
413
419
  const key = localDayKey(new Date(row.t));
414
420
  const dayMs = dateOfKey(key).getTime();
415
421
  const tk = d.tokens || {};
@@ -472,9 +478,12 @@ async function attributeUsage(startMs, endMs, periodStartsMs) {
472
478
  const ag = sl.msgAgentAgg[agent] || (sl.msgAgentAgg[agent] = { o: 0, ms: 0 });
473
479
  if (hasDur) { ag.o += ov; ag.ms += (t1 - t0); }
474
480
  }
475
- if ((processed & 0x3fff) === 0) await yieldToLoop();
481
+
482
+ // Throttle: yield every ITHROTTLE_BATCH rows to avoid saturating disk
483
+ if ((++processed % ITHROTTLE_BATCH) === 0) await throttle(processed);
476
484
  }
477
485
 
486
+ // Session table: smaller, keep as-is (only ~800 rows)
478
487
  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};`) || [];
479
488
  let sessProcessed = 0;
480
489
  for (const s of srows) {
@@ -574,6 +583,14 @@ let attrLastSave = 0;
574
583
  let attrLastScan = 0; // timestamp of last scan start
575
584
  // Set OPENCODE_ATTR_SCAN_DISABLED=1 to disable background attr scans entirely
576
585
  const ATTR_SCAN_DISABLED = process.env.OPENCODE_ATTR_SCAN_DISABLED === '1';
586
+
587
+ // Throttle helper: yields to event loop after N iterations
588
+ function throttle(iteration) {
589
+ if (iteration % ITHROTTLE_BATCH === 0) {
590
+ return new Promise((r) => setTimeout(r, ITHROTTLE_DELAY_MS));
591
+ }
592
+ return Promise.resolve();
593
+ }
577
594
  const EMPTY_ATTR = {
578
595
  perDay: {}, perModel: {}, perAgent: {}, perSession: {},
579
596
  totals: { sessions: 0, messages: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 },
@@ -732,6 +749,8 @@ function getAttrPeriod(startMs) {
732
749
  // cache stores, so the swap-in path is identical either way.
733
750
  function refreshAttrBundle() {
734
751
  if (attrBundlePending) return attrAllCache ? attrAllCache.a : null;
752
+ // Allow completely disabling background attribute scans via env var.
753
+ if (ATTR_SCAN_DISABLED) return attrAllCache ? attrAllCache.a : null;
735
754
  const now = Date.now();
736
755
  if (attrAllCache && now - attrAllCache.at < ATTR_TTL) return attrAllCache.a;
737
756
  // Enforce minimum scan interval to prevent excessive scanning when DB
@@ -1010,7 +1029,9 @@ async function refresh() {
1010
1029
  state.error = state.error || 'failed to read database';
1011
1030
  }
1012
1031
  } catch (e) {
1032
+ console.error("refresh error:", e);
1013
1033
  state.error = e.message;
1034
+ state.loading = false;
1014
1035
  } finally {
1015
1036
  state.busy = false;
1016
1037
  }