Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

stop a federated peer's stale quota reading from standing in as the current one

[._.]/ Adam Eivybe5e4362652f
diff --git a/client/src/components/models/SubscriptionsTab.jsx b/client/src/components/models/SubscriptionsTab.jsx
index 49482a4253..7eed33212a 100644
--- a/client/src/components/models/SubscriptionsTab.jsx
+++ b/client/src/components/models/SubscriptionsTab.jsx
@@ -13,6 +13,7 @@ import {
parseCostInput,
rowCells,
} from '../usage/SubscriptionSavingsCard';
+import { useQuotaPendingPoll } from '../../hooks/useQuotaPendingPoll';
import useUrlParams from '../../hooks/useUrlParams';
import { USAGE_PERIOD_OPTIONS, resolveUsagePeriod, DEFAULT_USAGE_PERIOD } from '../../lib/usagePeriods';
@@ -40,6 +41,7 @@ import { USAGE_PERIOD_OPTIONS, resolveUsagePeriod, DEFAULT_USAGE_PERIOD } from '
const NO_ROWS = [];
+
/**
* Parse a tier input to the patch value the API expects: a trimmed label, or
* `null` to CLEAR it. Empty means "I'm not recording a tier", which must be
@@ -221,6 +223,13 @@ export default function SubscriptionsTab() {
// Window-dependent read, re-run per period click — and only this one.
useEffect(() => { loadSavings(); }, [loadSavings]);
+ // A quota read never blocks the response: a family whose CLI scrape is still
+ // running answers `pending` and the reading lands behind it. Poll only while
+ // something is pending — without it this tab showed whatever stood in for the
+ // reading (a federated peer's older meters, or a spinner) until the user
+ // navigated away and back. The Usage page does the same.
+ useQuotaPendingPoll(loadQuotas, quotas);
+
const setPeriod = (id) => updateParams(
{ period: id === DEFAULT_USAGE_PERIOD ? null : id },
{ replace: true },
diff --git a/client/src/components/usage/ProviderQuotaBody.jsx b/client/src/components/usage/ProviderQuotaBody.jsx
index e0cc9d2193..0f4a76b6c8 100644
--- a/client/src/components/usage/ProviderQuotaBody.jsx
+++ b/client/src/components/usage/ProviderQuotaBody.jsx
@@ -33,6 +33,9 @@ export function StatTile({ label, value, detail }) {
export default function ProviderQuotaBody({ quota, showActivity = true, showNote = true }) {
if (!quota) return null;
+ // Whether this card has anything to put on screen — the pending branch and the
+ // empty state ask the same question from opposite sides, so they ask it once.
+ const hasReadings = Boolean(quota.limits?.length || quota.metrics?.length);
if (!quota.supported) {
return (
<p className="text-xs sm:text-sm text-gray-500">
@@ -41,11 +44,16 @@ export default function ProviderQuotaBody({ quota, showActivity = true, showNote
);
}
- // The reading is still being taken. It comes BEFORE the error and empty
- // branches because a pending card has no limits — rendering it through those
- // says "No rate-limit data reported", which is a verdict about the provider
- // rather than a statement about a scrape still in flight.
- if (quota.pending) {
+ // The reading is still being taken AND there is nothing to show meanwhile. It
+ // comes BEFORE the error and empty branches because a pending card has no
+ // limits — rendering it through those says "No rate-limit data reported",
+ // which is a verdict about the provider rather than a statement about a scrape
+ // still in flight.
+ //
+ // A pending card CAN carry meters: on a federated install a peer's reading
+ // fills it while this machine's scrape runs. Those are worth showing, so this
+ // branch yields to the meters below and the spinner moves down beside them.
+ if (quota.pending && !hasReadings) {
return (
<div className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-gray-400 py-1">
<BrailleSpinner />
@@ -71,6 +79,15 @@ export default function ProviderQuotaBody({ quota, showActivity = true, showNote
return (
<div className="space-y-1 sm:space-y-2">
+ {/* Meters from the fleet, with this machine's own reading still in
+ flight — say so, or the peer's numbers look like the final answer. */}
+ {quota.pending && (
+ <div className="flex items-center gap-1.5 sm:gap-2 text-[10px] sm:text-xs text-gray-400">
+ <BrailleSpinner />
+ <span>Reading this machine&apos;s usage…</span>
+ </div>
+ )}
+
{quota.limits?.length > 0 && (
<div>
{quota.limits.map((limit) => (
@@ -79,7 +96,7 @@ export default function ProviderQuotaBody({ quota, showActivity = true, showNote
</div>
)}
- {!quota.limits?.length && !quota.metrics?.length && (
+ {!hasReadings && (
<div className="text-xs sm:text-sm text-gray-500">No rate-limit data reported</div>
)}
diff --git a/client/src/components/usage/UsageMeter.jsx b/client/src/components/usage/UsageMeter.jsx
index e400e6ea97..eff1c3de63 100644
--- a/client/src/components/usage/UsageMeter.jsx
+++ b/client/src/components/usage/UsageMeter.jsx
@@ -1,6 +1,6 @@
import { Clock } from 'lucide-react';
import ProgressBar from '../ui/ProgressBar';
-import { timeUntil } from '../../utils/formatters';
+import { timeAgo, timeUntil } from '../../utils/formatters';
/**
* One quota window's meter — the shared rendering for a `limits[]` entry from
@@ -41,9 +41,28 @@ export function meterTone(percentUsed) {
return 'success';
}
+// How old a STAND-IN reading has to be before the meter says so. A federated
+// card takes the freshest reading per window across machines, so a meter can be
+// another instance's — fine when it was read moments ago, misleading once it is
+// hours behind, because the account it describes has been spent since. Local
+// readings (`readBy` null) are never captioned: their age is the card's own.
+const STALE_READING_MS = 60 * 60 * 1000;
+
+export function readingAttribution(limit) {
+ if (!limit?.readBy) return null;
+ // `?? ''` because an undated contribution carries `readAt: null`, and
+ // `new Date(null)` is the epoch — a date, and a very stale one.
+ const readMs = new Date(limit.readAt ?? '').getTime();
+ const dated = Number.isFinite(readMs);
+ if (dated && Date.now() - readMs < STALE_READING_MS) return null;
+ const who = limit.readByName || 'another instance';
+ return dated ? `read ${timeAgo(readMs)} on ${who}` : `read on ${who}`;
+}
+
export default function UsageMeter({ limit }) {
const used = limit.percentUsed ?? 0;
const remaining = limit.percentRemaining;
+ const attribution = readingAttribution(limit);
return (
<div className="py-1 sm:py-2 border-b border-port-border last:border-0">
<div className="flex items-baseline justify-between gap-2 mb-0.5 sm:mb-1">
@@ -59,6 +78,7 @@ export default function UsageMeter({ limit }) {
fully spent must not render as untouched. */}
<span className="text-[9px] sm:text-xs text-gray-500">
{limit.percentUsed == null ? '—' : `${used}% used`}
+ {attribution && <span className="text-gray-600"> · {attribution}</span>}
</span>
{limit.resetsAt && (
<span className="flex min-w-0 text-[9px] sm:text-xs text-gray-500 items-start sm:justify-end gap-1 sm:text-right leading-tight">
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index ad82e2f14b..3f0df6bf34 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -39,6 +39,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| Hook | Purpose | Use when |
|---|---|---|
+| `useQuotaPendingPoll` | `useQuotaPendingPoll(reload, cards)` — re-reads provider quota cards every 4s while any is `pending` (a scrape still in flight), paused on a hidden tab. | A surface renders `ProviderQuotaBody` cards from `GET /api/usage/providers` — without it the page keeps a spinner, or a federated peer's older meters, until a manual refresh. |
| `useSseProgress` | Generic JSON-frame EventSource subscriber. | New SSE progress stream — start here, build on top. |
| `useSseJobSlot` | Generic single-slot SSE job: captured target from preparation through completion, terminal-frame handling (`complete`/`error`/`canceled`), and `sse.closed`-without-terminal-frame recovery in one place. Returns `{ active, pending, jobId, percent, stage, context, start, cancel }`; reserves synchronously, exposes context during kickoff and ignores unmounted responses. Optional `readPercent` adapts other progress scales. Pass `startRequest`/`eventsUrl`/`cancelRequest` + per-feature toast copy. | Any "kick off a job → stream SSE → settle on terminal frame" hook. The reference-audio/YouTube/video-download/MIDI/music-video-render hooks all wrap this — don't re-roll the terminal-frame + lost-connection dance. |
| `useInstallStream` | BYO-runtime install-log stream lifecycle: `stage`/`log`/`complete`/`error` frame dispatch, capped + optionally-debounced log accumulation, "connection lost" handling, ref-stashed `onComplete`, auto-scroll. `method: 'GET'` uses EventSource; `method: 'POST'` reads one fetch stream for a non-idempotent install. | A streamed install/setup modal that shows live SSE log lines (FLUX.2, video runtimes, OpenCode). Don't re-roll the teardown/onComplete-ref dance. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 5da42249dd..792aeb7265 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -139,6 +139,7 @@ export * from './useProcessLogs.js';
export * from './useOpenClawStream.js';
export * from './usePipelineProgress.js';
export * from './usePortosRestartWatch.js';
+export * from './useQuotaPendingPoll.js';
export * from './useReaderPanel.js';
export * from './useSeriesEditorial.js';
export * from './useImageTo3dTargets.js';
diff --git a/client/src/hooks/useQuotaPendingPoll.js b/client/src/hooks/useQuotaPendingPoll.js
new file mode 100644
index 0000000000..78d1267592
--- /dev/null
+++ b/client/src/hooks/useQuotaPendingPoll.js
@@ -0,0 +1,34 @@
+import { useAutoRefetch } from './useAutoRefetch.js';
+
+// A scrape is a 10-20s PTY spawn, so this is a handful of polls, not a busy loop.
+export const PENDING_POLL_MS = 4000;
+
+/**
+ * Re-read provider quota cards while any of them is still being scraped.
+ *
+ * `GET /api/usage/providers` never blocks on a 10-20s PTY spawn: a cold cache
+ * answers with `pending: true` cards and the reading lands behind the response.
+ * Something therefore has to ask again, or the page keeps whatever stood in for
+ * the reading — a spinner, or a federated peer's older meters — until the user
+ * refreshes by hand.
+ *
+ * One hook rather than the same six lines on each surface: three pages render
+ * the same cards (Usage, Subscriptions, Quota Burn), and the cadence and the
+ * "which state keeps polling" rule are exactly the pair that must not drift
+ * between them — the card BODY was already extracted for that reason
+ * (`components/usage/ProviderQuotaBody.jsx`), and its lifecycle is the half
+ * that was left behind.
+ *
+ * Polling only while something is pending is the point: this is not a
+ * background refresh loop, and `useAutoRefetch` pauses on a hidden tab so a
+ * backgrounded copy can never re-request a multi-second scrape.
+ *
+ * @param {Function} reload - re-fetches the cards; called for its side effect.
+ * @param {Array<{pending?: boolean}>} cards - the cards currently rendered.
+ */
+export function useQuotaPendingPoll(reload, cards) {
+ const anyPending = Boolean(cards?.some((card) => card?.pending));
+ useAutoRefetch(reload, PENDING_POLL_MS, { enabled: anyPending, immediate: false, pollOnly: true });
+}
+
+export default useQuotaPendingPoll;
diff --git a/client/src/pages/QuotaBurn.jsx b/client/src/pages/QuotaBurn.jsx
index 279f0770cb..fd8a78a606 100644
--- a/client/src/pages/QuotaBurn.jsx
+++ b/client/src/pages/QuotaBurn.jsx
@@ -23,7 +23,7 @@ import PageSkeleton from '../components/ui/PageSkeleton';
import FamilyCard from '../components/quotaBurn/FamilyCard';
import { NumberField } from '../components/quotaBurn/fields';
import * as api from '../services/api';
-import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { useQuotaPendingPoll } from '../hooks/useQuotaPendingPoll';
import { mergeQuotaBurnPatch } from '../lib/quotaBurnPatch';
import { buildQuotaBurnTaskCatalog, flattenTaskCatalog } from '../lib/quotaBurnTasks';
import { safeReadJsonSession, safeRemoveSession, safeWriteJsonSession } from '../lib/safeStorage';
@@ -35,9 +35,6 @@ import { timeAgo } from '../utils/formatters';
// every universe bible — one full scan per character typed.
export const SAVE_DEBOUNCE_MS = 500;
-// How often to re-ask while a family's quota scrape is still running. A scrape
-// is a 10-20s PTY spawn, so this is a handful of polls, not a busy loop.
-export const PENDING_POLL_MS = 4000;
// What the burn's OWN catalog endpoint still supplies: the managed apps a step
// can target and the providers a per-invocation pin may name. The work itself is
@@ -256,13 +253,9 @@ export default function QuotaBurn() {
// A cold quota cache comes back as `pending` families rather than holding the
// response open for a 20s-per-family PTY scrape, so the page renders its plan
- // immediately and fills the numbers in when the scrape lands. Enabled ONLY
- // while something is actually pending — this is not a background refresh loop
- // — and `useAutoRefetch` (rather than a hand-rolled timer) so it pauses on a
- // hidden tab: re-requesting a multi-second scrape behind a backgrounded tab is
- // the one thing this poll must not do.
- const anyPending = (status?.families || []).some((row) => row.pending);
- useAutoRefetch(load, PENDING_POLL_MS, { enabled: anyPending, immediate: false, pollOnly: true });
+ // immediately and fills the numbers in when the scrape lands. The shared hook
+ // owns the cadence and the hidden-tab pause (hooks/useQuotaPendingPoll.js).
+ useQuotaPendingPoll(load, status?.families);
// There is no Save button: an edit lands in local state immediately and is
// persisted on a trailing edge. Successive edits fold into ONE patch body, so
diff --git a/client/src/pages/QuotaBurn.test.jsx b/client/src/pages/QuotaBurn.test.jsx
index 543e2ba5a7..3d0998a1a0 100644
--- a/client/src/pages/QuotaBurn.test.jsx
+++ b/client/src/pages/QuotaBurn.test.jsx
@@ -3,7 +3,8 @@ import { act, render, screen, waitFor } from '@testing-library/react';
import { findEnabledByLabelText, findEnabledByRole } from '../test/enabledBarrier.js';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes } from 'react-router';
-import QuotaBurn, { PENDING_POLL_MS, SAVE_DEBOUNCE_MS } from './QuotaBurn';
+import QuotaBurn, { SAVE_DEBOUNCE_MS } from './QuotaBurn';
+import { PENDING_POLL_MS } from '../hooks/useQuotaPendingPoll';
vi.mock('../services/api', () => ({
getQuotaBurn: vi.fn(),
diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsx
index dcac086274..bb16afefbc 100644
--- a/client/src/pages/UsagePage.jsx
+++ b/client/src/pages/UsagePage.jsx
@@ -7,7 +7,7 @@ import PageSkeleton from '../components/ui/PageSkeleton';
import Pill from '../components/ui/Pill';
import { formatCompactCountOrDash as formatNumber, formatCount, formatUsd, timeAgo } from '../utils/formatters';
import { useAsyncAction } from '../hooks/useAsyncAction';
-import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { useQuotaPendingPoll } from '../hooks/useQuotaPendingPoll';
import SubscriptionSavingsCard from '../components/usage/SubscriptionSavingsCard';
import FleetUsageCard from '../components/usage/FleetUsageCard';
import FreeTierUsageCard from '../components/usage/FreeTierUsageCard';
@@ -15,9 +15,6 @@ import ProviderQuotaBody from '../components/usage/ProviderQuotaBody';
import ModelsTabsHeader from '../components/models/ModelsTabsHeader';
import { USAGE_PERIOD_OPTIONS, DEFAULT_USAGE_PERIOD } from '../lib/usagePeriods';
-// How often to re-ask while a provider's quota reading is still being taken. A
-// CLI/TUI scrape is a 10-20s spawn, so this is a handful of polls, not a loop.
-const PENDING_POLL_MS = 4000;
// A subscription is one account across every federated instance, but each
// instance can only read its own CLI's panel. When peers have contributed a
@@ -151,12 +148,9 @@ function ProviderQuotaSection() {
});
}, []);
- // A quota read never blocks the response: a cold cache answers with `pending`
- // cards and the reading lands behind it. Without this poll those cards would
- // sit on "reading quota…" until the user hit Refresh by hand. Enabled only
- // while something is pending — the section does not otherwise auto-refresh.
- const anyPending = (quotas || []).some((quota) => quota.pending);
- useAutoRefetch(load, PENDING_POLL_MS, { enabled: anyPending, immediate: false, pollOnly: true });
+ // Cards still being scraped come back `pending`; the shared hook re-asks
+ // until the readings land. See hooks/useQuotaPendingPoll.js.
+ useQuotaPendingPoll(load, quotas);
return (
<div className="space-y-3">
diff --git a/client/src/pages/UsagePage.test.jsx b/client/src/pages/UsagePage.test.jsx
index 9324a06432..888c17579e 100644
--- a/client/src/pages/UsagePage.test.jsx
+++ b/client/src/pages/UsagePage.test.jsx
@@ -250,6 +250,39 @@ describe('UsagePage federated quota readings', () => {
await screen.findByText('Claude Code');
expect(screen.queryByText(/^\d+ instances$/)).not.toBeInTheDocument();
});
+
+ // A federated card can be filled by a peer while this machine's own scrape is
+ // still running. The meters are worth showing meanwhile, but the card must
+ // keep saying it is still reading — that flag is what keeps the page polling
+ // until the local reading lands, instead of settling on a stand-in.
+ it('shows a peer reading while this machine is still scraping, without hiding that it is still reading', async () => {
+ api.getProviderUsage.mockResolvedValue({ providers: [{ ...fleetCard, pending: true }] });
+ render(<MemoryRouter><UsagePage /></MemoryRouter>);
+
+ // Both, not either: the meters are the best number available right now, and
+ // the spinner is what says a better one is coming (and what the page's
+ // pending poll keys on, so the local reading actually swaps in).
+ expect(await screen.findByText('65% used')).toBeInTheDocument();
+ expect(screen.getByText("Reading this machine's usage…")).toBeInTheDocument();
+ });
+
+ it("attributes a meter standing on another machine's older reading", async () => {
+ const hoursAgo = (h) => new Date(Date.now() - h * 60 * 60 * 1000).toISOString();
+ api.getProviderUsage.mockResolvedValue({ providers: [{
+ ...fleetCard,
+ limits: [
+ { key: 'week', label: 'Weekly', percentUsed: 12, percentRemaining: 88, readAt: hoursAgo(50), readBy: 'inst-peer', readByName: 'Example Box' },
+ { key: 'session', label: 'Session', percentUsed: 30, percentRemaining: 70, readAt: hoursAgo(0), readBy: null, readByName: null },
+ ],
+ }] });
+ render(<MemoryRouter><UsagePage /></MemoryRouter>);
+
+ // The stand-in says whose reading it is and how old — a 12% weekly figure
+ // read two days ago must not read as this moment's.
+ expect(await screen.findByText(/read 2d ago on Example Box/)).toBeInTheDocument();
+ // This machine's own reading carries no such caption.
+ expect(screen.getByText('30% used')).toBeInTheDocument();
+ });
});
describe('UsagePage mobile provider-card layout', () => {
diff --git a/server/lib/fleetQuotas.js b/server/lib/fleetQuotas.js
index 2466bb7876..88223294f7 100644
--- a/server/lib/fleetQuotas.js
+++ b/server/lib/fleetQuotas.js
@@ -25,6 +25,7 @@
*/
import { compareNewerWins, parseTsMs } from './lwwTimestamp.js';
+import { limitWindowExpired } from './quotaReset.js';
import { isNonBlankStr } from './textUtils.js';
// Structural bounds on ONE peer-supplied quota payload. Same reasoning as the
@@ -96,6 +97,17 @@ export function sanitizeQuotaCards(raw) {
return out;
}
+/**
+ * Does this card carry numbers to act on?
+ *
+ * The one question every `pending` consumer actually asks. `pending` means
+ * "this machine's scrape is in flight" — which, since a federated peer's
+ * reading can fill the meters meanwhile, no longer implies "empty". Consumers
+ * that need a number (the burn gate) or that choose between a spinner and
+ * meters ask this instead of re-deriving it from the flag.
+ */
+export const cardHasReading = (card) => Boolean(card?.limits?.length || card?.metrics?.length);
+
/** The most recent `fetchedAt` in a set of cards, or null when none parses. */
export const latestFetchedAt = (cards) => (Array.isArray(cards) ? cards : []).reduce((latest, card) => {
const ms = parseTsMs(card?.fetchedAt);
@@ -107,12 +119,20 @@ export const latestFetchedAt = (cards) => (Array.isArray(cards) ? cards : []).re
* Freshest reading per limit key across contributors, keeping the local card's
* ordering first and appending keys only a peer reported (a window this
* machine's CLI has not surfaced yet is still real).
+ *
+ * Every surviving limit carries WHEN it was read (`readAt`) and BY WHICH
+ * instance, so a consumer can age a stand-in reading instead of presenting a
+ * peer's day-old meter as this moment's number. `readBy` is null for the local
+ * contribution, which is how the UI tells "this machine" from a stand-in.
*/
-function unifyLimits(contributions) {
+function unifyLimits(contributions, now) {
const best = new Map();
const order = [];
for (const c of contributions) {
for (const limit of c.limits || []) {
+ // A window whose reset has passed is not a reading of the current
+ // allowance — drop it rather than let it win its key on freshness.
+ if (limitWindowExpired(limit, { now })) continue;
const incumbent = best.get(limit.key);
if (!incumbent) order.push(limit.key);
// Unparseable-loses, tie → incumbent: the shared LWW polarity, so the
@@ -123,8 +143,8 @@ function unifyLimits(contributions) {
}
}
return order.map((key) => {
- const { limit, instanceId, name } = best.get(key);
- return { ...limit, readBy: instanceId, readByName: name };
+ const { limit, fetchedAt, instanceId, name } = best.get(key);
+ return { ...limit, readAt: fetchedAt ?? null, readBy: instanceId, readByName: name };
});
}
@@ -174,7 +194,7 @@ export function fleetNote(contributions, { hasActivity }) {
* caption included — a single-machine install has nothing to combine, and
* claiming otherwise would be worse than the wording this replaces.
*/
-export function mergeQuotaCard(local, peerCards = []) {
+export function mergeQuotaCard(local, peerCards = [], now = Date.now()) {
const localContribution = {
instanceId: local.instanceId || null,
name: local.name || null,
@@ -186,7 +206,7 @@ export function mergeQuotaCard(local, peerCards = []) {
const contributions = [localContribution, ...peerCards.filter((c) => (c.limits?.length || c.activity?.length))];
if (contributions.length < 2) return local;
- const limits = unifyLimits(contributions);
+ const limits = unifyLimits(contributions, now);
const activity = unifyActivity(contributions);
// Plan/tier is account-wide, same as the meters: take the freshest named
// reading so a card this machine could not label still shows SuperGrok/Pro
@@ -210,10 +230,19 @@ export function mergeQuotaCard(local, peerCards = []) {
limits,
activity,
fleet,
- // A local card that could not be read (a logged-out CLI, a scrape still in
- // flight) is no longer empty once a peer has read the SAME account — so it
- // stops reporting a failure it no longer has.
- pending: limits.length ? false : local.pending,
+ // A local card that could not be read (a logged-out CLI) is no longer empty
+ // once a peer has read the SAME account — so it stops reporting a failure it
+ // no longer has.
+ //
+ // `pending` is NOT cleared that way, because it does not mean "empty": it
+ // means THIS machine's reading is in flight and will land in a moment. The
+ // Usage page polls while any card is pending and stops when none is, so
+ // clearing it here ended the poll on the peer's stand-in numbers — a
+ // days-old "12% used" sat on screen as the current weekly figure until the
+ // user hit Refresh by hand, then came back at the next cold cache.
+ // A peer's reading fills the card meanwhile; the poll swaps in this
+ // machine's the moment it arrives.
+ pending: local.pending,
error: limits.length ? null : local.error,
note: fleetNote(contributions, { hasActivity: activity.length > 0 }),
};
@@ -226,7 +255,7 @@ export function mergeQuotaCard(local, peerCards = []) {
* provider we don't is that machine's business, and inventing a card here would
* put a meter on screen for a plan the viewer can't spend.
*/
-export function mergeFleetQuotaCards(localCards, peerEntries = []) {
+export function mergeFleetQuotaCards(localCards, peerEntries = [], { now = Date.now() } = {}) {
const cards = Array.isArray(localCards) ? localCards : [];
if (!cards.length || !peerEntries.length) return cards;
const byFamily = new Map();
@@ -237,5 +266,5 @@ export function mergeFleetQuotaCards(localCards, peerEntries = []) {
byFamily.set(card.family, list);
}
}
- return cards.map((card) => mergeQuotaCard(card, byFamily.get(card.family) || []));
+ return cards.map((card) => mergeQuotaCard(card, byFamily.get(card.family) || [], now));
}
diff --git a/server/lib/fleetQuotas.test.js b/server/lib/fleetQuotas.test.js
index a8cd906457..f5a887e37e 100644
--- a/server/lib/fleetQuotas.test.js
+++ b/server/lib/fleetQuotas.test.js
@@ -95,14 +95,54 @@ describe('mergeQuotaCard', () => {
});
it('fills a card this machine could not read from a peer that could', () => {
+ const merged = mergeFleetQuotaCards(
+ [localCard({ limits: [], activity: [], error: 'No quota data found.', note: 'Reading the Claude Code /usage panel…' })],
+ [peerEntry()],
+ )[0];
+ expect(merged.error).toBeNull();
+ expect(merged.limits).toEqual([expect.objectContaining({ key: 'session', percentUsed: 65 })]);
+ });
+
+ // Regression: a peer's stand-in reading used to clear the flag, ending the
+ // page's poll on a possibly days-old number.
+ it('stays pending while this machine is still reading, even once a peer has filled it', () => {
const merged = mergeFleetQuotaCards(
[localCard({ limits: [], activity: [], pending: true, error: null, note: 'Reading the Claude Code /usage panel…' })],
[peerEntry()],
)[0];
- expect(merged.pending).toBe(false);
+ expect(merged.pending).toBe(true);
expect(merged.limits).toEqual([expect.objectContaining({ key: 'session', percentUsed: 65 })]);
});
+ // A peer syncs on its own cadence, so its reading can describe a window that
+ // has since rolled over — a spent meter, not the current allowance.
+ it('drops a contributed window whose reset has already passed', () => {
+ const now = Date.parse('2026-09-10T00:00:00.000Z');
+ const merged = mergeFleetQuotaCards(
+ [localCard({ limits: [], activity: [], error: 'No quota data found.' })],
+ [peerEntry({ quotas: [{ ...peerEntry().quotas[0], limits: [
+ limit('session', 63, { resetsAt: '2026-09-04T06:10:00.000Z' }),
+ limit('week', 12, { resetsAt: '2026-09-14T21:00:00.000Z' }),
+ ] }] })],
+ { now },
+ )[0];
+ // The expired `session` row is gone; the open weekly window survives.
+ expect(merged.limits.map((l) => l.key)).toEqual(['week']);
+ // …and it says WHEN and WHERE it was read, so it can be aged on screen.
+ expect(merged.limits[0]).toMatchObject({ readAt: '2026-09-03T11:00:00.000Z', readBy: 'peer-1', readByName: 'Example Box' });
+ });
+
+ it('does not let an expired peer window beat this machine on the same key', () => {
+ const now = Date.parse('2026-09-10T00:00:00.000Z');
+ const merged = mergeFleetQuotaCards(
+ [localCard({ limits: [limit('week', 76, { resetsAt: '2026-09-14T21:00:00.000Z' })], fetchedAt: '2026-09-09T23:00:00.000Z' })],
+ // Newer stamp, but the window it describes closed days ago.
+ [peerEntry({ quotas: [{ ...peerEntry().quotas[0], limits: [limit('week', 12, { resetsAt: '2026-09-07T21:00:00.000Z' })], fetchedAt: '2026-09-09T23:30:00.000Z' }] })],
+ { now },
+ )[0];
+ expect(merged.limits).toEqual([expect.objectContaining({ key: 'week', percentUsed: 76, readBy: null })]);
+ });
+
it('leaves a still-unreadable card reporting its own failure', () => {
const merged = mergeFleetQuotaCards(
[localCard({ limits: [], activity: [], error: 'No quota data found.' })],
diff --git a/server/lib/quotaReset.js b/server/lib/quotaReset.js
index e3e67a424e..dbbe962905 100644
--- a/server/lib/quotaReset.js
+++ b/server/lib/quotaReset.js
@@ -150,6 +150,28 @@ export function normalizeResetAt(limit, { now = Date.now(), timeZone } = {}) {
return epochMs === null ? { epochMs: null, source: 'unknown' } : { epochMs, source: 'parsed' };
}
+/**
+ * Has this window already rolled over as of `now`?
+ *
+ * A limit states the reset its allowance runs to, so once that moment has
+ * passed the percentage describes a SPENT window, not the current one. A window
+ * whose reset can't be resolved has not been shown to have passed, so it counts
+ * as live.
+ *
+ * One definition because three surfaces ask it: the retained Codex card prunes
+ * meter-by-meter at serve time (`unexpiredLimits` in services/providerUsage.js),
+ * the federated merge drops a peer's rolled-over contribution
+ * (`lib/fleetQuotas.js`), and the Codex log parser skips a spent telemetry
+ * window (`codexWindowExpired`). It goes through `normalizeResetAt` rather than
+ * a bare `Date.parse` so an older peer's zone-less wall-clock reset — the case
+ * that function exists for — is judged, not ignored.
+ */
+export function limitWindowExpired(limit, opts = {}) {
+ const now = opts.now ?? Date.now();
+ const { epochMs } = normalizeResetAt(limit, { ...opts, now });
+ return epochMs !== null && epochMs <= now;
+}
+
/**
* Compute fractional hours remaining until quota window reset.
*
diff --git a/server/services/providerUsage.js b/server/services/providerUsage.js
index 12b809050b..874b45cf2c 100644
--- a/server/services/providerUsage.js
+++ b/server/services/providerUsage.js
@@ -8,7 +8,7 @@ import { PROVIDER_FAMILIES, familyForProvider } from '../lib/providerFamilies.js
import { scrapeTuiUsage } from '../lib/tuiUsageScrape.js';
import { applyCredentialBootstrap, needsProcessGroup } from '../lib/credentialBootstrap.js';
import { createStaleWhileRevalidate, PENDING, WAIT } from '../lib/staleWhileRevalidate.js';
-import { parseHumanReset, normalizeResetAt } from '../lib/quotaReset.js';
+import { parseHumanReset, limitWindowExpired } from '../lib/quotaReset.js';
import { compareNewerWins, parseTsMs } from '../lib/lwwTimestamp.js';
import { createSingleFlight } from '../lib/singleFlight.js';
import { readFileTail } from '../lib/fileUtils.js';
@@ -339,10 +339,33 @@ async function readLiveCodexQuota() {
* reset can't be resolved hasn't been shown to have passed, so it counts live.
*/
const unexpiredLimits = (card, now) =>
- (card?.limits || []).filter((limit) => {
- const { epochMs } = normalizeResetAt(limit, { now });
- return epochMs === null || epochMs > now;
- });
+ (card?.limits || []).filter((limit) => !limitWindowExpired(limit, { now }));
+
+/**
+ * Every card, with the windows that have already reset dropped.
+ *
+ * Applied to EVERY family rather than only the retained Codex card, because
+ * every adapter can serve a reading older than the window it describes: the
+ * claude cache serves stale for 60s, the TUI scrapes for 5 minutes, and the
+ * federated store keeps the last card until a newer one is read. A spent
+ * meter's percentage is a reading of an allowance that has since come back, so
+ * it must not reach the page, the burn gate, or a peer.
+ *
+ * A card emptied by the pruning says WHY. Otherwise it renders through the
+ * empty branch as "No rate-limit data reported", which is a verdict about the
+ * provider rather than a statement about a reading that simply aged out.
+ */
+const EXPIRED_ONLY_MESSAGE = 'Every window in this reading has since reset — refresh for a current one.';
+
+const pruneExpiredWindows = (card, now) => {
+ const limits = unexpiredLimits(card, now);
+ if (limits.length === (card?.limits?.length ?? 0)) return card;
+ return {
+ ...card,
+ limits,
+ ...(limits.length ? {} : { error: card.error || EXPIRED_ONLY_MESSAGE }),
+ };
+};
/**
* Passive reads stay local; a fresh request queries the account without
@@ -872,9 +895,15 @@ async function readProviderQuotas({ wait, family }) {
// scrape, and it reads as a footnote to the model-quota cards above it. Not
// raced with the family scrapes — this is two small local file reads against
// their multi-second TUI PTY spawns, so concurrency would buy no wall-clock.
- if (family && family !== IMAGE_GEN_FAMILY) return familyCards;
+ // One expiry pass over every card, here rather than inside an adapter or the
+ // fleet merge: "this window has already reset" is a property of any reading,
+ // and a rule applied only on the federated path would have a single-machine
+ // install rendering a spent meter its federated twin drops.
+ const now = Date.now();
+ const prune = (cards) => cards.map((card) => pruneExpiredWindows(card, now));
+ if (family && family !== IMAGE_GEN_FAMILY) return prune(familyCards);
const imageCard = await fetchImageGenQuota();
- return imageCard ? [...familyCards, imageCard] : familyCards;
+ return prune(imageCard ? [...familyCards, imageCard] : familyCards);
}
/**
diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.js
index 4cd4d31fa8..a130a35033 100644
--- a/server/services/providerUsage.test.js
+++ b/server/services/providerUsage.test.js
@@ -64,7 +64,7 @@ import {
} from './providerUsage.js';
import { getAllProviders } from './providers.js';
import { scrapeTuiUsage } from '../lib/tuiUsageScrape.js';
-import { systemTimeZone } from './claudeCodeUsage.js';
+import { getClaudeCodeUsage, systemTimeZone } from './claudeCodeUsage.js';
import { getSettings } from './settings.js';
import { getImageGenQuota } from './imageGenQuota.js';
@@ -442,6 +442,48 @@ describe('getProviderQuotas', () => {
expect(await getProviderQuotas({ family: 'grok' })).toEqual([]);
});
+ // A reading outlives the window it describes — every adapter serves from a
+ // cache (60s claude, 5min TUI) and the federated store keeps the last card
+ // until a newer one is read. A meter whose reset has passed is a percentage of
+ // an allowance that has since come back, so it must not reach the page, the
+ // burn gate, or a peer — on EVERY install, not only a federated one.
+ it('drops a window whose reset has already passed, and says why when that empties the card', async () => {
+ getAllProviders.mockResolvedValueOnce({
+ activeProvider: null,
+ providers: [{ id: 'claude', enabled: true, type: 'cli', command: 'claude' }]
+ });
+ // What the claude cache serves a minute after the session window turned
+ // over: a real reading, stamped honestly, of an allowance that is now back.
+ getClaudeCodeUsage.mockResolvedValueOnce({
+ plan: 'subscription',
+ limits: [
+ { key: 'session', label: 'Current session', percentUsed: 97, percentRemaining: 3, resetsAt: '2020-01-01T00:00:00.000Z' },
+ { key: 'week', label: 'Current week', percentUsed: 40, percentRemaining: 60, resetsAt: '2099-01-01T00:00:00.000Z' },
+ ],
+ activity: [], approximate: true, fetchedAt: '2020-01-01T00:00:00.000Z',
+ });
+ const [card] = await getProviderQuotas({ family: 'claude' });
+ // The spent session window is gone; the open weekly one stays.
+ expect(card.limits.map((l) => l.key)).toEqual(['week']);
+ expect(card.error).toBeUndefined();
+ });
+
+ it('says why a card is empty when expiry took its last window', async () => {
+ getAllProviders.mockResolvedValueOnce({
+ activeProvider: null,
+ providers: [{ id: 'claude', enabled: true, type: 'cli', command: 'claude' }]
+ });
+ getClaudeCodeUsage.mockResolvedValueOnce({
+ plan: 'subscription',
+ limits: [{ key: 'session', label: 'Current session', percentUsed: 97, percentRemaining: 3, resetsAt: '2020-01-01T00:00:00.000Z' }],
+ activity: [], approximate: true, fetchedAt: '2020-01-01T00:00:00.000Z',
+ });
+ const [card] = await getProviderQuotas({ family: 'claude' });
+ expect(card.limits).toEqual([]);
+ // Not "No rate-limit data reported" — that is a verdict about the provider.
+ expect(card.error).toMatch(/has since reset/i);
+ });
+
// #7496. The scrape kills its PTY on every exit path, and with a credential
// bootstrap the PTY's direct child is the WRAPPER — node-pty's kill() signals
// that pid alone, so the harness would go on rendering into a PTY nobody
diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.js
index 8e2cfa48ba..f684543b49 100644
--- a/server/services/quotaBurn.js
+++ b/server/services/quotaBurn.js
@@ -23,6 +23,7 @@ import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { familyHasRunnableJobs, familyIsConfigured, isUnlimitedDispatchCap, normalizeQuotaBurnFamily } from '../lib/quotaBurnConfig.js';
import { isPlainObject } from '../lib/objects.js';
import { hoursUntilReset, normalizeResetAt } from '../lib/quotaReset.js';
+import { cardHasReading } from '../lib/fleetQuotas.js';
import { classifyWindows, windowLabelOf } from '../lib/quotaWindows.js';
import { isBlockActive } from './quotaBurnDenials.js';
@@ -209,7 +210,13 @@ export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}
// empty allowance — it is "ask again in a moment". A candidate here would burn
// against a card with no numbers on it, so it fails closed like every other
// unknown, and holds even under force.
- if (card.pending) return { skipReason: 'reading provider quota…' };
+ //
+ // `pending` says THIS machine's scrape is in flight, not that the card is
+ // empty: on a federated install a peer's reading fills the meters meanwhile
+ // (`lib/fleetQuotas.js`). Those are real numbers for the same account, so gate
+ // on having none — otherwise every cold cache reported "reading provider
+ // quota…" for a family whose allowance was on screen one page over.
+ if (card.pending && !cardHasReading(card)) return { skipReason: 'reading provider quota…' };
// `error` covers both a failed read and a successful one with nothing to
// meter (see the card contract in providerUsage.js) — either way there are no
// numbers to burn against, so the reason quotes the card rather than
diff --git a/server/services/quotaBurn.test.js b/server/services/quotaBurn.test.js
index bce2317af4..d0a08d43bb 100644
--- a/server/services/quotaBurn.test.js
+++ b/server/services/quotaBurn.test.js
@@ -45,6 +45,15 @@ describe('selectBurnCandidates', () => {
expect(selectBurnCandidates([pending], config, { now: NOW, bypassGatesFor: 'grok' })).toEqual([]);
});
+ // `pending` means THIS machine's scrape is in flight, not that the card is
+ // empty: on a federated install a peer's reading for the same account fills
+ // the meters meanwhile (lib/fleetQuotas.js). Gating on the flag alone reported
+ // "reading provider quota…" for a family whose headroom was already known.
+ it('burns against a pending card that a peer has already filled', () => {
+ const filled = { ...quota('grok', '2026-07-26T18:00:00.000Z'), pending: true };
+ expect(selectBurnCandidates([filled], config, { now: NOW })).toHaveLength(1);
+ });
+
it('selects burnable windows by reset time then priority', () => {
const candidates = selectBurnCandidates([
quota('codex', '2026-07-27T00:00:00.000Z'),