opencode-statboard 2.1.0 → 2.3.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
@@ -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
@@ -42,6 +42,7 @@ Token/cost attribution uses a hybrid model:
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
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
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.
45
+ 5. **Savings estimate (pricing.js, shared with checks)** — Market value at paid rates from the local opencode catalog (`~/.cache/opencode/models.json`, USD/1M). Free models map to a paid basis in order: exact provider/model → strip `-free`/`-contributor-free`, same provider → same base under `opencode` → same base anywhere (sorted) → `proxy:opencode/deepseek-v4-flash` fallback. Reasoning bills at the output rate; `pricedAs` records the entry used per row. Overview and report both use session-meta grouping so the two panels agree (message-level splits would price model-switched sessions differently).
45
46
 
46
47
  This ensures multi-day sessions (e.g. a session created Monday, updated Thursday) don't dump all tokens onto Thursday.
47
48
 
package/README.md CHANGED
@@ -9,6 +9,9 @@ Real-time dashboard for your [opencode](https://opencode.ai) token usage and cos
9
9
  - Tool usage breakdown with percentage bars (collapsible)
10
10
  - Per-model usage with cache read stats and generation speed (output tok/s)
11
11
  - Usage reports: per-agent speed, wall/active time, and top-20 sessions by duration
12
+ - Savings estimate: market value at paid catalog rates vs actual cost (per-model, per-report, overview cards)
13
+ - Visual charts for model speed, agent wall/active time, and longest sessions
14
+ - Collapsible sections (collapse state remembered in browser)
12
15
  - Daily trend chart (7D / 30D / 90D)
13
16
  - Usage reports: Daily / Weekly / Monthly / All time
14
17
  - 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.1.0",
3
+ "version": "2.3.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 pricing.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/pricing.js ADDED
@@ -0,0 +1,94 @@
1
+ // Shared market-price engine for the "how much did I save" feature.
2
+ // Pricing comes from the user's local opencode models catalog
3
+ // (~/.cache/opencode/models.json):
4
+ // { provider: { models: { name: { cost: { input, output, cache_read } } } } }
5
+ // in USD per 1M tokens. Free variants (cost 0) are mapped to a paid basis:
6
+ // 1. exact provider/model with nonzero cost
7
+ // 2. strip -free / -contributor-free suffix, same provider, nonzero cost
8
+ // 3. same base name under provider 'opencode', nonzero cost
9
+ // 4. same base name under any provider (sorted, first nonzero)
10
+ // 5. proxy fallback: opencode/deepseek-v4-flash rates (marked "proxy:")
11
+ // Reasoning tokens have no catalog rate and are billed at the output rate.
12
+ // cache_write is always 0 in the DB and contributes nothing.
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+
16
+ function catalogCandidates() {
17
+ const homes = [process.env.USERPROFILE, process.env.HOME].filter(Boolean);
18
+ const out = [];
19
+ for (const h of homes) out.push(path.join(h, '.cache', 'opencode', 'models.json'));
20
+ return [...new Set(out)];
21
+ }
22
+
23
+ let cache = { mtimeMs: 0, data: null, path: null };
24
+
25
+ function loadCatalog() {
26
+ for (const p of catalogCandidates()) {
27
+ try {
28
+ const st = fs.statSync(p);
29
+ if (cache.data && cache.path === p && cache.mtimeMs === st.mtimeMs) return cache;
30
+ const data = JSON.parse(fs.readFileSync(p, 'utf8'));
31
+ cache = { mtimeMs: st.mtimeMs, data, path: p };
32
+ return cache;
33
+ } catch (_) { /* try next candidate */ }
34
+ }
35
+ cache = { mtimeMs: 0, data: null, path: null };
36
+ return cache;
37
+ }
38
+
39
+ function nonzero(cost) {
40
+ if (!cost) return false;
41
+ return (cost.input || 0) > 0 || (cost.output || 0) > 0 || (cost.cache_read || 0) > 0;
42
+ }
43
+
44
+ function ratesOf(data, provider, model) {
45
+ const cost = data[provider] && data[provider].models && data[provider].models[model] && data[provider].models[model].cost;
46
+ if (!nonzero(cost)) return null;
47
+ return { input: cost.input || 0, output: cost.output || 0, cacheRead: cost.cache_read || 0, source: `${provider}/${model}` };
48
+ }
49
+
50
+ // Map a usage model (provider/model as seen in the DB) to paid rates.
51
+ // Returns { input, output, cacheRead, source, exact } or null when no catalog.
52
+ function priceFor(provider, model) {
53
+ const cat = loadCatalog();
54
+ if (!cat.data) return null;
55
+ const data = cat.data;
56
+ provider = provider || 'unknown';
57
+ model = model || 'unknown';
58
+ let r = ratesOf(data, provider, model);
59
+ if (r) return { ...r, exact: true };
60
+ if (model === 'unknown') {
61
+ const fb = ratesOf(data, 'opencode', 'deepseek-v4-flash');
62
+ return fb ? { ...fb, source: 'proxy:opencode/deepseek-v4-flash', exact: false } : null;
63
+ }
64
+ const base = String(model).replace(/-contributor-free$/, '').replace(/-free$/, '');
65
+ const cands = [];
66
+ if (base !== model) cands.push([provider, base]);
67
+ cands.push(['opencode', base]);
68
+ for (const pid of Object.keys(data).sort()) {
69
+ if (pid !== provider && pid !== 'opencode') cands.push([pid, base]);
70
+ }
71
+ for (const [p, m] of cands) {
72
+ r = ratesOf(data, p, m);
73
+ if (r) return { ...r, exact: false };
74
+ }
75
+ const fb = ratesOf(data, 'opencode', 'deepseek-v4-flash');
76
+ return fb ? { ...fb, source: 'proxy:opencode/deepseek-v4-flash', exact: false } : null;
77
+ }
78
+
79
+ // Market value (USD) of token usage at the given rates.
80
+ function marketOf(tok, rates) {
81
+ if (!rates) return null;
82
+ const m = (tok.input || 0) / 1e6 * rates.input
83
+ + (tok.output || 0) / 1e6 * rates.output
84
+ + (tok.reasoning || 0) / 1e6 * rates.output
85
+ + (tok.cacheRead || 0) / 1e6 * rates.cacheRead;
86
+ return Math.round(m * 10000) / 10000;
87
+ }
88
+
89
+ function catalogInfo() {
90
+ const cat = loadCatalog();
91
+ return cat.data ? { ok: true, path: cat.path, mtimeMs: cat.mtimeMs } : { ok: false };
92
+ }
93
+
94
+ module.exports = { priceFor, marketOf, catalogInfo };
package/public/index.html CHANGED
@@ -90,21 +90,23 @@
90
90
 
91
91
  <div class="error-banner" id="errbanner"></div>
92
92
 
93
- <section>
94
- <h2 data-i18n="overview">OVERVIEW</h2>
93
+ <details class="tool-section" open id="sec-overview">
94
+ <summary><h2 data-i18n="overview">OVERVIEW</h2></summary>
95
95
  <div class="cards">
96
96
  <div class="card"><div class="l" data-i18n="sessions">Sessions</div><div class="v" id="ov-sessions">—</div></div>
97
97
  <div class="card"><div class="l" data-i18n="messages">Messages</div><div class="v" id="ov-messages">—</div></div>
98
98
  <div class="card"><div class="l" data-i18n="days">Days</div><div class="v" id="ov-days">—</div></div>
99
99
  <div class="card"><div class="l" data-i18n="totalCost">Total Cost</div><div class="v" id="ov-total">—</div></div>
100
+ <div class="card"><div class="l" data-i18n="marketValue">Market Value</div><div class="v" id="ov-market">—</div></div>
101
+ <div class="card"><div class="l" data-i18n="saved">Saved</div><div class="v" id="ov-saved">—</div></div>
100
102
  <div class="card"><div class="l" data-i18n="avgCostDay">Avg Cost / Day</div><div class="v" id="ov-avgday">—</div></div>
101
103
  <div class="card"><div class="l" data-i18n="avgTokensSession">Avg Tokens / Session</div><div class="v" id="ov-avg">—</div></div>
102
104
  <div class="card"><div class="l" data-i18n="medianTokensSession">Median Tokens / Session</div><div class="v" id="ov-med">—</div></div>
103
105
  </div>
104
- </section>
106
+ </details>
105
107
 
106
- <section>
107
- <h2 data-i18n="tokenStats">TOKEN STATISTICS</h2>
108
+ <details class="tool-section" open id="sec-tokens">
109
+ <summary><h2 data-i18n="tokenStats">TOKEN STATISTICS</h2></summary>
108
110
  <div class="legend">
109
111
  <span><i class="sw" style="background:var(--in)"></i>Input</span>
110
112
  <span><i class="sw" style="background:var(--out)"></i>Output</span>
@@ -113,32 +115,32 @@
113
115
  <span><i class="sw" style="background:var(--cost)"></i>Cache Write</span>
114
116
  </div>
115
117
  <div id="token-bars"></div>
116
- </section>
118
+ </details>
117
119
 
118
- <details class="tool-section" open>
120
+ <details class="tool-section" open id="sec-tools">
119
121
  <summary><h2 data-i18n="toolUsage">TOOL USAGE</h2></summary>
120
122
  <div id="tool-bars"></div>
121
123
  </details>
122
124
 
123
- <section>
124
- <h2 data-i18n="modelUsage">MODEL USAGE</h2>
125
+ <details class="tool-section" open id="sec-models">
126
+ <summary><h2 data-i18n="modelUsage">MODEL USAGE</h2></summary>
125
127
  <table>
126
128
  <thead>
127
129
  <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
130
  </thead>
129
131
  <tbody id="model-rows"></tbody>
130
132
  </table>
131
- </section>
133
+ </details>
132
134
 
133
- <section>
134
- <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
135
+ <details class="tool-section" open id="sec-trend">
136
+ <summary><div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
135
137
  <h2 id="trendTitle" style="margin:0"></h2>
136
138
  <div class="range-btns" id="rangeBtns">
137
139
  <span class="pill active" data-days="7" onclick="setRange(7)">7D</span>
138
140
  <span class="pill" data-days="30" onclick="setRange(30)">30D</span>
139
141
  <span class="pill" data-days="90" onclick="setRange(90)">90D</span>
140
142
  </div>
141
- </div>
143
+ </div></summary>
142
144
  <div style="display:flex;gap:24px;flex-wrap:wrap">
143
145
  <div style="flex:1;min-width:300px">
144
146
  <div class="legend">
@@ -158,10 +160,10 @@
158
160
  <div id="costZeroNote" style="display:none;font-size:12px;color:var(--muted);padding:20px 0;text-align:center"></div>
159
161
  </div>
160
162
  </div>
161
- </section>
163
+ </details>
162
164
 
163
- <section>
164
- <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
165
+ <details class="tool-section" open id="sec-report">
166
+ <summary><div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
165
167
  <h2 data-i18n="report" style="margin:0">USAGE REPORT</h2>
166
168
  <div class="range-btns" id="reportBtns">
167
169
  <span class="pill" data-days="-1" onclick="loadReport(-1)" data-i18n="all">All</span>
@@ -169,9 +171,40 @@
169
171
  <span class="pill" data-days="7" onclick="loadReport(7)" data-i18n="weekly">Weekly</span>
170
172
  <span class="pill" data-days="30" onclick="loadReport(30)" data-i18n="monthly">Monthly</span>
171
173
  </div>
172
- </div>
174
+ </div></summary>
173
175
  <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
- </section>
176
+ </details>
177
+
178
+ <details class="tool-section" open id="sec-speed">
179
+ <summary><h2 data-i18n="modelSpeed">MODEL SPEED</h2></summary>
180
+ <div id="speed-bars"></div>
181
+ </details>
182
+
183
+ <details class="tool-section" open id="sec-agent">
184
+ <summary><h2 data-i18n="agentTime">AGENT TIME</h2></summary>
185
+ <div class="legend">
186
+ <span><i class="sw" style="background:var(--cache)"></i>wall</span>
187
+ <span><i class="sw" style="background:var(--out)"></i>active</span>
188
+ </div>
189
+ <div id="agent-bars"></div>
190
+ </details>
191
+
192
+ <details class="tool-section" open id="sec-sessions">
193
+ <summary><h2 data-i18n="topSessions">TOP SESSIONS</h2></summary>
194
+ <div class="legend">
195
+ <span><i class="sw" style="background:var(--cache)"></i>wall</span>
196
+ <span><i class="sw" style="background:var(--out)"></i>active</span>
197
+ </div>
198
+ <div id="session-bars"></div>
199
+ </details>
200
+
201
+ <details class="tool-section" open id="sec-savings">
202
+ <summary><h2 data-i18n="savings">SAVINGS</h2></summary>
203
+ <div class="legend">
204
+ <span><i class="sw" style="background:var(--cost)"></i>market value</span>
205
+ </div>
206
+ <div id="savings-bars"></div>
207
+ </details>
175
208
 
176
209
  <script>
177
210
  const STRINGS = {
@@ -180,12 +213,12 @@ const STRINGS = {
180
213
  overview: 'OVERVIEW',
181
214
  sessions: 'Sessions', messages: 'Messages', days: 'Days',
182
215
  totalCost: 'Total Cost', avgCostDay: 'Avg Cost / Day',
183
- avgTokensSession: 'Avg Tokens / Session', medianTokensSession: 'Median Tokens / Session',
216
+ avgTokensSession: 'Avg Tokens / Session', medianTokensSession: 'Median Tokens / Session', marketValue: 'Market Value', saved: 'Saved', savings: 'SAVINGS',
184
217
  tokenStats: 'TOKEN STATISTICS', toolUsage: 'TOOL USAGE', modelUsage: 'MODEL USAGE',
185
218
  thModel: 'Model', thMsgs: 'Messages', thSpeed: 'Speed', thUsage: 'Usage', thCost: 'Cost',
186
219
  dailyTrend: 'DAILY TREND ({days} DAYS)',
187
220
  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',
221
+ report: 'USAGE REPORT', all: 'All', daily: 'Daily', weekly: 'Weekly', monthly: 'Monthly', modelSpeed: 'MODEL SPEED', agentTime: 'AGENT TIME', topSessions: 'TOP SESSIONS',
189
222
  updating: 'updating…', generating: 'Generating trend data…', cachedAt: 'cached at', allFree: 'All models free — no cost recorded',
190
223
  live: 'Live', loading: 'Loading…', lastUpdated: 'Last updated', dataAgo: 'data generated',
191
224
  statsFail: 'Failed to read opencode stats', connFail: 'Connection failed',
@@ -197,12 +230,12 @@ const STRINGS = {
197
230
  overview: '概覽',
198
231
  sessions: '工作階段', messages: '訊息數', days: '使用天數',
199
232
  totalCost: '總費用', avgCostDay: '平均費用 / 天',
200
- avgTokensSession: '平均 tokens / 場', medianTokensSession: '中位數 tokens / 場',
233
+ avgTokensSession: '平均 tokens / 場', medianTokensSession: '中位數 tokens / 場', marketValue: '市價', saved: '已節省', savings: '節省金額',
201
234
  tokenStats: 'Tokens 統計', toolUsage: '工具使用', modelUsage: '模型使用',
202
235
  thModel: '模型', thMsgs: '訊息', thSpeed: '速度', thUsage: '用量', thCost: '費用',
203
236
  dailyTrend: '近 {days} 天趨勢',
204
237
  inputDay: 'Input / 天', outputDay: 'Output / 天', cacheReadDay: 'Cache Read / 天', costDay: '費用 / 天',
205
- report: '用量報告', all: '全部', daily: '每日', weekly: '每週', monthly: '每月',
238
+ report: '用量報告', all: '全部', daily: '每日', weekly: '每週', monthly: '每月', modelSpeed: '模型速度', agentTime: '代理時間', topSessions: '最長場次',
206
239
  updating: '更新中…', generating: '趨勢資料產生中…', cachedAt: '快取於', allFree: '全部使用免費模型,無費用紀錄',
207
240
  live: '即時更新', loading: '載入中…', lastUpdated: '更新於', dataAgo: '數據產生於',
208
241
  statsFail: 'opencode stats 讀取失敗', connFail: '連線失敗',
@@ -226,6 +259,20 @@ function applyI18n() {
226
259
  $('trendTitle').textContent = t('dailyTrend').replace('{days}', currentDays);
227
260
  }
228
261
 
262
+ function restoreSections() {
263
+ document.querySelectorAll('#rangeBtns .pill, #reportBtns .pill').forEach((el) => {
264
+ el.addEventListener('click', (e) => e.stopPropagation());
265
+ });
266
+ document.querySelectorAll('details.tool-section[id]').forEach((el) => {
267
+ try {
268
+ if (localStorage.getItem('oc-sec-' + el.id) === '0') el.removeAttribute('open');
269
+ el.addEventListener('toggle', () => {
270
+ try { localStorage.setItem('oc-sec-' + el.id, el.open ? '1' : '0'); } catch (_) {}
271
+ });
272
+ } catch (_) {}
273
+ });
274
+ }
275
+
229
276
  function toggleLang() {
230
277
  lang = lang === 'en' ? 'zh-TW' : 'en';
231
278
  localStorage.setItem('lang', lang);
@@ -265,6 +312,8 @@ const fmt = (n) => {
265
312
  return String(Math.round(n));
266
313
  };
267
314
  const fmtCost = (n) => (n == null || isNaN(n)) ? '—' : '$' + n.toFixed(2);
315
+ 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'; };
316
+ const esc = (s) => String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
268
317
  const fmtSpeed = (n) => (n == null || isNaN(n) || !isFinite(n)) ? '—' : ((n >= 100 ? Math.round(n) : Math.round(n * 10) / 10) + ' tok/s');
269
318
 
270
319
  function barRow(name, value, max, color) {
@@ -280,6 +329,8 @@ function render(d, models, trend) {
280
329
  $('ov-messages').textContent = fmt(o.messages);
281
330
  $('ov-days').textContent = fmt(o.days);
282
331
  $('ov-total').textContent = fmtCost(d.cost && d.cost.total);
332
+ $('ov-market').textContent = fmtCost(d.cost && d.cost.marketTotal);
333
+ $('ov-saved').textContent = fmtCost(d.cost && d.cost.savedTotal);
283
334
  $('ov-avgday').textContent = fmtCost(d.cost && d.cost.avgDay);
284
335
  $('ov-avg').textContent = fmt(d.cost && d.cost.avgTokensSession);
285
336
  $('ov-med').textContent = fmt(d.cost && d.cost.medianTokensSession);
@@ -446,12 +497,59 @@ let reportLoading = false;
446
497
  let reportRetry = 0;
447
498
  const MAX_REPORT_RETRIES = 12;
448
499
 
500
+ function twoBars(name, wallMs, activeMs, maxWall, valText, sub) {
501
+ const w = maxWall > 0 ? Math.max(0.5, (wallMs / maxWall) * 100) : 0;
502
+ const a = maxWall > 0 ? Math.max(0.5, (activeMs / maxWall) * 100) : 0;
503
+ return `<div class="bar-row"><div class="name" title="${esc(sub || '')}">${esc(name)}</div>
504
+ <div><div class="track" style="height:8px;margin-bottom:3px"><div class="fill" style="width:${w}%;background:var(--cache)"></div></div>
505
+ <div class="track" style="height:8px"><div class="fill" style="width:${a}%;background:var(--out)"></div></div></div>
506
+ <div class="val">${valText}</div></div>`;
507
+ }
508
+
509
+ function renderReportCharts(r) {
510
+ if (!r) return;
511
+ const spd = (r.providers || []).slice().sort((a, b) => (b.speed == null ? -1 : b.speed) - (a.speed == null ? -1 : a.speed));
512
+ const smax = Math.max(0, ...spd.map((p) => p.speed || 0));
513
+ const fullName = (p) => p.provider + '/' + p.model;
514
+ $('speed-bars').innerHTML = spd.length ? spd.map((p) => {
515
+ 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>
517
+ <div class="track"><div class="fill" style="width:${pct}%;background:var(--in)"></div></div>
518
+ <div class="val">${fmtSpeed(p.speed)}</div></div>`;
519
+ }).join('') : '<div class="val">—</div>';
520
+
521
+ const agents = r.agents || [];
522
+ const amax = Math.max(0, ...agents.map((a) => a.wallMs || 0));
523
+ $('agent-bars').innerHTML = agents.length ? agents.map((a) =>
524
+ twoBars(a.agent, a.wallMs || 0, a.activeMs || 0, amax,
525
+ fmtDur(a.wallMs) + ' / ' + fmtDur(a.activeMs), (a.sessions || 0) + ' sessions')
526
+ ).join('') : '<div class="val">—</div>';
527
+
528
+ const sess = r.sessions || [];
529
+ const xmax = Math.max(0, ...sess.map((s) => s.wallMs || 0));
530
+ $('session-bars').innerHTML = sess.length ? sess.map((s) =>
531
+ twoBars(String(s.id).slice(0, 12), s.wallMs || 0, s.activeMs || 0, xmax,
532
+ fmtDur(s.wallMs) + ' · ' + fmtSpeed(s.speed),
533
+ (s.title || '') + ' · ' + s.agent + ' · ' + s.provider + '/' + s.model + ' · ' + (s.messages || 0) + ' msgs')
534
+ ).join('') : '<div class="val">—</div>';
535
+
536
+ const mkt = (r.providers || []).slice().sort((a, b) => (b.market || 0) - (a.market || 0));
537
+ const mmax = Math.max(0, ...mkt.map((p) => p.market || 0));
538
+ $('savings-bars').innerHTML = mkt.length ? mkt.map((p) => {
539
+ const pct = mmax > 0 ? Math.max(0.5, ((p.market || 0) / mmax) * 100) : 0;
540
+ const sv = p.saved == null ? '—' : fmtCost(p.saved) + ' saved';
541
+ 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>
543
+ <div class="track"><div class="fill" style="width:${pct}%;background:var(--cost)"></div></div>
544
+ <div class="val" title="${esc(tip)}">${sv}</div></div>`;
545
+ }).join('') : '<div class="val">—</div>';
546
+ }
547
+
449
548
  function formatReport(jr) {
450
549
  const genTime = jr.generatedAt ? new Date(jr.generatedAt).toLocaleTimeString(lang === 'zh-TW' ? 'zh-TW' : 'en', { hour12: false }) : '?';
451
550
  const cachedNote = jr.stale ? ' [⟳ ' + t('updating') + ']' : ' [' + t('cachedAt') + ' ' + genTime + ']';
452
551
  const fmtCost = (n) => { const v = parseFloat(n); if (isNaN(v)) return '—'; return v === 0 ? '$0.00' : '$' + v.toFixed(4); };
453
552
  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'; };
455
553
  const pad = (s, w) => { s = String(s); return s.length >= w ? s : s + ' '.repeat(w - s.length); };
456
554
  const rpad = (s, w) => { s = String(s); return s.length >= w ? s : ' '.repeat(w - s.length) + s; };
457
555
  let out = '';
@@ -470,25 +568,35 @@ function formatReport(jr) {
470
568
  out += ' Tokens In/Out ...... ' + fmtT(c.input) + ' / ' + fmtT(c.output) + '\n';
471
569
  out += ' Tokens Reasoning ... ' + fmtT(c.reasoning) + '\n';
472
570
  out += ' Cache Read/Write ... ' + fmtT(c.cacheRead) + ' / ' + fmtT(c.cacheWrite) + '\n';
571
+ out += ' Market value ..... ' + (c.marketTotal == null ? '—' : '$' + c.marketTotal.toFixed(2)) + '\n';
572
+ out += ' Saved ............ ' + (c.savedTotal == null ? '—' : '$' + c.savedTotal.toFixed(2)) + (c.marketTotal > 0 && c.savedPct != null ? ' (' + c.savedPct + '%)' : '') + '\n';
473
573
  out += '\n';
474
574
  }
475
575
  if (jr.providers && jr.providers.length) {
476
576
  out += 'PROVIDERS & MODELS\n';
477
577
  jr.providers.forEach((p) => {
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';
578
+ 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) + ' mkt:' + rpad(fmtCost(p.market), 11) + ' svd:' + rpad(fmtCost(p.saved), 11) + '\n';
479
579
  });
480
580
  out += '\n';
581
+ const basis = (jr.providers || []).filter((p) => p.pricedAs && p.pricedAs !== (p.provider + '/' + p.model));
582
+ if (basis.length) {
583
+ out += 'PRICING (free → paid basis' + (jr.priceAsOf ? ', prices as of ' + jr.priceAsOf.slice(0, 10) : '') + ')\n';
584
+ basis.forEach((p) => {
585
+ out += ' ' + pad(p.provider + '/' + p.model, 45) + '→ ' + p.pricedAs + '\n';
586
+ });
587
+ out += '\n';
588
+ }
481
589
  }
482
590
  if (jr.agents && jr.agents.length) {
483
591
  out += 'AGENTS\n';
484
592
  jr.agents.forEach((a) => {
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';
593
+ 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) + ' mkt:' + rpad(fmtCost(a.market), 11) + ' svd:' + rpad(fmtCost(a.saved), 11) + '\n';
486
594
  });
487
595
  }
488
596
  if (jr.sessions && jr.sessions.length) {
489
597
  out += 'SESSIONS (top ' + jr.sessions.length + ' by wall time)\n';
490
598
  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';
599
+ 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) + ' mkt:' + rpad(fmtCost(s.market), 11) + ' svd:' + rpad(fmtCost(s.saved), 11) + '\n';
492
600
  });
493
601
  out += '\n';
494
602
  }
@@ -517,6 +625,7 @@ async function loadReport(days) {
517
625
  }
518
626
  reportRetry = 0;
519
627
  $('reportContent').textContent = formatReport(j.report);
628
+ renderReportCharts(j.report);
520
629
  } catch (e) {
521
630
  $('reportContent').textContent = t('connFail') + ': ' + e.message;
522
631
  }
@@ -524,6 +633,7 @@ async function loadReport(days) {
524
633
  }
525
634
 
526
635
  applyI18n();
636
+ restoreSections();
527
637
  poll();
528
638
  setInterval(poll, 15000);
529
639
  loadReport(1);
package/server.js CHANGED
@@ -10,6 +10,7 @@ const pipelineAsync = promisify(pipeline);
10
10
 
11
11
  let Database;
12
12
  try { Database = require('better-sqlite3'); } catch (_) { Database = null; }
13
+ const pricing = require('./pricing');
13
14
 
14
15
  const PORT = parseInt(process.env.OC_PORT || '4868', 10);
15
16
  const REFRESH_MS = 15000;
@@ -276,6 +277,18 @@ function splitModelName(name) {
276
277
  return i < 0 ? { provider: 'unknown', model: String(name) } : { provider: String(name).slice(0, i), model: String(name).slice(i + 1) };
277
278
  }
278
279
 
280
+ // Market estimate for token usage at catalog paid rates (USD). saved is
281
+ // market minus actual cost. pricedAs records the catalog entry used
282
+ // ("proxy:" prefix = fallback estimate). Null when no pricing catalog.
283
+ // Market-price engine rules live in pricing.js (shared with check scripts).
284
+ function marketOf(tok, provider, model) {
285
+ const pr = pricing.priceFor(provider, model);
286
+ if (!pr) return { market: null, saved: null, pricedAs: null };
287
+ const market = pricing.marketOf(tok, pr);
288
+ const r4m = (v) => Math.round(v * 10000) / 10000;
289
+ return { market: r4m(market), saved: r4m(market - (tok.cost || 0)), pricedAs: pr.source };
290
+ }
291
+
279
292
  // Hybrid usage attribution over [startMs, endMs).
280
293
  // Why hybrid: session-level totals are COMPLETE (message table only covers
281
294
  // ~2026-08 onward; 287/469 sessions in 90d have zero messages) but a
@@ -463,6 +476,29 @@ function getStatsFromDb(days) {
463
476
  }))
