claude-code-cost 0.12.1 → 0.14.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/lib/net-guard.js +267 -0
- package/package.json +5 -3
- package/public/app.js +89 -37
- package/public/style.css +26 -0
- package/server.js +124 -59
package/lib/net-guard.js
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Network boundary for a local-only dev server.
|
|
4
|
+
//
|
|
5
|
+
// Binding loopback is necessary but not sufficient. Three distinct attackers:
|
|
6
|
+
//
|
|
7
|
+
// * LAN peer — http://192.168.1.42:3541/api/... The loopback bind stops this
|
|
8
|
+
// outright; the handshake never completes off-box.
|
|
9
|
+
// * DNS rebinding — the victim loads evil.com, the attacker re-resolves that
|
|
10
|
+
// name to 127.0.0.1, and the page fetches http://evil.com:3541/api/...
|
|
11
|
+
// The page's origin *is* evil.com:3541, so the request is same-origin and
|
|
12
|
+
// CORS never fires; the connection is to loopback, so the bind is satisfied.
|
|
13
|
+
// The only thing that differs from a legitimate request is the Host header,
|
|
14
|
+
// which script cannot forge. A Host allowlist is the entire defense.
|
|
15
|
+
// * Plain CSRF — evil.com POSTs straight at 127.0.0.1:3541. Host is a real
|
|
16
|
+
// allowlisted value, so hostGuard passes it; this needs a separate Origin /
|
|
17
|
+
// Sec-Fetch-Site check on state-changing methods.
|
|
18
|
+
//
|
|
19
|
+
// There is no authentication. Exposing this to a network means trusting everyone
|
|
20
|
+
// on it with the user's Claude Code history.
|
|
21
|
+
//
|
|
22
|
+
// CANONICAL COPY: scripts/security-lib/net-guard.js in the claude-code-hub repo.
|
|
23
|
+
// Run scripts/sync-security-lib.sh after editing.
|
|
24
|
+
|
|
25
|
+
const LOOPBACK_HOSTS = new Set([
|
|
26
|
+
'localhost',
|
|
27
|
+
'127.0.0.1',
|
|
28
|
+
'::1',
|
|
29
|
+
'0:0:0:0:0:0:0:1',
|
|
30
|
+
'::ffff:127.0.0.1',
|
|
31
|
+
]);
|
|
32
|
+
|
|
33
|
+
// Hoisted: parseHostHeader runs on every request, and neither the regex nor the
|
|
34
|
+
// predicate depends on the argument.
|
|
35
|
+
const PORT_RE = /^[0-9]{1,5}$/;
|
|
36
|
+
// The port is validated but not compared — the listen(0) fallbacks make the real
|
|
37
|
+
// port dynamic, so only the host is allowlisted.
|
|
38
|
+
const validPort = (p) => PORT_RE.test(p) && Number(p) >= 1 && Number(p) <= 65535;
|
|
39
|
+
|
|
40
|
+
function isLoopbackAddress(host) {
|
|
41
|
+
if (!host) return false;
|
|
42
|
+
const h = String(host).toLowerCase();
|
|
43
|
+
return LOOPBACK_HOSTS.has(h) || h.startsWith('127.');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Hand-parsed rather than via new URL(), which is far more permissive than we
|
|
47
|
+
// want here and happily accepts things no real client sends. Returns the bare
|
|
48
|
+
// hostname, lowercased, or null if the header is malformed.
|
|
49
|
+
//
|
|
50
|
+
// The port is deliberately ignored: ports are dynamic in these apps because of
|
|
51
|
+
// the listen(0) fallback when the default is busy, so pinning one would break
|
|
52
|
+
// the fallback path.
|
|
53
|
+
function parseHostHeader(value) {
|
|
54
|
+
if (typeof value !== 'string') return null;
|
|
55
|
+
const raw = value.trim();
|
|
56
|
+
if (!raw || raw.length > 259) return null;
|
|
57
|
+
|
|
58
|
+
// Reject whitespace and control characters. Written as a code-point scan rather
|
|
59
|
+
// than a character class so it cannot be misread — a stray range in a regex
|
|
60
|
+
// here would silently reject legitimate hostnames containing a dash.
|
|
61
|
+
for (let i = 0; i < raw.length; i++) {
|
|
62
|
+
const code = raw.charCodeAt(i);
|
|
63
|
+
if (code <= 0x20 || code === 0x7f) return null;
|
|
64
|
+
}
|
|
65
|
+
if (raw.includes('@')) return null; // userinfo has no business in a Host header
|
|
66
|
+
|
|
67
|
+
let host;
|
|
68
|
+
if (raw.startsWith('[')) {
|
|
69
|
+
const end = raw.indexOf(']');
|
|
70
|
+
if (end === -1) return null;
|
|
71
|
+
host = raw.slice(1, end);
|
|
72
|
+
const rest = raw.slice(end + 1);
|
|
73
|
+
if (rest && !(rest.startsWith(':') && validPort(rest.slice(1)))) return null;
|
|
74
|
+
} else {
|
|
75
|
+
const parts = raw.split(':');
|
|
76
|
+
if (parts.length > 2) return null; // bare IPv6 without brackets, or garbage
|
|
77
|
+
host = parts[0];
|
|
78
|
+
if (parts.length === 2 && !validPort(parts[1])) return null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (!host) return null;
|
|
82
|
+
if (host.endsWith('.')) host = host.slice(0, -1); // one trailing root dot is legal
|
|
83
|
+
if (!host) return null;
|
|
84
|
+
return host.toLowerCase();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function parseList(value) {
|
|
88
|
+
return String(value || '')
|
|
89
|
+
.split(',')
|
|
90
|
+
.map((s) => s.trim().toLowerCase())
|
|
91
|
+
.filter(Boolean);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function getFlag(name) {
|
|
95
|
+
const idx = process.argv.findIndex((a) => a === `--${name}` || a.startsWith(`--${name}=`));
|
|
96
|
+
if (idx === -1) return null;
|
|
97
|
+
const arg = process.argv[idx];
|
|
98
|
+
if (arg.includes('=')) return arg.slice(arg.indexOf('=') + 1);
|
|
99
|
+
const next = process.argv[idx + 1];
|
|
100
|
+
return next && !next.startsWith('--') ? next : null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* @param {{appName?: string}} [config]
|
|
105
|
+
*/
|
|
106
|
+
function createNetGuard(config = {}) {
|
|
107
|
+
const appName = config.appName || 'This app';
|
|
108
|
+
|
|
109
|
+
const BIND_HOST = getFlag('host') || process.env.HOST || '127.0.0.1';
|
|
110
|
+
const BIND_HOST_LC = BIND_HOST.toLowerCase();
|
|
111
|
+
const EXPOSED = !isLoopbackAddress(BIND_HOST);
|
|
112
|
+
// Resolved here and re-exported so the hub can forward the same value to its
|
|
113
|
+
// children rather than re-parsing the flag with its own argv scanner — a parent
|
|
114
|
+
// and child that disagree means the shell serves while every iframe 403s.
|
|
115
|
+
const ALLOWED_HOSTS = getFlag('allowed-hosts') || process.env.ALLOWED_HOSTS || '';
|
|
116
|
+
const extraHosts = new Set(parseList(ALLOWED_HOSTS));
|
|
117
|
+
|
|
118
|
+
// The hub frames each sub-app, so its origin must be accepted as an Origin and
|
|
119
|
+
// permitted as a framing ancestor.
|
|
120
|
+
let hubOrigin = null;
|
|
121
|
+
if (process.env.HUB_URL) {
|
|
122
|
+
try { hubOrigin = new URL(process.env.HUB_URL).origin; } catch { /* ignore a malformed HUB_URL */ }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Resolved only once listen() succeeds — the requested port may have been busy.
|
|
126
|
+
let actualPort = null;
|
|
127
|
+
|
|
128
|
+
function hostAllowed(host) {
|
|
129
|
+
if (!host) return false;
|
|
130
|
+
if (isLoopbackAddress(host)) return true;
|
|
131
|
+
if (extraHosts.has(host)) return true;
|
|
132
|
+
// Binding a specific non-loopback address implies that address is a valid name for us.
|
|
133
|
+
if (EXPOSED && host === BIND_HOST_LC) return true;
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function hostGuard(req, res, next) {
|
|
138
|
+
const host = parseHostHeader(req.headers.host);
|
|
139
|
+
if (hostAllowed(host)) return next();
|
|
140
|
+
res.status(403).type('text/plain').send(
|
|
141
|
+
`403 Forbidden - unrecognized Host header: ${req.headers.host || '(none)'}\n\n` +
|
|
142
|
+
`${appName} only answers requests addressed to localhost. This protects you\n` +
|
|
143
|
+
`from DNS rebinding, where a website you visit re-points its own hostname at\n` +
|
|
144
|
+
`127.0.0.1 in order to read your local data.\n\n` +
|
|
145
|
+
`If you meant to reach this from another machine, restart with:\n` +
|
|
146
|
+
` --host 0.0.0.0 --allowed-hosts=${host || '<your-hostname>'}\n\n` +
|
|
147
|
+
`Only do that on a network you trust - there is no authentication.\n`
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// true = allow, false = block, null = no Origin header, caller decides.
|
|
152
|
+
function originVerdict(origin) {
|
|
153
|
+
if (!origin || origin === 'null') return null;
|
|
154
|
+
let parsed;
|
|
155
|
+
try { parsed = new URL(origin); } catch { return false; }
|
|
156
|
+
if (hubOrigin && parsed.origin === hubOrigin) return true;
|
|
157
|
+
if (!isLoopbackAddress(parsed.hostname)) return false;
|
|
158
|
+
// Same port, any loopback spelling. A different local port is a different app
|
|
159
|
+
// and has no business driving this one.
|
|
160
|
+
if (actualPort && parsed.port && Number(parsed.port) !== Number(actualPort)) return false;
|
|
161
|
+
return true;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function originGuard(req, res, next) {
|
|
165
|
+
if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return next();
|
|
166
|
+
|
|
167
|
+
const verdict = originVerdict(req.headers.origin);
|
|
168
|
+
if (verdict === true) return next();
|
|
169
|
+
if (verdict === false) {
|
|
170
|
+
return res.status(403).type('text/plain')
|
|
171
|
+
.send(`403 Forbidden - cross-origin ${req.method} from ${req.headers.origin} is not allowed.\n`);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// No Origin header: a non-browser client (curl, the CLI, the hub's own fetch).
|
|
175
|
+
// Trust it unless the browser explicitly tells us otherwise.
|
|
176
|
+
const site = req.headers['sec-fetch-site'];
|
|
177
|
+
if (site && site !== 'same-origin' && site !== 'none') {
|
|
178
|
+
return res.status(403).type('text/plain')
|
|
179
|
+
.send(`403 Forbidden - cross-site ${req.method} (Sec-Fetch-Site: ${site}) is not allowed.\n`);
|
|
180
|
+
}
|
|
181
|
+
return next();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Constant for the life of the process, and frameGuard runs ahead of
|
|
185
|
+
// express.static — so this is built once rather than per asset fetch.
|
|
186
|
+
//
|
|
187
|
+
// Under the hub, X-Frame-Options is deliberately omitted: it has no multi-origin
|
|
188
|
+
// form, and sending SAMEORIGIN would break the hub's iframes.
|
|
189
|
+
//
|
|
190
|
+
// The port is wildcarded rather than pinned to HUB_URL's. The hub spawns its
|
|
191
|
+
// children before it binds, so if its own preferred port is busy it hands them a
|
|
192
|
+
// HUB_URL with the wrong port and every iframe would break. Any loopback port may
|
|
193
|
+
// frame us; that is not the threat being addressed here — a remote page still
|
|
194
|
+
// cannot, which is what matters.
|
|
195
|
+
//
|
|
196
|
+
// No IPv6 literal: Chrome rejects `http://[::1]:*` as a source expression and
|
|
197
|
+
// logs it on every framed load. The hub's own origin is added verbatim instead,
|
|
198
|
+
// which covers a hub reached over [::1].
|
|
199
|
+
let CSP;
|
|
200
|
+
if (hubOrigin) {
|
|
201
|
+
const ancestors = ["'self'", 'http://localhost:*', 'http://127.0.0.1:*'];
|
|
202
|
+
if (!/^http:\/\/(localhost|127\.0\.0\.1)(:|$)/.test(hubOrigin)) ancestors.push(hubOrigin);
|
|
203
|
+
CSP = `frame-ancestors ${ancestors.join(' ')}`;
|
|
204
|
+
} else {
|
|
205
|
+
CSP = "frame-ancestors 'none'";
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function frameGuard(_req, res, next) {
|
|
209
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
210
|
+
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
211
|
+
res.setHeader('Content-Security-Policy', CSP);
|
|
212
|
+
if (!hubOrigin) res.setHeader('X-Frame-Options', 'DENY');
|
|
213
|
+
next();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Bind BIND_HOST, then opportunistically serve the other loopback family on the
|
|
218
|
+
* same resolved port via a second server sharing the same request handler.
|
|
219
|
+
*
|
|
220
|
+
* That second bind is what keeps `http://localhost:<port>` working no matter how
|
|
221
|
+
* the OS resolver orders A/AAAA records - binding only 127.0.0.1 breaks hosts
|
|
222
|
+
* where `localhost` resolves to ::1, and vice versa. Doing it on the *resolved*
|
|
223
|
+
* port means every existing URL, startup banner and postMessage origin is
|
|
224
|
+
* unchanged. Failures are swallowed: it is an optimization, not a requirement.
|
|
225
|
+
*
|
|
226
|
+
* Returns the primary server, so callers keep attaching their own 'error'
|
|
227
|
+
* handler for the EADDRINUSE fallback.
|
|
228
|
+
*
|
|
229
|
+
* @param {any} app express app (or any http request handler)
|
|
230
|
+
* @param {number} port 0 selects a free port
|
|
231
|
+
* @param {(port: number) => void} [onReady]
|
|
232
|
+
* @param {{maxHeaderSize?: number}} [opts]
|
|
233
|
+
*/
|
|
234
|
+
function listenLoopback(app, port, onReady, opts = {}) {
|
|
235
|
+
const http = require('http');
|
|
236
|
+
const serverOpts = opts.maxHeaderSize ? { maxHeaderSize: opts.maxHeaderSize } : {};
|
|
237
|
+
const makeServer = (handler) => http.createServer(serverOpts, handler);
|
|
238
|
+
const server = makeServer(app);
|
|
239
|
+
let secondary = null;
|
|
240
|
+
|
|
241
|
+
server.on('listening', () => {
|
|
242
|
+
actualPort = server.address().port;
|
|
243
|
+
if (!EXPOSED) {
|
|
244
|
+
const otherFamily = BIND_HOST.includes(':') ? '127.0.0.1' : '::1';
|
|
245
|
+
try {
|
|
246
|
+
secondary = makeServer(app);
|
|
247
|
+
secondary.on('error', () => {}); // that family may not exist on this host
|
|
248
|
+
secondary.listen({ host: otherFamily, port: actualPort, ipv6Only: otherFamily === '::1' });
|
|
249
|
+
} catch { /* best effort */ }
|
|
250
|
+
}
|
|
251
|
+
if (onReady) onReady(actualPort);
|
|
252
|
+
});
|
|
253
|
+
server.on('close', () => { try { if (secondary) secondary.close(); } catch { /* already gone */ } });
|
|
254
|
+
|
|
255
|
+
server.listen(port, BIND_HOST);
|
|
256
|
+
return server;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function exposureWarning() {
|
|
260
|
+
if (!EXPOSED) return null;
|
|
261
|
+
return `WARNING: listening on ${BIND_HOST} - reachable from your network, with no authentication.`;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
return { BIND_HOST, ALLOWED_HOSTS, hostGuard, originGuard, frameGuard, listenLoopback, exposureWarning };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
module.exports = { createNetGuard, parseHostHeader, isLoopbackAddress };
|
package/package.json
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "claude-code-cost",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"description": "Cost dashboard for Claude Code usage",
|
|
5
5
|
"main": "server.js",
|
|
6
6
|
"bin": {
|
|
7
|
-
"claude-code-cost": "
|
|
7
|
+
"claude-code-cost": "server.js"
|
|
8
8
|
},
|
|
9
9
|
"scripts": {
|
|
10
10
|
"start": "node server.js",
|
|
11
11
|
"dev": "node server.js --open",
|
|
12
|
-
"prepare": "husky || true"
|
|
12
|
+
"prepare": "husky || true",
|
|
13
|
+
"test": "node --test test/*.test.js"
|
|
13
14
|
},
|
|
14
15
|
"engines": {
|
|
15
16
|
"node": ">=20.0.0"
|
|
@@ -43,6 +44,7 @@
|
|
|
43
44
|
"license": "MIT",
|
|
44
45
|
"files": [
|
|
45
46
|
"server.js",
|
|
47
|
+
"lib/",
|
|
46
48
|
"public/",
|
|
47
49
|
"README.md",
|
|
48
50
|
"LICENSE"
|
package/public/app.js
CHANGED
|
@@ -4,7 +4,7 @@ let currentView = 'overview';
|
|
|
4
4
|
let overviewData = null;
|
|
5
5
|
let projectsData = null;
|
|
6
6
|
let sessionsData = null;
|
|
7
|
-
let
|
|
7
|
+
let sessionsCostSeries = null;
|
|
8
8
|
let sessionsModelDistribution = null;
|
|
9
9
|
let sessionDetailData = null;
|
|
10
10
|
let currentProjectPath = null;
|
|
@@ -33,10 +33,27 @@ let navCounter = 0;
|
|
|
33
33
|
|
|
34
34
|
// #region UTILS
|
|
35
35
|
|
|
36
|
+
// The div.textContent -> innerHTML trick escapes only & < > : innerHTML serializes
|
|
37
|
+
// for *text* context, where quotes are correctly left raw. That made every
|
|
38
|
+
// attribute interpolation breakable with a bare " . It cannot be patched, so the
|
|
39
|
+
// escaping is explicit here.
|
|
40
|
+
const HTML_ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '`': '`' };
|
|
41
|
+
|
|
36
42
|
function esc(str) {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
43
|
+
if (str == null) return '';
|
|
44
|
+
return String(str).replace(/[&<>"'`]/g, (c) => HTML_ESCAPES[c]);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// For a value landing inside a quoted JS string inside an HTML attribute —
|
|
48
|
+
// onclick="fn('${escAttrJs(x)}')". The browser HTML-decodes the attribute before
|
|
49
|
+
// the JS parser sees it, so the JS escape must happen first and be escaped in turn.
|
|
50
|
+
function escAttrJs(value) {
|
|
51
|
+
const js = String(value == null ? '' : value)
|
|
52
|
+
.replace(/\\/g, '\\\\')
|
|
53
|
+
.replace(/'/g, "\\'")
|
|
54
|
+
.replace(/\r/g, '\\r')
|
|
55
|
+
.replace(/\n/g, '\\n');
|
|
56
|
+
return esc(js);
|
|
40
57
|
}
|
|
41
58
|
|
|
42
59
|
function formatCost(usd) {
|
|
@@ -74,9 +91,17 @@ function timeAgo(ts) {
|
|
|
74
91
|
return new Date(ts).toLocaleDateString();
|
|
75
92
|
}
|
|
76
93
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
94
|
+
// Bucket keys arrive as YYYY-MM-DD (day) or YYYY-MM-DDTHH (hour), both in the server's local
|
|
95
|
+
// time with no zone suffix.
|
|
96
|
+
function bucketLabel(key, bucket) {
|
|
97
|
+
if (bucket === 'hour') {
|
|
98
|
+
return new Date(`${key}:00:00`).toLocaleTimeString(undefined, { hour: 'numeric' });
|
|
99
|
+
}
|
|
100
|
+
return new Date(`${key}T00:00:00`).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function costSeriesTitle(series) {
|
|
104
|
+
return series?.bucket === 'hour' ? 'Hourly Cost' : 'Daily Cost';
|
|
80
105
|
}
|
|
81
106
|
|
|
82
107
|
function shortModel(model) {
|
|
@@ -201,6 +226,10 @@ function rangeLabel(r) {
|
|
|
201
226
|
return r === 'today' ? 'today' : `${r} days`;
|
|
202
227
|
}
|
|
203
228
|
|
|
229
|
+
function rangeScopeLabel(r) {
|
|
230
|
+
return r === 'today' ? rangeLabel(r) : `last ${rangeLabel(r)}`;
|
|
231
|
+
}
|
|
232
|
+
|
|
204
233
|
function loadSort() {
|
|
205
234
|
for (const view of Object.keys(DEFAULT_SORT)) {
|
|
206
235
|
const raw = localStorage.getItem(`cc-cost:sort:${view}`);
|
|
@@ -238,7 +267,7 @@ function updateUrl() {
|
|
|
238
267
|
// #region FETCH
|
|
239
268
|
|
|
240
269
|
const BROWSER_CACHE_TTL = 5 * 60 * 1000; // 5 min
|
|
241
|
-
const CACHE_VERSION =
|
|
270
|
+
const CACHE_VERSION = 4;
|
|
242
271
|
let forceRefresh = false;
|
|
243
272
|
// Age of the data on screen, for the auto-refresh staleness check. A cache hit carries its own
|
|
244
273
|
// timestamp forward, so a reload with a warm cache doesn't look freshly fetched.
|
|
@@ -351,12 +380,12 @@ async function fetchProjects() {
|
|
|
351
380
|
async function fetchSessions(encodedPath) {
|
|
352
381
|
const data = await fetchJSON(`/api/projects/${encodeURIComponent(encodedPath)}/sessions?range=${dateRange}`, true);
|
|
353
382
|
sessionsData = data.sessions;
|
|
354
|
-
|
|
383
|
+
sessionsCostSeries = data.costSeries;
|
|
355
384
|
sessionsModelDistribution = data.modelDistribution || [];
|
|
356
385
|
}
|
|
357
386
|
|
|
358
387
|
async function fetchSessionDetail(sessionId) {
|
|
359
|
-
sessionDetailData = await fetchJSON(`/api/sessions/${encodeURIComponent(sessionId)}`, true);
|
|
388
|
+
sessionDetailData = await fetchJSON(`/api/sessions/${encodeURIComponent(sessionId)}?range=${dateRange}`, true);
|
|
360
389
|
// Populate project context when opening via deep link (no project in URL)
|
|
361
390
|
if (sessionDetailData && !currentProjectPath) {
|
|
362
391
|
currentProjectPath = sessionDetailData.encodedProjectPath;
|
|
@@ -383,7 +412,7 @@ function renderOverview() {
|
|
|
383
412
|
if (lastRenderHash.overview === h) return;
|
|
384
413
|
lastRenderHash.overview = h;
|
|
385
414
|
|
|
386
|
-
const
|
|
415
|
+
const costSeries = overviewData.costSeries;
|
|
387
416
|
const models = overviewData.modelDistribution || [];
|
|
388
417
|
|
|
389
418
|
// Return before any chart call so no canvas is touched — there are none in this markup.
|
|
@@ -434,8 +463,8 @@ function renderOverview() {
|
|
|
434
463
|
|
|
435
464
|
<div class="charts-row">
|
|
436
465
|
<div class="chart-box">
|
|
437
|
-
<div class="chart-title"
|
|
438
|
-
<canvas id="
|
|
466
|
+
<div class="chart-title">${costSeriesTitle(costSeries)}</div>
|
|
467
|
+
<canvas id="costChart"></canvas>
|
|
439
468
|
</div>
|
|
440
469
|
<div class="chart-box">
|
|
441
470
|
<div class="chart-title">Cost by Model</div>
|
|
@@ -459,7 +488,7 @@ function renderOverview() {
|
|
|
459
488
|
.sort((a, b) => sortCompare(a, b, viewSort.overview.field, viewSort.overview.order))
|
|
460
489
|
.map(
|
|
461
490
|
(p) => `
|
|
462
|
-
<tr data-clickable onclick="navigateToSessions('${
|
|
491
|
+
<tr data-clickable onclick="navigateToSessions('${escAttrJs(p.encodedPath)}', '${escAttrJs(p.name)}')">
|
|
463
492
|
<td>${esc(p.name)}</td>
|
|
464
493
|
<td class="cost-cell">${formatCost(p.totalCost)}</td>
|
|
465
494
|
<td>${p.sessionCount}</td>
|
|
@@ -475,7 +504,7 @@ function renderOverview() {
|
|
|
475
504
|
|
|
476
505
|
// Render charts after DOM is ready
|
|
477
506
|
requestAnimationFrame(() => {
|
|
478
|
-
|
|
507
|
+
renderCostChart(costSeries);
|
|
479
508
|
renderModelChart(models);
|
|
480
509
|
});
|
|
481
510
|
}
|
|
@@ -529,7 +558,7 @@ function renderProjects() {
|
|
|
529
558
|
${sorted
|
|
530
559
|
.map(
|
|
531
560
|
(p) => `
|
|
532
|
-
<tr data-clickable onclick="navigateToSessions('${
|
|
561
|
+
<tr data-clickable onclick="navigateToSessions('${escAttrJs(p.encodedPath)}', '${escAttrJs(p.name)}')">
|
|
533
562
|
<td>${esc(p.name)}</td>
|
|
534
563
|
<td class="cost-cell">${formatCost(p.totalCost)}</td>
|
|
535
564
|
<td>${p.sessionCount}</td>
|
|
@@ -555,7 +584,7 @@ function renderSessions() {
|
|
|
555
584
|
return;
|
|
556
585
|
}
|
|
557
586
|
|
|
558
|
-
const h = JSON.stringify({ sessionsData,
|
|
587
|
+
const h = JSON.stringify({ sessionsData, sessionsCostSeries, sessionsModelDistribution, sort: viewSort.sessions });
|
|
559
588
|
if (lastRenderHash.sessions === h) return;
|
|
560
589
|
lastRenderHash.sessions = h;
|
|
561
590
|
|
|
@@ -580,8 +609,8 @@ function renderSessions() {
|
|
|
580
609
|
</div>
|
|
581
610
|
<div class="charts-row" style="grid-template-columns:3fr 2fr auto">
|
|
582
611
|
<div class="chart-box">
|
|
583
|
-
<div class="chart-title"
|
|
584
|
-
<canvas id="
|
|
612
|
+
<div class="chart-title">${costSeriesTitle(sessionsCostSeries)}</div>
|
|
613
|
+
<canvas id="sessionsCostChart"></canvas>
|
|
585
614
|
</div>
|
|
586
615
|
<div class="chart-box">
|
|
587
616
|
<div class="chart-title">Cost by Model</div>
|
|
@@ -609,7 +638,7 @@ function renderSessions() {
|
|
|
609
638
|
.sort((a, b) => sortCompare(a, b, viewSort.sessions.field, viewSort.sessions.order))
|
|
610
639
|
.map(
|
|
611
640
|
(s) => `
|
|
612
|
-
<tr data-clickable onclick="navigateToDetail('${
|
|
641
|
+
<tr data-clickable onclick="navigateToDetail('${escAttrJs(s.sessionId)}')">
|
|
613
642
|
<td class="truncate" title="${esc(s.customTitle || s.firstPrompt || s.sessionId)}">${esc(s.customTitle || s.firstPrompt || s.sessionId)}</td>
|
|
614
643
|
<td class="cost-cell">${formatCost(s.totalCost)}</td>
|
|
615
644
|
<td>${formatTokens(s.totalTokens)}</td>
|
|
@@ -625,7 +654,7 @@ function renderSessions() {
|
|
|
625
654
|
</div>`;
|
|
626
655
|
|
|
627
656
|
requestAnimationFrame(() => {
|
|
628
|
-
|
|
657
|
+
renderCostChart(sessionsCostSeries, 'sessionsCostChart', 'sessionsCost');
|
|
629
658
|
renderModelChart(sessionsModelDistribution || [], 'sessionsModelChart', 'sessionsModel');
|
|
630
659
|
});
|
|
631
660
|
}
|
|
@@ -652,7 +681,7 @@ function renderDetail() {
|
|
|
652
681
|
<div class="breadcrumb">
|
|
653
682
|
${parentBreadcrumb()}
|
|
654
683
|
<span class="sep">/</span>
|
|
655
|
-
<a onclick="navigateToSessions('${
|
|
684
|
+
<a onclick="navigateToSessions('${escAttrJs(d.encodedProjectPath)}', '${escAttrJs(d.projectPath)}')">${esc(d.projectPath)}</a>
|
|
656
685
|
<span class="sep">/</span>
|
|
657
686
|
<span class="current">${esc(d.customTitle || d.firstPrompt || d.sessionId)}</span>
|
|
658
687
|
</div>
|
|
@@ -662,7 +691,7 @@ function renderDetail() {
|
|
|
662
691
|
<div class="detail-header">
|
|
663
692
|
<div class="detail-stat">
|
|
664
693
|
<div class="detail-label">Total Cost</div>
|
|
665
|
-
<div class="detail-value cost">${formatCost(d.totalCost)}</div>
|
|
694
|
+
<div class="detail-value cost">${formatCost(d.totalCost)}<span class="detail-label detail-scope">all time</span></div>
|
|
666
695
|
</div>
|
|
667
696
|
<div class="detail-stat">
|
|
668
697
|
<div class="detail-label">Input</div>
|
|
@@ -682,17 +711,16 @@ function renderDetail() {
|
|
|
682
711
|
</div>
|
|
683
712
|
<div class="detail-stat">
|
|
684
713
|
<div class="detail-label">Messages</div>
|
|
685
|
-
<div class="detail-value">${d.messages.length}</div>
|
|
714
|
+
<div class="detail-value">${d.messages.length}<span class="detail-label detail-scope">all time</span></div>
|
|
686
715
|
</div>
|
|
687
716
|
<div class="detail-stat">
|
|
688
717
|
<div class="detail-label">Models</div>
|
|
689
|
-
<div class="detail-value">${d.models
|
|
690
|
-
.map((m) => shortModel(m))
|
|
691
|
-
.filter(Boolean)
|
|
692
|
-
.join(', ')}</div>
|
|
718
|
+
<div class="detail-value">${esc(d.models.map((m) => shortModel(m)).join(', '))}</div>
|
|
693
719
|
</div>
|
|
694
720
|
</div>
|
|
695
721
|
|
|
722
|
+
${detailRangeNote(d)}
|
|
723
|
+
|
|
696
724
|
<div class="charts-row" style="margin-bottom:20px">
|
|
697
725
|
<div class="chart-box">
|
|
698
726
|
<div class="chart-title">Cumulative Cost</div>
|
|
@@ -730,6 +758,23 @@ function renderDetail() {
|
|
|
730
758
|
});
|
|
731
759
|
}
|
|
732
760
|
|
|
761
|
+
// The session row that links here is scoped to the active range, so a session older than the
|
|
762
|
+
// range would otherwise show larger numbers here with no explanation.
|
|
763
|
+
function detailRangeNote(d) {
|
|
764
|
+
const all = d.messages.length;
|
|
765
|
+
const slice = (label, s) =>
|
|
766
|
+
`<span class="scope-label">${esc(label)}</span> <strong>${formatCost(s.totalCost)}</strong> / ${s.messageCount} msg`;
|
|
767
|
+
// A slice worth showing is a real subset: neither empty nor the whole session.
|
|
768
|
+
const worthShowing = (s) => s && s.messageCount > 0 && s.messageCount < all;
|
|
769
|
+
const parts = [];
|
|
770
|
+
if (worthShowing(d.inRange)) parts.push(slice(rangeScopeLabel(d.range), d.inRange));
|
|
771
|
+
if (worthShowing(d.today) && d.today.messageCount !== d.inRange?.messageCount) {
|
|
772
|
+
parts.push(slice('today', d.today));
|
|
773
|
+
}
|
|
774
|
+
if (!parts.length) return '';
|
|
775
|
+
return `<div class="detail-range-note">Totals above are all-time · ${parts.join(' · ')}</div>`;
|
|
776
|
+
}
|
|
777
|
+
|
|
733
778
|
function buildMessageRowsWithSubagents(d) {
|
|
734
779
|
return [...d.messages]
|
|
735
780
|
.reverse()
|
|
@@ -821,9 +866,10 @@ function destroyChart(id) {
|
|
|
821
866
|
}
|
|
822
867
|
}
|
|
823
868
|
|
|
824
|
-
function
|
|
869
|
+
function renderCostChart(series, canvasId = 'costChart', chartKey = 'cost') {
|
|
870
|
+
const points = series?.points;
|
|
825
871
|
const canvas = document.getElementById(canvasId);
|
|
826
|
-
if (!canvas || !
|
|
872
|
+
if (!canvas || !points?.length) return;
|
|
827
873
|
destroyChart(chartKey);
|
|
828
874
|
|
|
829
875
|
const c = getChartColors();
|
|
@@ -832,11 +878,11 @@ function renderDailyChart(daily, canvasId = 'dailyChart', chartKey = 'daily') {
|
|
|
832
878
|
charts[chartKey] = new Chart(canvas, {
|
|
833
879
|
type: 'bar',
|
|
834
880
|
data: {
|
|
835
|
-
labels:
|
|
881
|
+
labels: points.map((p) => bucketLabel(p.key, series.bucket)),
|
|
836
882
|
datasets: [
|
|
837
883
|
{
|
|
838
|
-
label:
|
|
839
|
-
data:
|
|
884
|
+
label: costSeriesTitle(series),
|
|
885
|
+
data: points.map((p) => p.cost),
|
|
840
886
|
backgroundColor: c.chartFill,
|
|
841
887
|
borderColor: c.accent,
|
|
842
888
|
borderWidth: 1.5,
|
|
@@ -1551,7 +1597,7 @@ async function refreshIfStale() {
|
|
|
1551
1597
|
document.addEventListener('keydown', (e) => {
|
|
1552
1598
|
const fwd = (key) => {
|
|
1553
1599
|
e.preventDefault();
|
|
1554
|
-
|
|
1600
|
+
hubPost({ type: 'hub:keydown', key, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey });
|
|
1555
1601
|
};
|
|
1556
1602
|
if (e.ctrlKey && e.altKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) {
|
|
1557
1603
|
fwd(e.key);
|
|
@@ -1569,9 +1615,16 @@ async function refreshIfStale() {
|
|
|
1569
1615
|
// Hoisted out of initHubTheme so initHubProject can share it.
|
|
1570
1616
|
const hubOrigin = () => (window.__HUB__?.url ? new URL(window.__HUB__.url).origin : null);
|
|
1571
1617
|
|
|
1618
|
+
// Every send is addressed to the hub explicitly. With targetOrigin '*' any page that
|
|
1619
|
+
// framed this app also received the forwarded keystrokes and navigation intents.
|
|
1620
|
+
function hubPost(message) {
|
|
1621
|
+
const origin = hubOrigin();
|
|
1622
|
+
if (origin) window.parent?.postMessage(message, origin);
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1572
1625
|
window.hubNavigate = function hubNavigate(app, url) {
|
|
1573
1626
|
if (!window.__HUB__?.enabled) return;
|
|
1574
|
-
|
|
1627
|
+
hubPost({ type: 'hub:navigate', app, url });
|
|
1575
1628
|
};
|
|
1576
1629
|
|
|
1577
1630
|
(function initHubTheme() {
|
|
@@ -1599,8 +1652,7 @@ window.hubNavigate = function hubNavigate(app, url) {
|
|
|
1599
1652
|
if (t === lastTheme && ct === lastColorTheme) return;
|
|
1600
1653
|
lastTheme = t;
|
|
1601
1654
|
lastColorTheme = ct;
|
|
1602
|
-
|
|
1603
|
-
if (origin) window.parent.postMessage({ type: 'hub:theme', theme: t, colorTheme: ct }, origin);
|
|
1655
|
+
hubPost({ type: 'hub:theme', theme: t, colorTheme: ct });
|
|
1604
1656
|
}).observe(document.body, {
|
|
1605
1657
|
attributes: true,
|
|
1606
1658
|
attributeFilter: ['class', 'data-color-theme'],
|
package/public/style.css
CHANGED
|
@@ -639,6 +639,32 @@ body {
|
|
|
639
639
|
color: var(--accent-text);
|
|
640
640
|
}
|
|
641
641
|
|
|
642
|
+
/* Rides on .detail-label for the small-muted-caption look; only the offset differs. */
|
|
643
|
+
.detail-stat .detail-scope {
|
|
644
|
+
margin-left: 5px;
|
|
645
|
+
font-weight: 400;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
.detail-header:has(+ .detail-range-note) {
|
|
649
|
+
margin-bottom: 8px;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
.detail-range-note {
|
|
653
|
+
margin: 0 0 18px;
|
|
654
|
+
font-size: 10px;
|
|
655
|
+
color: var(--text-muted);
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
.detail-range-note .scope-label {
|
|
659
|
+
text-transform: uppercase;
|
|
660
|
+
letter-spacing: 0.03em;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
.detail-range-note strong {
|
|
664
|
+
color: var(--text-secondary);
|
|
665
|
+
font-weight: 500;
|
|
666
|
+
}
|
|
667
|
+
|
|
642
668
|
.messages-table {
|
|
643
669
|
width: 100%;
|
|
644
670
|
border-collapse: collapse;
|
package/server.js
CHANGED
|
@@ -7,6 +7,7 @@ const fs = require('fs');
|
|
|
7
7
|
const { createReadStream } = require('fs');
|
|
8
8
|
const { createInterface } = require('readline');
|
|
9
9
|
const os = require('os');
|
|
10
|
+
const { createNetGuard } = require('./lib/net-guard');
|
|
10
11
|
|
|
11
12
|
// #region CLI_ARGS
|
|
12
13
|
|
|
@@ -237,20 +238,48 @@ function localDateStr(d) {
|
|
|
237
238
|
return `${y}-${m}-${day}`;
|
|
238
239
|
}
|
|
239
240
|
|
|
240
|
-
function
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
241
|
+
function localHourStr(d) {
|
|
242
|
+
return `${localDateStr(d)}T${String(d.getHours()).padStart(2, '0')}`;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Cost is bucketed by one of these; the key doubles as the aggregation key and the wire label.
|
|
246
|
+
// An hour key extends the day key (YYYY-MM-DD -> YYYY-MM-DDTHH), so a startsWith test on a day
|
|
247
|
+
// string matches either granularity.
|
|
248
|
+
const BUCKETS = {
|
|
249
|
+
day: {
|
|
250
|
+
key: localDateStr,
|
|
251
|
+
floor: (d) => d.setHours(0, 0, 0, 0),
|
|
252
|
+
next: (d) => d.setDate(d.getDate() + 1),
|
|
253
|
+
},
|
|
254
|
+
hour: {
|
|
255
|
+
key: localHourStr,
|
|
256
|
+
floor: (d) => d.setMinutes(0, 0, 0),
|
|
257
|
+
next: (d) => d.setHours(d.getHours() + 1),
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
// A one-day window collapses the daily chart into a single bar, so those ranges bucket by hour.
|
|
262
|
+
function rangeBucket(range) {
|
|
263
|
+
return range === 'today' || range === 1 ? 'hour' : 'day';
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// Gap-filled so empty buckets stay visible in the chart.
|
|
267
|
+
function buildCostSeries(costs, start, end, bucket) {
|
|
268
|
+
const b = BUCKETS[bucket];
|
|
269
|
+
const points = [];
|
|
270
|
+
if (Object.keys(costs).length === 0) return points;
|
|
271
|
+
const d = new Date(start);
|
|
272
|
+
b.floor(d);
|
|
273
|
+
for (; d <= end; b.next(d)) {
|
|
274
|
+
const k = b.key(d);
|
|
275
|
+
points.push({ key: k, cost: costs[k] || 0 });
|
|
247
276
|
}
|
|
248
|
-
return
|
|
277
|
+
return points;
|
|
249
278
|
}
|
|
250
279
|
|
|
251
280
|
function buildModelDistribution(modelCosts) {
|
|
252
281
|
return Object.entries(modelCosts)
|
|
253
|
-
.filter(([model, cost]) => cost > 0 &&
|
|
282
|
+
.filter(([model, cost]) => cost > 0 && isRealModel(model))
|
|
254
283
|
.map(([model, cost]) => ({ model, cost }))
|
|
255
284
|
.sort((a, b) => b.cost - a.cost);
|
|
256
285
|
}
|
|
@@ -338,6 +367,11 @@ function scanSubagentDir(sessionDir) {
|
|
|
338
367
|
return result;
|
|
339
368
|
}
|
|
340
369
|
|
|
370
|
+
// `<synthetic>` and friends are Claude Code bookkeeping entries, not models the user chose.
|
|
371
|
+
function isRealModel(model) {
|
|
372
|
+
return !!model && !model.startsWith('<');
|
|
373
|
+
}
|
|
374
|
+
|
|
341
375
|
function mostFrequentModel(counts) {
|
|
342
376
|
return Object.entries(counts).sort((a, b) => b[1] - a[1])[0]?.[0] || 'unknown';
|
|
343
377
|
}
|
|
@@ -432,7 +466,7 @@ async function loadProjectData(files, pricing) {
|
|
|
432
466
|
session.outputTokens += usage.output_tokens || 0;
|
|
433
467
|
session.cacheCreationTokens += (usage.cache_creation_input_tokens || 0);
|
|
434
468
|
session.cacheReadTokens += (usage.cache_read_input_tokens || 0);
|
|
435
|
-
session.models.add(model);
|
|
469
|
+
if (isRealModel(model)) session.models.add(model);
|
|
436
470
|
|
|
437
471
|
if (!session.firstTimestamp || ts < session.firstTimestamp) session.firstTimestamp = ts;
|
|
438
472
|
if (!session.lastTimestamp || ts > session.lastTimestamp) session.lastTimestamp = ts;
|
|
@@ -471,7 +505,7 @@ async function loadProjectData(files, pricing) {
|
|
|
471
505
|
session.outputTokens += sa.outputTokens;
|
|
472
506
|
session.cacheCreationTokens += sa.cacheCreationTokens;
|
|
473
507
|
session.cacheReadTokens += sa.cacheReadTokens;
|
|
474
|
-
for (const m of sa.models) session.models.add(m);
|
|
508
|
+
for (const m of sa.models) if (isRealModel(m)) session.models.add(m);
|
|
475
509
|
session.messages.push({
|
|
476
510
|
timestamp: sa.firstTimestamp || session.firstTimestamp,
|
|
477
511
|
model: sa.models[0] || 'unknown',
|
|
@@ -502,6 +536,18 @@ function rangeToCutoff(range, now) {
|
|
|
502
536
|
return c;
|
|
503
537
|
}
|
|
504
538
|
|
|
539
|
+
function summarizeMessages(msgs) {
|
|
540
|
+
const sum = { messageCount: msgs.length, totalCost: 0, inputTokens: 0, outputTokens: 0, cacheCreationTokens: 0, cacheReadTokens: 0 };
|
|
541
|
+
for (const m of msgs) {
|
|
542
|
+
sum.totalCost += m.cost;
|
|
543
|
+
sum.inputTokens += m.inputTokens;
|
|
544
|
+
sum.outputTokens += m.outputTokens;
|
|
545
|
+
sum.cacheCreationTokens += m.cacheCreationTokens;
|
|
546
|
+
sum.cacheReadTokens += m.cacheReadTokens;
|
|
547
|
+
}
|
|
548
|
+
return sum;
|
|
549
|
+
}
|
|
550
|
+
|
|
505
551
|
async function getOverviewData(range, projectFilter) {
|
|
506
552
|
const cacheKey = `overview_${range}_${projectFilter || 'all'}`;
|
|
507
553
|
if (isCacheValid(cacheKey)) return dataCache[cacheKey];
|
|
@@ -514,7 +560,9 @@ async function getOverviewData(range, projectFilter) {
|
|
|
514
560
|
|
|
515
561
|
let totalCost = 0, totalSessions = 0;
|
|
516
562
|
let totalInput = 0, totalOutput = 0, totalCacheCreation = 0, totalCacheRead = 0;
|
|
517
|
-
const
|
|
563
|
+
const bucket = rangeBucket(range);
|
|
564
|
+
const bucketKey = BUCKETS[bucket].key;
|
|
565
|
+
const bucketCosts = {};
|
|
518
566
|
const modelCosts = {};
|
|
519
567
|
const projectSummaries = [];
|
|
520
568
|
|
|
@@ -535,9 +583,9 @@ async function getOverviewData(range, projectFilter) {
|
|
|
535
583
|
sessionOutput += m.outputTokens;
|
|
536
584
|
sessionCacheCreation += m.cacheCreationTokens;
|
|
537
585
|
sessionCacheRead += m.cacheReadTokens;
|
|
538
|
-
const
|
|
539
|
-
|
|
540
|
-
if (m.model
|
|
586
|
+
const k = bucketKey(new Date(m.timestamp));
|
|
587
|
+
bucketCosts[k] = (bucketCosts[k] || 0) + m.cost;
|
|
588
|
+
if (isRealModel(m.model)) {
|
|
541
589
|
modelCosts[m.model] = (modelCosts[m.model] || 0) + m.cost;
|
|
542
590
|
projModels.add(m.model);
|
|
543
591
|
}
|
|
@@ -566,12 +614,12 @@ async function getOverviewData(range, projectFilter) {
|
|
|
566
614
|
}
|
|
567
615
|
}
|
|
568
616
|
|
|
569
|
-
const
|
|
570
|
-
dailyStart.setHours(0, 0, 0, 0);
|
|
571
|
-
const filledDaily = buildFilledDaily(dailyCosts, dailyStart, now);
|
|
617
|
+
const costSeries = buildCostSeries(bucketCosts, cutoff, now, bucket);
|
|
572
618
|
|
|
573
619
|
const todayStr = localDateStr(now);
|
|
574
|
-
const todayCost =
|
|
620
|
+
const todayCost = Object.entries(bucketCosts)
|
|
621
|
+
.filter(([k]) => k.startsWith(todayStr))
|
|
622
|
+
.reduce((s, [, c]) => s + c, 0);
|
|
575
623
|
|
|
576
624
|
const totalInputAll = totalInput + totalCacheCreation + totalCacheRead;
|
|
577
625
|
const cacheEfficiency = totalInputAll > 0 ? totalCacheRead / totalInputAll : 0;
|
|
@@ -586,7 +634,7 @@ async function getOverviewData(range, projectFilter) {
|
|
|
586
634
|
totalInput, totalOutput, totalCacheCreation, totalCacheRead,
|
|
587
635
|
cacheEfficiency,
|
|
588
636
|
},
|
|
589
|
-
|
|
637
|
+
costSeries: { bucket, points: costSeries },
|
|
590
638
|
modelDistribution,
|
|
591
639
|
projects: projectSummaries.sort((a, b) => b.totalCost - a.totalCost),
|
|
592
640
|
};
|
|
@@ -621,7 +669,7 @@ async function getProjectsData(range, projectFilter) {
|
|
|
621
669
|
totalCost += cost;
|
|
622
670
|
sessionCount++;
|
|
623
671
|
for (const m of msgs) {
|
|
624
|
-
if (m.model
|
|
672
|
+
if (isRealModel(m.model)) {
|
|
625
673
|
projModelCounts[m.model] = (projModelCounts[m.model] || 0) + 1;
|
|
626
674
|
}
|
|
627
675
|
}
|
|
@@ -656,12 +704,14 @@ async function getProjectSessionsData(encodedPath, range) {
|
|
|
656
704
|
const cutoff = rangeToCutoff(range, now);
|
|
657
705
|
const projects = scanProjectDirs(cutoff);
|
|
658
706
|
const proj = projects.get(encodedPath);
|
|
659
|
-
|
|
707
|
+
const bucket = rangeBucket(range);
|
|
708
|
+
if (!proj) return { sessions: [], costSeries: { bucket, points: [] }, modelDistribution: [] };
|
|
660
709
|
|
|
661
710
|
const sessions = await loadProjectData(proj.files, pricing);
|
|
662
711
|
const cutoffStr = cutoff ? cutoff.toISOString() : null;
|
|
663
712
|
const result = [];
|
|
664
|
-
const
|
|
713
|
+
const bucketKey = BUCKETS[bucket].key;
|
|
714
|
+
const bucketCosts = {};
|
|
665
715
|
const modelCosts = {};
|
|
666
716
|
|
|
667
717
|
for (const [, session] of sessions) {
|
|
@@ -670,14 +720,12 @@ async function getProjectSessionsData(encodedPath, range) {
|
|
|
670
720
|
: session.messages;
|
|
671
721
|
if (msgs.length === 0) continue;
|
|
672
722
|
|
|
673
|
-
|
|
723
|
+
const sum = summarizeMessages(msgs);
|
|
674
724
|
const sessionModelCounts = {};
|
|
675
725
|
for (const m of msgs) {
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
dailyCosts[day] = (dailyCosts[day] || 0) + m.cost;
|
|
680
|
-
if (m.model && !m.model.startsWith('<')) {
|
|
726
|
+
const k = bucketKey(new Date(m.timestamp));
|
|
727
|
+
bucketCosts[k] = (bucketCosts[k] || 0) + m.cost;
|
|
728
|
+
if (isRealModel(m.model)) {
|
|
681
729
|
modelCosts[m.model] = (modelCosts[m.model] || 0) + m.cost;
|
|
682
730
|
sessionModelCounts[m.model] = (sessionModelCounts[m.model] || 0) + 1;
|
|
683
731
|
}
|
|
@@ -690,13 +738,8 @@ async function getProjectSessionsData(encodedPath, range) {
|
|
|
690
738
|
result.push({
|
|
691
739
|
sessionId: session.sessionId,
|
|
692
740
|
customTitle: session.customTitle,
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
outputTokens: output,
|
|
696
|
-
cacheCreationTokens: cacheCreation,
|
|
697
|
-
cacheReadTokens: cacheRead,
|
|
698
|
-
totalTokens: input + output + cacheCreation + cacheRead,
|
|
699
|
-
messageCount: msgs.length,
|
|
741
|
+
...sum,
|
|
742
|
+
totalTokens: sum.inputTokens + sum.outputTokens + sum.cacheCreationTokens + sum.cacheReadTokens,
|
|
700
743
|
models: [...session.models],
|
|
701
744
|
primaryModel,
|
|
702
745
|
firstPrompt: session.firstPrompt,
|
|
@@ -706,25 +749,43 @@ async function getProjectSessionsData(encodedPath, range) {
|
|
|
706
749
|
});
|
|
707
750
|
}
|
|
708
751
|
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
const dates = Object.keys(dailyCosts).sort();
|
|
715
|
-
dailyStart = dates.length ? new Date(dates[0] + 'T00:00:00') : now;
|
|
752
|
+
// No range means "everything", so the series starts at the first bucket that has cost.
|
|
753
|
+
let seriesStart = cutoff;
|
|
754
|
+
if (!seriesStart) {
|
|
755
|
+
const keys = Object.keys(bucketCosts).sort();
|
|
756
|
+
seriesStart = keys.length ? new Date(`${keys[0]}T00:00:00`) : now;
|
|
716
757
|
}
|
|
717
|
-
const
|
|
718
|
-
const filledDaily = buildFilledDaily(dailyCosts, dailyStart, dailyEnd);
|
|
758
|
+
const costSeries = buildCostSeries(bucketCosts, seriesStart, now, bucket);
|
|
719
759
|
|
|
720
760
|
const modelDistribution = buildModelDistribution(modelCosts);
|
|
721
761
|
|
|
722
762
|
const sorted = result.sort((a, b) => (b.lastTimestamp || '').localeCompare(a.lastTimestamp || ''));
|
|
723
|
-
const response = {
|
|
763
|
+
const response = {
|
|
764
|
+
sessions: sorted,
|
|
765
|
+
costSeries: { bucket, points: costSeries },
|
|
766
|
+
modelDistribution,
|
|
767
|
+
};
|
|
724
768
|
setCache(cacheKey, response);
|
|
725
769
|
return response;
|
|
726
770
|
}
|
|
727
771
|
|
|
772
|
+
// The detail view is always the whole session, unlike every other view. `inRange`/`today` carry
|
|
773
|
+
// the slices the UI needs to reconcile itself with the range-scoped session row that linked here,
|
|
774
|
+
// instead of silently disagreeing with it. They are derived outside the cache so switching ranges
|
|
775
|
+
// does not re-parse the session's JSONL.
|
|
776
|
+
function withSessionSlices(base, range) {
|
|
777
|
+
const now = new Date();
|
|
778
|
+
const cutoff = rangeToCutoff(range, now);
|
|
779
|
+
const sliceFrom = (from) => summarizeMessages(base.messages.filter(m => m.timestamp >= from));
|
|
780
|
+
const inRange = cutoff ? sliceFrom(cutoff.toISOString()) : null;
|
|
781
|
+
return {
|
|
782
|
+
...base,
|
|
783
|
+
range,
|
|
784
|
+
inRange,
|
|
785
|
+
today: range === 'today' ? inRange : sliceFrom(rangeToCutoff('today', now).toISOString()),
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
|
|
728
789
|
async function getSessionDetailData(sessionId) {
|
|
729
790
|
const cacheKey = `detail_${sessionId}`;
|
|
730
791
|
if (isCacheValid(cacheKey)) return dataCache[cacheKey];
|
|
@@ -780,6 +841,13 @@ async function getSessionDetailData(sessionId) {
|
|
|
780
841
|
// #region EXPRESS
|
|
781
842
|
|
|
782
843
|
const app = express();
|
|
844
|
+
|
|
845
|
+
// Mounted before express.json() so a rejected request never buffers a body.
|
|
846
|
+
const net = createNetGuard({ appName: 'Claude Code Cost Dashboard' });
|
|
847
|
+
app.use(net.hostGuard);
|
|
848
|
+
app.use(net.frameGuard);
|
|
849
|
+
app.use(net.originGuard);
|
|
850
|
+
|
|
783
851
|
app.use(express.json());
|
|
784
852
|
app.use(express.static(path.join(__dirname, 'public')));
|
|
785
853
|
|
|
@@ -844,9 +912,9 @@ app.get('/api/projects/:path/sessions', async (req, res) => {
|
|
|
844
912
|
|
|
845
913
|
app.get('/api/sessions/:id', async (req, res) => {
|
|
846
914
|
try {
|
|
847
|
-
const
|
|
848
|
-
if (!
|
|
849
|
-
res.json(
|
|
915
|
+
const base = await getSessionDetailData(req.params.id);
|
|
916
|
+
if (!base) return res.status(404).json({ error: 'Session not found' });
|
|
917
|
+
res.json(withSessionSlices(base, parseRange(req.query.range)));
|
|
850
918
|
} catch (err) {
|
|
851
919
|
console.error('[API] session detail error:', err);
|
|
852
920
|
res.status(500).json({ error: 'Failed to load session detail' });
|
|
@@ -878,25 +946,22 @@ app.post('/api/refresh', (_req, res) => {
|
|
|
878
946
|
|
|
879
947
|
// #region STARTUP
|
|
880
948
|
|
|
881
|
-
const
|
|
882
|
-
const actualPort = server.address().port;
|
|
949
|
+
const onReady = (actualPort) => {
|
|
883
950
|
console.log(`Claude Code Cost Dashboard running at http://localhost:${actualPort}`);
|
|
951
|
+
const warning = net.exposureWarning();
|
|
952
|
+
if (warning) console.log(warning);
|
|
884
953
|
|
|
885
954
|
if (process.argv.includes('--open')) {
|
|
886
955
|
import('open').then(mod => mod.default(`http://localhost:${actualPort}`));
|
|
887
956
|
}
|
|
888
|
-
}
|
|
957
|
+
};
|
|
958
|
+
|
|
959
|
+
const server = net.listenLoopback(app, PORT, onReady);
|
|
889
960
|
|
|
890
961
|
server.on('error', (err) => {
|
|
891
962
|
if (err.code === 'EADDRINUSE') {
|
|
892
963
|
console.log(`Port ${PORT} in use, trying random port...`);
|
|
893
|
-
|
|
894
|
-
const p = fallback.address().port;
|
|
895
|
-
console.log(`Claude Code Cost Dashboard running at http://localhost:${p}`);
|
|
896
|
-
if (process.argv.includes('--open')) {
|
|
897
|
-
import('open').then(mod => mod.default(`http://localhost:${p}`));
|
|
898
|
-
}
|
|
899
|
-
});
|
|
964
|
+
net.listenLoopback(app, 0, onReady);
|
|
900
965
|
} else {
|
|
901
966
|
throw err;
|
|
902
967
|
}
|