csusage 0.4.15

Coding agent CLI usage reports (ccusage fork with Claude Science support)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="light">
<title>csusage · Token 用量</title>
<style>
:root {
  --page: #ffffff;
  --text: #171717;
  --muted: #6f6f6f;
  --faint: #a1a1a1;
  --line: #ececec;
  --line-strong: #dedede;
  --blue-0: #f2f2f2;
  --blue-1: #e2ecfa;
  --blue-2: #c8dcf5;
  --blue-3: #9fc3ed;
  --blue-4: #5d97d9;
  --blue-5: #2f73c8;
  --shadow: 0 18px 50px rgba(0, 0, 0, 0.06);
}

* { box-sizing: border-box; }
html { min-width: 320px; }

body {
  margin: 0;
  background: var(--page);
  color: var(--text);
  font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif;
  font-size: 14px;
  -webkit-font-smoothing: antialiased;
}

button, summary { font: inherit; }
button:focus-visible, summary:focus-visible {
  outline: 2px solid var(--blue-5);
  outline-offset: 2px;
}

.shell {
  width: min(100% - 40px, 860px);
  margin: 0 auto;
  padding: 32px 0 64px;
}

.profile {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 0 42px;
  text-align: center;
}

.avatar {
  display: grid;
  width: 78px;
  height: 78px;
  place-items: center;
  border: 4px solid #fff;
  border-radius: 50%;
  background: linear-gradient(145deg, #ac69c2 0%, #8a42ad 100%);
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.03), var(--shadow);
  color: #fff;
  font-size: 29px;
  font-weight: 450;
  letter-spacing: -0.04em;
}

.profile h1 {
  margin: 15px 0 7px;
  font-size: 24px;
  font-weight: 600;
  letter-spacing: -0.025em;
}

