Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions web/src/features/quota/__fixtures__/devFixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
* `&providers=two` to record only Claude and Codex (no xAI/Antigravity pools),
* `&pool=owner` for the owner's hub (Claude Pro + Max 5x, Codex Plus + prolite,
* one Antigravity account with four group windows, one xAI weekly window),
* and `&weights=off` to simulate a hub without server-side plan weights
* `&pool=live` for a hub's real `quota-history` response saved (untracked) as
* `__fixtures__/live.local.json`, and `&weights=off` to simulate a hub without server-side plan weights
* (`/routing/plan-weights` 404, weights kept in the browser). Loaded through a dynamic import
* guarded by `import.meta.env.DEV`, so production bundles never contain it.
*
Expand Down Expand Up @@ -49,7 +50,24 @@ export function installQuotaHistoryFixture(): void {
const params = new URLSearchParams(window.location.search);
const historyOff = params.get('history') === 'off';
const weightsOff = params.get('weights') === 'off';
if (params.get('pool') === 'owner') {
const liveDump = Object.values(
import.meta.glob('./live.local.json', { eager: true, import: 'default' })
)[0] as { now: number; accounts: never[]; samples: never[] } | undefined;
if (params.get('pool') === 'live' && liveDump) {
fixture.payload.now = liveDump.now;
fixture.payload.accounts = liveDump.accounts;
fixture.payload.samples = liveDump.samples;
fixture.credentials.files = (liveDump.accounts as Array<Record<string, unknown>>).map(
(account) => ({
name: `${account.provider}-${account.auth_index}.json`,
type: account.provider,
provider: account.provider,
email: account.label,
auth_index: account.auth_index,
status: 'active',
})
) as never;
} else if (params.get('pool') === 'owner') {
const owner = buildOwnerPoolHistory(fixture.payload.now);
fixture.payload.accounts = owner.accounts;
fixture.payload.samples = owner.samples;
Expand Down
12 changes: 11 additions & 1 deletion web/src/features/quota/accountRows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import type { QuotaBudget, QuotaHistory, QuotaHistorySample } from '@/services/api';
import { claudePlanIncludesFable } from '@/utils/quota/claudePlans';
import {
HOUR_MS,
MINUTE_MS,
isLivePoolProvider,
nextResetAfter,
Expand Down Expand Up @@ -80,17 +81,26 @@ export const ROW_WINDOW_KEYS = {

const EPSILON = 1e-6;

/** Latest successful reading of one window key at or before `now`. */
/** Readings that keep arriving without a window this long mean the account lost it. */
const RETIRED_WINDOW_MS = 6 * HOUR_MS;

/**
* Latest successful reading of one window key at or before `now`; null when
* the account's later readings stopped listing the window (it was retired).
*/
export function readWindow(
samples: readonly QuotaHistorySample[],
key: string,
now: number
): WindowReading | null {
let latestReading = -Infinity;
for (let i = samples.length - 1; i >= 0; i -= 1) {
const sample = samples[i];
if (sample.t > now || sample.error) continue;
latestReading = Math.max(latestReading, sample.t);
const window = sample.windows[key];
if (!window || window.usedPercent == null) continue;
if (latestReading - sample.t > RETIRED_WINDOW_MS) return null;
const passed = window.resetsAt !== null && window.resetsAt <= now;
return {
remaining: passed ? 100 : Math.min(100, Math.max(0, 100 - window.usedPercent)),
Expand Down
15 changes: 13 additions & 2 deletions web/src/features/quota/components/PoolChart.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -74,16 +74,27 @@
stroke-width: 3px;
}

.nowRule,
.hoverRule {
stroke: var(--border-strong);
stroke-width: 1;
shape-rendering: crispEdges;
}

/* Now: a solid full-height rule with a chip on top, the strongest mark on the chart. */
.nowRule {
stroke: var(--foreground);
stroke-opacity: 0.75;
stroke-width: 1.5;
}

.nowChip {
fill: var(--foreground);
}

.nowLabel {
fill: var(--muted-foreground);
fill: var(--card);
font-size: var(--text-xs);
font-weight: 600;
}

.nowDot,
Expand Down
94 changes: 64 additions & 30 deletions web/src/features/quota/components/PoolChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,11 @@ export interface PoolChartProps {
const HEIGHT = 300;
const COMPACT_HEIGHT = 220;
const COMPACT_WIDTH = 560;
const MARGIN = { top: 28, right: 12, bottom: 26, left: 44 };
const MARGIN = { top: 34, right: 12, bottom: 26, left: 44 };
const DEFAULT_WIDTH = 960;
const LABEL_MIN_GAP_X = 40;
/** The Now chip sits this far above the plot. */
const NOW_CHIP_OFFSET = 18;

const linePath = (
points: readonly SeriesPoint[],
Expand Down Expand Up @@ -151,10 +153,15 @@ export function PoolChart({
return labels.filter((_, index) => index % step === 0);
}, [days, locale, spanEnd, spanStart, width]);

// Jump annotations over every line, greedily thinned so labels never overlap.
const nowVisible = now >= spanStart && now <= spanEnd;
const nowX = plotLeft + ((now - spanStart) / span) * (plotRight - plotLeft);

// Jump annotations over every line, greedily thinned so labels never overlap
// each other or the Now chip.
const jumpLabels = useMemo(() => {
if (compact) return [];
const out: { x: number; y: number; label: string; color: string }[] = [];
const nowChip = nowVisible ? { x: nowX, y: plotTop - NOW_CHIP_OFFSET } : null;
series
.flatMap((line) => line.view.jumps.map((jump) => ({ jump, color: line.color })))
.sort((a, b) => a.jump.t - b.jump.t)
Expand All @@ -163,19 +170,29 @@ export function PoolChart({
const jy =
plotBottom - (Math.min(Math.max(jump.value, 0), yMax) / yMax) * (plotBottom - plotTop);
const labelY = Math.max(plotTop - 6, jy - 9);
const clash = out.some(
(other) => Math.abs(other.x - jx) < LABEL_MIN_GAP_X && Math.abs(other.y - labelY) < 14
const clash = [...out, ...(nowChip ? [nowChip] : [])].some(
(other) => Math.abs(other.x - jx) < LABEL_MIN_GAP_X && Math.abs(other.y - labelY) < 16
);
if (clash || jx < plotLeft || jx > plotRight) return;
out.push({ x: jx, y: labelY, label: units.signed(jump.amount), color });
});
return out;
}, [compact, plotBottom, plotLeft, plotRight, plotTop, series, span, spanStart, units, yMax]);

const nowVisible = now >= spanStart && now <= spanEnd;
const nowX = x(now);

// "Empty" markers, stacked upward so two lines emptying close together stay legible.
}, [
compact,
nowVisible,
nowX,
plotBottom,
plotLeft,
plotRight,
plotTop,
series,
span,
spanStart,
units,
yMax,
]);

// "Empty" markers: a ring per line where its pool runs dry.
const empties = series
.map((line) => ({ line, at: line.view.poolEmptyAt }))
.filter((item): item is { line: PoolChartSeries; at: number } => item.at !== null);
Expand Down Expand Up @@ -343,8 +360,28 @@ export function PoolChart({

{nowVisible && (
<g>
<line className={styles.nowRule} x1={nowX} x2={nowX} y1={plotTop - 6} y2={plotBottom} />
<text className={styles.nowLabel} x={nowX} y={plotTop - 12} textAnchor="middle">
<line
className={styles.nowRule}
x1={nowX}
x2={nowX}
y1={plotTop - NOW_CHIP_OFFSET + 8}
y2={plotBottom}
/>
<rect
className={styles.nowChip}
x={nowX - 18}
y={plotTop - NOW_CHIP_OFFSET - 9}
width={36}
height={17}
rx={8.5}
/>
<text
className={styles.nowLabel}
x={nowX}
y={plotTop - NOW_CHIP_OFFSET}
textAnchor="middle"
dy="0.35em"
>
{t('quota_pool.now', { defaultValue: 'Now' })}
</text>
{series
Expand All @@ -362,25 +399,22 @@ export function PoolChart({
</g>
)}

{empties.map(({ line, at }, index) => (
{empties.map(({ line, at }) => (
<g key={line.key} style={seriesStyle(line.color)}>
<text
className={styles.emptyLabel}
x={Math.min(Math.max(x(at), plotLeft + 60), plotRight - 60)}
y={plotBottom - 14 - index * 18}
textAnchor="middle"
>
{single
? t('quota_pool.empty_at', {
defaultValue: 'Empty {{time}}',
time: formatWeekdayTime(at, locale),
})
: t('quota_pool.empty_at_series', {
defaultValue: '{{label}} empty {{time}}',
label: line.label,
time: formatWeekdayTime(at, locale),
})}
</text>
{/* Several lines: the table above names each empty time; captions would cover the lines. */}
{single && (
<text
className={styles.emptyLabel}
x={Math.min(Math.max(x(at), plotLeft + 60), plotRight - 60)}
y={plotBottom - 14}
textAnchor="middle"
>
{t('quota_pool.empty_at', {
defaultValue: 'Empty {{time}}',
time: formatWeekdayTime(at, locale),
})}
</text>
)}
<circle
className={
single ? styles.emptyRing : `${styles.emptyRing} ${styles.emptyRingSeries}`
Expand Down
7 changes: 7 additions & 0 deletions web/src/features/quota/components/QuotaPoolCard.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,13 @@
color: var(--muted-foreground);
}

.burnAverage {
display: block;
color: var(--muted-foreground);
font-size: var(--text-xs);
font-weight: 400;
}

.seriesHint {
display: block;
color: var(--muted-foreground);
Expand Down
28 changes: 24 additions & 4 deletions web/src/features/quota/components/QuotaPoolCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import {
type PoolView,
type PoolWindowChoice,
} from '../poolModel';
import { formatDuration, formatMonthDay, formatWeekdayTime, POOL_UNITS } from '../poolFormat';
import { formatDuration, formatMonthDay, formatResetInstant, POOL_UNITS } from '../poolFormat';
import { formatPlanName, formatWeight, planKey } from '../poolPrefs';
import { windowLabel } from '../poolWindowLabels';
import type { PlanWeightsMode } from '../hooks/usePlanWeights';
Expand Down Expand Up @@ -257,6 +257,21 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) {
notBy
);

// The projection leans on the 7-day average further out, so show it when it differs.
const burnValue = (view: PoolView): ReactNode => {
const recent = units.rate(view.burnRate);
const sustained = units.rate(view.burnEstimate.sustainedRate);
if (sustained === recent) return recent;
return (
<>
{recent}
<span className={styles.burnAverage}>
{t('quota_pool.burn_week_average', { rate: sustained })}
</span>
</>
);
};

// Labels follow the main window; every line uses the same burn window.
const limited = primary?.view.burnEstimate.confidence === 'limited';
const statsFor = (view: PoolView): StatItem[] => {
Expand All @@ -271,7 +286,9 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) {
: collecting
? t('quota_pool.collecting_data')
: view.poolEmptyAt !== null
? formatWeekdayTime(view.poolEmptyAt, locale)
? view.poolEmptyAt <= now
? t('quota_pool.pool_empty_now')
: formatResetInstant(view.poolEmptyAt, now, locale)
: notBy,
},
{
Expand All @@ -289,7 +306,10 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) {
key: 'next-reset',
label: t('quota_pool.stat_next_reset'),
value: view.nextReset
? `${units.signed(view.nextReset.amount)}, ${formatWeekdayTime(view.nextReset.at, locale)}`
? // A reset that restores nothing (an untouched window) shows just when it comes.
units.signed(view.nextReset.amount) === units.signed(0)
? formatResetInstant(view.nextReset.at, now, locale)
: `${units.signed(view.nextReset.amount)}, ${formatResetInstant(view.nextReset.at, now, locale)}`
: '—',
},
{
Expand All @@ -300,7 +320,7 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) {
value: !hasTracks
? '—'
: view.burnEstimate.ready
? units.rate(view.burnRate)
? burnValue(view)
: t('quota_pool.collecting_data'),
},
];
Expand Down
49 changes: 49 additions & 0 deletions web/src/features/quota/poolModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -506,8 +506,10 @@ export function buildAccountTracks(
const windowKey = selectWindowKey(samples, choice, provider);
if (!windowKey) return;
const points: TrackPoint[] = [];
let latestReading = -Infinity;
samples.forEach((sample) => {
if (sample.error) return;
latestReading = Math.max(latestReading, sample.t);
const window: QuotaHistoryWindow | undefined = sample.windows[windowKey];
if (!window || window.usedPercent == null) return;
points.push({
Expand All @@ -517,7 +519,12 @@ export function buildAccountTracks(
periodHours: window.periodHours,
});
});
if (provider === 'antigravity') dropTransientRefills(points);
if (points.length === 0) return;
// The account still reports but no longer lists this window (Antigravity
// drops a model group an account loses): it has left this pool, and its
// last reading must not be carried forward.
if (latestReading - points[points.length - 1].t > retireGraceMs(history)) return;
tracks.push({
authIndex: account.authIndex,
label: account.label || account.authIndex,
Expand All @@ -535,6 +542,48 @@ export function buildAccountTracks(
return tracks;
}

/** How long a window may go unreported before it counts as retired. */
const retireGraceMs = (history: QuotaHistory): number =>
Math.max(CURRENT_WINDOW_GRACE_MS, 3 * history.intervalSeconds * 1000);

/** A refill at least this large before the previous reading's reset is suspect. */
const SUSPECT_REFILL_POINTS = 20;
/** Readings returning to within this many points of the earlier level undo the refill. */
const REFILL_UNDONE_POINTS = 10;
const REFILL_SLACK_MS = 10 * MINUTE_MS;

/**
* Antigravity sometimes answers with every window untouched while an account
* is failing, then returns to the real figures; those readings would draw a
* spike. Remove a run of readings that refills before the previous reading's
* reset and is followed by a reading back near the earlier level. A refill
* that lasts (Antigravity does reset some windows early) is kept. In place.
*/
export function dropTransientRefills(points: TrackPoint[]): void {
const kept: TrackPoint[] = [];
let i = 0;
while (i < points.length) {
const previous = kept[kept.length - 1];
const suspect = (point: TrackPoint) =>
previous !== undefined &&
previous.resetsAt !== null &&
point.t < previous.resetsAt - REFILL_SLACK_MS &&
point.remaining - previous.remaining >= SUSPECT_REFILL_POINTS;
if (suspect(points[i])) {
let end = i;
while (end < points.length && suspect(points[end])) end += 1;
const after = points[end];
if (after && after.remaining <= previous!.remaining + REFILL_UNDONE_POINTS) {
i = end;
continue;
}
}
kept.push(points[i]);
i += 1;
}
points.splice(0, points.length, ...kept);
}

/** Capacity of one account in pool percent: 100 × its share of the heaviest plan. */
export const accountCapacity = (track: Pick<AccountTrack, 'share'>): number => 100 * track.share;

Expand Down
Loading