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

fix: age a quota meter against its own window's period, server-side (#7662)

[._.]/ Adam Eivye836051682ef
diff --git a/client/src/components/usage/UsageMeter.jsx b/client/src/components/usage/UsageMeter.jsx
index eff1c3de63..f7b7d3e1c9 100644
--- a/client/src/components/usage/UsageMeter.jsx
+++ b/client/src/components/usage/UsageMeter.jsx
@@ -41,20 +41,19 @@ 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;
-
+// Staleness itself is decided server-side, against the window's own period
+// (a fraction of it, not a flat constant) — see `lib/quotaWindows.js`. This
+// component only formats the verdict it's handed on `limit.stale`. A
+// federated card's meter can be another instance's stand-in reading
+// (`readBy` set); a purely local reading ages the same way, just without the
+// "on <machine>" attribution.
export function readingAttribution(limit) {
- if (!limit?.readBy) return null;
- // `?? ''` because an undated contribution carries `readAt: null`, and
+ if (!limit?.stale) return null;
+ // `?? ''` because an undated reading 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;
+ if (!limit.readBy) return dated ? `read ${timeAgo(readMs)}` : null;
const who = limit.readByName || 'another instance';
return dated ? `read ${timeAgo(readMs)} on ${who}` : `read on ${who}`;
}
diff --git a/client/src/components/usage/UsageMeter.test.jsx b/client/src/components/usage/UsageMeter.test.jsx
index ba6bf4b065..03991dbebd 100644
--- a/client/src/components/usage/UsageMeter.test.jsx
+++ b/client/src/components/usage/UsageMeter.test.jsx
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { render, screen } from '@testing-library/react';
-import UsageMeter, { meterTone, formatResetsAt } from './UsageMeter';
+import UsageMeter, { meterTone, formatResetsAt, readingAttribution } from './UsageMeter';
describe('meterTone', () => {
// The thresholds are the whole reason this meter was extracted rather than
@@ -32,6 +32,36 @@ describe('formatResetsAt', () => {
});
});
+describe('readingAttribution', () => {
+ // #7662: staleness is a server-computed flag now, not a client-side clock —
+ // these assert the component renders from `limit.stale`, never re-deriving
+ // an age threshold of its own.
+ it('renders nothing for a fresh reading, however old readAt looks', () => {
+ const ancientButFresh = { readAt: '2000-01-01T00:00:00.000Z', readBy: 'peer-1', readByName: 'Example Box', stale: false };
+ expect(readingAttribution(ancientButFresh)).toBeNull();
+ });
+
+ it('attributes a stale peer reading to the instance that took it', () => {
+ const limit = { readAt: '2026-09-03T11:00:00.000Z', readBy: 'peer-1', readByName: 'Example Box', stale: true };
+ expect(readingAttribution(limit)).toMatch(/^read .+ on Example Box$/);
+ });
+
+ it('captions a stale LOCAL reading too, with no "on <machine>" attribution', () => {
+ const limit = { readAt: '2026-09-03T11:00:00.000Z', readBy: null, stale: true };
+ expect(readingAttribution(limit)).toMatch(/^read .+$/);
+ expect(readingAttribution(limit)).not.toMatch(/ on /);
+ });
+
+ it('falls back to naming the instance without an age when readAt is unparseable', () => {
+ const limit = { readAt: null, readBy: 'peer-1', readByName: 'Example Box', stale: true };
+ expect(readingAttribution(limit)).toBe('read on Example Box');
+ });
+
+ it('renders nothing for an undated stale local reading', () => {
+ expect(readingAttribution({ readAt: null, readBy: null, stale: true })).toBeNull();
+ });
+});
+
describe('UsageMeter', () => {
it('shows the window, the remaining share and the used share', () => {
render(<UsageMeter limit={{ key: 'week', label: 'Weekly', percentUsed: 40, percentRemaining: 60 }} />);
diff --git a/client/src/pages/UsagePage.test.jsx b/client/src/pages/UsagePage.test.jsx
index 888c17579e..9f05e252c4 100644
--- a/client/src/pages/UsagePage.test.jsx
+++ b/client/src/pages/UsagePage.test.jsx
@@ -268,11 +268,15 @@ describe('UsagePage federated quota readings', () => {
it("attributes a meter standing on another machine's older reading", async () => {
const hoursAgo = (h) => new Date(Date.now() - h * 60 * 60 * 1000).toISOString();
+ // `stale` is now a server-computed verdict (period-relative, see
+ // server/lib/quotaWindows.js) — this fixture stands in for what the API
+ // would have stamped: the 50h-old weekly reading is well past its window's
+ // threshold, the moment-old session reading is not.
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 },
+ { key: 'week', label: 'Weekly', percentUsed: 12, percentRemaining: 88, readAt: hoursAgo(50), readBy: 'inst-peer', readByName: 'Example Box', stale: true },
+ { key: 'session', label: 'Session', percentUsed: 30, percentRemaining: 70, readAt: hoursAgo(0), readBy: null, readByName: null, stale: false },
],
}] });
render(<MemoryRouter><UsagePage /></MemoryRouter>);
diff --git a/server/lib/README.md b/server/lib/README.md
index 8f67e142d9..be71e9a642 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -90,7 +90,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `quotaBurnTaskRef.js` | The quota-burn STEP model: a discriminated scheduled-task reference (`builtin` task type + validated target app, or `custom` app-job id whose own scope is authoritative) plus the per-invocation `overrides` bag (provider/model/effort/params — unset inherits the task's saved settings, and nothing written here edits the schedule). `normalizeQuotaBurnTaskRef` / `normalizeQuotaBurnOverrides` / `normalizeQuotaBurnParams`, the `QUOTA_BURN_UNAVAILABLE` reason codes, `resolveQuotaBurnStepAvailability` (catalog passed IN, so this stays pure) / `applyQuotaBurnAvailability`, `quotaBurnStepIsDispatchable`, and `evaluateOnDemandEligibility` — the ONE on-demand gate ladder (`enabled` / instance feature / invocation eligibility / target scope / per-app switch / master Improve) shared with `taskSchedule.triggerOnDemandTask`, with `enabledAppIdsByTaskType` deriving its per-app input. |
| `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body, `run once` re-arm body). |
| `quotaReset.js` | `parseHumanReset` turns a provider CLI's human reset string into ISO 8601 (call it from the adapter); `normalizeResetAt`/`hoursUntilReset` compute time remaining without treating unknown values as imminent resets; `parseObservedReset` pulls the reset a provider stated in its own refusal text, and `isObservedBlockActive` is the shared "is that refusal still holding?" predicate every observed-refusal ledger uses. |
-| `quotaWindows.js` | Classifies a quota window by PERIOD (`windowPeriodHours`); `classifyWindows` splits one card's windows into the weekly allowance that expires unused and the 5-hour one that refuses first, in one pass. `windowLabelOf` names a window. Pure. |
+| `quotaWindows.js` | Classifies a quota window by PERIOD (`windowPeriodHours`); `classifyWindows` splits one card's windows into the weekly allowance that expires unused and the 5-hour one that refuses first, in one pass. `windowLabelOf` names a window. `staleThresholdMs` / `isLimitStale` judge a reading's age against 10% of ITS OWN window period (floored at 5min) — the period-relative "is this reading too old to trust" verdict every quota card stamps. Pure. |
| `cronFields.js` | Cron FIELD semantics (pure, browser-safe): `matchesCronField(value, expr, fieldMin)` — the matcher `services/eventScheduler.js` walks minute by minute with — plus `expandCronField(expr, min, max)` and `cronWeekdayHours(expr)` → `{days, hours}`, the weekday/hour OCCUPANCY view a scheduler planner needs. Sibling of `cronValidation.js` (syntax/range only); one matcher so a planner reading an hour as free and the walker firing in it cannot disagree. `cronWeekdayHours` over-approximates on purpose — a `dayOfMonth`/`month` restriction lands on an unpredictable weekday, so it reports the whole week. |
| `cronValidation.js` | Cron syntax + field-range validation (pure, import-free, browser-safe). `isValidCronExpression` / `findCronExpressionError` (a user-facing reason string) / `isValidCronField` / `isCronShaped` (5-token SHAPE only — the named-cadence detector, never a stand-in for validity), plus `CRON_FIELD_NAMES` / `CRON_FIELD_BOUNDS`. ONE implementation shared by `services/eventScheduler.js`, the CoS schedule + per-app task-type save routes, the app-override schema in `validation.js`, and the browser cron editor via `client/src/utils/cronHelpers.js` (#6634). Syntax validity is deliberately separate from whether an occurrence exists in the scheduler bounded search window — a leap-day cron is valid. |
| `recurrenceValidation.js` | Shared Zod shape and vocabulary for anchored calendar recurrences that cannot be represented faithfully by five-field cron. |
diff --git a/server/lib/fleetQuotas.js b/server/lib/fleetQuotas.js
index 88223294f7..db528d957a 100644
--- a/server/lib/fleetQuotas.js
+++ b/server/lib/fleetQuotas.js
@@ -26,6 +26,7 @@
import { compareNewerWins, parseTsMs } from './lwwTimestamp.js';
import { limitWindowExpired } from './quotaReset.js';
+import { isLimitStale } from './quotaWindows.js';
import { isNonBlankStr } from './textUtils.js';
// Structural bounds on ONE peer-supplied quota payload. Same reasoning as the
@@ -49,6 +50,7 @@ function sanitizeLimit(raw) {
const key = str(raw?.key, 120);
if (!key) return null;
const percentUsed = pct(raw?.percentUsed);
+ const periodHours = Number.isFinite(raw?.periodHours) && raw.periodHours > 0 ? raw.periodHours : null;
return {
key,
label: str(raw?.label, 200) || key,
@@ -56,6 +58,12 @@ function sanitizeLimit(raw) {
percentRemaining: percentUsed === null ? null : 100 - percentUsed,
resetsAt: str(raw?.resetsAt, 60),
timezone: str(raw?.timezone, 60),
+ // How long this window's allowance lasts, when the adapter states it
+ // exactly (`lib/quotaWindows.js`'s `windowPeriodHours`). Additive and
+ // back-compatible: an older peer simply omits it, and staleness falls back
+ // to the scope-word classifier. Carried through so a federated merge can
+ // age a peer's reading against its own window, not just a local one.
+ ...(periodHours !== null ? { periodHours } : {}),
};
}
@@ -124,6 +132,14 @@ export const latestFetchedAt = (cards) => (Array.isArray(cards) ? cards : []).re
* 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.
+ *
+ * `stale` is recomputed here rather than carried over from whichever
+ * contribution stamped it: the winning reading's `readAt` becomes the WINNING
+ * contribution's `fetchedAt`, which can differ from what the limit itself was
+ * last judged against (a peer's own stamp, taken at a different `now`) — so
+ * the verdict has to be re-derived against this merge's own `now` and the
+ * limit's own window period (`lib/quotaWindows.js`), the same rule a
+ * single-machine card applies.
*/
function unifyLimits(contributions, now) {
const best = new Map();
@@ -144,7 +160,10 @@ function unifyLimits(contributions, now) {
}
return order.map((key) => {
const { limit, fetchedAt, instanceId, name } = best.get(key);
- return { ...limit, readAt: fetchedAt ?? null, readBy: instanceId, readByName: name };
+ const readAt = fetchedAt ?? null;
+ const readAtMs = parseTsMs(readAt);
+ const ageMs = readAtMs === null ? null : now - readAtMs;
+ return { ...limit, readAt, readBy: instanceId, readByName: name, stale: isLimitStale(limit, ageMs) };
});
}
diff --git a/server/lib/fleetQuotas.test.js b/server/lib/fleetQuotas.test.js
index f5a887e37e..98364f425b 100644
--- a/server/lib/fleetQuotas.test.js
+++ b/server/lib/fleetQuotas.test.js
@@ -53,6 +53,22 @@ describe('sanitizeQuotaCards', () => {
it('ignores a non-array payload', () => {
expect(sanitizeQuotaCards({ family: 'claude' })).toEqual([]);
});
+
+ // #7662: periodHours has to survive the wire rebuild, or a federated merge
+ // can only classify a peer's window from its scope/label text.
+ it('carries a stated periodHours through, and omits it when absent', () => {
+ const [card] = sanitizeQuotaCards([{
+ family: 'codex', label: 'Codex', fetchedAt: '2026-09-03T10:00:00.000Z',
+ limits: [
+ { key: 'session', percentUsed: 10, periodHours: 7 },
+ { key: 'week', percentUsed: 10 },
+ { key: 'burst', percentUsed: 10, periodHours: 0 },
+ ],
+ }]);
+ expect(card.limits[0]).toMatchObject({ key: 'session', periodHours: 7 });
+ expect(Object.hasOwn(card.limits[1], 'periodHours')).toBe(false);
+ expect(Object.hasOwn(card.limits[2], 'periodHours')).toBe(false);
+ });
});
describe('latestFetchedAt', () => {
@@ -175,6 +191,30 @@ describe('mergeQuotaCard', () => {
expect(merged.plan).toBe('Max 20x');
});
+ // #7662: the merged limit's `stale` verdict is re-derived at merge time from
+ // the WINNING contribution's own readAt, not carried over from whichever
+ // side stamped it first — a peer's periodHours-aware reading must age the
+ // same way a local one does.
+ it('recomputes stale against the winning readAt and the limit\'s own period', () => {
+ const now = Date.parse('2026-09-03T12:00:00.000Z');
+ // Peer's session (5h window) reading is 55 minutes old at merge time —
+ // past the 30-minute threshold — while the local weekly reading is fresh.
+ const peer = peerEntry({
+ quotas: [{
+ family: 'claude', limits: [limit('session', 65, { periodHours: 5 })],
+ fetchedAt: '2026-09-03T11:05:00.000Z',
+ }],
+ });
+ const merged = mergeFleetQuotaCards(
+ [localCard({ limits: [limit('week', 20, { periodHours: 168 })], fetchedAt: '2026-09-03T11:59:00.000Z' })],
+ [peer],
+ { now },
+ )[0];
+ const bySession = Object.fromEntries(merged.limits.map((l) => [l.key, l]));
+ expect(bySession.session).toMatchObject({ stale: true, readBy: 'peer-1' });
+ expect(bySession.week).toMatchObject({ stale: false, readBy: null });
+ });
+
it('collapses the name list past three instances', () => {
const peers = ['a', 'b', 'c', 'd'].map((id) => peerEntry({ instanceId: id, name: id.toUpperCase() }));
expect(mergeFleetQuotaCards([localCard()], peers)[0].note)
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index 86e883c855..f5e0297513 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -746,7 +746,14 @@ describe('deferred imports stay deferred (#6156)', () => {
// resolver through `await import()` so it costs 2 instead of 27. Measured
// before 114,486, after 114,692; its whole share is 206. Restores the ~400 of
// headroom the recent entries carry — main had eroded to 164 again.
-const MAX_STATIC_INSTANTIATIONS = 115100;
+// 115,100 → 115,300 (#7662 quota staleness): `lib/fleetQuotas.js` and
+// `services/providerUsage.js` gain a new edge into `lib/quotaWindows.js`, a
+// dependency-free leaf (staleness now needs the same window-period classifier
+// the quota-burn gate already used) — so every closure that reaches either
+// module without already reaching `quotaWindows.js` through `quotaBurn.js`
+// pays one node for it. No subtree. Measured before 114,692, after 114,853;
+// restores the ~400 of headroom the recent entries carry.
+const MAX_STATIC_INSTANTIATIONS = 115300;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
diff --git a/server/lib/quotaWindows.js b/server/lib/quotaWindows.js
index c9013879af..5ecbf62edb 100644
--- a/server/lib/quotaWindows.js
+++ b/server/lib/quotaWindows.js
@@ -84,6 +84,38 @@ export function windowPeriodHours(limit) {
/** How a window is named wherever one is reported to a human or an agent. */
export const windowLabelOf = (limit) => limit?.label || limit?.scope || 'window';
+// Tolerable age is a FRACTION of the window's own period, not a flat constant:
+// a weekly meter read 70 minutes ago is fine, a 5-hour session meter read 55
+// minutes ago is ~18% out of date. 10% keeps a weekly meter quiet for most of a
+// day while catching a session meter inside one cache generation. Floored so a
+// fast-moving window (a 30-minute period, if one ever ships) is not
+// permanently captioned.
+const STALE_FRACTION = 0.1;
+const STALE_FLOOR_MS = 5 * 60 * 1000;
+
+/**
+ * How old a reading of a window with this period may be before it counts as
+ * stale, in milliseconds — or null when the period isn't known (an unreadable
+ * period cannot be asserted stale or fresh).
+ */
+export function staleThresholdMs(periodHours) {
+ if (!Number.isFinite(periodHours) || periodHours <= 0) return null;
+ return Math.max(STALE_FLOOR_MS, periodHours * 60 * 60 * 1000 * STALE_FRACTION);
+}
+
+/**
+ * Is this limit's reading stale, given how old it is? Takes `ageMs` rather
+ * than a timestamp + `now` so this module stays free of date parsing (see the
+ * module doc) — callers already hold a parsed age from `lib/lwwTimestamp.js`.
+ * An unknown period or an unparseable age can't be judged, so both read as
+ * "not stale" rather than guessed at.
+ */
+export function isLimitStale(limit, ageMs) {
+ const threshold = staleThresholdMs(windowPeriodHours(limit));
+ if (threshold === null || !Number.isFinite(ageMs)) return false;
+ return ageMs > threshold;
+}
+
/**
* Split one card's windows into the two roles a burn reasons about, in a single
* scoring pass:
diff --git a/server/lib/quotaWindows.test.js b/server/lib/quotaWindows.test.js
index 1e7dcda3a6..29d5701f20 100644
--- a/server/lib/quotaWindows.test.js
+++ b/server/lib/quotaWindows.test.js
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { classifyWindows, windowLabelOf, windowPeriodHours } from './quotaWindows.js';
+import { classifyWindows, isLimitStale, staleThresholdMs, windowLabelOf, windowPeriodHours } from './quotaWindows.js';
// The scope/label vocabulary the four in-tree adapters actually emit — the point
// of the classifier is that each of these resolves, so a real card is never
@@ -104,6 +104,40 @@ describe('classifyWindows', () => {
});
});
+describe('staleThresholdMs / isLimitStale', () => {
+ it('scales the threshold to 10% of the window, floored at 5 minutes', () => {
+ // 5h session: 10% is 30min, well above the floor.
+ expect(staleThresholdMs(5)).toBe(30 * 60 * 1000);
+ // Weekly: 10% of 168h is ~16.8h.
+ expect(staleThresholdMs(168)).toBe(16.8 * 60 * 60 * 1000);
+ // A hypothetical fast-moving window still floors at 5 minutes rather than
+ // going permanently stale.
+ expect(staleThresholdMs(0.5)).toBe(5 * 60 * 1000);
+ });
+
+ it('returns null for an unclassifiable period', () => {
+ expect(staleThresholdMs(null)).toBeNull();
+ expect(staleThresholdMs(0)).toBeNull();
+ expect(staleThresholdMs(-1)).toBeNull();
+ });
+
+ it('flags a 5-hour session meter read 55 minutes ago, but not a weekly one read 70 minutes ago', () => {
+ const session = { scope: 'session', label: 'Current session' };
+ const weekly = { scope: 'week', label: 'Weekly' };
+ expect(isLimitStale(session, 55 * 60 * 1000)).toBe(true);
+ expect(isLimitStale(weekly, 70 * 60 * 1000)).toBe(false);
+ });
+
+ it('never flags a window whose period is unknown, however old the reading', () => {
+ expect(isLimitStale({ scope: 'burst', label: 'Burst' }, 999 * 60 * 60 * 1000)).toBe(false);
+ });
+
+ it('never flags an unparseable age', () => {
+ expect(isLimitStale({ scope: 'session' }, null)).toBe(false);
+ expect(isLimitStale({ scope: 'session' }, NaN)).toBe(false);
+ });
+});
+
describe('windowLabelOf', () => {
it('names a window however the adapter labelled it, falling back to its scope', () => {
expect(windowLabelOf({ label: 'Weekly', scope: 'week' })).toBe('Weekly');
diff --git a/server/services/providerUsage.js b/server/services/providerUsage.js
index 874b45cf2c..82e2f2c59e 100644
--- a/server/services/providerUsage.js
+++ b/server/services/providerUsage.js
@@ -9,6 +9,7 @@ import { scrapeTuiUsage } from '../lib/tuiUsageScrape.js';
import { applyCredentialBootstrap, needsProcessGroup } from '../lib/credentialBootstrap.js';
import { createStaleWhileRevalidate, PENDING, WAIT } from '../lib/staleWhileRevalidate.js';
import { parseHumanReset, limitWindowExpired } from '../lib/quotaReset.js';
+import { isLimitStale } from '../lib/quotaWindows.js';
import { compareNewerWins, parseTsMs } from '../lib/lwwTimestamp.js';
import { createSingleFlight } from '../lib/singleFlight.js';
import { readFileTail } from '../lib/fileUtils.js';
@@ -367,6 +368,28 @@ const pruneExpiredWindows = (card, now) => {
};
};
+/**
+ * Stamp every limit with WHEN it was read and whether that reading has aged
+ * past its own window's staleness threshold (`lib/quotaWindows.js`).
+ *
+ * Applied to EVERY card here — not only the ones a federated merge later
+ * touches — so a purely local install (or a multi-instance one whose card
+ * never gets a second contributor) still ages a cached TUI/log-tail reading by
+ * the same rule a peer's reading is judged by. `mergeQuotaCard`'s
+ * `unifyLimits` recomputes both fields for a MERGED limit, since the winning
+ * reading can come from a peer whose own `fetchedAt` differs from this card's.
+ */
+const stampReadAt = (card, now) => {
+ if (!card?.limits?.length) return card;
+ const readAt = card.fetchedAt || null;
+ const readAtMs = parseTsMs(readAt);
+ const ageMs = readAtMs === null ? null : now - readAtMs;
+ return {
+ ...card,
+ limits: card.limits.map((limit) => ({ ...limit, readAt, stale: isLimitStale(limit, ageMs) })),
+ };
+};
+
/**
* Passive reads stay local; a fresh request queries the account without
* starting a turn.
@@ -900,7 +923,7 @@ async function readProviderQuotas({ wait, family }) {
// 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));
+ const prune = (cards) => cards.map((card) => stampReadAt(pruneExpiredWindows(card, now), now));
if (family && family !== IMAGE_GEN_FAMILY) return prune(familyCards);
const imageCard = await fetchImageGenQuota();
return prune(imageCard ? [...familyCards, imageCard] : familyCards);
diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.js
index a130a35033..223d9eb387 100644
--- a/server/services/providerUsage.test.js
+++ b/server/services/providerUsage.test.js
@@ -484,6 +484,31 @@ describe('getProviderQuotas', () => {
expect(card.error).toMatch(/has since reset/i);
});
+ // #7662. Staleness is judged against the window's OWN period, server-side,
+ // for every card — not just a federated merge's winners — so a purely local
+ // install ages its cached reading by the same rule a peer's would be.
+ it('stamps every limit with readAt and a period-relative stale verdict', async () => {
+ getAllProviders.mockResolvedValueOnce({
+ activeProvider: null,
+ providers: [{ id: 'claude', enabled: true, type: 'cli', command: 'claude' }]
+ });
+ // 55 minutes old: past 10% of a 5h session window (30min), well inside
+ // 10% of a weekly one (~16.8h).
+ const fetchedAt = new Date(Date.now() - 55 * 60 * 1000).toISOString();
+ getClaudeCodeUsage.mockResolvedValueOnce({
+ plan: 'subscription',
+ limits: [
+ { key: 'session', label: 'Current session', percentUsed: 40, percentRemaining: 60, resetsAt: '2099-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,
+ });
+ const [card] = await getProviderQuotas({ family: 'claude' });
+ const [session, week] = card.limits;
+ expect(session).toMatchObject({ key: 'session', readAt: fetchedAt, stale: true });
+ expect(week).toMatchObject({ key: 'week', readAt: fetchedAt, stale: false });
+ });
+
// #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