1076 lines
65 KiB
HTML
1076 lines
65 KiB
HTML
<!doctype html>
|
||
<html>
|
||
<head>
|
||
<meta charset="utf-8" />
|
||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||
<title>Plan usage</title>
|
||
<style>
|
||
[hidden] { display: none !important; }
|
||
:root {
|
||
--sky: #0ea5e9; --amber: #f59e0b; --red: #ef4444; --emerald: #10b981;
|
||
--tracked: #0ea5e9; --untracked: #f59e0b;
|
||
}
|
||
/* the app's chart palette: the 500 step in light mode, 600 in dark */
|
||
html.dark { --sky: #0284c7; --amber: #d97706; --red: #dc2626; --emerald: #059669; --tracked: #0284c7; --untracked: #d97706; }
|
||
html, body { margin: 0; background: hsl(var(--background, 0 0% 100%)); color: hsl(var(--foreground, 222 47% 11%)); }
|
||
body { overflow-x: hidden; }
|
||
/* figures: the kit's mono face, digits in columns */
|
||
.mono { font-family: var(--aia-mono, ui-monospace, monospace); font-variant-numeric: tabular-nums; }
|
||
.chk { display: inline-flex; align-items: center; gap: 5px; cursor: pointer; }
|
||
.chk input { margin: 0; accent-color: hsl(var(--primary, 24 95% 53%)); }
|
||
svg.i { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; flex-shrink: 0; }
|
||
svg.i.sm { width: 12px; height: 12px; }
|
||
.content { display: flex; flex-direction: column; gap: 20px; transition: opacity .15s; }
|
||
.content.busy { opacity: .6; }
|
||
.acct { display: flex; flex-direction: column; gap: 20px; }
|
||
.acct .ah { padding-bottom: 4px; border-bottom: 1px solid hsl(var(--border, 214 32% 91%)); }
|
||
|
||
/* one panel: an aia-card with a title row, the finding, then chart ⇄ table */
|
||
.panel { padding: 14px 16px; }
|
||
.ph { display: flex; align-items: flex-start; gap: 8px; margin-bottom: 12px; }
|
||
.ph .t { min-width: 0; flex: 1; }
|
||
.finding { margin: 0 0 12px; line-height: 1.6; font-size: 12px; }
|
||
.n { font-family: var(--aia-mono, ui-monospace, monospace); font-weight: 600; font-variant-numeric: tabular-nums; }
|
||
.status ul { margin: 0; padding: 0; list-style: none; }
|
||
.status li + li { margin-top: 2px; }
|
||
.fg { color: hsl(var(--foreground, 222 47% 11%)); font-weight: 500; }
|
||
.warn { color: var(--amber); font-weight: 500; }
|
||
|
||
/* the table twin */
|
||
.tbl { overflow-x: auto; }
|
||
.tbl td { white-space: nowrap; }
|
||
.tbl td.aia-num { font-family: var(--aia-mono, ui-monospace, monospace); color: hsl(var(--muted-foreground, 215 16% 47%)); }
|
||
|
||
.plot { position: relative; }
|
||
.tip {
|
||
position: absolute; z-index: 20; pointer-events: none; transform: translateY(calc(-100% - 10px)); white-space: nowrap;
|
||
border-radius: 6px; border: 1px solid hsl(var(--border, 214 32% 91%)); background: hsl(var(--card, 0 0% 100%));
|
||
padding: 4px 8px; font-size: 11px; box-shadow: 0 6px 16px rgb(0 0 0 / .15);
|
||
}
|
||
.axis { margin-top: 4px; display: flex; justify-content: space-between; font-size: 9px; color: hsl(var(--muted-foreground, 215 16% 47%)); }
|
||
.legend { margin-top: 8px; display: flex; flex-wrap: wrap; gap: 4px 12px; }
|
||
.legend div { display: flex; align-items: center; gap: 6px; font-size: 10px; color: hsl(var(--muted-foreground, 215 16% 47%)); }
|
||
.dot { display: inline-block; width: 8px; height: 8px; border-radius: 2px; flex-shrink: 0; }
|
||
|
||
/* gauges */
|
||
.gauges { display: grid; gap: 12px; grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||
.gauges.one { grid-template-columns: minmax(0, 1fr); }
|
||
.gauge { display: flex; min-width: 0; flex-direction: column; align-items: center; text-align: center; }
|
||
.gauge .dial { position: relative; width: 100%; max-width: 150px; }
|
||
.gauge .dial svg { width: 100%; display: block; }
|
||
.gauge .fig { position: absolute; left: 0; right: 0; bottom: 0; font-size: 24px; font-weight: 600; line-height: 1; }
|
||
.gauge .lab { margin-top: 6px; display: flex; align-items: center; gap: 4px; font-size: 12px; font-weight: 500; }
|
||
.gauge .lab small { font-size: 10px; font-weight: 400; }
|
||
.gauge .lines { margin-top: 2px; width: 100%; min-width: 0; font-size: 11px; color: hsl(var(--muted-foreground, 215 16% 47%)); }
|
||
.gauge .lines div { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||
.read { margin-top: 12px; display: flex; align-items: center; justify-content: center; gap: 6px; font-size: 10px; color: hsl(var(--muted-foreground, 215 16% 47%)); }
|
||
|
||
/* plan timeline */
|
||
.ptl { display: flex; height: 36px; width: 100%; overflow: hidden; border-radius: 8px; border: 1px solid hsl(var(--border, 214 32% 91%)); font-size: 10px; }
|
||
.ptl div { display: flex; min-width: 56px; flex-direction: column; justify-content: center; overflow: hidden; padding: 0 6px; line-height: 1.2; background: hsl(var(--muted, 210 40% 96%) / .4); color: hsl(var(--muted-foreground, 215 16% 47%)); }
|
||
.ptl div + div { border-left: 1px solid hsl(var(--border, 214 32% 91%)); }
|
||
.ptl div.live { background: hsl(var(--primary, 24 95% 53%) / .15); color: hsl(var(--foreground, 222 47% 11%)); }
|
||
.ptl b, .ptl span { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||
.cards { margin-top: 8px; display: grid; gap: 8px; grid-template-columns: minmax(0, 1fr); }
|
||
@media (min-width: 640px) { .cards { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||
.pc { padding: 8px 12px; font-size: 12px; }
|
||
.pc .row { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
|
||
.pc .sm { font-size: 10px; }
|
||
.pc .xs { margin-top: 2px; font-size: 11px; }
|
||
|
||
/* billing */
|
||
.big { font-family: var(--aia-mono, ui-monospace, monospace); font-size: 24px; font-weight: 600; line-height: 1; font-variant-numeric: tabular-nums; }
|
||
.bhead { margin-bottom: 12px; display: flex; align-items: baseline; justify-content: space-between; gap: 12px; }
|
||
.bchart { position: relative; height: 128px; border-bottom: 1px solid hsl(var(--border, 214 32% 91%)); }
|
||
.bchart .cap { position: absolute; left: 0; right: 0; border-top: 1px dashed var(--amber); pointer-events: none; }
|
||
.bchart .cap span { position: absolute; top: -8px; right: 0; width: 56px; text-align: right; font-size: 10px; line-height: 1; color: var(--amber); }
|
||
.bchart .hund { position: absolute; left: 0; right: 0; border-top: 1px solid hsl(var(--border, 214 32% 91%)); pointer-events: none; }
|
||
.bchart .bars { position: absolute; top: 0; bottom: 0; left: 0; right: 64px; display: flex; align-items: flex-end; gap: 6px; padding: 0 4px; }
|
||
.bchart .wk { display: flex; height: 100%; min-width: 0; flex: 1; flex-direction: column; align-items: center; justify-content: flex-end; }
|
||
.bchart .wk span { margin-bottom: 2px; font-size: 10px; }
|
||
.bchart .wk i { display: block; width: 100%; max-width: 40px; border-radius: 4px 4px 0 0; background: hsl(var(--primary, 24 95% 53%)); }
|
||
.bchart .wk i.prev { background: hsl(var(--primary, 24 95% 53%) / .4); }
|
||
.bchart .wk i.cur { background: hsl(var(--primary, 24 95% 53%) / .6); outline: 1px dashed hsl(var(--primary, 24 95% 53%)); }
|
||
.blabels { margin: 4px 64px 0 0; display: flex; gap: 6px; padding: 0 4px; }
|
||
.blabels div { min-width: 0; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center; font-size: 10px; color: hsl(var(--muted-foreground, 215 16% 47%)); }
|
||
|
||
/* columns (observed per day, $ per 1% per fit) */
|
||
.cols { display: flex; align-items: flex-end; gap: 2px; border-bottom: 1px solid hsl(var(--border, 214 32% 91%)); }
|
||
.cols .c { position: relative; display: flex; height: 100%; min-width: 0; flex: 1; flex-direction: column; align-items: center; justify-content: flex-end; }
|
||
.stack { display: flex; width: 100%; max-width: 24px; flex-direction: column-reverse; gap: 2px; }
|
||
.stack i { display: block; flex-basis: 0; }
|
||
.stack i.tr { background: var(--tracked); }
|
||
.stack i.un { background: var(--untracked); border-radius: 4px 4px 0 0; }
|
||
.stack i.top { border-radius: 4px 4px 0 0; }
|
||
.predtick { position: absolute; height: 2px; width: 100%; max-width: 28px; border-radius: 999px; background: hsl(var(--foreground, 222 47% 11%) / .7); pointer-events: none; }
|
||
.bar { position: relative; width: 100%; max-width: 24px; border-radius: 4px 4px 0 0; }
|
||
.bar.faded { opacity: .3; }
|
||
.bar .brk { position: absolute; left: 0; right: 0; top: 5px; height: 2px; background: hsl(var(--card, 0 0% 100%)); }
|
||
|
||
/* rate */
|
||
.rates { display: grid; gap: 12px; grid-template-columns: minmax(0, 1fr); }
|
||
@media (min-width: 640px) { .rates { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||
.rate { padding: 12px; }
|
||
.rate .k { margin-bottom: 8px; font-size: 10px; text-transform: uppercase; letter-spacing: .04em; color: hsl(var(--muted-foreground, 215 16% 47%)); }
|
||
.rate .vals { display: flex; align-items: baseline; gap: 12px; }
|
||
.rate .v1 { font-size: 20px; font-weight: 600; line-height: 1; }
|
||
.rate .v2 { font-family: var(--aia-mono, ui-monospace, monospace); font-size: 16px; font-weight: 600; line-height: 1; }
|
||
.rate .u { margin-top: 4px; font-size: 10px; color: hsl(var(--muted-foreground, 215 16% 47%)); }
|
||
.rate .stats { margin-top: 8px; display: flex; flex-wrap: wrap; gap: 2px 12px; font-family: var(--aia-mono, ui-monospace, monospace); font-size: 10px; color: hsl(var(--muted-foreground, 215 16% 47%)); }
|
||
.ceil { margin-top: 12px; border-radius: 8px; background: hsl(var(--muted, 210 40% 96%) / .4); padding: 8px 12px; font-size: 12px; }
|
||
.badges { margin-bottom: 12px; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; font-size: 11px; color: hsl(var(--muted-foreground, 215 16% 47%)); }
|
||
.two { display: grid; gap: 16px; grid-template-columns: minmax(0, 1fr); }
|
||
@media (min-width: 640px) { .two { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||
.sub { margin-bottom: 6px; display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
|
||
.sub b { font-size: 11px; font-weight: 500; }
|
||
.sub span { font-size: 10px; }
|
||
.lines + .lines { margin-top: 16px; }
|
||
.method { margin: 0; padding-bottom: 8px; font-size: 11px; line-height: 1.6; }
|
||
.method b { font-weight: 500; color: hsl(var(--foreground, 222 47% 11%)); }
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<div class="aia-page aia-stack" id="wrap">
|
||
<div class="aia-toolbar" style="margin:0">
|
||
<div class="aia-seg" id="days"></div>
|
||
<div class="aia-seg" id="scopes"></div>
|
||
<span class="aia-spacer"></span>
|
||
<label class="chk aia-small aia-muted" title="When recalibrating, also refit the weekly fits over the whole history (the '$ per 1% over time' chart)"><input type="checkbox" id="backfill" /> backfill when recalibrating</label>
|
||
</div>
|
||
<div id="status" class="status" hidden></div>
|
||
<div id="note" class="aia-small aia-muted" hidden></div>
|
||
<div id="msg" hidden></div>
|
||
<div id="content" class="content" hidden></div>
|
||
</div>
|
||
<script>
|
||
(function () {
|
||
"use strict";
|
||
var api = window.aiAgentPlugin || null;
|
||
var init = (api && api.init) || {};
|
||
var config = init.config || {};
|
||
var HOUR = 3600000, DAY = 86400000;
|
||
var DAY_OPTIONS = [7, 14, 30, 90];
|
||
var WEEKS_PER_MONTH = 4.35;
|
||
var KEY = "aia-plan-usage";
|
||
var saved = {};
|
||
try { saved = JSON.parse(localStorage.getItem(KEY) || "{}") || {}; } catch (e) { saved = {}; }
|
||
var state = {
|
||
scope: typeof init.scope === "string" && init.scope ? init.scope : (saved.scope || ""),
|
||
days: DAY_OPTIONS.indexOf(saved.days) >= 0 ? saved.days : 14,
|
||
asTable: {},
|
||
recal: { busy: false, result: null, error: null },
|
||
};
|
||
// data: the shown scope's answer; profiles: the scope switch (kept across a
|
||
// failed read); q: the live read; busy: a new scope / range is on its way
|
||
var data = null, profiles = [], q = null, seq = 0, busy = false, loadError = null, staleError = null;
|
||
|
||
// ── the bridge: reads through the host's query (cached, then fresh) ───────
|
||
/** query() on a current host; on an older one, the action itself (refresh re-runs it). */
|
||
function read(name, payload, cb) {
|
||
if (api.query) return api.query(name, payload, cb);
|
||
var live = true, last = null;
|
||
function run() {
|
||
return api.action(name, payload).then(
|
||
function (d) { last = d; if (live) cb(d, { fromCache: false, fetching: false, at: Date.now() }); },
|
||
function (e) { if (live) cb(last, { error: String((e && e.message) || e), fromCache: false, fetching: false, at: Date.now() }); });
|
||
}
|
||
run();
|
||
return { stop: function () { live = false; }, refresh: run };
|
||
}
|
||
var headerJson = "";
|
||
/** The page's line in the app's header (posted only when it changed). */
|
||
function setHeader(h) {
|
||
var j = JSON.stringify(h);
|
||
if (j === headerJson || !api || !api.setHeader) return;
|
||
headerJson = j;
|
||
api.setHeader(h);
|
||
}
|
||
|
||
// ── helpers ──────────────────────────────────────────────────────────────
|
||
function $(id) { return document.getElementById(id); }
|
||
function el(tag, attrs, kids) {
|
||
var n = document.createElement(tag);
|
||
for (var k in attrs || {}) {
|
||
if (attrs[k] == null || attrs[k] === false) continue;
|
||
if (k === "text") n.textContent = attrs[k];
|
||
else if (k === "style") n.setAttribute("style", attrs[k]);
|
||
else n.setAttribute(k, attrs[k] === true ? "" : attrs[k]);
|
||
}
|
||
(kids || []).forEach(function (c) {
|
||
if (c == null || c === false) return;
|
||
n.appendChild(typeof c === "string" || typeof c === "number" ? document.createTextNode(String(c)) : c);
|
||
});
|
||
return n;
|
||
}
|
||
var SVGNS = "http://www.w3.org/2000/svg";
|
||
function s(tag, attrs, kids) {
|
||
var n = document.createElementNS(SVGNS, tag);
|
||
for (var k in attrs || {}) if (attrs[k] != null) n.setAttribute(k, attrs[k]);
|
||
(kids || []).forEach(function (c) { if (c) n.appendChild(c); });
|
||
return n;
|
||
}
|
||
var ICONS = {
|
||
table: "M3 5h18v14H3zM3 10h18M3 15h18M9 5v14",
|
||
chart: "M3 3v18h18M7 15l4-4 3 3 5-6",
|
||
clock: "M12 7v5l3 2M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z",
|
||
alert: "M12 9v4M12 17h.01M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z",
|
||
octagon: "M7.9 2h8.2L22 7.9v8.2L16.1 22H7.9L2 16.1V7.9zM12 8v4M12 16h.01",
|
||
check: "M20 6 9 17l-5-5",
|
||
repeat: "M17 2l4 4-4 4M3 11V9a3 3 0 0 1 3-3h15M7 22l-4-4 4-4M21 13v2a3 3 0 0 1-3 3H3",
|
||
sprout: "M7 20h10M12 20v-9M12 11c0-3 2-5 6-5 0 3-2 5-6 5zM12 13c0-2.5-2-4.5-5-4.5 0 2.5 2 4.5 5 4.5z",
|
||
};
|
||
function svg(name, cls) {
|
||
return s("svg", { viewBox: "0 0 24 24", class: "i" + (cls ? " " + cls : "") }, [s("path", { d: ICONS[name] })]);
|
||
}
|
||
function sum(a) { return a.reduce(function (n, v) { return n + (v || 0); }, 0); }
|
||
function fix(v, d) { return Number(v).toFixed(d); }
|
||
|
||
// money: dollars unless the plugin's settings pick euros
|
||
var EUR = config.currency === "EUR";
|
||
var RATE = Number(config.usdToEur) > 0 ? Number(config.usdToEur) : 0.92;
|
||
function fmtCost(usd) {
|
||
var v = EUR ? usd * RATE : usd;
|
||
var num = !v ? "0" : v < 0.01 ? fix(v, 4) : v < 1 ? fix(v, 3) : v < 100 ? fix(v, 2) : Math.round(v).toLocaleString();
|
||
return EUR ? num + " €" : "$" + num;
|
||
}
|
||
function fmtPlanPct(p, digits) {
|
||
digits = digits == null ? 1 : digits;
|
||
if (p == null || !isFinite(p)) return "—";
|
||
var floor = 0.5 * Math.pow(10, -digits);
|
||
if (p > 0 && p < floor) return "<" + fix(Math.pow(10, -digits), digits) + "%";
|
||
return fix(p, digits) + "%";
|
||
}
|
||
function fmtWholePct(p) { return Math.round(p) + "%"; }
|
||
function fmtStampDate(ts) {
|
||
if (!ts) return null;
|
||
return new Date(ts * 1000).toLocaleDateString(undefined, { day: "numeric", month: "short" });
|
||
}
|
||
function fmtBillDate(ts, opts) { return new Date(ts * 1000).toLocaleDateString(undefined, opts || { day: "numeric", month: "short" }); }
|
||
function fmtCountdown(resetsAt, now) {
|
||
if (!resetsAt) return null;
|
||
var sec = Math.round(resetsAt - now / 1000);
|
||
if (sec <= 0) return "now";
|
||
var m = Math.floor(sec / 60);
|
||
if (m < 60) return m + "m";
|
||
var h = Math.floor(m / 60);
|
||
if (h < 24) return h + "h " + (m % 60) + "m";
|
||
return Math.floor(h / 24) + "d " + (h % 24) + "h";
|
||
}
|
||
function relTime(ts) {
|
||
var sec = Math.max(0, (Date.now() - ts * 1000) / 1000);
|
||
if (sec < 60) return "just now";
|
||
var m = sec / 60; if (m < 60) return Math.round(m) + "m ago";
|
||
var h = m / 60; if (h < 24) return Math.round(h) + "h ago";
|
||
var d = h / 24; if (d < 30) return Math.round(d) + "d ago";
|
||
return Math.round(d / 30) + "mo ago";
|
||
}
|
||
/** "2026-10-12" → "12/10", the dashboards' day label. */
|
||
function fmtDay(day) { var p = day.split("-").map(Number); return p[2] + "/" + p[1]; }
|
||
function fmtWhen(t) { return new Date(t).toLocaleString(undefined, { weekday: "short", day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }); }
|
||
function fmtShortDay(t) { return new Date(t).toLocaleDateString(undefined, { day: "numeric", month: "short" }); }
|
||
function fmtScale(k) { return k ? String(Math.round(k * 100) / 100) : "1"; }
|
||
var WINDOW_NAMES = { week: "week", h5: "5-hour" };
|
||
function fmtWindows(w) {
|
||
return w && w.length ? w.map(function (x) { return WINDOW_NAMES[x] || x; }).join(" + ") + " window" + (w.length > 1 ? "s" : "") : "—";
|
||
}
|
||
/** 0.25 → "a quarter", 0.05 → "1/20". */
|
||
function fmtFraction(capPct) {
|
||
var f = capPct / 100;
|
||
if (Math.abs(f - 0.25) < 1e-6) return "a quarter";
|
||
if (Math.abs(f - 0.5) < 1e-6) return "half";
|
||
return "1/" + Math.round(1 / f);
|
||
}
|
||
function N(text) { return el("span", { class: "n", text: String(text) }); }
|
||
|
||
// ── plan maths (the app's lib/planUsage + lib/billing) ─────────────────────
|
||
function isTrusted(c) {
|
||
if (!c || c.source !== "fit") return false;
|
||
if (c.trusted != null) return !!c.trusted;
|
||
return [c.week, c.h5].filter(Boolean).every(function (w) { return (w.r2 || 0) >= 0.5 && (w.n || 0) >= 24; });
|
||
}
|
||
function monthlyCeiling(c) { var u = c && c.week && c.week.usdPerPct; return u ? 100 * u * WEEKS_PER_MONTH : null; }
|
||
var TIERS = [{ label: "Pro", multiplier: 1 }, { label: "Max 5×", multiplier: 5 }, { label: "Max 20×", multiplier: 20 }];
|
||
function smallerTiers(mult) {
|
||
if (!mult) return [];
|
||
return TIERS.filter(function (t) { return t.multiplier < mult; })
|
||
.map(function (t) { return { label: t.label, capPct: (100 * t.multiplier) / mult }; }).reverse();
|
||
}
|
||
function daysUntil(at, now) { return Math.max(0, Math.ceil((at - now) / 86400)); }
|
||
function nextRenewal(b, now) {
|
||
if (b.nextBillingAt > now) return b.nextBillingAt;
|
||
var d = new Date(b.nextBillingAt * 1000); d.setUTCMonth(d.getUTCMonth() + 1); return d.getTime() / 1000;
|
||
}
|
||
function topPeak(weeks) { return weeks.length ? Math.max.apply(null, weeks.map(function (w) { return w.peak; })) : null; }
|
||
var PLAN_LABEL = { none: "Pay-as-you-go", pro: "Pro", max5: "Max 5×", max20: "Max 20×", team: "Team seat", enterprise: "Enterprise seat" };
|
||
var LIMIT_WINDOWS = [
|
||
{ key: "five_hour", fit: "h5", label: "5-hour window" },
|
||
{ key: "seven_day", fit: "week", label: "Week" },
|
||
];
|
||
var UNTRACKED = {
|
||
claude: "claude.ai, the desktop app, a machine the hub doesn't mirror",
|
||
opencode: "chatgpt.com, Codex, a machine the hub doesn't mirror",
|
||
pi: "a machine the hub doesn't mirror",
|
||
agy: "the Antigravity app, the Gemini app, a machine the hub doesn't mirror",
|
||
};
|
||
|
||
// ── frame plumbing ──────────────────────────────────────────────────────
|
||
function persist() { try { localStorage.setItem(KEY, JSON.stringify({ scope: state.scope, days: state.days })); } catch (e) {} }
|
||
|
||
/** A tooltip inside `host` (a `.plot`), kept within its width. */
|
||
function tipFor(host) {
|
||
var tip = el("div", { class: "tip", hidden: true });
|
||
host.appendChild(tip);
|
||
return {
|
||
show: function (e, kids) {
|
||
var r = host.getBoundingClientRect();
|
||
tip.textContent = "";
|
||
kids.forEach(function (k) { tip.appendChild(typeof k === "string" ? document.createTextNode(k) : k); });
|
||
tip.hidden = false;
|
||
var w = tip.offsetWidth;
|
||
tip.style.left = Math.max(0, Math.min(e.clientX - r.left - w / 2, host.clientWidth - w)) + "px";
|
||
tip.style.top = (e.clientY - r.top) + "px";
|
||
},
|
||
hide: function () { tip.hidden = true; }
|
||
};
|
||
}
|
||
|
||
/** One question per panel: title + question, the finding, then chart ⇄ table. */
|
||
function panel(key, title, question, finding, chart, table) {
|
||
var box = el("section", { class: "aia-card panel" });
|
||
var asTable = !!state.asTable[key] && !!table;
|
||
var head = el("div", { class: "ph" }, [
|
||
el("div", { class: "t" }, [el("h3", { class: "aia-title", text: title }), el("p", { class: "aia-subtitle", text: question })])
|
||
]);
|
||
if (table) {
|
||
var b = el("button", { type: "button", class: "aia-btn aia-btn-ghost aia-btn-sm aia-btn-icon aia-muted",
|
||
title: asTable ? "Show the chart" : "Show the numbers as a table",
|
||
"aria-label": asTable ? "Show the chart" : "Show the numbers as a table" },
|
||
[svg(asTable ? "chart" : "table")]);
|
||
b.addEventListener("click", function () { state.asTable[key] = !state.asTable[key]; render(); });
|
||
head.appendChild(b);
|
||
}
|
||
box.appendChild(head);
|
||
if (finding && finding.length) box.appendChild(el("p", { class: "aia-note finding" }, finding));
|
||
var body = asTable ? table() : chart();
|
||
if (body) box.appendChild(body);
|
||
return box;
|
||
}
|
||
function dataTable(head, rows) {
|
||
return el("div", { class: "tbl" }, [el("table", { class: "aia-table" }, [
|
||
el("thead", {}, [el("tr", {}, head.map(function (h, i) { return el("th", { class: i ? "aia-num" : null, text: h }); }))]),
|
||
el("tbody", {}, rows.map(function (r) { return el("tr", {}, r.map(function (c, i) { return el("td", { class: i ? "aia-num" : null, text: String(c) }); })); }))
|
||
])]);
|
||
}
|
||
function legend(items) {
|
||
return el("div", { class: "legend" }, items.map(function (it) {
|
||
return el("div", {}, [el("i", { class: "dot", style: "background:" + it.color + (it.opacity ? ";opacity:" + it.opacity : "") }), it.label]);
|
||
}));
|
||
}
|
||
function plotWidth() { return Math.max(260, Math.min(1048, ($("content").clientWidth || 600) - 34)); }
|
||
|
||
// ── the gauge ───────────────────────────────────────────────────────────
|
||
function level(p) {
|
||
if (p >= 90) return { color: "var(--red)", icon: "octagon", word: "near the cap" };
|
||
if (p >= 70) return { color: "var(--amber)", icon: "alert", word: "filling up" };
|
||
return { color: "hsl(var(--primary, 24 95% 53%))", text: "", icon: null, word: null };
|
||
}
|
||
function arcGauge(pct, label, lines) {
|
||
var v = pct == null ? null : Math.max(0, pct);
|
||
var lv = level(v || 0);
|
||
var fill = Math.min(v || 0, 100);
|
||
var arc = "M 10 50 A 40 40 0 0 1 90 50";
|
||
var dial = s("svg", { viewBox: "0 0 100 56", role: "img", "aria-label": label + ": " + (v == null ? "unknown" : fix(v, 0) + "% used") }, [
|
||
s("path", { d: arc, fill: "none", stroke: "hsl(var(--muted, 210 40% 96%))", "stroke-width": "8", "stroke-linecap": "round" }),
|
||
fill > 0 ? s("path", { d: arc, fill: "none", pathLength: "100", "stroke-dasharray": fill + " 100", stroke: lv.color, "stroke-width": "8", "stroke-linecap": "round" }) : null,
|
||
]);
|
||
var figColor = v != null && v >= 70 ? lv.color : "";
|
||
return el("div", { class: "gauge" }, [
|
||
el("div", { class: "dial" }, [dial, el("div", { class: "fig", style: figColor ? "color:" + figColor : null,
|
||
text: v == null ? "—" : (v < 10 ? fix(v, 1) : fix(v, 0)) + "%" })]),
|
||
el("div", { class: "lab" }, [
|
||
lv.icon ? el("span", { style: "color:" + lv.color + ";display:inline-flex" }, [svg(lv.icon)]) : null,
|
||
label,
|
||
lv.word ? el("small", { style: "color:" + lv.color, text: "· " + lv.word }) : null,
|
||
]),
|
||
el("div", { class: "lines" }, lines),
|
||
]);
|
||
}
|
||
|
||
// ── one account ─────────────────────────────────────────────────────────
|
||
function weeklyPace(h) {
|
||
var d = ((h && h.daily) || []).filter(function (x) { return x.observedWeek != null; }).slice(-7);
|
||
if (!d.length) return null;
|
||
return sum(d.map(function (x) { return x.observedWeek; })) / d.length;
|
||
}
|
||
|
||
function gaugesPanel(id, label, limits, cal, history, now) {
|
||
function win(k) { return (limits && limits.windows && limits.windows[k]) || null; }
|
||
var week = win("seven_day");
|
||
var windows = LIMIT_WINDOWS.filter(function (w) { return w.fit === "week" || !!(cal && cal.h5) || !!win(w.key); });
|
||
function usd(fit) { return cal && cal[fit] && cal[fit].usdPerPct != null ? cal[fit].usdPerPct : null; }
|
||
var pace = weeklyPace(history);
|
||
var left = week ? 100 - week.pct : null;
|
||
var toCap = pace && left != null && pace > 0 ? left / pace : null;
|
||
var resetDays = week && week.resetsAt ? (week.resetsAt * 1000 - now) / DAY : null;
|
||
var finding;
|
||
if (week) {
|
||
finding = ["The ", N(label), " week is at ", N(fmtPlanPct(week.pct))];
|
||
if (usd("week") != null) finding.push(" — about ", N(fmtCost(week.pct * usd("week"))), " of list-price work at today's rate (",
|
||
N(fmtCost(usd("week"))), " per 1%), with ≈ ", N(fmtCost((left || 0) * usd("week"))), " left");
|
||
if (week.resetsAt) finding.push(", resetting in ", N(fmtCountdown(week.resetsAt, now)));
|
||
finding.push(".");
|
||
if (pace != null && pace > 0 && toCap != null) {
|
||
finding.push(" At the last week's pace (", N(fix(pace, 1) + "%"), " a day) it would hit the cap in ", N(fix(toCap, 1) + " days"));
|
||
if (resetDays != null) finding.push.apply(finding, toCap < resetDays ? [" — ", N("before"), " the reset."] : [" — after the reset, so no throttling."]);
|
||
else finding.push(".");
|
||
}
|
||
} else {
|
||
finding = ["No /usage reading for ", N(label), " yet — the status line or the usage notifier writes one."];
|
||
}
|
||
return panel(id + ":now", "Where the limits stand · " + label,
|
||
"How much of each window is used right now, and when does it free up?", finding,
|
||
function () {
|
||
var grid = el("div", { class: "gauges" + (windows.length > 1 ? "" : " one") }, windows.map(function (w) {
|
||
var v = win(w.key), rate = usd(w.fit), cd = fmtCountdown(v && v.resetsAt, now);
|
||
return arcGauge(v ? v.pct : null, w.label, [
|
||
cd ? el("div", {}, ["resets in ", el("span", { class: "mono fg", text: cd })]) : null,
|
||
v && rate != null ? el("div", {}, ["≈ ", el("span", { class: "mono", text: fmtCost(v.pct * rate) }), " of ",
|
||
el("span", { class: "mono", text: fmtCost(100 * rate) })]) : null,
|
||
]);
|
||
}));
|
||
var box = el("div", {}, [grid]);
|
||
if (limits) box.appendChild(el("div", { class: "read" }, [
|
||
limits.stale ? el("span", { class: "aia-badge", "data-tone": "warn", title: "No fresh reading for over 30 minutes — no terminal open and the notifier hasn't refreshed it" }, [svg("clock", "sm"), "stale"]) : null,
|
||
el("span", { text: limits.updatedAt ? "read " + relTime(limits.updatedAt) : "never read" }),
|
||
]));
|
||
return box;
|
||
},
|
||
function () {
|
||
return dataTable(["Window", "Used", "Resets in", "≈ list $ used"], windows.map(function (w) {
|
||
var v = win(w.key), rate = usd(w.fit);
|
||
return [w.label, v ? fmtPlanPct(v.pct) : "—", v ? (fmtCountdown(v.resetsAt, now) || "—") : "—",
|
||
v && rate != null ? fmtCost(v.pct * rate) : "—"];
|
||
}));
|
||
});
|
||
}
|
||
|
||
function segmentOf(c, plans) {
|
||
if (c.plan) return plans.find(function (p) { return p.since === c.plan.since; }) || null;
|
||
var start = c.fittedAt - c.days * 86400;
|
||
var cur = plans[0] || null;
|
||
plans.forEach(function (p) { if (p.since <= start) cur = p; });
|
||
return cur;
|
||
}
|
||
|
||
function planPanel(id, label, cal, planHist, fits, now) {
|
||
var segs = (planHist && planHist.history) || [];
|
||
var cur = (planHist && planHist.current) || null;
|
||
if (!cur) return null;
|
||
function rateOf(seg) {
|
||
if (seg.since === cur.since) return cal;
|
||
var hs = ((fits && fits.history) || []).slice().reverse();
|
||
return hs.find(function (c) { return c.source === "fit" && c.trusted && (segmentOf(c, segs) || {}).since === seg.since; }) || null;
|
||
}
|
||
var t0 = (segs[0] && segs[0].since) || cur.since;
|
||
var span = Math.max(1, now / 1000 - t0);
|
||
function name(p) { return p.tier ? p.label : "Unknown tier"; }
|
||
var prev = segs.length > 1 ? segs[segs.length - 2] : null;
|
||
var changed = cur.reason && cur.source !== "assumed";
|
||
var f = [N(label), " is on ", N(name(cur))];
|
||
if (cur.displayName && cur.displayName !== name(cur)) f.push(" (Claude calls it “" + cur.displayName + "”)");
|
||
if (changed) f.push(" since ", N(fmtStampDate(cur.since)), " (" + cur.reason + ")");
|
||
f.push(", with " + (cur.windows && cur.windows.length === 1 ? "a " : ""), N(fmtWindows(cur.windows)), ". Each plan is calibrated on its own hours");
|
||
if (cal && cal.source !== "fit" && cal.source !== "default") {
|
||
f.push(": until this one has enough of them, 1% of its week ≈ ", N(fix(cal.week.unitsPerPct, 1)), " plan units, ",
|
||
cal.source === "scaled" ? "the previous plan's rate × " + fmtScale(cal.scale) : "carried over from the previous plan");
|
||
} else if (cal && cal.source === "fit") {
|
||
f.push(": 1% of its week ≈ ", N(fix(cal.week.unitsPerPct, 1)), " plan units");
|
||
var pr = prev ? rateOf(prev) : null;
|
||
if (pr) f.push(" against ", N(fix(pr.week.unitsPerPct, 1)), " on the plan before");
|
||
}
|
||
f.push(".");
|
||
return panel(id + ":plan", "Which plan · " + label,
|
||
"Which tier is the login on, since when — and what is 1% of its week worth on it?", f,
|
||
function () {
|
||
var tl = el("div", { class: "ptl" }, segs.map(function (p) {
|
||
var end = p.until || now / 1000;
|
||
return el("div", { class: p.since === cur.since ? "live" : "", style: "flex-grow:" + Math.max(0.02, (end - p.since) / span),
|
||
title: name(p) + " · " + fmtWindows(p.windows) + " · " + fmtStampDate(p.since) + " → " + (p.until ? fmtStampDate(p.until) : "now") + (p.reason ? " · " + p.reason : "") },
|
||
[el("b", { text: name(p) }), el("span", { text: fmtWindows(p.windows) })]);
|
||
}));
|
||
var cards = el("div", { class: "cards" }, segs.slice().reverse().slice(0, 4).map(function (p) {
|
||
var r = rateOf(p);
|
||
return el("div", { class: "aia-card pc" }, [
|
||
el("div", { class: "row" }, [el("span", { class: "fg", text: name(p) }),
|
||
el("span", { class: "sm aia-muted", text: fmtStampDate(p.since) + " → " + (p.until ? fmtStampDate(p.until) : "now") + (p.source === "assumed" ? " · assumed" : "") })]),
|
||
el("div", { class: "xs aia-muted", text: fmtWindows(p.windows) + (p.reason && p.source !== "assumed" ? " · " + p.reason : "") }),
|
||
el("div", { class: "xs mono" }, r ? ["1% wk ≈ " + fix(r.week.unitsPerPct, 1) + " units" + (r.week.usdPerPct != null ? " ≈ " + fmtCost(r.week.usdPerPct) : ""),
|
||
el("span", { class: "aia-muted", text: " · " + (r.source === "fit" ? "fitted" : r.source) })]
|
||
: [el("span", { class: "aia-muted", text: "no trusted fit on this plan" })]),
|
||
]);
|
||
}));
|
||
return el("div", {}, [tl, cards]);
|
||
},
|
||
function () {
|
||
return dataTable(["Plan", "From", "To", "Windows", "1% wk units", "1% wk list $", "Rate"], segs.slice().reverse().map(function (p) {
|
||
var r = rateOf(p);
|
||
return [name(p) + (p.source === "assumed" ? " (assumed)" : ""), fmtStampDate(p.since) || "—",
|
||
p.until ? (fmtStampDate(p.until) || "—") : "now", fmtWindows(p.windows),
|
||
r ? fix(r.week.unitsPerPct, 1) : "—", r && r.week.usdPerPct != null ? fmtCost(r.week.usdPerPct) : "—",
|
||
r ? (r.source === "fit" ? "fit " + fmtStampDate(r.fittedAt) : r.source) : "—"];
|
||
}));
|
||
});
|
||
}
|
||
|
||
function billingPanel(id, label, billing, plan, now) {
|
||
var nowS = now / 1000;
|
||
var next = nextRenewal(billing, nowS);
|
||
var days = daysUntil(next, nowS);
|
||
var weeks = billing.weeks || [];
|
||
var mult = plan && plan.multiplier ? plan.multiplier : null;
|
||
var tiers = smallerTiers(mult);
|
||
var top = topPeak(weeks);
|
||
var closed = weeks.filter(function (w) { return !w.current; });
|
||
var scale = Math.max(100, top || 0);
|
||
function tierPct(peak, t) { return (peak * 100) / t.capPct; }
|
||
function over(t) { return weeks.filter(function (w) { return w.peak > t.capPct; }).length; }
|
||
var biggest = tiers[0];
|
||
var long = { weekday: "short", day: "numeric", month: "short" };
|
||
var f = [N((plan && plan.label) || label), " renews on ", N(fmtBillDate(next, long)), " (in ", N(days + " day" + (days === 1 ? "" : "s")),
|
||
") — estimated: monthly on the day the subscription started (" + fmtBillDate(billing.subscriptionStartedAt, { day: "numeric", month: "short", year: "numeric" }) +
|
||
"); claude.ai → Settings → Billing has the exact date."];
|
||
if (top != null) {
|
||
f.push(" Since ", N(fmtBillDate(billing.previousPeriodStart || billing.periodStart)), " the weeks peaked at up to ", N(fmtWholePct(top)));
|
||
if (biggest && mult) {
|
||
f.push(". On ", N(biggest.label), " — " + fmtFraction(biggest.capPct) + " of this plan — the same work would reach ",
|
||
N(fmtWholePct(tierPct(top, biggest))), ": ", N(over(biggest)), " of ", N(weeks.length), " weeks over its cap");
|
||
if (over(biggest) === 0) f.push(", so it would have held" + (closed.length < weeks.length ? " so far" : ""));
|
||
}
|
||
f.push(".");
|
||
}
|
||
return panel(id + ":bill", "Billing cycle · " + label, "When is the next charge — and would a smaller plan have held these weeks?", f,
|
||
function () {
|
||
var box = el("div", {}, [el("div", { class: "bhead" }, [
|
||
el("div", {}, [el("div", { class: "big", text: fmtBillDate(next) }),
|
||
el("div", { class: "aia-muted", style: "margin-top:4px;font-size:11px", text: "next charge · in " + days + " day" + (days === 1 ? "" : "s") + " · estimated" })]),
|
||
el("div", { class: "aia-muted", style: "text-align:right;font-size:11px", text: "cycle " + fmtBillDate(billing.periodStart) + " → " + fmtBillDate(next) }),
|
||
])]);
|
||
if (!weeks.length) { box.appendChild(el("div", { class: "aia-empty", text: "No weekly readings this cycle yet." })); return box; }
|
||
var chart = el("div", { class: "bchart" });
|
||
tiers.forEach(function (t) {
|
||
chart.appendChild(el("div", { class: "cap", style: "bottom:" + (t.capPct / scale) * 100 + "%" }, [el("span", { text: t.label })]));
|
||
});
|
||
if (scale > 100) chart.appendChild(el("div", { class: "hund", style: "bottom:" + (100 / scale) * 100 + "%" }));
|
||
chart.appendChild(el("div", { class: "bars" }, weeks.map(function (w) {
|
||
return el("div", { class: "wk", title: "Week ending " + fmtBillDate(w.resetsAt, long) + ": peak " + fmtWholePct(w.peak) + (w.current ? " (still open)" : "") }, [
|
||
el("span", { class: "mono aia-muted", text: Math.round(w.peak) + "%" }),
|
||
el("i", { class: w.current ? "cur" : w.inCycle === false ? "prev" : "", style: "height:" + Math.max(1, (w.peak / scale) * 100) + "%" }),
|
||
]);
|
||
})));
|
||
box.appendChild(chart);
|
||
box.appendChild(el("div", { class: "blabels" }, weeks.map(function (w) { return el("div", { text: fmtBillDate(w.resetsAt) }); })));
|
||
var items = [{ label: "this cycle", color: "hsl(var(--primary, 24 95% 53%))" },
|
||
{ label: "previous cycle", color: "hsl(var(--primary, 24 95% 53%) / .4)" }];
|
||
if (tiers.length) items.push({ label: "smaller plan's cap, on this plan's scale", color: "var(--amber)" });
|
||
box.appendChild(legend(items));
|
||
return box;
|
||
},
|
||
function () {
|
||
return dataTable(["Week ending", "Cycle", "Peak"].concat(tiers.map(function (t) { return "On " + t.label; })),
|
||
weeks.slice().reverse().map(function (w) {
|
||
return [fmtBillDate(w.resetsAt, long) + (w.current ? " (open)" : ""), w.inCycle === false ? "previous" : "this", fmtWholePct(w.peak)]
|
||
.concat(tiers.map(function (t) { return fmtWholePct(tierPct(w.peak, t)); }));
|
||
}));
|
||
});
|
||
}
|
||
|
||
/** Where each window instance peaked (instances keyed by their reset time). */
|
||
function windowPeakPoints(points) {
|
||
var by = {};
|
||
points.forEach(function (p) {
|
||
var k = Math.round((p.resetsAt || 0) / 600);
|
||
if (!by[k] || p.pct > by[k].v) by[k] = { t: p.t * 1000, v: p.pct };
|
||
});
|
||
return Object.keys(by).map(function (k) { return by[k]; }).sort(function (a, b) { return a.t - b.t; });
|
||
}
|
||
|
||
/** A time line on [from, to]: a gap past `gapMs` breaks it; peaks get a dot and a label. */
|
||
function linePlot(pts, from, to, yMax, color, peaks) {
|
||
var W = plotWidth(), H = 96, L = 32, R = 6, T = 8, B = 4;
|
||
var x = function (t) { return L + ((t - from) / Math.max(1, to - from)) * (W - L - R); };
|
||
var y = function (v) { return T + (1 - Math.min(v, yMax) / yMax) * (H - T - B); };
|
||
var host = el("div", { class: "plot" });
|
||
var g = s("svg", { viewBox: "0 0 " + W + " " + H, width: "100%", style: "display:block;overflow:visible" });
|
||
[0, 50, 100].filter(function (v) { return v <= yMax; }).forEach(function (v) {
|
||
g.appendChild(s("line", { x1: L, x2: W - R, y1: y(v), y2: y(v), stroke: "hsl(var(--border, 214 32% 91%))", "stroke-width": "1", "stroke-dasharray": v ? "3 3" : null }));
|
||
var tx = s("text", { x: L - 4, y: y(v) + 3, "text-anchor": "end", "font-size": "9", fill: "hsl(var(--muted-foreground, 215 16% 47%))" });
|
||
tx.textContent = v + "%"; g.appendChild(tx);
|
||
});
|
||
var d = "", prev = null;
|
||
pts.forEach(function (p) {
|
||
d += (prev && p.t - prev.t <= 3 * HOUR ? "L" : "M") + fix(x(p.t), 1) + " " + fix(y(p.v), 1);
|
||
prev = p;
|
||
});
|
||
if (d) g.appendChild(s("path", { d: d, fill: "none", stroke: color, "stroke-width": "1.75", "stroke-linejoin": "round", "stroke-linecap": "round" }));
|
||
// label the peaks that have room (≥ 46 px apart), highest first
|
||
var placed = [];
|
||
peaks.slice().sort(function (a, b) { return b.v - a.v; }).forEach(function (p) {
|
||
var px = x(p.t);
|
||
g.appendChild(s("circle", { cx: px, cy: y(p.v), r: "2.5", fill: color }));
|
||
if (placed.every(function (q) { return Math.abs(q - px) >= 46; })) {
|
||
placed.push(px);
|
||
var tx = s("text", { x: Math.max(L + 10, Math.min(W - R - 10, px)), y: Math.max(8, y(p.v) - 5), "text-anchor": "middle", "font-size": "9",
|
||
"font-family": "ui-monospace, monospace", fill: "hsl(var(--muted-foreground, 215 16% 47%))" });
|
||
tx.textContent = Math.round(p.v) + "%"; g.appendChild(tx);
|
||
}
|
||
});
|
||
var cursor = s("line", { y1: T, y2: H - B, stroke: "hsl(var(--foreground, 222 47% 11%) / .3)", "stroke-width": "1", visibility: "hidden" });
|
||
g.appendChild(cursor);
|
||
host.appendChild(g);
|
||
var tip = tipFor(host);
|
||
host.addEventListener("mousemove", function (e) {
|
||
if (!pts.length) return;
|
||
var r = g.getBoundingClientRect();
|
||
var t = from + ((e.clientX - r.left) / r.width * W - L) / (W - L - R) * (to - from);
|
||
var best = pts.reduce(function (b, p) { return Math.abs(p.t - t) < Math.abs(b.t - t) ? p : b; }, pts[0]);
|
||
cursor.setAttribute("x1", x(best.t)); cursor.setAttribute("x2", x(best.t)); cursor.setAttribute("visibility", "visible");
|
||
tip.show(e, [fmtWhen(best.t) + " · ", el("span", { class: "mono", text: Math.round(best.v) + "%" })]);
|
||
});
|
||
host.addEventListener("mouseleave", function () { tip.hide(); cursor.setAttribute("visibility", "hidden"); });
|
||
host.appendChild(el("div", { class: "axis" }, [el("span", { text: fmtShortDay(from) }), el("span", { text: fmtShortDay(to) })]));
|
||
return host;
|
||
}
|
||
|
||
var WINDOW_LINES = [
|
||
{ key: "seven_day", fit: "week", title: "Week", color: "hsl(var(--primary, 24 95% 53%))" },
|
||
{ key: "five_hour", fit: "h5", title: "5-hour window", color: "var(--sky)" },
|
||
];
|
||
function historyPanel(id, history, days, windows, now) {
|
||
var to = now, from = now - days * DAY;
|
||
var lines = WINDOW_LINES.filter(function (w) { return w.fit === "week" || windows.indexOf(w.fit) >= 0; }).map(function (w) {
|
||
var raw = (history.series && history.series[w.key]) || [];
|
||
var pts = raw.map(function (p) { return { t: p.t * 1000, v: p.pct }; }).filter(function (p) { return p.t >= from; });
|
||
var peaks = windowPeakPoints(raw.filter(function (p) { return p.t * 1000 >= from; }));
|
||
return { w: w, pts: pts, peaks: peaks, max: Math.max.apply(null, [100].concat(pts.map(function (p) { return p.v; }))) };
|
||
});
|
||
var week = lines[0];
|
||
var h5 = lines.find(function (l) { return l.w.fit === "h5"; });
|
||
var peak = week.pts.reduce(function (b, p) { return !b || p.v > b.v ? p : b; }, null);
|
||
var h5Peaks = h5 ? h5.peaks.map(function (p) { return p.v; }) : [];
|
||
var hot = h5Peaks.filter(function (v) { return v >= 90; }).length;
|
||
var capped = h5Peaks.filter(function (v) { return v >= 100; }).length;
|
||
var f;
|
||
if (peak) {
|
||
f = ["The week peaked at ", N(fmtPlanPct(peak.v)), " on ", N(fmtShortDay(peak.t)), "."];
|
||
if (h5) {
|
||
f.push(" Of ", N(h5Peaks.length), " 5-hour windows recorded, ", N(hot), " went past 90%");
|
||
if (capped > 0) f.push(" and ", N(capped), " hit the cap");
|
||
f.push(".");
|
||
}
|
||
f.push(" Gaps are hours with no reading (no terminal open, notifier idle).");
|
||
} else f = ["No /usage readings in the last " + days + " days."];
|
||
return panel(id + ":hist", "How the windows filled",
|
||
"The official /usage % over the last " + days + " days — " + (h5 ? "two plots, one per window, on one time range." : "the weekly window, the plan's only one."), f,
|
||
function () {
|
||
return el("div", {}, lines.map(function (l) {
|
||
var last = l.pts.length ? l.pts[l.pts.length - 1].v : null;
|
||
return el("div", { class: "lines" }, [
|
||
el("div", { class: "sub" }, [el("b", { text: l.w.title }), el("span", { class: "mono aia-muted", text: last != null ? "now " + fmtPlanPct(last) : "no readings" })]),
|
||
linePlot(l.pts, from, to, l.max, l.w.color, l.peaks.filter(function (p) { return p.v > 0; })),
|
||
]);
|
||
}));
|
||
},
|
||
function () {
|
||
return dataTable(["Window", "Readings", "Peak", "Latest"], lines.map(function (l) {
|
||
var vs = l.pts.map(function (p) { return p.v; });
|
||
return [l.w.title, l.pts.length, vs.length ? fmtPlanPct(Math.max.apply(null, vs)) : "—", vs.length ? fmtPlanPct(vs[vs.length - 1]) : "—"];
|
||
}));
|
||
});
|
||
}
|
||
|
||
function observedColumns(days) {
|
||
var host = el("div", { class: "plot" });
|
||
var max = Math.max.apply(null, days.map(function (d) { return Math.max(d.observedWeek || 0, d.predictedWeek || 0); }).concat([1e-9]));
|
||
function h(v) { return (Math.max(0, v) / max) * 100 + "%"; }
|
||
var tip;
|
||
var cols = el("div", { class: "cols", style: "height:112px" }, days.map(function (d) {
|
||
var obs = d.observedWeek || 0, pred = d.predictedWeek || 0;
|
||
var untracked = d.untrackedWeek != null ? d.untrackedWeek : Math.max(0, obs - pred);
|
||
var tracked = Math.max(0, obs - untracked);
|
||
var stack = el("div", { class: "stack", style: "height:" + h(obs) }, [
|
||
tracked > 0 ? el("i", { class: "tr" + (untracked > 0.01 ? "" : " top"), style: "flex-grow:" + tracked }) : null,
|
||
untracked > 0.01 ? el("i", { class: "un", style: "flex-grow:" + untracked }) : null,
|
||
]);
|
||
var c = el("div", { class: "c" }, [stack, pred > 0 ? el("span", { class: "predtick", style: "bottom:calc(" + h(pred) + " - 1px)" }) : null]);
|
||
c.addEventListener("mousemove", function (e) {
|
||
var parts = [fmtDay(d.day) + " · rose ", el("span", { class: "mono", text: fix(obs, 1) + "%" }), " · predicted ", el("span", { class: "mono", text: fix(pred, 1) + "%" })];
|
||
if (untracked > 0.05) parts.push(" · untracked ", el("span", { class: "mono", text: fix(untracked, 1) + "%" }));
|
||
parts.push(" · " + fmtCost(d.cost || 0));
|
||
tip.show(e, parts);
|
||
});
|
||
c.addEventListener("mouseleave", function () { tip.hide(); });
|
||
return c;
|
||
}));
|
||
host.appendChild(cols);
|
||
tip = tipFor(host);
|
||
host.appendChild(el("div", { class: "axis" }, [el("span", { text: days[0] ? fmtDay(days[0].day) : "" }),
|
||
el("span", { text: days.length ? fmtDay(days[days.length - 1].day) : "" })]));
|
||
return host;
|
||
}
|
||
|
||
function observedPanel(id, history, harness) {
|
||
var days = history.daily || [];
|
||
var obs = sum(days.map(function (d) { return d.observedWeek; }));
|
||
var pred = sum(days.map(function (d) { return d.predictedWeek; }));
|
||
var untracked = sum(days.map(function (d) { return d.untrackedWeek; }));
|
||
var cost = sum(days.map(function (d) { return d.cost; }));
|
||
var worst = days.reduce(function (b, d) { return (d.untrackedWeek || 0) > ((b && b.untrackedWeek) || 0) ? d : b; }, null);
|
||
var f;
|
||
if (obs > 0) {
|
||
f = ["Over these ", N(days.length), " days the week meter rose ", N(fix(obs, 1) + "%"), " in the hours it could be measured; the ",
|
||
N(fmtCost(cost)), " of archived list-price spend predicts ", N(fix(pred, 1) + "%"), ". "];
|
||
if (untracked > 0.05) {
|
||
f.push(N(fix(untracked, 1) + "%"), " (", N(Math.round((untracked / obs) * 100) + "%"), " of the rise) is ", el("strong", { text: "untracked" }),
|
||
" — usage the archive can't see: " + (UNTRACKED[harness] || UNTRACKED.claude));
|
||
if (worst && (worst.untrackedWeek || 0) > 0.05) f.push(", most of it on ", N(fmtDay(worst.day)));
|
||
f.push(".");
|
||
} else f.push("Practically all of it is explained by the conversations archived here.");
|
||
} else f = ["No measurable rise of the week's % in this range."];
|
||
return panel(id + ":obs", "Does the archive explain the meter?",
|
||
"Per day: how much the week's % rose, how much the archived spend predicts at the rate in force, and the untracked rest.", f,
|
||
function () {
|
||
return el("div", {}, [observedColumns(days), legend([
|
||
{ label: "explained by archived spend", color: "var(--tracked)" },
|
||
{ label: "untracked (outside the lab)", color: "var(--untracked)" },
|
||
{ label: "predicted from spend (tick)", color: "hsl(var(--foreground, 222 47% 11%) / .7)" },
|
||
])]);
|
||
},
|
||
function () {
|
||
return dataTable(["Day", "List $", "Rose", "Predicted", "Untracked", "5h rose"], days.map(function (d) {
|
||
return [fmtDay(d.day), fmtCost(d.cost || 0), d.observedWeek != null ? fix(d.observedWeek, 2) + "%" : "—",
|
||
d.predictedWeek != null ? fix(d.predictedWeek, 2) + "%" : "—", d.untrackedWeek != null ? fix(d.untrackedWeek, 2) + "%" : "—",
|
||
d.observed5h != null ? fix(d.observed5h, 1) + "%" : "—"];
|
||
}));
|
||
});
|
||
}
|
||
|
||
function confidenceBadge(cal) {
|
||
if (cal.source === "carried" || cal.source === "scaled")
|
||
return el("span", { class: "aia-badge", "data-tone": "info", title: "A new plan: its rate starts from the previous plan's last fit (scaled by the tiers' multipliers) until it has ~24 hours of its own" },
|
||
[svg("repeat", "sm"), cal.source === "scaled" ? "scaled ×" + fmtScale(cal.scale) : "carried over"]);
|
||
if (cal.source === "default")
|
||
return el("span", { class: "aia-badge", title: "No trustworthy fit yet — the rate is the shipped seed (docs/usage-calibration.md)" }, [svg("sprout", "sm"), "seeded"]);
|
||
return isTrusted(cal)
|
||
? el("span", { class: "aia-badge", "data-tone": "success", title: "Enough hours, R² ≥ 0.5 and within ×3 of the seed rate" }, [svg("check", "sm"), "trusted"])
|
||
: el("span", { class: "aia-badge", "data-tone": "warn", title: "Too few hours, a weak R² or too far from the seed — usage outside the lab skews it" }, [svg("alert", "sm"), "low confidence"]);
|
||
}
|
||
|
||
function ratePanel(id, label, cal, harness, sub) {
|
||
var ceiling = monthlyCeiling(cal);
|
||
var rows = [];
|
||
if (cal) rows.push(["week", "Week", cal.week]);
|
||
if (cal && cal.h5) rows.push(["h5", "5-hour window", cal.h5]);
|
||
var f;
|
||
if (cal) {
|
||
f = ["1% of the week ≈ ", N(fix(cal.week.unitsPerPct, 1)), " plan units ≈ ", N(cal.week.usdPerPct != null ? fmtCost(cal.week.usdPerPct) : "—"), " of list-price work"];
|
||
if (cal.h5 && cal.h5.usdPerPct != null) f.push(", and 1% of a 5-hour window ≈ ", N(fmtCost(cal.h5.usdPerPct)));
|
||
f.push(". ");
|
||
if (ceiling != null) {
|
||
f.push("Spending ", N("100%"), " of the week every week would be worth ≈ ", N(fmtCost(ceiling)), " list a month");
|
||
if (sub && sub.monthlyCost > 0) f.push(" — ", N(fix(ceiling / sub.monthlyCost, 0) + "×"), " the ", N(PLAN_LABEL[sub.plan] || sub.plan), " plan's ", N(fmtCost(sub.monthlyCost)));
|
||
f.push(". ");
|
||
}
|
||
if (harness === "agy") f.push("Antigravity draws the Gemini group (Neon, Hydrogen, Flash) down by API price, so its plan units are plain Gemini list $; Argon and the Claude / GPT models have buckets of their own.");
|
||
else if (harness !== "opencode") f.push("Fable tokens weigh ≈ ", N("1.75×"), " their list price on the meter, so the same dollars of Fable use ~1.75× the percent; there is no Fable-only weekly bucket.");
|
||
else f.push("This plan has a weekly window only; its plan units are plain GPT list $.");
|
||
} else f = ["No calibration for ", N(label), "."];
|
||
return panel(id + ":rate", "The exchange rate in force · " + label,
|
||
"How many plan units — and list-price dollars — make 1% of each window?", f,
|
||
function () {
|
||
if (!cal) return null;
|
||
var why;
|
||
if (cal.source === "fit") why = el("span", {}, [cal.days + "-day fit ending ", el("span", { class: "fg", text: fmtStampDate(cal.fittedAt) || "" })]);
|
||
else if (cal.source === "default") why = el("span", { text: "seed rate from the 2026-10-12 fit" });
|
||
else why = el("span", {}, ["the previous plan's fit of ", el("span", { class: "fg", text: fmtStampDate(cal.basedOn) || "" }),
|
||
cal.source === "scaled" ? " × " + fmtScale(cal.scale) + " (tier change)" : "", " — until this plan has enough hours of its own"]);
|
||
var box = el("div", {}, [el("div", { class: "badges" }, [confidenceBadge(cal), why])]);
|
||
box.appendChild(el("div", { class: "rates" }, rows.map(function (r) {
|
||
var w = r[2];
|
||
return el("div", { class: "aia-card rate" }, [
|
||
el("div", { class: "k", text: "1% of the " + r[1].toLowerCase() }),
|
||
el("div", { class: "vals" }, [
|
||
el("div", {}, [el("div", { class: "v1", text: w.usdPerPct != null ? fmtCost(w.usdPerPct) : "—" }), el("div", { class: "u", text: "list $" })]),
|
||
el("div", {}, [el("div", { class: "v2", text: fix(w.unitsPerPct, 1) }), el("div", { class: "u", text: "plan units" })]),
|
||
]),
|
||
el("div", { class: "stats" }, [
|
||
el("span", { title: "Share of the hourly % rises the fit explains", text: "R² " + (w.r2 != null ? fix(w.r2, 2) : "—") }),
|
||
el("span", { title: "Hours with spend the fit used", text: "n " + (w.n || 0) + " h" }),
|
||
w.interceptPct != null ? el("span", { title: "% per hour the archive can't explain (usage outside the lab)", text: "+" + fix(w.interceptPct, 2) + "%/h untracked" }) : null,
|
||
]),
|
||
]);
|
||
})));
|
||
if (ceiling != null) box.appendChild(el("div", { class: "ceil" }, [
|
||
el("span", { class: "aia-muted", text: "Theoretical ceiling · " }), "100% every week ≈ ", el("b", { text: fmtCost(ceiling) }), " list / month",
|
||
el("span", { class: "aia-muted", text: " (100 × " + fmtCost(cal.week.usdPerPct || 0) + " × " + WEEKS_PER_MONTH + " weeks)" }),
|
||
]));
|
||
return box;
|
||
}, null);
|
||
}
|
||
|
||
/** The "$ per 1%" exchange rate per stored fit — small multiples, low-confidence fits faded. */
|
||
function columns(bins, max, color, detail) {
|
||
var host = el("div", { class: "plot" });
|
||
var tip;
|
||
host.appendChild(el("div", { class: "cols", style: "height:96px" }, bins.map(function (b, i) {
|
||
var over = b.value > max;
|
||
var c = el("div", { class: "c" }, [el("div", { class: "bar" + (b.faded ? " faded" : ""),
|
||
style: "background:" + color + ";height:" + Math.max(Math.min(b.value / max, 1) * 100, b.value > 0 ? 2 : 0) + "%" },
|
||
[over ? el("span", { class: "brk" }) : null])]);
|
||
c.addEventListener("mousemove", function (e) { tip.show(e, detail(b, i)); });
|
||
c.addEventListener("mouseleave", function () { tip.hide(); });
|
||
return c;
|
||
})));
|
||
tip = tipFor(host);
|
||
host.appendChild(el("div", { class: "axis" }, [el("span", { text: bins[0] ? bins[0].label : "" }), el("span", { text: bins.length ? bins[bins.length - 1].label : "" })]));
|
||
return host;
|
||
}
|
||
function usdOf(c, fit) { return c[fit] && c[fit].usdPerPct != null ? c[fit].usdPerPct : null; }
|
||
var RATE_WINDOWS = [
|
||
{ fit: "week", title: "1% of the week", color: "hsl(var(--primary, 24 95% 53%))" },
|
||
{ fit: "h5", title: "1% of a 5-hour window", color: "var(--sky)" },
|
||
];
|
||
function trendPanel(id, label, fitsHist) {
|
||
var fits = ((fitsHist && fitsHist.history) || []).filter(function (c) { return c.source === "fit"; })
|
||
.sort(function (a, b) { return a.fittedAt - b.fittedAt; });
|
||
var trusted = fits.filter(isTrusted);
|
||
var first = trusted.find(function (c) { return usdOf(c, "week") != null; });
|
||
var last = trusted.slice().reverse().find(function (c) { return usdOf(c, "week") != null; });
|
||
var lowCount = fits.length - trusted.length;
|
||
var f;
|
||
if (first && last) {
|
||
var a = usdOf(first, "week"), b = usdOf(last, "week"), change = a ? b / a - 1 : 0;
|
||
f = ["On the ", N(label), " account, 1% of the week was worth ", N(fmtCost(b)), " of list-price work in the latest trusted fit (", N(fmtStampDate(last.fittedAt)), ")"];
|
||
if (first !== last) f.push(" against ", N(fmtCost(a)), " on ", N(fmtStampDate(first.fittedAt)), " — ", N((change >= 0 ? "+" : "") + fix(change * 100, 0) + "%"),
|
||
Math.abs(change) < 0.1 ? ", so the limits have held steady in dollar terms"
|
||
: change > 0 ? ": each percent now buys more list-price work (cheaper models, or looser limits)"
|
||
: ": each percent now buys less (a pricier model mix, or tighter limits)");
|
||
f.push(". ");
|
||
if (lowCount > 0) f.push(N(lowCount), " low-confidence " + (lowCount === 1 ? "fit is" : "fits are") + " drawn faded — weeks with usage outside the lab skew the ratio.");
|
||
} else f = ["No calibration fit yet for ", N(label), " — the seeded rate is in force."];
|
||
return panel(id + ":trend", "What 1% of the week costs over time · " + label,
|
||
"List-price dollars per 1% of each window, one fit per week — has the exchange rate moved?", f,
|
||
function () {
|
||
if (!fits.length) return el("div", { class: "aia-empty", text: "No fits recorded yet." });
|
||
var box = el("div", { class: "two" }, RATE_WINDOWS.map(function (w) {
|
||
var vals = fits.map(function (c) { return usdOf(c, w.fit) || 0; });
|
||
var ok = trusted.map(function (c) { return usdOf(c, w.fit) || 0; });
|
||
var max = (ok.length ? Math.max.apply(null, ok) : Math.max.apply(null, vals.concat([1e-9]))) * 1.15 || 1e-9;
|
||
var latest = trusted.slice().reverse().find(function (c) { return usdOf(c, w.fit) != null; });
|
||
return el("div", {}, [
|
||
el("div", { class: "sub" }, [el("b", { text: w.title }), latest ? el("span", { class: "mono aia-muted", text: "now " + fmtCost(usdOf(latest, w.fit)) }) : null]),
|
||
columns(fits.map(function (c) { return { label: fmtStampDate(c.fittedAt) || "", value: usdOf(c, w.fit) || 0, faded: !isTrusted(c) }; }), max, w.color,
|
||
function (bn, i) { return ["fit of " + bn.label + " · " + fmtCost(bn.value) + " per 1% · " + (isTrusted(fits[i]) ? "trusted" : "low confidence")]; }),
|
||
]);
|
||
}));
|
||
if (!lowCount) return box;
|
||
return el("div", {}, [box, legend([
|
||
{ label: "trusted fit", color: "hsl(var(--muted-foreground, 215 16% 47%))" },
|
||
{ label: "faded = low-confidence fit — usage outside the lab that week", color: "hsl(var(--muted-foreground, 215 16% 47%))", opacity: ".3" },
|
||
])]);
|
||
},
|
||
function () {
|
||
return dataTable(["Fitted", "$ / 1% wk", "$ / 1% 5h", "R² wk", "Hours", "Confidence"], fits.map(function (c) {
|
||
return [fmtStampDate(c.fittedAt) || "—", usdOf(c, "week") != null ? fmtCost(usdOf(c, "week")) : "—",
|
||
usdOf(c, "h5") != null ? fmtCost(usdOf(c, "h5")) : "—", c.week.r2 != null ? fix(c.week.r2, 2) : "—", c.week.n || 0,
|
||
isTrusted(c) ? "trusted" : "low"];
|
||
}));
|
||
});
|
||
}
|
||
|
||
function accountSection(a, heading, now) {
|
||
var id = a.id, label = a.label || id;
|
||
var limits = data.limits[id] || null;
|
||
var history = (data.history || {})[id] || null;
|
||
var fits = (data.calibration || {})[id] || null;
|
||
var cal = (limits && limits.calibration) || (history && history.calibration) || (fits && fits.current) || null;
|
||
var harness = a.harness || "claude";
|
||
var box = el("div", { class: "acct" });
|
||
if (heading) box.appendChild(el("h2", { class: "aia-title ah", text: label }));
|
||
box.appendChild(gaugesPanel(id, label, limits, cal, history, now));
|
||
var pp = planPanel(id, label, cal, (data.plans || {})[id], fits, now);
|
||
if (pp) box.appendChild(pp);
|
||
if (limits && limits.billing) box.appendChild(billingPanel(id, label, limits.billing, limits.plan || null, now));
|
||
if (history) {
|
||
box.appendChild(historyPanel(id, history, data.days || state.days, a.planWindows || ["week", "h5"], now));
|
||
box.appendChild(observedPanel(id, history, harness));
|
||
} else box.appendChild(el("section", { class: "aia-card" }, [el("div", { class: "aia-empty", text: "No history." })]));
|
||
box.appendChild(ratePanel(id, label, cal, harness, a.subscription || null));
|
||
box.appendChild(trendPanel(id, label, fits));
|
||
return box;
|
||
}
|
||
|
||
function methodology() {
|
||
return el("p", { class: "method aia-muted" }, [
|
||
el("b", { text: "%" }), " is what Claude's own /usage reports, recorded by the hub whenever it moves. ",
|
||
el("b", { text: "Plan units" }), " are what the limits appear to count: every token priced as the model it is metered as (a new model at its predecessor's price), Fable ×1.75. The rate is a least-squares fit of each hour's % rise against the archived plan units over 14 days, refitted daily; it replaces the one in force only when it is trustworthy. ",
|
||
el("b", { text: "List $" }), " is the API price at the exact model version — on a flat-rate plan, value returned rather than money spent. The weekly window is the binding cap.",
|
||
]);
|
||
}
|
||
|
||
// ── controls ────────────────────────────────────────────────────────────
|
||
function scopeSegs() {
|
||
var segs = profiles.map(function (p) { return { id: "profile:" + p.id, label: p.label || p.id }; });
|
||
if (segs.length) segs.push({ id: "all", label: "All" });
|
||
return segs;
|
||
}
|
||
/** The scope shown: the picked one, else the one the hub answered for, else the first. */
|
||
function curScope() {
|
||
var segs = scopeSegs();
|
||
return state.scope || (data && data.scope) || (segs[0] && segs[0].id) || "";
|
||
}
|
||
function renderControls() {
|
||
var dbox = $("days"); dbox.textContent = "";
|
||
dbox.setAttribute("role", "radiogroup"); dbox.setAttribute("aria-label", "History length");
|
||
DAY_OPTIONS.forEach(function (d) {
|
||
var on = state.days === d;
|
||
var b = el("button", { type: "button", role: "radio", "aria-checked": String(on), class: on ? "aia-active" : null, text: d + "d" });
|
||
b.addEventListener("click", function () { if (state.days === d) return; state.days = d; persist(); load(); });
|
||
dbox.appendChild(b);
|
||
});
|
||
var box = $("scopes"); box.textContent = "";
|
||
var segs = scopeSegs();
|
||
box.hidden = !segs.length;
|
||
box.setAttribute("role", "radiogroup"); box.setAttribute("aria-label", "Profile");
|
||
var cur = curScope();
|
||
segs.forEach(function (sg) {
|
||
var on = sg.id === cur;
|
||
var b = el("button", { type: "button", role: "radio", "aria-checked": String(on), class: on ? "aia-active" : null, text: sg.label });
|
||
b.addEventListener("click", function () { if (curScope() === sg.id) return; state.scope = sg.id; persist(); load(); });
|
||
box.appendChild(b);
|
||
});
|
||
}
|
||
|
||
/** The header: the scope and range in words (+ the week's % for one account), and Recalibrate. */
|
||
function renderHeader() {
|
||
var cur = curScope(), parts = [];
|
||
var seg = scopeSegs().filter(function (sg) { return sg.id === cur; })[0];
|
||
if (cur === "all") parts.push("All profiles");
|
||
else if (seg) parts.push(seg.label);
|
||
var accounts = (data && data.accounts) || [];
|
||
if (accounts.length > 1) parts.push(accounts.length + " accounts");
|
||
else if (accounts.length === 1) {
|
||
var lim = data.limits && data.limits[accounts[0].id];
|
||
var wk = lim && lim.windows && lim.windows.seven_day;
|
||
if (wk && wk.pct != null) parts.push("week at " + fmtPlanPct(wk.pct, 0));
|
||
}
|
||
parts.push("last " + state.days + " days");
|
||
var busyCal = state.recal.busy;
|
||
setHeader({
|
||
subtitle: parts.join(" · "),
|
||
actions: api ? [{ id: "recal", label: busyCal ? "Recalibrating…" : "Recalibrate now", icon: "calculator", disabled: busyCal }] : [],
|
||
});
|
||
}
|
||
|
||
function renderStatus() {
|
||
var box = $("status"), r = state.recal;
|
||
box.textContent = "";
|
||
if (!r.result && !r.error) { box.hidden = true; return; }
|
||
box.hidden = false;
|
||
box.className = "status " + (r.error ? "aia-error" : "aia-note aia-small");
|
||
box.setAttribute("role", "status");
|
||
if (r.error) { box.textContent = "Recalibration failed: " + r.error; return; }
|
||
var fitted = Object.keys(r.result.calibrations || {}).map(function (k) { return r.result.calibrations[k]; });
|
||
if (!fitted.length) { box.textContent = "Not enough signal for a new fit — the rate in force is unchanged."; return; }
|
||
var labels = {};
|
||
((data && data.accounts) || []).forEach(function (a) { labels[a.id] = a.label; });
|
||
box.appendChild(el("ul", {}, fitted.map(function (c) {
|
||
return el("li", {}, [el("span", { class: "fg", text: labels[c.account] || c.account }), ": 1% of the week = ",
|
||
el("span", { class: "mono", text: fmtCost(c.week.usdPerPct || 0) }), " (", el("span", { class: "mono", text: fix(c.week.unitsPerPct, 1) }),
|
||
" units, R² ", el("span", { class: "mono", text: fix(c.week.r2 || 0, 2) }), ")", isTrusted(c) ? " — in force" : " — low confidence, not applied",
|
||
(r.result.shifted || []).indexOf(c.account) >= 0 ? el("span", { class: "warn", text: " · rate shifted > 20%" }) : null]);
|
||
})));
|
||
}
|
||
|
||
/** A line in place of the panels: an error, or the empty state. */
|
||
function showMsg(kind, text, detail) {
|
||
var m = $("msg");
|
||
m.hidden = false; $("content").hidden = true;
|
||
m.className = kind === "error" ? "aia-error" : "aia-empty";
|
||
m.textContent = "";
|
||
if (kind === "error") m.textContent = text;
|
||
else { m.appendChild(el("strong", { text: text })); if (detail) m.appendChild(document.createTextNode(detail)); }
|
||
}
|
||
|
||
function render() {
|
||
renderControls();
|
||
renderHeader();
|
||
renderStatus();
|
||
var note = $("note");
|
||
note.hidden = !(staleError && data);
|
||
note.textContent = staleError && data ? "Couldn't refresh (" + staleError + ") — showing the last answer." : "";
|
||
if (!api) { showMsg("empty", "Open this page from the ai-agent."); return; }
|
||
if (!data) { if (loadError) showMsg("error", loadError); return; }
|
||
var content = $("content");
|
||
content.classList.toggle("busy", busy);
|
||
var accounts = data.accounts || [];
|
||
if (!accounts.length) { showMsg("empty", "No account with a usage limit in this scope.", "Pick another profile above."); return; }
|
||
$("msg").hidden = true; content.hidden = false;
|
||
var now = Date.now();
|
||
var y = window.scrollY;
|
||
content.textContent = "";
|
||
accounts.forEach(function (a) { content.appendChild(accountSection(a, accounts.length > 1, now)); });
|
||
content.appendChild(methodology());
|
||
window.scrollTo(0, y);
|
||
}
|
||
|
||
var EMPTY = { accounts: [], limits: {}, history: {}, plans: {}, calibration: {}, profiles: [] };
|
||
/** (Re)start the overview read for the picked scope and range. */
|
||
function load() {
|
||
var my = ++seq;
|
||
if (q) q.stop();
|
||
if (!api) { render(); return; }
|
||
busy = !!data; // keep the previous numbers, dimmed, until the new answer
|
||
if (busy) render();
|
||
q = read("overview", { scope: state.scope, days: state.days }, function (d, meta) {
|
||
if (my !== seq) return;
|
||
meta = meta || {};
|
||
busy = false;
|
||
if (d == null) {
|
||
// nothing to show for this scope / range: the error in place of the panels
|
||
data = null; loadError = meta.error || "No answer from the hub."; staleError = null;
|
||
} else {
|
||
data = Array.isArray(d.accounts) ? d : EMPTY;
|
||
if (Array.isArray(d.profiles) && d.profiles.length) profiles = d.profiles;
|
||
loadError = null; staleError = meta.error || null;
|
||
}
|
||
render();
|
||
});
|
||
}
|
||
|
||
function recalibrate() {
|
||
if (!api || state.recal.busy) return;
|
||
state.recal = { busy: true, result: null, error: null };
|
||
render();
|
||
api.action("calibrate", { backfill: !!$("backfill").checked }).then(function (r) {
|
||
state.recal = { busy: false, result: r || { calibrations: {}, shifted: [] }, error: null };
|
||
render();
|
||
if (q) q.refresh();
|
||
}).catch(function (e) {
|
||
state.recal = { busy: false, result: null, error: String((e && e.message) || e) };
|
||
render();
|
||
});
|
||
}
|
||
|
||
if (api && api.onHeaderAction) api.onHeaderAction(function (id) { if (id === "recal") recalibrate(); });
|
||
// readings move every few minutes: read again every 2 min while the page is seen
|
||
setInterval(function () { if (q && !document.hidden) q.refresh(); }, 120000);
|
||
// the countdowns and "read 3 min ago" tick every 30 s
|
||
setInterval(function () { if (data && !document.hidden) render(); }, 30000);
|
||
document.addEventListener("visibilitychange", function () { if (!document.hidden && q) q.refresh(); });
|
||
if (api && typeof api.onTheme === "function") api.onTheme(function () { if (data) render(); });
|
||
load();
|
||
})();
|
||
</script>
|
||
</body>
|
||
</html>
|