464
477
  .sort((a, b) => b.cost - a.cost);
465
478
 
479
+ // Savings estimate: market value of all-time usage at catalog paid rates.
480
+ // Basis is session-meta grouping (same rows/basis as the report providers
481
+ // table) so the two panels agree; message-level model splits would price
482
+ // model-switched sessions differently.
483
+ let marketTotal = null, savedTotal = null, priceAsOf = null;
484
+ {
485
+ const info = pricing.catalogInfo();
486
+ if (info.ok) {
487
+ priceAsOf = new Date(info.mtimeMs).toISOString();
488
+ marketTotal = 0;
489
+ const grows = dbQuery(`SELECT COALESCE(json_extract(model,'$.providerID'),'unknown') AS provider, COALESCE(json_extract(model,'$.id'),'unknown') AS model, SUM(tokens_input) AS i, SUM(tokens_output) AS o, SUM(tokens_reasoning) AS r, SUM(tokens_cache_read) AS cr FROM ${schema.session} GROUP BY provider, model`) || [];
490
+ for (const g of grows) {
491
+ const mk = marketOf({ input: g.i, output: g.o, reasoning: g.r, cacheRead: g.cr, cost: 0 }, g.provider, g.model);
492
+ if (mk.market === null) { marketTotal = null; break; }
493
+ marketTotal += mk.market;
494
+ }
495
+ if (marketTotal !== null) {
496
+ marketTotal = Math.round(marketTotal * 10000) / 10000;
497
+ savedTotal = Math.round((marketTotal - (costRow ? costRow.total : 0)) * 10000) / 10000;
498
+ } else { savedTotal = null; }
499
+ }
500
+ }
501
+
466
502
  return {
467
503
  ok: true,
468
504
  overview: {
@@ -480,6 +516,7 @@ function getStatsFromDb(days) {
480
516
  reasoning: costRow ? costRow.reasoning : 0,
481
517
  cacheRead: costRow ? costRow.cacheRead : 0,
482
518
  cacheWrite: costRow ? costRow.cacheWrite : 0,
519
+ marketTotal, savedTotal, priceAsOf,
483
520
  },
484
521
  tools,
485
522
  models,
@@ -624,7 +661,7 @@ function buildReportFromDb(days) {
624
661
  // time). One GROUP BY over the merged message view, mapped onto the same
625
662
  // session-meta buckets as tokens so row sets stay identical.
626
663
  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`) || [])) {
664
+ 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,'$.tokens.reasoning') AS INTEGER) ELSE 0 END), 0) AS rq, 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
665
  msgAgg[m.sid] = m;
629
666
  }
630
667
  const periodDays = {};
@@ -686,14 +723,16 @@ function buildReportFromDb(days) {
686
723
  const meta = metaMap[sid] || { agent: 'unknown', provider: 'unknown', model: 'unknown' };
687
724
  const agent = meta.agent || 'unknown';
688
725
  const modelName = `${meta.provider}/${meta.model}`;
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 };
726
+ 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, market: 0, saved: 0 };
690
727
  agentAgg[agent].sessions.add(sid);
691
728
  agentAgg[agent].input += ps.input; agentAgg[agent].output += ps.output;
692
729
  agentAgg[agent].reasoning += ps.reasoning; agentAgg[agent].cacheRead += ps.cacheRead;
693
730
  agentAgg[agent].cost += ps.cost;
694
- const mg = msgAgg[sid] || { n: 0, o: 0, ms: 0 };
731
+ const mg = msgAgg[sid] || { n: 0, o: 0, ms: 0, rq: 0 };
695
732
  agentAgg[agent].speedOut += mg.o; agentAgg[agent].speedMs += mg.ms; agentAgg[agent].activeMs += mg.ms;
696
733
  agentAgg[agent].wallMs += Math.max(0, (meta.tu || 0) - (meta.tc || 0));
734
+ const mkA = marketOf({ input: ps.input, output: ps.output, reasoning: ps.reasoning, cacheRead: ps.cacheRead, cost: ps.cost }, meta.provider || 'unknown', meta.model || 'unknown');
735
+ if (mkA.market !== null) { agentAgg[agent].market += mkA.market; agentAgg[agent].saved += mkA.saved; }
697
736
  if (!modelAgg[modelName]) modelAgg[modelName] = { sessions: new Set(), cost: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, speedOut: 0, speedMs: 0 };
698
737
  modelAgg[modelName].sessions.add(sid);
699
738
  modelAgg[modelName].input += ps.input; modelAgg[modelName].output += ps.output;
@@ -710,29 +749,37 @@ function buildReportFromDb(days) {
710
749
  tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
711
750
  speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
712
751
  wallMs: Math.round(m.wallMs), activeMs: Math.round(m.activeMs),
752
+ market: Math.round(m.market * 10000) / 10000, saved: Math.round(m.saved * 10000) / 10000,
713
753
  }))
714
754
  .sort((x, y) => y.cost - x.cost);
715
755
  var pProviderRows = Object.entries(modelAgg)
716
756
  .map(([name, m]) => {
717
757
  const { provider, model } = splitModelName(name);
758
+ const mk = marketOf({ input: m.input, output: m.output, reasoning: m.reasoning, cacheRead: m.cacheRead, cost: m.cost }, provider, model);
718
759
  return {
719
760
  provider, model, sessions: m.sessions.size, cost: r4(m.cost),
720
761
  tok_in: Math.round(m.input), tok_out: Math.round(m.output),
721
762
  tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
722
763
  speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
764
+ market: mk.market, saved: mk.saved, pricedAs: mk.pricedAs,
723
765
  };
724
766
  })
725
767
  .sort((x, y) => y.cost - x.cost);
726
768
  var pSessionRows = sessRows
727
- .map(({ sid, meta, ps, mg }) => ({
769
+ .map(({ sid, meta, ps, mg }) => {
770
+ const mkS = marketOf({ input: ps.input, output: ps.output, reasoning: mg.rq || 0, cacheRead: ps.cacheRead, cost: ps.cost }, meta.provider || 'unknown', meta.model || 'unknown');
771
+ return {
728
772
  id: sid, title: (meta.title || '').slice(0, 40), agent: meta.agent || 'unknown',
729
773
  provider: meta.provider || 'unknown', model: meta.model || 'unknown',
730
774
  wallMs: Math.max(0, (meta.tu || 0) - (meta.tc || 0)),
731
775
  activeMs: mg.ms || 0, messages: mg.n || 0,
732
776
  tok_in: Math.round(ps.input), tok_out: Math.round(ps.output),
777
+ tok_reasoning: Math.round(mg.rq || 0),
733
778
  cost: r4(ps.cost),
734
779
  speed: (mg.ms || 0) > 0 ? Math.round(((mg.o || 0) / (mg.ms / 1000)) * 10) / 10 : null,
735
- }))
780
+ market: mkS.market, saved: mkS.saved, pricedAs: mkS.pricedAs,
781
+ };
782
+ })
736
783
  .sort((x, y) => y.wallMs - x.wallMs)
737
784
  .slice(0, 20);
738
785
  } else {
@@ -741,6 +788,12 @@ function buildReportFromDb(days) {
741
788
  var pSessionRows = [];
742
789
  }
743
790
 
791
+ const sumMkt = (rows) => rows.reduce((s, r) => s + (r.market || 0), 0);
792
+ statsR.cost.marketTotal = Math.round(sumMkt(pProviderRows) * 10000) / 10000;
793
+ statsR.cost.savedTotal = Math.round((sumMkt(pProviderRows) - t.cost) * 10000) / 10000;
794
+ statsR.cost.savedPct = statsR.cost.marketTotal > 0 ? Math.round((statsR.cost.savedTotal / statsR.cost.marketTotal) * 1000) / 10 : null;
795
+ statsR.cost.priceAsOf = pricing.catalogInfo().ok ? new Date(pricing.catalogInfo().mtimeMs).toISOString() : null;
796
+
744
797
  return {
745
798
  label,
746
799
  days,
@@ -748,6 +801,7 @@ function buildReportFromDb(days) {
748
801
  agents: pAgentRows,
749
802
  providers: pProviderRows,
750
803
  sessions: pSessionRows,
804
+ priceAsOf: statsR.cost.priceAsOf,
751
805
  generatedAt: now,
752
806
  };
753
807
  }