.profile-meta {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  gap: 7px;
  color: var(--faint);
  font-size: 13px;
}
.profile-meta .dot { color: #cfcfcf; }

.stats {
  display: grid;
  grid-template-columns: repeat(5, minmax(0, 1fr));
  margin-bottom: 40px;
  padding: 11px 0;
  border: 1px solid var(--line);
  border-radius: 17px;
}

.stat {
  min-width: 0;
  padding: 0 13px;
  text-align: center;
}
.stat + .stat { border-left: 1px solid var(--line); }

.stat-value, .stat-label {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.stat-value {
  color: #262626;
  font-size: 14px;
  font-variant-numeric: tabular-nums;
  line-height: 1.5;
}
.stat-label { color: var(--muted); font-size: 13px; line-height: 1.45; }

.activity { margin-bottom: 46px; }
.activity-heading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}
.activity-heading h2, .section-heading {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  letter-spacing: -0.01em;
}

.view-switcher { display: inline-flex; align-items: center; gap: 17px; }
.view-switcher button {
  padding: 0;
  border: 0;
  background: transparent;
  color: #a1a1a1;
  cursor: pointer;
  font-size: 13px;
  line-height: 24px;
  transition: color 150ms ease;
}
.view-switcher button:hover { color: #555; }
.view-switcher button.active { color: var(--text); font-weight: 600; }

.heatmap-scroll {
  overflow-x: auto;
  /* Room for the hovered cell's scale(1.22) so it never triggers a scrollbar. */
  padding: 3px 8px 6px;
  scrollbar-width: thin;
  scrollbar-color: #d8d8d8 transparent;
}
.heatmap-content { min-width: 720px; }
.month-labels, .heatmap-grid {
  display: grid;
  grid-template-columns: repeat(53, minmax(0, 1fr));
  gap: 4px;
}
.month-labels {
  min-height: 18px;
  margin-top: 8px;
  color: #9a9a9a;
  font-size: 11px;
  line-height: 1;
}
.month-label { overflow: visible; white-space: nowrap; }
.week-column {
  display: flex;
  min-width: 0;
  flex-direction: column;
  gap: 4px;
}
.heat-cell {
  width: 100%;
  aspect-ratio: 1;
  padding: 0;
  border: 0;
  border-radius: 3px;
  background: var(--blue-0);
  cursor: default;
  transition: transform 100ms ease, box-shadow 100ms ease;
}
.heat-cell:hover {
  position: relative;
  z-index: 1;
  transform: scale(1.22);
  box-shadow: 0 0 0 2px #fff;
}
.week-column.weekly .heat-cell { height: 14px; aspect-ratio: auto; }

.tooltip {
  position: fixed;
  z-index: 20;
  display: none;
  max-width: min(310px, calc(100vw - 24px));
  padding: 8px 11px;
  border: 1px solid rgba(255, 255, 255, 0.12);
  border-radius: 8px;
  background: #202020;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);
  color: #fff;
  font-size: 12px;
  line-height: 1.5;
  pointer-events: none;
}

.details-stack {
  display: grid;
  gap: 12px;
  padding-top: 4px;
  border-top: 1px solid var(--line);
}
.data-panel {
  overflow: hidden;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: #fff;
}
.data-panel summary {
  display: flex;
  min-height: 52px;
  align-items: center;
  justify-content: space-between;
  padding: 0 17px;
  cursor: pointer;
  list-style: none;
  user-select: none;
}
.data-panel summary::-webkit-details-marker { display: none; }
.data-panel th.sortable { cursor: pointer; user-select: none; }
.data-panel th.sortable:hover { color: var(--text); }
.summary-copy { display: flex; align-items: baseline; gap: 8px; }
.summary-count { color: var(--faint); font-size: 12px; }
.chevron {
  width: 7px;
  height: 7px;
  border-right: 1.5px solid #888;
  border-bottom: 1.5px solid #888;
  transform: rotate(45deg) translateY(-2px);
  transition: transform 150ms ease;
}
.data-panel[open] .chevron { transform: rotate(225deg) translate(-1px, -1px); }
.table-scroll { overflow-x: auto; border-top: 1px solid var(--line); }

table {
  width: 100%;
  min-width: 680px;
  border-collapse: collapse;
  font-size: 12px;
  font-variant-numeric: tabular-nums;
}
th, td {
  padding: 11px 14px;
  border-bottom: 1px solid var(--line);
  text-align: left;
  white-space: nowrap;
}
th { background: #fbfbfb; color: var(--muted); font-size: 11px; font-weight: 500; }
td { color: #404040; }
tr:last-child td { border-bottom: 0; }
.num { text-align: right; }
.agent-name { display: inline-flex; align-items: center; gap: 8px; color: #252525; font-weight: 500; }
.agent-dot { width: 8px; height: 8px; flex: 0 0 auto; border-radius: 50%; }

.loading-state, .error-state {
  display: grid;
  min-height: 72vh;
  place-items: center;
  color: var(--muted);
  text-align: center;
}
.spinner {
  width: 22px;
  height: 22px;
  margin: 0 auto 13px;
  border: 2px solid #e7e7e7;
  border-top-color: #777;
  border-radius: 50%;
  animation: spin 700ms linear infinite;
}
.retry {
  margin-top: 14px;
  padding: 7px 14px;
  border: 1px solid var(--line-strong);
  border-radius: 8px;
  background: #fff;
  color: var(--text);
  cursor: pointer;
}
@keyframes spin { to { transform: rotate(360deg); } }

@media (max-width: 680px) {
  .shell { width: min(100% - 28px, 860px); padding-top: 24px; }
  .profile { padding-bottom: 32px; }
  .avatar { width: 70px; height: 70px; font-size: 26px; }
  .stats { grid-template-columns: repeat(2, minmax(0, 1fr)); padding: 0; }
  .stat { padding: 12px 8px; }
  .stat + .stat { border-left: 0; }
  .stat:nth-child(even) { border-left: 1px solid var(--line); }
  .stat:nth-child(n + 3) { border-top: 1px solid var(--line); }
  .stat:last-child { grid-column: 1 / -1; }
  .activity-heading { align-items: flex-start; gap: 12px; }
  .view-switcher { gap: 13px; }
}

@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after { scroll-behavior: auto !important; transition: none !important; animation: none !important; }
}
</style>
</head>
<body>
<main id="app" class="loading-state" aria-live="polite">
  <div><div class="spinner"></div>正在汇总用量数据…</div>
</main>
<div class="tooltip" id="tooltip" role="tooltip"></div>

<script>
const HEAT = ['var(--blue-0)', 'var(--blue-1)', 'var(--blue-2)', 'var(--blue-3)', 'var(--blue-4)', 'var(--blue-5)'];
const AGENT_COLORS = ['#2f73c8', '#8a42ad', '#16866f', '#ce6b32', '#b83e6c', '#66853b', '#7f6acb', '#398aab', '#a97318', '#5b6c88'];
const DAY_MS = 86_400_000;
let data = null;
let mode = 'daily';

const fmtInt = value => Number(value || 0).toLocaleString('zh-CN');

function fmtCompact(value) {
  const number = Number(value || 0);
  if (number >= 1e8) return trimDecimal(number / 1e8) + '亿';
  if (number >= 1e4) return trimDecimal(number / 1e4) + '';
  return fmtInt(number);
}

function trimDecimal(value) {
  return value.toLocaleString('zh-CN', {maximumFractionDigits: 1, minimumFractionDigits: value < 100 ? 1 : 0});
}

function fmtCost(value) {
  if (value == null) return '';
  const number = Number(value);
  return number > 0 && number < 0.01 ? '$' + number.toFixed(4) : '$' + number.toFixed(2);
}

function fmtDuration(ms) {
  if (!ms || ms <= 0) return '';
  const minutes = Math.floor(ms / 60_000);
  if (minutes < 1) return '<1 分钟';
  if (minutes < 60) return minutes + ' 分钟';
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return hours + ' 小时 ' + (minutes % 60) + '';
  return Math.floor(hours / 24) + '' + (hours % 24) + ' 小时';
}

function escapeHtml(value) {
  return String(value ?? '')
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;');
}

function utcDate(value) {
  const date = value instanceof Date ? new Date(value) : new Date(value + 'T00:00:00Z');
  return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
}
const dateKey = date => date.toISOString().slice(0, 10);
const addUtcDays = (date, days) => new Date(date.getTime() + days * DAY_MS);

function initials(name) {
  const clean = String(name || 'user').trim();
  const words = clean.split(/[\s_-]+/).filter(Boolean);
  if (words.length > 1) return (words[0][0] + words[1][0]).toUpperCase();
  return (clean.length <= 3 ? clean.slice(0, 2) : clean.slice(0, 1)).toUpperCase();
}

async function main() {
  try {
    const response = await fetch('/api/usage', {headers: {'Accept': 'application/json'}});
    const payload = await response.json();
    if (!response.ok) throw new Error(payload.error || '无法加载用量数据');
    data = payload;
    render();
  } catch (error) {
    const app = document.getElementById('app');
    app.className = 'error-state';
    app.innerHTML = `<div><strong></strong><div style="margin-top:8px">${escapeHtml(error.message)}</div><button class="retry" onclick="location.reload()"></button></div>`;
  }
}

function render() {
  const user = String(data.user || 'user');
  const agents = Array.isArray(data.agents) ? data.agents : [];
  const sessions = Array.isArray(data.sessions) ? data.sessions : [];
  const peak = data.peakDay || {};
  const generatedAt = data.generatedAt ? new Date(data.generatedAt).toLocaleString('zh-CN', {dateStyle: 'medium', timeStyle: 'short'}) : '';
  const app = document.getElementById('app');
  app.className = 'shell';
  app.innerHTML = `
    <header class="profile">
      <div class="avatar" aria-hidden="true">${escapeHtml(initials(user))}</div>
      <h1>${escapeHtml(user)}</h1>
      <div class="profile-meta">
        <span>@${escapeHtml(user)}</span><span class="dot">·</span>
        <span>${fmtInt(agents.length)}  Agent</span><span class="dot">·</span>
        <span>${fmtInt(data.totalSessions)} </span><span class="dot">·</span>
        <span>${fmtCost(data.totalCostUsd)}</span>
      </div>
    </header>
    <section class="stats" aria-label="">
      ${stat(fmtCompact(data.totalTokens), '累计 Token 数', ` ${fmtInt(data.totalInputTokens)} ${fmtInt(data.totalOutputTokens)}`)}
      ${stat(fmtCompact(peak.totalTokens), '峰值 Token 数', peak.date || '')}
      ${stat(fmtDuration(data.longestSessionMs), '最长聊天时长')}
      ${stat(fmtInt(data.currentStreakDays) + '', '当前连续天数')}
      ${stat(fmtInt(data.longestStreakDays) + '', '最长连续天数')}
    </section>
    <section class="activity" aria-labelledby="activity-title">
      <div class="activity-heading">
        <h2 id="activity-title">Token </h2>
        <div class="view-switcher" role="group" aria-label="">
          <button id="btn-daily" type="button" onclick="setMode('daily')"></button>
          <button id="btn-weekly" type="button" onclick="setMode('weekly')"></button>
          <button id="btn-cumulative" type="button" onclick="setMode('cumulative')"></button>
        </div>
      </div>
      <div class="heatmap-scroll"><div id="heatmap"></div></div>
    </section>
    <section class="details-stack" aria-label="">
      ${renderAgentPanel(agents)}
      ${renderModelPanel(Array.isArray(data.models) ? data.models : [])}
      ${renderSessionPanel(sessions)}
    </section>
    <div style="margin-top:18px;text-align:center;color:var(--faint);font-size:11px"> ${escapeHtml(generatedAt)}</div>
  `;
  setMode(mode);
}

function stat(value, label, title = '') {
  return `<div class="stat"${title ? ` title="${escapeHtml(title)}"` : ''}><div class="stat-value">${escapeHtml(value)}</div><div class="stat-label">${escapeHtml(label)}</div></div>`;
}

function renderAgentPanel(agents) {
  if (!agents.length) return '';
  const rows = agents.map((agent, index) => `
    <tr><td><span class="agent-name"><span class="agent-dot" style="background:${AGENT_COLORS[index % AGENT_COLORS.length]}"></span>${escapeHtml(agent.agent)}</span></td>
    <td class="num">${fmtInt(agent.inputTokens)}</td><td class="num">${fmtInt(agent.outputTokens)}</td>
    <td class="num">${fmtInt(agent.cacheReadTokens)}</td><td class="num">${fmtInt(agent.cacheWriteTokens)}</td>
    <td class="num">${fmtInt(agent.totalTokens)}</td><td class="num">${fmtCost(agent.costUsd)}</td></tr>`).join('');
  return `<details class="data-panel" open>
    <summary><span class="summary-copy"><span class="section-heading">Agent </span><span class="summary-count">${fmtInt(agents.length)}</span></span><span class="chevron" aria-hidden="true"></span></summary>
    <div class="table-scroll"><table><thead><tr><th>Agent</th><th class="num"></th><th class="num"></th><th class="num"></th><th class="num"></th><th class="num"></th><th class="num"></th></tr></thead><tbody>${rows}</tbody></table></div>
  </details>`;
}

let modelSort = { key: 'totalTokens', desc: true };

function sortModels(key) {
  if (modelSort.key === key) {
    modelSort.desc = !modelSort.desc;
  } else {
    modelSort = { key, desc: true };
  }
  render();
}

function renderModelPanel(models) {
  if (!models.length) return '';
  const columns = [
    ['model', '模型', ''],
    ['inputTokens', '输入', 'num'],
    ['outputTokens', '输出', 'num'],
    ['cacheReadTokens', '缓存读', 'num'],
    ['cacheWriteTokens', '缓存写', 'num'],
    ['totalTokens', '合计', 'num'],
    ['costUsd', '成本', 'num'],
    ['sessions', '会话', 'num'],
  ];
  const head = columns.map(([key, label, cls]) => {
    const arrow = modelSort.key === key ? (modelSort.desc ? '' : '') : '';
    return `<th class="sortable ${cls}" onclick="sortModels('${key}')" title="">${label}${arrow}</th>`;
  }).join('');
  const sorted = [...models].sort((a, b) => {
    const va = a[modelSort.key], vb = b[modelSort.key];
    const cmp = typeof va === 'string' || typeof vb === 'string'
      ? String(va).localeCompare(String(vb))
      : (va || 0) - (vb || 0);
    return modelSort.desc ? -cmp : cmp;
  });
  const rows = sorted.map(m => `
    <tr><td>${escapeHtml(m.model || '')}</td>
    <td class="num">${fmtInt(m.inputTokens)}</td><td class="num">${fmtInt(m.outputTokens)}</td>
    <td class="num">${fmtInt(m.cacheReadTokens)}</td><td class="num">${fmtInt(m.cacheWriteTokens)}</td>
    <td class="num">${fmtInt(m.totalTokens)}</td><td class="num">${fmtCost(m.costUsd)}</td>
    <td class="num">${fmtInt(m.sessions)}</td></tr>`).join('');
  return `<details class="data-panel" open>
    <summary><span class="summary-copy"><span class="section-heading"></span><span class="summary-count">${fmtInt(models.length)}</span></span><span class="chevron" aria-hidden="true"></span></summary>
    <div class="table-scroll"><table><thead><tr>${head}</tr></thead><tbody>${rows}</tbody></table></div>
  </details>`;
}

function renderSessionPanel(sessions) {
  if (!sessions.length) return '';
  const visible = sessions.slice(0, 30);
  const rows = visible.map(session => {
    const id = String(session.sessionId || '');
    const shortId = id.length > 18 ? id.slice(0, 18) + '' : id;
    const started = session.startMs ? new Date(session.startMs).toLocaleString('zh-CN', {dateStyle: 'short', timeStyle: 'short'}) : '';
    return `<tr><td>${escapeHtml(session.agent)}${session.host ? ` <span class="dot">·</span>${escapeHtml(session.host)}` : ''}</td><td title="${escapeHtml(id)}">${escapeHtml(shortId)}</td>
      <td>${escapeHtml(started)}</td><td class="num">${escapeHtml(fmtDuration(session.durationMs))}</td>
      <td class="num">${fmtInt(session.totalTokens)}</td><td class="num">${fmtCost(session.costUsd)}</td>
      <td>${escapeHtml((session.models || []).join(', ') || '')}</td></tr>`;
  }).join('');
  return `<details class="data-panel" open>
    <summary><span class="summary-copy"><span class="section-heading"></span><span class="summary-count">${fmtInt(visible.length)}</span></span><span class="chevron" aria-hidden="true"></span></summary>
    <div class="table-scroll"><table><thead><tr><th>Agent</th><th></th><th></th><th class="num"></th><th class="num"></th><th class="num"></th><th></th></tr></thead><tbody>${rows}</tbody></table></div>
  </details>`;
}

function setMode(nextMode) {
  mode = nextMode;
  for (const key of ['daily', 'weekly', 'cumulative']) {
    const button = document.getElementById('btn-' + key);
    if (!button) continue;
    const active = key === mode;
    button.classList.toggle('active', active);
    button.setAttribute('aria-pressed', String(active));
  }
  const heatmap = document.getElementById('heatmap');
  if (heatmap) heatmap.innerHTML = renderHeatmap();
}

function activityRange() {
  const today = utcDate(new Date());
  const end = addUtcDays(today, 6 - today.getUTCDay());
  return {start: addUtcDays(end, -(53 * 7 - 1)), end};
}

function renderHeatmap() {
  const {start} = activityRange();
  const today = utcDate(new Date());
  const daysByDate = new Map((data.days || []).map(day => [String(day.date), day]));
  const columns = [];
  const weeklyTotals = new Map();
  let cumulative = 0;
  let maxValue = 1;

  for (let weekIndex = 0; weekIndex < 53; weekIndex++) {
    const weekStart = addUtcDays(start, weekIndex * 7);
    const week = [];
    let weekTotal = 0;
    for (let dayIndex = 0; dayIndex < 7; dayIndex++) {
      const date = addUtcDays(weekStart, dayIndex);
      const record = daysByDate.get(dateKey(date));
      weekTotal += Number(record?.totalTokens || 0);
      week.push({date, record});
    }
    weeklyTotals.set(dateKey(weekStart), weekTotal);
    columns.push(week);
  }

  const cells = columns.map(week => week.map(({date, record}) => {
    const dayValue = Number(record?.totalTokens || 0);
    cumulative += dayValue;
    let value = dayValue;
    if (mode === 'weekly') value = weeklyTotals.get(dateKey(week[0].date)) || 0;
    if (mode === 'cumulative') value = cumulative;
    if (date > today) value = 0;
    maxValue = Math.max(maxValue, value);
    return {date, record, value};
  }));

  const monthLabels = [];
  for (let index = 0; index < 53; index++) {
    const weekStart = columns[index][0].date;
    for (let offset = 0; offset < 7; offset++) {
      const date = addUtcDays(weekStart, offset);
      if (date.getUTCDate() === 1 && index > 1) {
        monthLabels.push({column: index + 1, label: (date.getUTCMonth() + 1) + ''});
        break;
      }
    }
  }

  const labelsHtml = monthLabels.map(item => `<span class="month-label" style="grid-column:${item.column}">${item.label}</span>`).join('');
  let gridHtml;
  if (mode === 'weekly') {
    gridHtml = cells.map(week => {
      const cell = week[0];
      const total = weeklyTotals.get(dateKey(cell.date)) || 0;
      const end = addUtcDays(cell.date, 6);
      return `<div class="week-column weekly">${heatCell(total, maxValue, `${dateKey(cell.date)}  ${dateKey(end)} · ${fmtInt(total)} tokens`)}</div>`;
    }).join('');
  } else {
    gridHtml = cells.map(week => `<div class="week-column">${week.map(cell => {
      const key = dateKey(cell.date);
      const tip = cell.date > today
        ? `${key} · `
        : mode === 'cumulative'
        ? `${key} ·  ${fmtInt(cell.value)} tokens`
        : cell.record
          ? `${key} · ${fmtCompact(cell.record.totalTokens)} tokens · ${fmtCost(cell.record.costUsd)}`
          : `${key} · `;
      return heatCell(cell.value, maxValue, tip);
    }).join('')}</div>`).join('');
  }
  return `<div class="heatmap-content"><div class="heatmap-grid">${gridHtml}</div><div class="month-labels">${labelsHtml}</div></div>`;
}

function heatCell(value, max, tip) {
  return `<span class="heat-cell" style="background:${HEAT[heatLevel(value, max)]}" data-tip="${escapeHtml(tip)}" role="img" aria-label="${escapeHtml(tip)}"></span>`;
}

function heatLevel(value, max) {
  if (!value || value <= 0) return 0;
  const ratio = Math.log1p(value) / Math.log1p(max);
  if (ratio <= 0.35) return 1;
  if (ratio <= 0.55) return 2;
  if (ratio <= 0.72) return 3;
  if (ratio <= 0.88) return 4;
  return 5;
}

const tooltip = document.getElementById('tooltip');
function showTooltip(cell, event) {
  tooltip.textContent = cell.dataset.tip;
  tooltip.style.display = 'block';
  const rect = cell.getBoundingClientRect();
  const left = event?.clientX || rect.left + rect.width / 2;
  const top = event?.clientY || rect.top;
  tooltip.style.left = Math.max(12, Math.min(left + 10, window.innerWidth - tooltip.offsetWidth - 12)) + 'px';
  tooltip.style.top = Math.max(12, top - tooltip.offsetHeight - 10) + 'px';
}

document.addEventListener('pointerover', event => {
  const cell = event.target.closest?.('.heat-cell');
  if (cell) showTooltip(cell, event);
});
document.addEventListener('pointerout', event => {
  if (event.target.closest?.('.heat-cell')) tooltip.style.display = 'none';
});
main();
</script>
</body>
</html>