-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclaude-usage-snapshot.user.js
More file actions
757 lines (676 loc) · 33.4 KB
/
Copy pathclaude-usage-snapshot.user.js
File metadata and controls
757 lines (676 loc) · 33.4 KB
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
// ==UserScript==
// @name Claude Usage Snapshot
// @namespace https://github.com/vector76/cc_usage_dashboard
// @version 0.9.0
// @description Reads "Current session", "All models", and "Fable" usage % from claude.ai and posts them to the local Claude Usage Dashboard trayapp.
// @author Claude Usage Dashboard
// @match https://claude.ai/*
// @grant GM.xmlHttpRequest
// @connect localhost
// @connect 127.0.0.1
// @updateURL https://raw.githubusercontent.com/vector76/cc_usage_dashboard/main/userscript/claude-usage-snapshot.user.js
// @downloadURL https://raw.githubusercontent.com/vector76/cc_usage_dashboard/main/userscript/claude-usage-snapshot.user.js
// @run-at document-start
// ==/UserScript==
(function () {
'use strict';
// ---------- visibility spoof (mirror of userscript/lib/visibility.js) ----------
//
// Installed first thing, before any other script reads the
// visibility API. See lib/visibility.js for full rationale; the
// short version is that claude.ai's poll loop pauses when the OS
// reports the tab as hidden (screensaver, minimize), and we want
// to keep it polling so the userscript still has fresh DOM to
// observe. `@run-at document-start` (above) is what lets this
// beat claude.ai's app init.
function installVisibilitySpoof(doc) {
if (!doc) return;
function defineAlwaysVisible(propName, value) {
try {
Object.defineProperty(doc, propName, {
configurable: true,
get() { return value; },
});
} catch (_) {
// Some hosts may have already locked the property
// as non-configurable; silently no-op.
}
}
defineAlwaysVisible('hidden', false);
defineAlwaysVisible('visibilityState', 'visible');
defineAlwaysVisible('webkitHidden', false);
defineAlwaysVisible('webkitVisibilityState', 'visible');
// Suppress visibilitychange events at the capture phase
// before any application-registered listener on `document`
// can observe them. (visibilitychange does not bubble to
// window, so listeners there are out of scope.) Cover the
// prefixed variant too.
if (typeof doc.addEventListener === 'function') {
const swallow = (e) => {
if (typeof e.stopImmediatePropagation === 'function') {
e.stopImmediatePropagation();
}
if (typeof e.stopPropagation === 'function') {
e.stopPropagation();
}
};
doc.addEventListener('visibilitychange', swallow, true);
doc.addEventListener('webkitvisibilitychange', swallow, true);
}
}
installVisibilitySpoof(typeof document !== 'undefined' ? document : null);
const ENDPOINT_SNAPSHOT = 'http://localhost:27812/snapshot';
const ENDPOINT_PARSE_ERROR = 'http://localhost:27812/parse_error';
// Legacy full-page route. As of the June 2026 redesign, settings is a
// hash-routed modal ("/new#settings/usage"); see isUsageRoute (mirror of
// userscript/lib/route.js) for the predicate that accepts both forms.
const USAGE_PATH = '/settings/usage';
// Backstop polling — primary signal is a MutationObserver on aria-valuenow,
// so the interval only catches edge cases (observer torn down by SPA
// re-render, tab woken from background throttle, etc.). Each tick is
// gated by the dedup decision, so a fast cadence is cheap.
const POST_INTERVAL_MS = 60 * 1000;
const DOM_WAIT_TIMEOUT_MS = 30 * 1000;
const DOM_MISSING_REPORT_MS = 5 * 60 * 1000;
const PARSE_ERROR_REPORT_COOLDOWN_MS = 60 * 60 * 1000;
// Section heading texts that anchor extraction. Row labels under each
// heading change as Anthropic adjusts plan features (Sonnet only, Claude
// Design, Routines, …); section names move occasionally too. We match
// any of the known variants as a prefix so a trailing plan-tier badge
// ("Your usage limitsTeam", "Plan usage limitsMax (20x)") doesn't break
// extraction. The first usage bar following each heading is the one
// we keep.
//
// Known session-heading history:
// "Plan usage limits" — through April 2026
// "Your usage limits" — observed May 2026
const SESSION_HEADINGS = ['Your usage limits', 'Plan usage limits'];
const WEEKLY_HEADING = 'Weekly limits';
// Mirror of userscript/lib/rows.js — see there for why the per-model
// Fable sub-row has to be matched by label while every other row we
// read is selected positionally. Edit both together.
const FABLE_ROW_LABEL_PREFIXES = ['fable'];
function isFableRowLabel(label) {
if (typeof label !== 'string') return false;
const t = label.trim().toLowerCase();
if (!t) return false;
return FABLE_ROW_LABEL_PREFIXES.some(p => t.startsWith(p));
}
// Coalesce burst mutations (multiple bars updating in one React commit)
// into a single dispatch.
const DISPATCH_DEBOUNCE_MS = 250;
let lastParseErrorAt = 0;
let domFirstMissingAt = null;
let dispatchTimer = null;
// Rolling reference for the limbo "Last updated decrease" trigger.
// Updated on every DOM read regardless of whether we sent, because
// the staleness counter can roll back (claude.ai re-poll) between
// two successive reads even when nothing else changes — and because
// anchoring this to last-sent state self-traps once an "age=0" send
// lands. Lost on page reload; cold-start handles re-establishment.
let lastObservedAgeMs = null;
// ---------- persistent state ----------
// Mirror of userscript/lib/state.js — same source of truth, inlined
// here so Tampermonkey runs without a build step. Edit both together.
const STATE_STORAGE_KEY = 'claude-usage-snapshot.state.v1';
function loadState() {
try {
const storage = (typeof globalThis !== 'undefined' && globalThis.localStorage) || null;
if (!storage) return null;
const raw = storage.getItem(STATE_STORAGE_KEY);
if (raw == null) return null;
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== 'object') return null;
if (typeof parsed.lastSentAtMs !== 'number') return null;
const result = {
lastSentAtMs: parsed.lastSentAtMs,
lastPercent: parsed.lastPercent,
lastResetText: parsed.lastResetText,
lastWindowEndsMs: parsed.lastWindowEndsMs,
// Records written before the Fable row existed have no such
// key. Normalize to null on read so the dedup comparison
// sees "absent" rather than undefined.
lastFablePercent: parsed.lastFablePercent === undefined ? null : parsed.lastFablePercent,
};
if (parsed.lastSessionActive !== undefined) result.lastSessionActive = parsed.lastSessionActive;
if (parsed.lastWeeklyActive !== undefined) result.lastWeeklyActive = parsed.lastWeeklyActive;
return result;
} catch (_) {
return null;
}
}
function recordSentState({ sentAtMs, percent, resetText, windowEndsMs, sessionActive, weeklyActive, fablePercent }) {
try {
const storage = (typeof globalThis !== 'undefined' && globalThis.localStorage) || null;
if (!storage) return;
const record = {
lastSentAtMs: sentAtMs,
lastPercent: percent,
lastResetText: resetText,
lastWindowEndsMs: windowEndsMs,
// Always written (null when the row is absent) so the dedup
// comparison has a stable reference on both sides.
lastFablePercent: fablePercent === undefined ? null : fablePercent,
};
if (sessionActive !== undefined) record.lastSessionActive = sessionActive;
if (weeklyActive !== undefined) record.lastWeeklyActive = weeklyActive;
storage.setItem(STATE_STORAGE_KEY, JSON.stringify(record));
} catch (_) {
// Persistence is best-effort.
}
}
// ---------- continuity decision (mirror of userscript/lib/continuity.js) ----------
const WALL_CLOCK_GAP_MS = 15 * 60 * 1000;
const WINDOW_ENDS_JUMP_MS = 60 * 60 * 1000;
function decideContinuity(observation, prevState, nowMs) {
if (!prevState) return false;
if (nowMs - prevState.lastSentAtMs > WALL_CLOCK_GAP_MS) return false;
if (observation.percent < prevState.lastPercent) return false;
const cur = observation.windowEndsMs;
const prev = prevState.lastWindowEndsMs;
if (typeof cur === 'number' && typeof prev === 'number' &&
Math.abs(cur - prev) > WINDOW_ENDS_JUMP_MS) {
return false;
}
return true;
}
// ---------- dedup decision (mirror of userscript/lib/dedup.js) ----------
// The parameter intentionally shadows the module-level
// `lastObservedAgeMs` so the body is textually identical to the
// single source of truth in userscript/lib/dedup.js; the shadow is
// local to this function and the module-level binding is unchanged.
// Absent-ness normalizer: a missing key and an explicit null must
// compare equal, or a page with no Fable row read against a pre-Fable
// state record would differ on every trigger and defeat the dedup.
function _absentAsNull(v) {
return v === undefined ? null : v;
}
function shouldSend(observation, prevState, lastObservedAgeMs) {
if (!prevState) return 'send';
if (observation.sessionUsed !== prevState.lastPercent) return 'send';
// Fable gets its own signal because its cap is tighter than the
// session window's, so it can gain a whole point while the session
// bar is still rounding to the same integer. The weekly aggregate
// needs no such check: its denominator is larger than the session's,
// so it cannot advance without the session percent advancing first.
if (_absentAsNull(observation.fableWeeklyUsed) !== _absentAsNull(prevState.lastFablePercent)) {
return 'send';
}
if (observation.resetText !== prevState.lastResetText) return 'send';
const wasLimbo = prevState.lastSessionActive === false;
const nowLimbo = observation.sessionActive === false;
if (wasLimbo !== nowLimbo) return 'send';
const wasWeeklyLimbo = prevState.lastWeeklyActive === false;
const nowWeeklyLimbo = observation.weeklyActive === false;
if (wasWeeklyLimbo !== nowWeeklyLimbo) return 'send';
if (nowLimbo) {
// While in limbo the visible numbers don't move, so a strict
// *decrease* in "Last updated" age is our only signal that a
// fresh poll landed. Compare against the rolling
// most-recently-observed age (not the persisted last-sent
// age, which would self-trap at its floor of 0). Null on
// either side is "no information" and must not fire. We do
// NOT fire on the age incrementing — that advances on pure
// wall-clock time and would re-introduce the spam dedup is
// meant to prevent.
const cur = observation.lastUpdatedAgeMs;
if (cur != null && lastObservedAgeMs != null && cur < lastObservedAgeMs) {
return 'send';
}
}
return 'skip';
}
// ---------- utilities ----------
function warn(...args) {
try { console.warn('[claude-usage-snapshot]', ...args); } catch (_) { /* ignore */ }
}
function postJSON(url, body, onSuccess) {
try {
const payload = JSON.stringify(body);
GM.xmlHttpRequest({
method: 'POST',
url: url,
headers: { 'Content-Type': 'application/json' },
data: payload,
timeout: 5000,
onerror: (e) => warn('POST failed', url, e && e.error),
ontimeout: () => warn('POST timed out', url),
onload: (resp) => {
if (resp.status < 200 || resp.status >= 300) {
warn('POST non-2xx', url, resp.status);
return;
}
if (typeof onSuccess === 'function') {
try { onSuccess(); } catch (e) { warn('onSuccess threw', e); }
}
},
});
} catch (e) {
warn('POST threw', url, e);
}
}
// Mirror of userscript/lib/route.js — edit both together. Accepts the
// legacy "/settings/usage" path and the hash-routed modal form
// ("/new#settings/usage") introduced in the June 2026 redesign.
function isUsageRoute(pathname, hash) {
if (pathname === USAGE_PATH) return true;
const route = String(hash || '').replace(/^#/, '');
return /^\/?settings\/usage(?:[/?]|$)/.test(route);
}
function onUsagePage() {
return isUsageRoute(location.pathname, location.hash);
}
// ---------- usage-bar recognition (mirror of userscript/lib/bars.js) ----------
//
// Markup history (see lib/bars.js for the full rationale):
// - Through early July 2026 each usage bar was
// <div role="progressbar" aria-label="Usage" aria-valuenow="…">.
// - As of July 2026 the page uses a design-system Meter component:
// <div data-cds="Meter"><div role="meter" aria-valuenow="…"
// aria-labelledby="…"> — role changed to "meter", no aria-label.
// The "Usage credits" meter also matches; section-heading anchoring in
// extractQuota discards it because its heading matches neither section.
const USAGE_BAR_SELECTOR =
'[role="progressbar"][aria-label="Usage"], [role="meter"][aria-valuenow]';
function isUsageBarTarget(role, ariaLabel) {
if (role === 'meter') return true;
return role === 'progressbar' && ariaLabel === 'Usage';
}
// ---------- DOM extraction ----------
// For each usage bar, the most recent <h2> in document order tells us
// which section it belongs to. This is robust to row-label edits and to
// the order of sub-rows within a section.
function precedingHeading(bar, headings) {
let result = null;
for (const h of headings) {
if (h.node.compareDocumentPosition(bar) & Node.DOCUMENT_POSITION_FOLLOWING) {
result = h.text;
} else {
break; // headings are in document order; stop at the first one not-before
}
}
return result;
}
// Resolve a usage bar's accessible name. The July 2026 Meter markup
// carries no aria-label; the name comes from aria-labelledby pointing at
// the row-label span (possibly several ids, space-separated, per ARIA).
// Falls back to aria-label for the legacy progressbar generation, and
// returns null when neither resolves — callers must treat that as
// "unknown row", never as a match.
function resolveBarLabel(bar) {
const ids = (bar.getAttribute('aria-labelledby') || '').split(/\s+/).filter(Boolean);
if (ids.length) {
const parts = [];
for (const id of ids) {
const node = document.getElementById(id);
if (node) parts.push((node.textContent || '').trim());
}
const joined = parts.join(' ').trim();
if (joined) return joined;
}
return bar.getAttribute('aria-label');
}
// Walk up from a usage bar to locate the row's reset hint. The label
// column for each row carries text like "Resets in 19 min" or
// "Resets Thu 11:00 PM" or "Resets May 1". Anthropic has shipped this
// hint inside <p>, <span>, and <div> elements at various points, so
// we scan any leaf element (one with no element children) under each
// ancestor and stop at the first whose trimmed text starts with
// "Resets". The leaf restriction prevents matching a row container
// whose textContent starts with the hint but trails into other copy.
function findRowResetText(bar) {
let node = bar.parentElement;
for (let i = 0; i < 6 && node; i++, node = node.parentElement) {
for (const el of node.querySelectorAll(':scope *')) {
if (el.children.length > 0) continue;
const t = (el.textContent || '').trim();
if (/^Resets\b/i.test(t)) return t;
}
}
return null;
}
// Detect the "no active window" limbo label on a row. Anthropic uses the
// same copy ("Starts when a message is sent") on both the session row and
// the weekly row when the corresponding window is not open. Same leaf-
// element walk as findRowResetText: scope to the row's ancestors so
// similar marketing/help text elsewhere on the page can't trigger a
// false match.
function isLimboLabel(bar) {
const needle = 'starts when a message is sent';
let node = bar.parentElement;
for (let i = 0; i < 6 && node; i++, node = node.parentElement) {
for (const el of node.querySelectorAll(':scope *')) {
if (el.children.length > 0) continue;
const t = (el.textContent || '').toLowerCase();
if (t.includes(needle)) return true;
}
}
return false;
}
// "Resets in 3 hr 33 min" / "Resets in 19 min" / "Resets in 5 hr".
// baseMs is the wall-clock time the reset string was current — typically
// Date.now() minus the page's "Last updated: N minutes ago" staleness, so
// a stale page doesn't shift the computed end forward in time.
function parseSessionEnds(text, baseMs) {
if (!text) return null;
const m = text.match(/Resets in\s+(?:(\d+)\s*hr)?\s*(?:(\d+)\s*min)?/i);
if (!m) return null;
const hours = parseInt(m[1] || '0', 10);
const mins = parseInt(m[2] || '0', 10);
if (hours === 0 && mins === 0) return null;
return new Date(baseMs + (hours * 60 + mins) * 60 * 1000).toISOString();
}
// Parse the page's "Last updated" indicator into staleness in milliseconds.
// The Anthropic page's progression is: "just now" → "less than a minute
// ago" → "1 minute ago" → "N minutes ago" → "N hours ago" (long-idle
// tabs). The first two collapse to 0; the rest are captured by the
// numeric regex. Both the percent values and the "Resets in …" text are
// accurate as of that timestamp, not as of Date.now(). Returns null when
// the indicator can't be located, in which case the caller falls back to
// treating the snapshot as current.
function findLastUpdatedAgeMs() {
const candidates = document.querySelectorAll('p, span, div');
for (const node of candidates) {
const t = (node.textContent || '').trim();
// Skip large containers; we only want the small label itself.
if (!t || t.length > 80) continue;
if (!/last updated/i.test(t)) continue;
if (/just now/i.test(t)) return 0;
if (/less than a minute ago/i.test(t)) return 0;
const m = t.match(/(\d+)\s*(minutes?|hours?)\s+ago/i);
if (!m) continue;
const n = parseInt(m[1], 10);
const unit = m[2].toLowerCase();
if (unit.startsWith('min')) return n * 60 * 1000;
if (unit.startsWith('hour')) return n * 60 * 60 * 1000;
}
return null;
}
// "Resets Thu 11:00 PM" — weekday + time-of-day in the browser's local
// timezone. We pick the next future occurrence of that weekday at that
// local time and convert to UTC. Format variants like "Resets May 1"
// (when far enough out that Anthropic switches to a date) are not
// currently parsed; null causes the server to skip minting a weekly
// window until a parseable hint arrives, and the dashboard renders a
// [now, now+7d] hypothetical projection in the meantime.
const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
function parseWeeklyEnds(text) {
if (!text) return null;
const m = text.match(/Resets\s+(Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*\s+(\d{1,2}):(\d{2})\s*(AM|PM)/i);
if (!m) return null;
const targetDow = WEEKDAYS.indexOf(m[1].slice(0, 3));
if (targetDow < 0) return null;
const ampm = m[4].toUpperCase();
let hour = parseInt(m[2], 10) % 12;
if (ampm === 'PM') hour += 12;
const min = parseInt(m[3], 10);
const now = new Date();
const target = new Date(now);
target.setHours(hour, min, 0, 0);
// Step forward until we hit the right weekday strictly in the future.
for (let i = 0; i < 8; i++) {
if (target.getDay() === targetDow && target > now) break;
target.setDate(target.getDate() + 1);
}
return target.toISOString();
}
// Returns { sessionUsed, weeklyUsed, sessionWindowEnds, weeklyWindowEnds,
// sessionActive, weeklyActive, observedAtMs, resetText,
// lastUpdatedAgeMs }
// or null when neither section yields a usable bar. observedAtMs is the
// wall-clock time the page's numbers were accurate (Date.now() minus the
// "Last updated" staleness, or Date.now() when the indicator is missing).
// sessionActive / weeklyActive are false only when the limbo label is
// positively detected on the corresponding row; left undefined otherwise
// (we never assert true). resetText is the verbatim "Resets in …" text on
// the session row (null in limbo or when missing), used by the dedup layer
// to spot string ticks. lastUpdatedAgeMs is the raw "Last updated"
// staleness in ms (null when unparsable).
function extractQuota() {
// Anthropic moved the section headings from <h2> to <h3> as of late
// April 2026 and started appending plan-tier badges to the heading
// text (e.g. "Plan usage limitsMax (20x)", "Your usage limitsTeam").
// We accept either tag and match the section name as a *prefix*
// against the known variants in SESSION_HEADINGS / WEEKLY_HEADING
// so a trailing badge or rename doesn't break extraction.
const headings = Array.from(document.querySelectorAll('h2, h3'))
.map(h => ({ node: h, text: (h.textContent || '').trim() }));
const bars = document.querySelectorAll(USAGE_BAR_SELECTOR);
const lastUpdatedAgeMs = findLastUpdatedAgeMs();
const observedAtMs = Date.now() - (lastUpdatedAgeMs || 0);
let sessionUsed = null, weeklyUsed = null, fableWeeklyUsed = null;
let sessionEnds = null, weeklyEnds = null;
let sessionActive;
let weeklyActive;
let sessionResetText = null;
for (const bar of bars) {
const heading = precedingHeading(bar, headings);
if (!heading) continue;
const value = parseFloat(bar.getAttribute('aria-valuenow'));
if (Number.isNaN(value)) continue;
if (SESSION_HEADINGS.some(h => heading.startsWith(h)) && sessionUsed === null) {
sessionUsed = value;
sessionResetText = findRowResetText(bar);
sessionEnds = parseSessionEnds(sessionResetText, observedAtMs);
if (isLimboLabel(bar)) sessionActive = false;
} else if (heading.startsWith(WEEKLY_HEADING)) {
// The weekly section holds an aggregate row plus per-model
// sub-rows. Fable is claimed by label; the aggregate stays
// positional (first non-Fable bar in the section), so a label
// rename can only ever cost us the fable series, never the
// weekly line. Checking the label first also means we stay
// correct if Anthropic ever renders Fable above "All models".
if (isFableRowLabel(resolveBarLabel(bar))) {
if (fableWeeklyUsed === null) fableWeeklyUsed = value;
} else if (weeklyUsed === null) {
weeklyUsed = value;
// Weekly hint is an absolute clock time ("Resets Thu 11:00 PM"),
// so page staleness doesn't shift it.
weeklyEnds = parseWeeklyEnds(findRowResetText(bar));
if (isLimboLabel(bar)) weeklyActive = false;
}
}
}
// The Fable row alone is not enough to call the page parsed: it is an
// optional sub-row, so treating it as sufficient would suppress the
// parse-error report that fires when the rows we actually depend on
// have gone missing.
if (sessionUsed === null && weeklyUsed === null) return null;
return {
sessionUsed,
weeklyUsed,
// Null when the row is absent — the account's plan may not show
// it, and it did not exist at all before July 2026.
fableWeeklyUsed,
sessionWindowEnds: sessionEnds,
weeklyWindowEnds: weeklyEnds,
sessionActive,
weeklyActive,
observedAtMs,
resetText: sessionResetText,
lastUpdatedAgeMs,
};
}
// ---------- diagnostics ----------
// buildFingerprint summarises the *structure* of the page when our
// extractor breaks, without including conversation text, account
// names, or any other PII. Earlier versions shipped up to 64 KiB of
// document.body.outerHTML; that landed verbatim in parse_errors and
// sat on disk for 30 days. The fingerprint captures what an admin
// actually needs to debug a parser break (which selectors matched
// how many times, what the section headings look like) and nothing
// else.
function buildFingerprint() {
try {
// Match the same tag set extractQuota anchors on so a heading
// rename or h2→h3 shuffle is visible in the fingerprint.
const headings = Array.from(document.querySelectorAll('h2, h3'))
.map(h => (h.textContent || '').trim().slice(0, 80))
.filter(Boolean)
.slice(0, 30);
const fp = {
pathname: location.pathname,
heading_count: headings.length,
heading_texts: headings,
progressbar_count: document.querySelectorAll('[role="progressbar"]').length,
meter_count: document.querySelectorAll('[role="meter"]').length,
usage_bar_count: document.querySelectorAll(USAGE_BAR_SELECTOR).length,
user_agent_short: (navigator.userAgent || '').slice(0, 120),
};
return JSON.stringify(fp);
} catch (e) {
return JSON.stringify({ fingerprint_error: String(e).slice(0, 200) });
}
}
// ---------- snapshot dispatch ----------
function buildSnapshotBody(extracted, continuousWithPrev) {
const body = {
observed_at: new Date(extracted.observedAtMs || Date.now()).toISOString(),
source: 'userscript',
continuous_with_prev: continuousWithPrev,
};
if (extracted.sessionUsed !== null) body.session_used = extracted.sessionUsed;
if (extracted.weeklyUsed !== null) body.weekly_used = extracted.weeklyUsed;
// Omitted when the row is absent, so the server records NULL rather
// than a fabricated zero. There is no fable_window_ends: the page
// reports the same reset time on both weekly rows.
if (extracted.fableWeeklyUsed !== null && extracted.fableWeeklyUsed !== undefined) {
body.fable_weekly_used = extracted.fableWeeklyUsed;
}
if (extracted.sessionWindowEnds) body.session_window_ends = extracted.sessionWindowEnds;
if (extracted.weeklyWindowEnds) body.weekly_window_ends = extracted.weeklyWindowEnds;
// Limbo signal: only emit when positively detected. We never assert
// session_active=true / weekly_active=true — absence means "unknown".
if (extracted.sessionActive === false) body.session_active = false;
if (extracted.weeklyActive === false) body.weekly_active = false;
return body;
}
// Freshness-driven dedup: emit only when at least one meaningful-change
// signal has fired since the last successful send. The decision lives in
// shouldSend(); see lib/dedup.js for the canonical logic and rationale.
function tryDispatch() {
if (!onUsagePage()) {
domFirstMissingAt = null;
return;
}
const extracted = extractQuota();
if (!extracted) {
if (domFirstMissingAt === null) domFirstMissingAt = Date.now();
const missingFor = Date.now() - domFirstMissingAt;
if (missingFor > DOM_MISSING_REPORT_MS &&
Date.now() - lastParseErrorAt > PARSE_ERROR_REPORT_COOLDOWN_MS) {
lastParseErrorAt = Date.now();
postJSON(ENDPOINT_PARSE_ERROR, {
source: 'userscript',
reason: 'usage progressbars missing for >5 minutes',
payload: buildFingerprint(),
});
}
return;
}
domFirstMissingAt = null;
const prevState = loadState();
const decision = shouldSend(extracted, prevState, lastObservedAgeMs);
// Update the rolling observed-age *after* the comparison, so
// the next call sees this read as "previous." Update on every
// read regardless of decision; otherwise we'd never detect a
// staleness rollback during a long limbo plateau.
if (extracted.lastUpdatedAgeMs != null) {
lastObservedAgeMs = extracted.lastUpdatedAgeMs;
}
if (decision === 'skip') return;
const windowEndsMs = extracted.sessionWindowEnds ? Date.parse(extracted.sessionWindowEnds) : null;
const nowMs = Date.now();
const continuousWithPrev = decideContinuity(
{
percent: extracted.sessionUsed,
resetText: extracted.resetText,
windowEndsMs,
sessionActive: extracted.sessionActive,
observedAtMs: extracted.observedAtMs,
},
prevState,
nowMs,
);
postJSON(ENDPOINT_SNAPSHOT, buildSnapshotBody(extracted, continuousWithPrev), () => {
recordSentState({
sentAtMs: Date.now(),
percent: extracted.sessionUsed,
resetText: extracted.resetText,
windowEndsMs,
sessionActive: extracted.sessionActive,
weeklyActive: extracted.weeklyActive,
fablePercent: extracted.fableWeeklyUsed,
});
});
}
function scheduleDispatch() {
if (dispatchTimer) return;
dispatchTimer = setTimeout(() => {
dispatchTimer = null;
tryDispatch();
}, DISPATCH_DEBOUNCE_MS);
}
// ---------- change observer ----------
// Body-level observer filtered to aria-valuenow attribute changes — fires
// within milliseconds of claude.ai's poll updating the DOM, regardless of
// tab focus or our setInterval phase. The attributeFilter keeps the
// callback rate low even though subtree=true.
function startChangeObserver() {
const observer = new MutationObserver(mutations => {
for (const m of mutations) {
if (m.type !== 'attributes' || m.attributeName !== 'aria-valuenow') continue;
const t = m.target;
if (t && t.getAttribute &&
isUsageBarTarget(t.getAttribute('role'), t.getAttribute('aria-label'))) {
scheduleDispatch();
return;
}
}
});
observer.observe(document.body, {
attributes: true,
subtree: true,
attributeFilter: ['aria-valuenow'],
});
}
// ---------- DOM readiness ----------
function waitForQuotaDOM(onReady) {
let fired = false;
const fire = () => {
if (fired) return;
fired = true;
try { onReady(); } catch (e) { warn('onReady threw', e); }
};
const check = () => document.querySelector(USAGE_BAR_SELECTOR) !== null;
if (check()) { fire(); return; }
let observer = null;
try {
observer = new MutationObserver(() => {
if (check()) {
observer.disconnect();
fire();
}
});
observer.observe(document.documentElement, { childList: true, subtree: true });
} catch (e) {
warn('MutationObserver setup failed', e);
}
setTimeout(() => {
if (observer) {
try { observer.disconnect(); } catch (_) { /* ignore */ }
}
fire();
}, DOM_WAIT_TIMEOUT_MS);
}
// ---------- bootstrap ----------
function start() {
// Initial sample, then hand the wheel to the change observer. The
// interval is a backstop only — if the observer is somehow torn down
// by an SPA re-render, or the tab is throttled, we still see a tick.
tryDispatch();
startChangeObserver();
setInterval(tryDispatch, POST_INTERVAL_MS);
}
waitForQuotaDOM(start);
})();