Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(quota): keep reset windows and reset-less limits on the quota panel (#17880)

Arvin Xu240f0492ab0e
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index 7f64dfcbace..434b76fe8d6 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -662,6 +662,71 @@ in-page sampler above. Either way, disarm with
`Page.removeScriptToEvaluateOnNewDocument` and reload before capturing the settled
state, or the comparison shot is taken against a still-crippled runtime.
+### The desktop instance pins a previous run's server port, and its saved OAuth login expires
+
+**Situation:** starting an Electron dev instance for a surface that needs the local
+backend (any tRPC-backed panel), in a fresh worktree.
+
+**Doesn't work:** starting the dev server on the port `init-dev-env.sh` allocates
+for this worktree and assuming the app will follow. The desktop app is a thin
+client β€” `BackendProxyProtocolManager` proxies `app://renderer/trpc/*` to whatever
+`dataSyncConfig.remoteServerUrl` the seeded login snapshot carries, which is the
+port an _earlier_ run allocated. The mismatch surfaces as `app-probe.sh server-auth`
+returning **502** (proxy reached nothing), not as an auth error. And once the port
+matches, the snapshot's OAuth tokens are usually expired anyway β€” the app shows
+γ€Œη™»ε½•ε·²θΏ‡ζœŸγ€ and `server-auth` returns **401**, while `auth` still reports
+`isSignedIn: true` from renderer state alone.
+
+**Works:** read the app's own target first, then start the server on that port:
+
+```bash
+agent-browser --cdp 9222 eval '(() => JSON.stringify(window.__LOBE_STORES.electron().dataSyncConfig))()'
+# β†’ {"storageMode":"selfHost","remoteServerUrl":"http://localhost:3111","active":true}
+SERVER_PORT=3111 .agents/acceptance/scripts/init-dev-env.sh dev-next
+```
+
+For the expired login, do **not** drive the OAuth flow. The proxy forwards the
+Electron session's cookies alongside its `Oidc-Auth` header, and the server accepts
+a better-auth session cookie β€” so mint one for the seeded user and inject it over
+raw CDP:
+
+```bash
+curl -c cookie.jar -H 'Content-Type: application/json' -X POST \
+ "$SERVER_URL/api/auth/sign-in/email" \
+ --data '{"callbackURL":"/","email":"[email protected]","password":"TestPassword123!"}'
+# then Network.setCookie better-auth.session_token / better-auth.session_data
+# for url http://localhost:<port>, domain localhost, httpOnly, on the renderer target
+```
+
+Gate on `app-probe.sh server-auth` returning `{"authenticated":true,"status":200}` β€”
+renderer `isSignedIn` alone never proves the server accepted anything.
+
+### `agent.updateAgentConfig` silently drops `agencyConfig.heterogeneousProvider`
+
+**Situation:** turning a test agent into a CLI-agent shape (Claude Code / Codex) so
+the heterogeneous chat input and its quota badges render.
+
+**Doesn't work:** `updateAgentConfigById(id, { agencyConfig: { heterogeneousProvider:
+{ type: 'claude-code', command: 'claude' } } })`. The store's optimistic write makes
+it look applied β€” reading `agentMap[id].agencyConfig` back returns the provider β€” but
+the DB row keeps only the sibling keys (`executionTarget` persists, the provider does
+not), so the next full reload drops it and the plain chat input comes back. Reads as
+"the agent isn't hetero" with no error anywhere.
+
+**Works:** seed the shape directly (public API first is the rule; this is the
+documented exception where the write path does not carry the field):
+
+```bash
+docker exec lobehub-agent-testing-postgres psql -U postgres -d postgres -tAc \
+ "update agents set agency_config = '{\"executionTarget\":\"local\",\"heterogeneousProvider\":{\"type\":\"claude-code\",\"command\":\"claude\"}}'::jsonb where id='<agentId>';"
+```
+
+Then cold-load: a plain reload keeps serving the agent config from the tiered SWR
+cache, so the renderer still shows the pre-write value (generic M18). Clear
+`lobechat-swr-cache*` + `lobehub-local-data` through
+`Page.addScriptToEvaluateOnNewDocument` and reload (see "Cold SWR cache" above),
+then assert `agentMap[id].agencyConfig` before drawing any conclusion.
+
## Detailed references
- [Probe field notes](./references/probe-field-notes.md) β€” all historical
diff --git a/apps/server/src/routers/lambda/agentQuota.ts b/apps/server/src/routers/lambda/agentQuota.ts
index 6f653f59b59..ea7c0c3e928 100644
--- a/apps/server/src/routers/lambda/agentQuota.ts
+++ b/apps/server/src/routers/lambda/agentQuota.ts
@@ -171,6 +171,15 @@ export const agentQuotaRouter = router({
.input(z.object({ accountId: z.string(), limit: z.number().optional() }))
.query(async ({ ctx, input }) => ctx.windowModel.listByAccount(input.accountId, input.limit)),
+ /**
+ * Display read model: the newest reading per limit bucket. Prefer this over
+ * `getWindows` for anything user-facing β€” windows are keyed by `resets_at`,
+ * so limits the provider reports without one never make it into that table.
+ */
+ getLatestReadings: quotaProcedure
+ .input(z.object({ accountId: z.string() }))
+ .query(async ({ ctx, input }) => ctx.quotaService.listLatestReadings(input.accountId)),
+
// ── load balancing ───────────────────────────────────────────────────────
resolveAccountLoads: quotaProcedure
.input(z.object({ accountIds: z.array(z.string()) }))
diff --git a/apps/server/src/services/agentQuota/__tests__/index.test.ts b/apps/server/src/services/agentQuota/__tests__/index.test.ts
index a54ac872207..cf548210e5f 100644
--- a/apps/server/src/services/agentQuota/__tests__/index.test.ts
+++ b/apps/server/src/services/agentQuota/__tests__/index.test.ts
@@ -112,6 +112,67 @@ describe('AgentQuotaService.ingestSnapshot', () => {
});
});
+describe('AgentQuotaService.listLatestReadings', () => {
+ const now = Date.parse('2026-07-02T00:00:00Z');
+ const weeklyReading = {
+ capturedAt: now - 60_000,
+ limitType: 'weekly_all',
+ resetsAt: now + 3 * 24 * HOUR,
+ scopeKey: '',
+ utilization: 21,
+ };
+
+ it('carries a limit the provider reports without a reset time', async () => {
+ // An untouched model-scoped weekly arrives as `resets_at: null`. Windows are
+ // keyed by that instant, so it can only ever exist as a reading β€” reading
+ // the panel off windows is what made the Fable row invisible.
+ const account = await service.ingestSnapshot({
+ identity,
+ provider: 'claude-code',
+ readings: [
+ weeklyReading,
+ {
+ capturedAt: now - 60_000,
+ limitType: 'weekly_scoped',
+ resetsAt: null,
+ scopeKey: 'Fable',
+ utilization: 0,
+ },
+ ],
+ });
+
+ expect(await windows.listByAccount(account.id)).toHaveLength(1);
+ expect(await service.listLatestReadings(account.id)).toContainEqual(
+ expect.objectContaining({ limitType: 'weekly_scoped', resetsAt: null, scopeKey: 'Fable' }),
+ );
+ });
+
+ it('counts a rolled-over session window as free when balancing accounts', async () => {
+ // Left at 100% six hours ago: that window has since reset, so the account
+ // is idle β€” not benched behind an exhausted session.
+ const account = await service.ingestSnapshot({
+ identity,
+ provider: 'claude-code',
+ readings: [
+ weeklyReading,
+ {
+ capturedAt: now - 6 * HOUR,
+ limitType: 'session',
+ resetsAt: now - HOUR,
+ scopeKey: '',
+ utilization: 100,
+ },
+ ],
+ });
+
+ const [load] = await service.resolveAccountLoads([account.id], now);
+
+ expect(load.sessionUtil).toBe(0);
+ expect(load.rateLimitedUntil).toBeNull();
+ expect(load.weeklyUtil).toBe(21);
+ });
+});
+
describe('AgentQuotaService.recordUsage', () => {
it('attributes the turn to the account and computes cost from model-bank rates', async () => {
const account = await service.ingestSnapshot({
diff --git a/apps/server/src/services/agentQuota/index.ts b/apps/server/src/services/agentQuota/index.ts
index bacd91ca949..fabc3a6cff7 100644
--- a/apps/server/src/services/agentQuota/index.ts
+++ b/apps/server/src/services/agentQuota/index.ts
@@ -2,6 +2,10 @@ import {
type AccountLoad,
calibrateCapacity,
computeTurnCostUsd,
+ currentUtilization,
+ isScopedWeeklyLimit,
+ isSessionLimit,
+ isWeeklyAllLimit,
MIN_CALIBRATION_SAMPLES,
projectWindows,
type QuotaAccountIdentity,
@@ -244,28 +248,58 @@ export class AgentQuotaService {
}
};
+ /**
+ * The newest reading per limit bucket, as plain numbers. This is the display
+ * read model: unlike `agent_quota_windows` it also carries limits the
+ * provider reports without a `resets_at` (an untouched model-scoped weekly),
+ * which have no window to be projected into.
+ */
+ listLatestReadings = async (accountId: string): Promise<QuotaLimitReading[]> => {
+ const rows = await this.snapshots.latestPerBucket(accountId);
+
+ return rows.map((row) => ({
+ capturedAt: row.capturedAt.getTime(),
+ isActive: row.isActive ?? undefined,
+ limitType: row.limitType,
+ resetsAt: row.resetsAt?.getTime() ?? null,
+ scopeKey: row.scopeKey,
+ severity: row.severity ?? undefined,
+ utilization: row.utilization,
+ }));
+ };
+
/** Build the LB load view for a set of accounts from their latest readings. */
- resolveAccountLoads = async (accountIds: string[]): Promise<AccountLoadView[]> => {
+ resolveAccountLoads = async (
+ accountIds: string[],
+ now: number = Date.now(),
+ ): Promise<AccountLoadView[]> => {
const accounts = await this.accounts.list();
const byId = new Map(accounts.map((a) => [a.id, a]));
return Promise.all(
accountIds.map(async (accountId) => {
const account = byId.get(accountId);
- const buckets = await this.snapshots.latestPerBucket(accountId);
+ const buckets = await this.listLatestReadings(accountId);
const scopedWeeklyUtil: Record<string, number> = {};
let sessionUtil = 0;
let weeklyUtil = 0;
let rateLimitedUntil: number | null = null;
for (const b of buckets) {
- if (b.limitType === 'session') {
- sessionUtil = b.utilization;
- if (b.utilization >= 100 && b.resetsAt) rateLimitedUntil = b.resetsAt.getTime();
- } else if (b.limitType === 'weekly_scoped' && b.scopeKey) {
- scopedWeeklyUtil[b.scopeKey] = b.utilization;
- } else if (b.limitType.startsWith('weekly')) {
- weeklyUtil = Math.max(weeklyUtil, b.utilization);
+ // A reading whose window has rolled over describes spend that has
+ // since refilled; counting it would keep an account benched long
+ // after its quota came back.
+ const utilization = currentUtilization(b, now);
+
+ if (isSessionLimit(b)) {
+ sessionUtil = utilization;
+ // `utilization` is already 0 once the window rolled over, so a
+ // stale 100% cannot bench the account past its own reset.
+ if (utilization >= 100 && b.resetsAt) rateLimitedUntil = b.resetsAt;
+ } else if (isScopedWeeklyLimit(b)) {
+ scopedWeeklyUtil[b.scopeKey] = utilization;
+ } else if (isWeeklyAllLimit(b)) {
+ weeklyUtil = Math.max(weeklyUtil, utilization);
}
}
@@ -332,7 +366,10 @@ export class AgentQuotaService {
if (pool.length === 0) return null;
const now = options.now ?? Date.now();
- const loads = await this.resolveAccountLoads(pool.map((b) => b.accountId));
+ const loads = await this.resolveAccountLoads(
+ pool.map((b) => b.accountId),
+ now,
+ );
const priorityById = new Map(pool.map((b) => [b.accountId, b.priority]));
const withPriority = loads.map((l) => ({ ...l, priority: priorityById.get(l.accountId) ?? 0 }));
diff --git a/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts
index 59ba7b61e82..7a550aa2797 100644
--- a/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts
@@ -165,7 +165,9 @@ describe('fetchClaudeCodeQuota', () => {
status: 'ok',
weekly: {
resetsAt: Date.parse('2026-07-08T12:00:00Z'),
- usedPercent: 62.5,
+ // Rounded like the readings we persist, so the panel cannot show one
+ // number live and another after ingest.
+ usedPercent: 63,
windowMinutes: 10_080,
},
});
@@ -198,7 +200,7 @@ describe('fetchClaudeCodeQuota', () => {
// resets_at in unix seconds; used_percentage instead of utilization
vi.mocked(fetch).mockResolvedValue(
okUsageResponse({
- five_hour: { resets_at: 1_782_741_600, used_percentage: 140 },
+ five_hour: { resets_at: 1_783_002_600, used_percentage: 140 },
}),
);
@@ -207,7 +209,7 @@ describe('fetchClaudeCodeQuota', () => {
expect(result.status).toBe('ok');
// clamped to 100, seconds converted to ms
expect(result.session).toEqual({
- resetsAt: 1_782_741_600 * 1000,
+ resetsAt: 1_783_002_600 * 1000,
usedPercent: 100,
windowMinutes: 300,
});
@@ -364,6 +366,56 @@ describe('fetchClaudeCodeQuota', () => {
});
});
+ it('reports a window whose reset already passed as refilled, not as spent', async () => {
+ setPlatform('linux');
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ // Idle for over five hours: the usage API keeps echoing the last session
+ // window, whose reset is now in the past. That quota has refilled β€” showing
+ // its 96% would paint an exhausted meter over a free window.
+ vi.mocked(fetch).mockResolvedValue(
+ okUsageResponse({
+ five_hour: { resets_at: '2026-07-02T06:00:00Z', utilization: 96 },
+ seven_day: { resets_at: '2026-07-08T12:00:00Z', utilization: 13 },
+ }),
+ );
+
+ const result = await fetchClaudeCodeQuota();
+
+ expect(result.session).toEqual({ resetsAt: null, usedPercent: 0, windowMinutes: 300 });
+ expect(result.weekly).toMatchObject({ usedPercent: 13 });
+ });
+
+ it('keeps a scoped weekly the provider reports without a reset time', async () => {
+ setPlatform('linux');
+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
+ // An untouched model-scoped weekly reports `resets_at: null` β€” there is no
+ // window to project it into, but the plan does have the limit.
+ vi.mocked(fetch).mockResolvedValue(
+ okUsageResponse({
+ limits: [
+ {
+ is_active: false,
+ kind: 'weekly_scoped',
+ percent: 0,
+ resets_at: null,
+ scope: { model: { display_name: 'Fable', id: null }, surface: null },
+ severity: 'normal',
+ },
+ ],
+ }),
+ );
+
+ const result = await fetchClaudeCodeQuota();
+
+ expect(result.scopedWeekly).toEqual({
+ modelName: 'Fable',
+ window: { resetsAt: null, usedPercent: 0, windowMinutes: 10_080 },
+ });
+ expect(result.readings).toContainEqual(
+ expect.objectContaining({ limitType: 'weekly_scoped', resetsAt: null, scopeKey: 'Fable' }),
+ );
+ });
+
it('treats a 401 as an expired login', async () => {
setPlatform('linux');
vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));
diff --git a/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts
index 5a2055b5a09..69f6546b954 100644
--- a/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts
+++ b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts
@@ -4,12 +4,9 @@ import { homedir } from 'node:os';
import path from 'node:path';
import { parseClaudeAccountIdentity } from '../quota/identity';
-import type {
- ClaudeCodeQuotaSnapshot,
- ClaudeCodeQuotaUnavailableReason,
- ClaudeCodeScopedWeekly,
- HeteroQuotaWindow,
-} from '../quota/snapshot';
+import { buildClaudeQuotaWindows } from '../quota/readings';
+import type { ClaudeCodeQuotaSnapshot, ClaudeCodeQuotaUnavailableReason } from '../quota/snapshot';
+import type { ClaudeUsagePayload } from '../quota/usageApi';
import { mapClaudeUsageToReadings } from '../quota/usageApi';
/**
@@ -203,98 +200,6 @@ const readClaudeOAuthCredentials = async (
return fresh ? { credentials: fresh, state: 'ok' } : { state: 'expired' };
};
-interface OAuthUsageWindow {
- resets_at?: number | string;
- used_percentage?: number;
- utilization?: number;
-}
-
-interface OAuthUsageLimit {
- kind?: string;
- percent?: number;
- resets_at?: number | string;
- scope?: { model?: { display_name?: string } } | null;
-}
-
-interface OAuthUsageResponse {
- fable_seven_day?: OAuthUsageWindow;
- fable_weekly?: OAuthUsageWindow;
- five_hour?: OAuthUsageWindow;
- limits?: OAuthUsageLimit[];
- seven_day?: OAuthUsageWindow;
- seven_day_fable?: OAuthUsageWindow;
-}
-
-const parseResetsAt = (value: number | string | undefined): number | null => {
- if (typeof value === 'number' && Number.isFinite(value)) {
- return value < 10_000_000_000 ? value * 1000 : value;
- }
-
- if (typeof value !== 'string' || !value.trim()) return null;
-
- const numeric = Number(value);
- if (Number.isFinite(numeric)) {
- return numeric < 10_000_000_000 ? numeric * 1000 : numeric;
- }
-
- const parsed = Date.parse(value);
- return Number.isFinite(parsed) ? parsed : null;
-};
-
-const mapUsageWindow = (
- raw: OAuthUsageWindow | undefined,
- windowMinutes: number,
-): HeteroQuotaWindow | null => {
- const usedPercent =
- typeof raw?.utilization === 'number' && Number.isFinite(raw.utilization)
- ? raw.utilization
- : typeof raw?.used_percentage === 'number' && Number.isFinite(raw.used_percentage)
- ? raw.used_percentage
- : null;
-
- if (usedPercent === null) return null;
-
- return {
- resetsAt: parseResetsAt(raw?.resets_at),
- usedPercent: Math.min(100, Math.max(0, usedPercent)),
- windowMinutes,
- };
-};
-
-/**
- * Model-scoped weekly windows (e.g. the Fable weekly meter) are reported in
- * the `limits` array as `kind: 'weekly_scoped'` with the model display name in
- * `scope`, not as a top-level window field. Older deployments exposed a
- * `fable_*` top-level window instead, so keep those as a fallback.
- */
-const mapScopedWeekly = (payload: OAuthUsageResponse): ClaudeCodeScopedWeekly | null => {
- const scoped = payload.limits?.find(
- (limit) =>
- limit?.kind === 'weekly_scoped' &&
- typeof limit.percent === 'number' &&
- Number.isFinite(limit.percent) &&
- typeof limit.scope?.model?.display_name === 'string' &&
- limit.scope.model.display_name.length > 0,
- );
-
- if (scoped) {
- return {
- modelName: scoped.scope!.model!.display_name!,
- window: {
- resetsAt: parseResetsAt(scoped.resets_at),
- usedPercent: Math.min(100, Math.max(0, scoped.percent!)),
- windowMinutes: 10_080,
- },
- };
- }
-
- const fableWindow = mapUsageWindow(
- payload.fable_weekly ?? payload.fable_seven_day ?? payload.seven_day_fable,
- 10_080,
- );
- return fableWindow ? { modelName: 'Fable', window: fableWindow } : null;
-};
-
/**
* Read the account identity for DB persistence. `~/.claude.json` (or the
* explicit profile dir's copy) carries `oauthAccount`; the credential blob
@@ -372,19 +277,23 @@ export const fetchClaudeCodeQuota = async (
return errorSnapshot(`Anthropic usage API returned ${response.status}`);
}
- const payload = (await response.json()) as OAuthUsageResponse;
+ const payload = (await response.json()) as ClaudeUsagePayload;
const capturedAt = Date.now();
+ // The panel windows are projected from the same readings we persist, so a
+ // limit can never render live yet go missing from the account's history.
+ const readings = mapClaudeUsageToReadings(payload, capturedAt);
+ const windows = buildClaudeQuotaWindows(readings, capturedAt);
return {
error: null,
identity: await readAccountIdentity(options),
provider: 'claude-code',
- readings: mapClaudeUsageToReadings(payload, capturedAt),
- scopedWeekly: mapScopedWeekly(payload),
- session: mapUsageWindow(payload.five_hour, 300),
+ readings,
+ scopedWeekly: windows.scopedWeekly,
+ session: windows.session,
status: 'ok',
updatedAt: capturedAt,
- weekly: mapUsageWindow(payload.seven_day, 10_080),
+ weekly: windows.weekly,
};
} catch (error) {
if (controller.signal.aborted) {
diff --git a/packages/heterogeneous-agents/src/quota/index.ts b/packages/heterogeneous-agents/src/quota/index.ts
index 375efd6f58e..24a5209e91c 100644
--- a/packages/heterogeneous-agents/src/quota/index.ts
+++ b/packages/heterogeneous-agents/src/quota/index.ts
@@ -2,6 +2,7 @@ export * from './calibration';
export * from './cost';
export * from './identity';
export * from './loadBalancer';
+export * from './readings';
export * from './snapshot';
export * from './types';
export * from './usageApi';
diff --git a/packages/heterogeneous-agents/src/quota/quota.test.ts b/packages/heterogeneous-agents/src/quota/quota.test.ts
index 1adf27c659e..79d1a7c5097 100644
--- a/packages/heterogeneous-agents/src/quota/quota.test.ts
+++ b/packages/heterogeneous-agents/src/quota/quota.test.ts
@@ -13,6 +13,7 @@ import {
parseCodexAccountIdentity,
} from './identity';
import { selectAccount } from './loadBalancer';
+import { buildClaudeQuotaWindows } from './readings';
import type { QuotaLimitReading } from './types';
import { CLAUDE_SESSION_WINDOW_SECONDS, windowSecondsForKind } from './types';
import { mapClaudeUsageToReadings, parseResetsAt } from './usageApi';
@@ -370,6 +371,112 @@ describe('mapClaudeUsageToReadings', () => {
});
});
+// ── readings β†’ display windows ────────────────────────────────────────────────
+describe('buildClaudeQuotaWindows', () => {
+ const now = Date.parse('2026-07-12T18:00:00Z');
+ const reading = (over: Partial<QuotaLimitReading> = {}): QuotaLimitReading => ({
+ capturedAt: now - 60_000,
+ limitType: 'session',
+ resetsAt: Date.parse('2026-07-12T20:50:00Z'),
+ scopeKey: '',
+ utilization: 26,
+ ...over,
+ });
+
+ it('maps session / weekly / scoped readings to their panel windows', () => {
+ const windows = buildClaudeQuotaWindows(
+ [
+ reading(),
+ reading({
+ limitType: 'weekly_all',
+ resetsAt: Date.parse('2026-07-18T14:00:00Z'),
+ utilization: 29,
+ }),
+ reading({
+ limitType: 'weekly_scoped',
+ resetsAt: Date.parse('2026-07-18T14:00:00Z'),
+ scopeKey: 'Fable',
+ utilization: 38,
+ }),
+ ],
+ now,
+ );
+
+ expect(windows.session).toEqual({
+ resetsAt: Date.parse('2026-07-12T20:50:00Z'),
+ usedPercent: 26,
+ windowMinutes: 300,
+ });
+ expect(windows.weekly).toMatchObject({ usedPercent: 29, windowMinutes: 10_080 });
+ expect(windows.scopedWeekly).toEqual({
+ modelName: 'Fable',
+ window: {
+ resetsAt: Date.parse('2026-07-18T14:00:00Z'),
+ usedPercent: 38,
+ windowMinutes: 10_080,
+ },
+ });
+ });
+
+ it('reports a rolled-over window as refilled instead of dropping the row', () => {
+ // The 5-hour window is the one that goes idle: after five quiet hours the
+ // provider still reports the last session's utilization against a reset
+ // that has passed. Hiding the row reads as "this plan has no session
+ // limit"; replaying 96% paints an exhausted meter over a free window.
+ const windows = buildClaudeQuotaWindows(
+ [reading({ resetsAt: now - 60_000, utilization: 96 })],
+ now,
+ );
+
+ expect(windows.session).toEqual({ resetsAt: null, usedPercent: 0, windowMinutes: 300 });
+ });
+
+ it('keeps a limit reported without a reset time until one full window passes', () => {
+ // An untouched model-scoped weekly arrives as `resets_at: null`; it can
+ // only speak for the window it was captured in.
+ const noReset = reading({ limitType: 'weekly_scoped', resetsAt: null, scopeKey: 'Fable' });
+
+ expect(buildClaudeQuotaWindows([noReset], now).scopedWeekly).toEqual({
+ modelName: 'Fable',
+ window: { resetsAt: null, usedPercent: 26, windowMinutes: 10_080 },
+ });
+ expect(
+ buildClaudeQuotaWindows([noReset], now + 8 * 24 * 60 * 60 * 1000).scopedWeekly,
+ ).toMatchObject({ window: { usedPercent: 0 } });
+ });
+
+ it('keeps the newest reading per bucket and tolerates renamed kinds', () => {
+ const windows = buildClaudeQuotaWindows(
+ [
+ reading({ capturedAt: now - 600_000, limitType: 'five_hour', utilization: 10 }),
+ reading({ capturedAt: now - 1000, utilization: 42 }),
+ reading({ limitType: 'weekly', resetsAt: now + 60_000, utilization: 7 }),
+ ],
+ now,
+ );
+
+ expect(windows.session).toMatchObject({ usedPercent: 42 });
+ // `weekly` (unscoped) still counts as the account-wide weekly window.
+ expect(windows.weekly).toMatchObject({ usedPercent: 7 });
+ });
+
+ it('clamps and rounds utilization the same way the persisted readings do', () => {
+ const windows = buildClaudeQuotaWindows([reading({ utilization: 140 })], now);
+ expect(windows.session?.usedPercent).toBe(100);
+ expect(
+ buildClaudeQuotaWindows([reading({ utilization: 62.5 })], now).session?.usedPercent,
+ ).toBe(63);
+ });
+
+ it('has no window for a limit the account never reported', () => {
+ expect(buildClaudeQuotaWindows([], now)).toEqual({
+ scopedWeekly: null,
+ session: null,
+ weekly: null,
+ });
+ });
+});
+
// ── load balancer ─────────────────────────────────────────────────────────────
describe('selectAccount', () => {
const base = { enabled: true, priority: 0 };
diff --git a/packages/heterogeneous-agents/src/quota/readings.ts b/packages/heterogeneous-agents/src/quota/readings.ts
new file mode 100644
index 00000000000..85c58894ca2
--- /dev/null
+++ b/packages/heterogeneous-agents/src/quota/readings.ts
@@ -0,0 +1,108 @@
+import type { ClaudeCodeScopedWeekly, HeteroQuotaWindow } from './snapshot';
+import type { QuotaLimitReading } from './types';
+import { windowSecondsForKind } from './types';
+
+/**
+ * The subset of a limit reading the display path needs. A live sample and a
+ * persisted `agent_quota_snapshots` row both satisfy it, so the panel can run
+ * the two through exactly the same rules instead of one set for each.
+ */
+export type QuotaDisplayReading = Pick<
+ QuotaLimitReading,
+ 'capturedAt' | 'limitType' | 'resetsAt' | 'scopeKey' | 'utilization'
+>;
+
+const clampPercent = (value: number) => Math.min(100, Math.max(0, Math.round(value)));
+
+/**
+ * Whether the window a reading describes has already rolled over β€” i.e. the
+ * quota it measured has since refilled.
+ *
+ * `resets_at` is the provider's own window boundary, so a boundary in the past
+ * settles it. Some limits arrive without one (an untouched model-scoped weekly
+ * reports `resets_at: null`), and those can only speak for the window they were
+ * captured in β€” so a reading older than one full window counts as rolled over
+ * too.
+ */
+export const hasWindowRolledOver = (reading: QuotaDisplayReading, now: number): boolean =>
+ reading.resetsAt == null
+ ? now - reading.capturedAt > windowSecondsForKind(reading.limitType) * 1000
+ : reading.resetsAt <= now;
+
+/**
+ * Utilization of the window that is live *now*: a rolled-over window refilled,
+ * so it reads 0 rather than replaying the spent window's last value.
+ */
+export const currentUtilization = (reading: QuotaDisplayReading, now: number): number =>
+ hasWindowRolledOver(reading, now) ? 0 : clampPercent(reading.utilization);
+
+/**
+ * A reading as a display window. A rolled-over window is reported as refilled
+ * (0% used, no countdown) rather than dropped: hiding the row reads as "this
+ * plan has no such limit", while replaying its last utilization paints an
+ * exhausted meter over a quota that is actually free.
+ */
+export const toQuotaWindow = (reading: QuotaDisplayReading, now: number): HeteroQuotaWindow => {
+ const rolledOver = hasWindowRolledOver(reading, now);
+
+ return {
+ resetsAt: rolledOver ? null : (reading.resetsAt ?? null),
+ usedPercent: rolledOver ? 0 : clampPercent(reading.utilization),
+ windowMinutes: windowSecondsForKind(reading.limitType) / 60,
+ };
+};
+
+/** The 5-hour window; `five_hour` is the pre-`limits[]` spelling. */
+export const isSessionLimit = (reading: QuotaDisplayReading): boolean =>
+ reading.limitType === 'session' || reading.limitType === 'five_hour';
+
+/**
+ * The account-wide weekly window. Anthropic has renamed this kind before
+ * (`seven_day` β†’ `weekly_all`), so key off "weekly and unscoped" rather than
+ * one literal.
+ */
+export const isWeeklyAllLimit = (reading: QuotaDisplayReading): boolean =>
+ reading.limitType.startsWith('weekly') && !reading.scopeKey;
+
+/** A weekly window scoped to one model, e.g. Fable. */
+export const isScopedWeeklyLimit = (reading: QuotaDisplayReading): boolean =>
+ reading.limitType.startsWith('weekly') && !!reading.scopeKey;
+
+const newestMatch = <T extends QuotaDisplayReading>(
+ readings: T[],
+ match: (reading: T) => boolean,
+): T | undefined =>
+ readings.reduce<T | undefined>(
+ (newest, reading) =>
+ match(reading) && (!newest || reading.capturedAt > newest.capturedAt) ? reading : newest,
+ undefined,
+ );
+
+export interface ClaudeQuotaWindows {
+ scopedWeekly: ClaudeCodeScopedWeekly | null;
+ session: HeteroQuotaWindow | null;
+ weekly: HeteroQuotaWindow | null;
+}
+
+/**
+ * Project limit readings onto the three windows the Claude panel renders. The
+ * single source of that mapping: the live sampler and the persisted read model
+ * both go through here, so a limit can never be visible on one path and
+ * missing on the other.
+ */
+export const buildClaudeQuotaWindows = (
+ readings: QuotaDisplayReading[],
+ now: number,
+): ClaudeQuotaWindows => {
+ const session = newestMatch(readings, isSessionLimit);
+ const weekly = newestMatch(readings, isWeeklyAllLimit);
+ const scoped = newestMatch(readings, isScopedWeeklyLimit);
+
+ return {
+ scopedWeekly: scoped
+ ? { modelName: scoped.scopeKey, window: toQuotaWindow(scoped, now) }
+ : null,
+ session: session ? toQuotaWindow(session, now) : null,
+ weekly: weekly ? toQuotaWindow(weekly, now) : null,
+ };
+};
diff --git a/packages/heterogeneous-agents/src/quota/usageApi.ts b/packages/heterogeneous-agents/src/quota/usageApi.ts
index abf71c4291f..be4e6b1e43d 100644
--- a/packages/heterogeneous-agents/src/quota/usageApi.ts
+++ b/packages/heterogeneous-agents/src/quota/usageApi.ts
@@ -22,9 +22,13 @@ export interface ClaudeUsageWindow {
}
export interface ClaudeUsagePayload {
+ /** Pre-`limits[]` spellings of the model-scoped weekly window. */
+ fable_seven_day?: ClaudeUsageWindow | null;
+ fable_weekly?: ClaudeUsageWindow | null;
five_hour?: ClaudeUsageWindow | null;
limits?: ClaudeUsageLimit[];
seven_day?: ClaudeUsageWindow | null;
+ seven_day_fable?: ClaudeUsageWindow | null;
}
/** < 1e12 β†’ epoch seconds; otherwise already epoch ms. */
@@ -95,5 +99,18 @@ export const mapClaudeUsageToReadings = (
utilization: utilOf(payload.seven_day),
});
}
+
+ // The model-scoped weekly had a top-level codename before `limits[]` existed.
+ const fable = payload.fable_weekly ?? payload.fable_seven_day ?? payload.seven_day_fable;
+ if (fable) {
+ readings.push({
+ capturedAt,
+ limitType: 'weekly_scoped',
+ resetsAt: parseResetsAt(fable.resets_at),
+ scopeKey: 'Fable',
+ utilization: utilOf(fable),
+ });
+ }
+
return readings;
};
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx
index f056f70ee82..8000fd27ba2 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/ClaudeCodeQuotaMenu.tsx
@@ -12,10 +12,10 @@ import QuotaAccountSwitcher from './QuotaAccountSwitcher';
import type { FetchQuotaOptions, QuotaWindowItem } from './QuotaMenu';
import QuotaMenu, { createQuotaSourceKey } from './QuotaMenu';
import {
- buildClaudeSnapshotFromWindows,
+ buildClaudePanelSnapshot,
hasRenderableWindow,
isQuotaStale,
- newestSeenAt,
+ newestCapturedAt,
} from './quotaViewModel';
/**
@@ -96,7 +96,9 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =
let account = deviceId
? claude.find((a) => a.externalAccountId === trustedExternalAccountId)
: (claude.find((a) => a.id === pinnedId) ?? claude[0]);
- let windows = account ? await agentQuotaService.getWindows(account.id).catch(() => []) : [];
+ let readings = account
+ ? await agentQuotaService.getLatestReadings(account.id).catch(() => [])
+ : [];
// 2) Throttled live refresh + ingest. Paint the persisted windows before
// awaiting the live fetch so the panel never blocks on it.
@@ -107,8 +109,8 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =
(deviceId && !trustedExternalAccountId) ||
isQuotaStale(account?.updatedAt, Date.now(), QUOTA_REFRESH_MS)
) {
- if (account && windows.length > 0) {
- const interim = buildClaudeSnapshotFromWindows(account, windows);
+ if (account && readings.length > 0) {
+ const interim = buildClaudePanelSnapshot(account, readings, null);
if (hasRenderableWindow(interim)) options?.onInterim?.(interim);
}
live = await fetchClaudeCodeQuotaSnapshot({ deviceId, env, force }).catch(() => null);
@@ -121,15 +123,15 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =
// readings we already persisted echoed back (same capturedAt).
// Snapshots are append-only, so re-ingesting an echo would duplicate
// history rows and rerun calibration without new evidence β€” skip it.
- const newestCapturedAt = live.readings.reduce((max, r) => Math.max(max, r.capturedAt), 0);
+ const liveCapturedAt = live.readings.reduce((max, r) => Math.max(max, r.capturedAt), 0);
const matchingAccount = claude.find(
(candidate) => candidate.externalAccountId === externalAccountId,
);
- const matchingWindows = matchingAccount
- ? await agentQuotaService.getWindows(matchingAccount.id).catch(() => [])
+ const matchingReadings = matchingAccount
+ ? await agentQuotaService.getLatestReadings(matchingAccount.id).catch(() => [])
: [];
const isCachedEcho =
- !!matchingAccount && newestCapturedAt <= newestSeenAt(matchingWindows);
+ !!matchingAccount && liveCapturedAt <= newestCapturedAt(matchingReadings);
if (!isCachedEcho) {
await agentQuotaService
@@ -141,28 +143,24 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =
claude.find((a) => a.externalAccountId === externalAccountId) ??
claude.find((a) => a.id === pinnedId) ??
claude[0];
- windows = account
- ? await agentQuotaService.getWindows(account.id).catch(() => windows)
- : windows;
+ readings = account
+ ? await agentQuotaService.getLatestReadings(account.id).catch(() => readings)
+ : readings;
} else {
account = matchingAccount;
- windows = matchingWindows;
+ readings = matchingReadings;
}
}
}
- // 3) Persisted view wins β€” it survives a failed live fetch. Otherwise fall
- // back to the live snapshot: identity may be unresolvable (no
- // oauthAccount.accountUuid in ~/.claude.json, while the quota itself comes
- // from the keychain), every reading may lack a usable reset and project to
- // zero windows, or every persisted window may have already reset (a device
- // offline since yesterday). Note the last case is invisible in the row
- // count β€” ask the built snapshot, not `windows.length`, or a live sample
- // that failed to persist loses to an empty panel.
- const persisted =
- account && windows.length > 0 ? buildClaudeSnapshotFromWindows(account, windows) : null;
- if (persisted && hasRenderableWindow(persisted)) return persisted;
- return live ?? persisted ?? unavailableSnapshot();
+ // 3) The persisted view survives a failed live fetch, and an attributable
+ // live sample fills what it has no reading for (an ingest that failed, a
+ // limit this account has no history for) β€” merged per limit, newest
+ // reading wins. With no account resolved at all there is nothing to
+ // attribute the sample to, so the live snapshot stands on its own.
+ const merged = account ? buildClaudePanelSnapshot(account, readings, live) : null;
+ if (merged && hasRenderableWindow(merged)) return merged;
+ return live ?? merged ?? unavailableSnapshot();
},
[deviceId, env, agentId],
);
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaAccountManagerModal.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaAccountManagerModal.tsx
index 6a1c7402184..88f1bf76c42 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaAccountManagerModal.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaAccountManagerModal.tsx
@@ -1,5 +1,6 @@
'use client';
+import { currentUtilization, isWeeklyAllLimit } from '@lobechat/heterogeneous-agents/quota';
import { ActionIcon, DropdownMenu, Flexbox, Icon, Input, Text } from '@lobehub/ui';
import { Button, createModal, type ModalInstance, Switch } from '@lobehub/ui/base-ui';
import { Radio } from 'antd';
@@ -56,17 +57,20 @@ const styles = createStaticStyles(({ css }) => ({
type Account = Awaited<ReturnType<typeof agentQuotaService.listAccounts>>[number];
type Binding = Awaited<ReturnType<typeof agentQuotaService.listBindings>>[number];
-type QuotaWindow = Awaited<ReturnType<typeof agentQuotaService.getWindows>>[number];
+type QuotaReading = Awaited<ReturnType<typeof agentQuotaService.getLatestReadings>>[number];
const AUTO = 'auto';
const clampPercent = (n: number) => Math.min(100, Math.max(0, Math.round(n)));
-const weeklyLeftOf = (windows: QuotaWindow[]): number | undefined => {
- const wk = windows.find((w) => w.limitType === 'weekly_all');
- if (!wk) return undefined;
- const used = wk.lastUtilization ?? wk.peakUtilization;
- return used == null ? undefined : clampPercent(100 - used);
+/**
+ * Weekly headroom for the account row. A reading whose window already rolled
+ * over describes spend that has since refilled, so it counts as free rather
+ * than as the last utilization it happened to record.
+ */
+const weeklyLeftOf = (readings: QuotaReading[], now = Date.now()): number | undefined => {
+ const weekly = readings.find((r) => isWeeklyAllLimit(r));
+ return weekly ? clampPercent(100 - currentUtilization(weekly, now)) : undefined;
};
const accountName = (a: Account) => a.label || a.email || a.externalAccountId;
@@ -93,8 +97,10 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
const entries = await Promise.all(
accs.map(async (a) => {
- const w = await agentQuotaService.getWindows(a.id).catch(() => [] as QuotaWindow[]);
- return [a.id, weeklyLeftOf(w)] as const;
+ const readings = await agentQuotaService
+ .getLatestReadings(a.id)
+ .catch(() => [] as QuotaReading[]);
+ return [a.id, weeklyLeftOf(readings)] as const;
}),
);
setWeeklyById(Object.fromEntries(entries));
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx
index d427b9c08a2..3037282f2fe 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx
@@ -99,7 +99,7 @@ vi.mock('@/libs/trpc/client', () => ({
// path without each one stalling on a real HTTP request; individual tests can
// hand it persisted accounts/windows.
const mockQuotaService = vi.hoisted(() => ({
- getWindows: vi.fn(async (): Promise<unknown[]> => []),
+ getLatestReadings: vi.fn(async (): Promise<unknown[]> => []),
ingestClaudeSnapshot: vi.fn(async () => undefined),
listAccounts: vi.fn(async (): Promise<unknown[]> => []),
listBindings: vi.fn(async (): Promise<unknown[]> => []),
@@ -205,15 +205,13 @@ const persistedAccount = (updatedAt = Date.now()) => ({
updatedAt: new Date(updatedAt),
});
-/** A persisted `agent_quota_windows` row whose newest reading is `lastSeenAt`. */
-const persistedSessionWindow = (lastSeenAt: number) => ({
- lastSeenAt: new Date(lastSeenAt),
- lastUtilization: 8,
+/** The account's newest persisted session reading, captured at `capturedAt`. */
+const persistedSessionReading = (capturedAt: number) => ({
+ capturedAt,
limitType: 'session',
- peakUtilization: 8,
resetsAt: null,
scopeKey: '',
- windowSeconds: 300 * 60,
+ utilization: 8,
});
/** A live session reading as fossilized by the desktop sampler at `capturedAt`. */
@@ -252,7 +250,7 @@ beforeEach(() => {
mockService.getCodexQuota.mockReset();
toastErrorMock.mockReset();
toastSuccessMock.mockReset();
- mockQuotaService.getWindows.mockResolvedValue([]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([]);
mockQuotaService.ingestClaudeSnapshot.mockClear();
mockQuotaService.listAccounts.mockResolvedValue([]);
mockQuotaService.listBindings.mockResolvedValue([]);
@@ -439,7 +437,7 @@ describe('ClaudeCodeQuotaMenu', () => {
mockQuotaService.listAccounts.mockResolvedValue([
{ externalAccountId: 'ext-1', id: 'acc-1', provider: 'claude-code' },
]);
- mockQuotaService.getWindows.mockResolvedValue([]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([]);
mockService.getClaudeCodeQuota.mockResolvedValue(
claudeSnapshot({ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 } }),
);
@@ -588,34 +586,90 @@ describe('ClaudeCodeQuotaMenu', () => {
expect(await screen.findByText('heteroAgent.quota.noData')).toBeTruthy();
});
- it('shows the live sample when every persisted window has already reset', async () => {
- // A device offline since yesterday leaves rows behind whose windows have
- // reset. The row count still looks like "we have data", so a live sample
- // that could not be persisted (identity without an external account id here)
- // must not lose to that empty persisted view.
+ it('shows the live sample when the persisted window has already reset', async () => {
+ // A device offline since yesterday leaves a reading behind whose window has
+ // since reset. Its 100% describes spend that already refilled, so a sample
+ // attributable to the same account must lead.
mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60 * 60_000)]);
- mockQuotaService.getWindows.mockResolvedValue([
+ mockQuotaService.getLatestReadings.mockResolvedValue([
{
- ...persistedSessionWindow(Date.now() - 24 * 60 * 60_000),
- lastUtilization: 100,
- peakUtilization: 100,
- resetsAt: new Date(Date.now() - 60 * 60_000),
+ ...persistedSessionReading(Date.now() - 24 * 60 * 60_000),
+ resetsAt: Date.now() - 60 * 60_000,
+ utilization: 100,
},
]);
mockService.getClaudeCodeQuota.mockResolvedValue(
- claudeSnapshot({ session: { resetsAt: null, usedPercent: 4, windowMinutes: 300 } }),
+ claudeSnapshot({
+ identity: { externalAccountId: 'ext-1' },
+ readings: [{ ...liveSessionReading(Date.now()), utilization: 4 }],
+ session: { resetsAt: null, usedPercent: 4, windowMinutes: 300 },
+ }),
);
render(<ClaudeCodeQuotaMenu />);
- // 96% left from the live sample β€” not the expired row's 0%, and not empty.
+ // 96% left from the live sample β€” not the reset row's 100%, and not empty.
expect(await screen.findByText('96%')).toBeTruthy();
expect(screen.queryByText('heteroAgent.quota.noData')).toBeNull();
});
+ it('will not paint an unattributable sample under a named account', async () => {
+ // Same setup, except the sample carries no account identity (no
+ // `oauthAccount` in ~/.claude.json while the quota came from the keychain).
+ // With several logins on the machine it may belong to another account, so
+ // the panel keeps the account's own refilled window instead.
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60 * 60_000)]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([
+ {
+ ...persistedSessionReading(Date.now() - 24 * 60 * 60_000),
+ resetsAt: Date.now() - 60 * 60_000,
+ utilization: 100,
+ },
+ ]);
+ mockService.getClaudeCodeQuota.mockResolvedValue(
+ claudeSnapshot({ session: { resetsAt: null, usedPercent: 4, windowMinutes: 300 } }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ // The reset window reads as refilled; the unattributable 96% is not shown.
+ expect(await screen.findByText('100%')).toBeTruthy();
+ expect(screen.queryByText('96%')).toBeNull();
+ });
+
+ it('keeps the 5-hour row on screen as refilled once its window resets', async () => {
+ // The regression: after five idle hours the session window rolls over and
+ // the panel used to drop the row entirely, leaving the weekly limit alone
+ // as if the plan had no session limit. A reset window is free, not absent.
+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60_000)]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([
+ {
+ ...persistedSessionReading(Date.now() - 60_000),
+ resetsAt: Date.now() - 30 * 60_000,
+ utilization: 83,
+ },
+ {
+ capturedAt: Date.now() - 60_000,
+ limitType: 'weekly_all',
+ resetsAt: Date.now() + 4 * 24 * 60 * 60_000,
+ scopeKey: '',
+ utilization: 21,
+ },
+ ]);
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ // Session refilled to 100% left, weekly still at 79% β€” two rows, not one.
+ expect(await screen.findByText('100%')).toBeTruthy();
+ expect(screen.getByText('79%')).toBeTruthy();
+ expect(mockService.getClaudeCodeQuota).not.toHaveBeenCalled();
+ });
+
it('renders persisted windows without a live call while the newest reading is fresh', async () => {
mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 60_000)]);
- mockQuotaService.getWindows.mockResolvedValue([persistedSessionWindow(Date.now() - 60_000)]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([
+ persistedSessionReading(Date.now() - 60_000),
+ ]);
render(<ClaudeCodeQuotaMenu />);
@@ -627,8 +681,8 @@ describe('ClaudeCodeQuotaMenu', () => {
// Under the previous 30 min policy this 31-minute-old reading is a
// conservative stale case; the gate now trips at 2 minutes.
mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 31 * 60_000)]);
- mockQuotaService.getWindows.mockResolvedValue([
- persistedSessionWindow(Date.now() - 31 * 60_000),
+ mockQuotaService.getLatestReadings.mockResolvedValue([
+ persistedSessionReading(Date.now() - 31 * 60_000),
]);
mockService.getClaudeCodeQuota.mockResolvedValue(claudeSnapshot());
@@ -642,8 +696,8 @@ describe('ClaudeCodeQuotaMenu', () => {
it('paints persisted windows while a stale live refresh is still in flight', async () => {
mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 31 * 60_000)]);
- mockQuotaService.getWindows.mockResolvedValue([
- persistedSessionWindow(Date.now() - 31 * 60_000),
+ mockQuotaService.getLatestReadings.mockResolvedValue([
+ persistedSessionReading(Date.now() - 31 * 60_000),
]);
const requests: Array<(snapshot: ElectronClientIpcModule.ClaudeCodeQuotaSnapshot) => void> = [];
mockService.getClaudeCodeQuota.mockImplementation(
@@ -671,7 +725,9 @@ describe('ClaudeCodeQuotaMenu', () => {
it('revalidates against the live API when the window regains focus', async () => {
// 90 s: fresh for the mount gate (2 min) but past the focus gate (60 s).
mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 90_000)]);
- mockQuotaService.getWindows.mockResolvedValue([persistedSessionWindow(Date.now() - 90_000)]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([
+ persistedSessionReading(Date.now() - 90_000),
+ ]);
mockService.getClaudeCodeQuota.mockResolvedValue(claudeSnapshot());
render(<ClaudeCodeQuotaMenu />);
@@ -710,7 +766,7 @@ describe('ClaudeCodeQuotaMenu', () => {
const capturedAt = Date.now();
const account = persistedAccount();
mockQuotaService.listAccounts.mockResolvedValue([account]);
- mockQuotaService.getWindows.mockResolvedValue([persistedSessionWindow(capturedAt)]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([persistedSessionReading(capturedAt)]);
mockLambdaDeviceQuota.mockResolvedValueOnce(
claudeSnapshot({
identity: { externalAccountId: 'ext-1' },
@@ -742,7 +798,9 @@ describe('ClaudeCodeQuotaMenu', () => {
});
mockQuotaService.listAccounts.mockResolvedValue([persistedAccount()]);
- mockQuotaService.getWindows.mockResolvedValue([persistedSessionWindow(Date.now() - 60_000)]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([
+ persistedSessionReading(Date.now() - 60_000),
+ ]);
mockService.getClaudeCodeQuota.mockResolvedValue(claudeSnapshot());
render(<ClaudeCodeQuotaMenu />);
@@ -767,7 +825,7 @@ describe('ClaudeCodeQuotaMenu', () => {
// 90 s: fresh for the mount gate (2 min) but past the focus gate (60 s).
const persistedAt = Date.now() - 90_000;
mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 90_000)]);
- mockQuotaService.getWindows.mockResolvedValue([persistedSessionWindow(persistedAt)]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([persistedSessionReading(persistedAt)]);
mockService.getClaudeCodeQuota.mockResolvedValue(
claudeSnapshot({
identity: { externalAccountId: 'ext-1' },
@@ -790,7 +848,7 @@ describe('ClaudeCodeQuotaMenu', () => {
it('ingests genuinely fresh readings surfaced by a revalidation', async () => {
const persistedAt = Date.now() - 90_000;
mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 90_000)]);
- mockQuotaService.getWindows.mockResolvedValue([persistedSessionWindow(persistedAt)]);
+ mockQuotaService.getLatestReadings.mockResolvedValue([persistedSessionReading(persistedAt)]);
const readings = [liveSessionReading(Date.now())];
mockService.getClaudeCodeQuota.mockResolvedValue(
claudeSnapshot({ identity: { externalAccountId: 'ext-1' }, readings }),
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.test.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.test.ts
index 0be8aaf8e66..a1fb31a8a29 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.test.ts
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.test.ts
@@ -1,13 +1,15 @@
+import type { ClaudeCodeQuotaSnapshot } from '@lobechat/electron-client-ipc';
import { describe, expect, it } from 'vitest';
-import type { QuotaWindowRow } from './quotaViewModel';
-import { buildClaudeSnapshotFromWindows, isQuotaStale } from './quotaViewModel';
+import type { QuotaReadingRow } from './quotaViewModel';
+import { buildClaudePanelSnapshot, isQuotaStale, newestCapturedAt } from './quotaViewModel';
-const reset = new Date('2026-07-21T14:00:00Z');
-const sessionReset = new Date('2026-07-18T20:50:00Z');
+const reset = Date.parse('2026-07-21T14:00:00Z');
+const sessionReset = Date.parse('2026-07-18T20:50:00Z');
// Fixed "now" inside both windows, so the fixtures stay live regardless of the
-// wall clock the suite runs on (an expired window is intentionally dropped).
-const now = new Date('2026-07-18T08:05:00Z').getTime();
+// wall clock the suite runs on.
+const now = Date.parse('2026-07-18T08:05:00Z');
+const capturedAt = Date.parse('2026-07-18T08:00:00Z');
const account = {
displayName: 'Arvin',
@@ -18,89 +20,73 @@ const account = {
updatedAt: new Date('2026-07-18T08:01:00Z'),
};
-const windows: QuotaWindowRow[] = [
+const readings: QuotaReadingRow[] = [
+ { capturedAt, limitType: 'session', resetsAt: sessionReset, scopeKey: '', utilization: 43 },
+ { capturedAt, limitType: 'weekly_all', resetsAt: reset, scopeKey: '', utilization: 62 },
{
- lastSeenAt: new Date('2026-07-18T08:00:00Z'),
- lastUtilization: 43,
- limitType: 'session',
- peakUtilization: 61,
- resetsAt: sessionReset,
- scopeKey: '',
- windowSeconds: 18_000,
- },
- {
- lastSeenAt: new Date('2026-07-18T08:00:00Z'),
- lastUtilization: 62,
- limitType: 'weekly_all',
- peakUtilization: 64,
- resetsAt: reset,
- scopeKey: '',
- windowSeconds: 604_800,
- },
- {
- lastSeenAt: new Date('2026-07-18T08:00:00Z'),
- lastUtilization: 100,
+ capturedAt,
limitType: 'weekly_scoped',
- peakUtilization: 100,
resetsAt: reset,
scopeKey: 'Fable',
- windowSeconds: 604_800,
+ utilization: 100,
},
];
-describe('buildClaudeSnapshotFromWindows', () => {
- it('maps DB windows to the panel snapshot (session / weekly / Fable scoped)', () => {
- const snap = buildClaudeSnapshotFromWindows(account, windows, now);
+describe('buildClaudePanelSnapshot β€” persisted readings', () => {
+ it('maps persisted readings to the panel snapshot (session / weekly / Fable scoped)', () => {
+ const snap = buildClaudePanelSnapshot(account, readings, null, now);
expect(snap.status).toBe('ok');
expect(snap.session).toEqual({
- resetsAt: sessionReset.getTime(),
+ resetsAt: sessionReset,
usedPercent: 43,
windowMinutes: 300,
});
- expect(snap.weekly).toEqual({
- resetsAt: reset.getTime(),
- usedPercent: 62,
- windowMinutes: 10_080,
- });
+ expect(snap.weekly).toEqual({ resetsAt: reset, usedPercent: 62, windowMinutes: 10_080 });
expect(snap.scopedWeekly).toEqual({
modelName: 'Fable',
- window: { resetsAt: reset.getTime(), usedPercent: 100, windowMinutes: 10_080 },
+ window: { resetsAt: reset, usedPercent: 100, windowMinutes: 10_080 },
});
});
- it('drops windows whose reset already passed instead of showing them as spent', () => {
- // A device that has been offline since yesterday leaves windows recorded at
- // 100% utilization whose reset has since elapsed. Rendering those paints an
- // exhausted "0% left" badge over a quota that actually refilled.
- const afterReset = reset.getTime() + 60_000;
- const snap = buildClaudeSnapshotFromWindows(account, windows, afterReset);
-
- expect(snap.session).toBeNull();
- expect(snap.weekly).toBeNull();
- expect(snap.scopedWeekly).toBeNull();
+ it('keeps a rolled-over window in the panel as refilled', () => {
+ // The 5-hour window rolls over first: after five idle hours the persisted
+ // session reading points at a reset that has passed. Dropping the row made
+ // the panel show the weekly limit alone, as if the plan had no session
+ // limit at all; replaying its 43% would claim spend that has refilled.
+ const afterSessionReset = sessionReset + 60_000;
+ const snap = buildClaudePanelSnapshot(account, readings, null, afterSessionReset);
+
+ expect(snap.session).toEqual({ resetsAt: null, usedPercent: 0, windowMinutes: 300 });
+ expect(snap.weekly).toMatchObject({ usedPercent: 62 });
+ expect(snap.scopedWeekly).toMatchObject({ window: { usedPercent: 100 } });
});
- it('keeps a window with no recorded reset time', () => {
- const snap = buildClaudeSnapshotFromWindows(
+ it('keeps a limit the provider reports without a reset time', () => {
+ // An untouched model-scoped weekly arrives as `resets_at: null`, so it has
+ // no window row to be projected into β€” only the reading carries it.
+ const snap = buildClaudePanelSnapshot(
account,
[
{
- lastUtilization: 30,
- limitType: 'session',
- peakUtilization: 30,
+ capturedAt,
+ limitType: 'weekly_scoped',
resetsAt: null,
- scopeKey: '',
- windowSeconds: 18_000,
+ scopeKey: 'Fable',
+ utilization: 0,
},
],
- Date.parse('2030-01-01T00:00:00Z'),
+ null,
+ now,
);
- expect(snap.session?.usedPercent).toBe(30);
+ expect(snap.scopedWeekly).toEqual({
+ modelName: 'Fable',
+ window: { resetsAt: null, usedPercent: 0, windowMinutes: 10_080 },
+ });
});
it('carries the account identity for the switcher', () => {
- const snap = buildClaudeSnapshotFromWindows(account, windows, now);
+ const snap = buildClaudePanelSnapshot(account, readings, null, now);
expect(snap.identity).toMatchObject({
externalAccountId: '48bfd5c6',
@@ -108,44 +94,127 @@ describe('buildClaudeSnapshotFromWindows', () => {
});
});
- it('prefers lastUtilization over peak and clamps to 0..100', () => {
- const snap = buildClaudeSnapshotFromWindows(
+ it('has no windows for an account with no readings', () => {
+ const snap = buildClaudePanelSnapshot(account, [], null, now);
+ expect(snap.session).toBeNull();
+ expect(snap.weekly).toBeNull();
+ expect(snap.scopedWeekly).toBeNull();
+ });
+});
+
+describe('newestCapturedAt', () => {
+ it('is the newest reading time, 0 with none', () => {
+ expect(newestCapturedAt(readings)).toBe(capturedAt);
+ expect(newestCapturedAt([{ ...readings[0], capturedAt: now }, ...readings])).toBe(now);
+ expect(newestCapturedAt([])).toBe(0);
+ });
+});
+
+describe('buildClaudePanelSnapshot β€” folding in a live sample', () => {
+ const liveReading = (over: Partial<QuotaReadingRow> = {}): QuotaReadingRow => ({
+ capturedAt: now,
+ limitType: 'session',
+ resetsAt: sessionReset,
+ scopeKey: '',
+ utilization: 7,
+ ...over,
+ });
+
+ const live: ClaudeCodeQuotaSnapshot = {
+ error: null,
+ identity: { externalAccountId: '48bfd5c6' },
+ provider: 'claude-code',
+ readings: [
+ liveReading(),
+ liveReading({ limitType: 'weekly_all', resetsAt: reset, utilization: 9 }),
+ ],
+ scopedWeekly: {
+ modelName: 'Fable',
+ window: { resetsAt: reset, usedPercent: 12, windowMinutes: 10_080 },
+ },
+ session: { resetsAt: sessionReset, usedPercent: 7, windowMinutes: 300 },
+ status: 'ok',
+ updatedAt: now,
+ weekly: { resetsAt: reset, usedPercent: 9, windowMinutes: 10_080 },
+ };
+
+ it('takes the newest reading per limit, not the newest snapshot', () => {
+ // Buckets can be persisted at different times (one device ingested the
+ // session at 08:00 while the weekly last landed at 06:00). Comparing whole
+ // snapshots would let the fresher session bucket suppress a live weekly
+ // that is genuinely newer than the persisted one.
+ const persisted = [
+ readings[0], // session, captured 08:00 β€” newer than the live sample below
+ { ...readings[1], capturedAt: Date.parse('2026-07-18T06:00:00Z') }, // weekly, stale
+ ];
+ const olderLive = { ...live, updatedAt: Date.parse('2026-07-18T07:00:00Z') };
+ const snap = buildClaudePanelSnapshot(
account,
- [
- {
- lastUtilization: null,
- limitType: 'session',
- peakUtilization: 150,
- resetsAt: reset,
- scopeKey: '',
- windowSeconds: 18_000,
- },
- ],
+ persisted,
+ {
+ ...olderLive,
+ readings: [
+ liveReading({ capturedAt: Date.parse('2026-07-18T07:00:00Z') }),
+ liveReading({
+ capturedAt: Date.parse('2026-07-18T07:00:00Z'),
+ limitType: 'weekly_all',
+ resetsAt: reset,
+ utilization: 9,
+ }),
+ ],
+ },
now,
);
- expect(snap.session?.usedPercent).toBe(100); // clamped; falls back to peak
+
+ expect(snap.session).toMatchObject({ usedPercent: 43 }); // persisted 08:00 wins
+ expect(snap.weekly).toMatchObject({ usedPercent: 9 }); // live 07:00 beats persisted 06:00
});
- it('tolerates string dates and missing windows', () => {
- const snap = buildClaudeSnapshotFromWindows(
- account,
- [
- {
- lastSeenAt: '2026-07-18T08:00:00Z',
- lastUtilization: 20,
- limitType: 'session',
- peakUtilization: 20,
- resetsAt: '2026-07-18T20:50:00Z',
- scopeKey: '',
- windowSeconds: 18_000,
- },
- ],
- now,
+ it('fills a limit the account has no reading for from the sample', () => {
+ const snap = buildClaudePanelSnapshot(account, [readings[1]], live, now);
+
+ expect(snap.session).toMatchObject({ usedPercent: 7 });
+ expect(snap.scopedWeekly).toMatchObject({ modelName: 'Fable' });
+ expect(snap.identity).toMatchObject({ externalAccountId: '48bfd5c6' });
+ });
+
+ it('refuses a sample it cannot attribute to this account', () => {
+ // `~/.claude.json` may carry no oauthAccount while the quota comes from the
+ // keychain. With several logins on the machine the CLI's current one is not
+ // necessarily this account, so an unidentified sample must not be painted
+ // under this account's name β€” not even to fill an empty window.
+ const unidentified = { ...live, identity: undefined };
+ const otherAccount = { ...live, identity: { externalAccountId: 'someone-else' } };
+
+ expect(buildClaudePanelSnapshot(account, [readings[1]], unidentified, now).session).toBeNull();
+ expect(buildClaudePanelSnapshot(account, [readings[1]], otherAccount, now).session).toBeNull();
+ // An account we cannot name has nothing to be confused with.
+ const anonymous = { ...account, externalAccountId: null };
+ expect(
+ buildClaudePanelSnapshot(anonymous, [readings[1]], unidentified, now).session,
+ ).toMatchObject({ usedPercent: 7 });
+ });
+
+ it('reports the sample time once a live sample has been consulted', () => {
+ // Otherwise the header says "3 εˆ†ι’Ÿε‰ζ›΄ζ–°" over just-fetched numbers and
+ // every staleness gate immediately refetches the quota we already have.
+ const stale = { ...account, updatedAt: new Date('2026-07-18T07:00:00Z') };
+
+ expect(buildClaudePanelSnapshot(stale, readings, live, now).updatedAt).toBe(live.updatedAt);
+ expect(buildClaudePanelSnapshot(stale, readings, null, now).updatedAt).toBe(
+ Date.parse('2026-07-18T07:00:00Z'),
);
- expect(snap.session?.usedPercent).toBe(20);
- expect(snap.session?.resetsAt).toBe(Date.parse('2026-07-18T20:50:00Z'));
- expect(snap.weekly).toBeNull();
- expect(snap.scopedWeekly).toBeNull();
+ });
+
+ it('keeps the persisted view when the live fetch failed', () => {
+ const failed = { ...live, error: 'fetch failed', status: 'error' as const };
+
+ expect(buildClaudePanelSnapshot(account, readings, failed, now).session).toMatchObject({
+ usedPercent: 43,
+ });
+ expect(buildClaudePanelSnapshot(account, readings, null, now).session).toMatchObject({
+ usedPercent: 43,
+ });
});
});
@@ -165,10 +234,11 @@ describe('isQuotaStale', () => {
});
it('ignores device clock skew when building display freshness', () => {
- const deviceClockAhead = [{ ...windows[0], lastSeenAt: new Date('2026-07-19T09:00:00Z') }];
- const snap = buildClaudeSnapshotFromWindows(
+ const deviceClockAhead = [{ ...readings[0], capturedAt: Date.parse('2026-07-19T09:00:00Z') }];
+ const snap = buildClaudePanelSnapshot(
{ ...account, updatedAt: new Date('2026-07-18T08:50:00Z') },
deviceClockAhead,
+ null,
now,
);
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.ts
index b3b6cde1ba3..9f6c74be9e2 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.ts
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/quotaViewModel.ts
@@ -1,23 +1,16 @@
import type {
ClaudeCodeAccountIdentity,
ClaudeCodeQuotaSnapshot,
- HeteroQuotaWindow,
} from '@lobechat/electron-client-ipc';
+import type { QuotaDisplayReading } from '@lobechat/heterogeneous-agents/quota';
+import { buildClaudeQuotaWindows } from '@lobechat/heterogeneous-agents/quota';
/**
- * Minimal shape of a persisted `agent_quota_windows` row as returned by
- * `agentQuota.getWindows` (dates arrive as `Date` via the superjson transformer,
- * but we tolerate strings too).
+ * Minimal shape of a persisted quota reading as returned by
+ * `agentQuota.getLatestReadings` β€” one row per (limitType, scopeKey), already
+ * flattened to epoch ms by the server.
*/
-export interface QuotaWindowRow {
- lastSeenAt?: Date | string | null;
- lastUtilization?: number | null;
- limitType: string;
- peakUtilization: number;
- resetsAt?: Date | string | null;
- scopeKey: string;
- windowSeconds: number;
-}
+export type QuotaReadingRow = QuotaDisplayReading;
export interface QuotaAccountRow {
displayName?: string | null;
@@ -35,27 +28,6 @@ const toMs = (v: Date | string | null | undefined): number | null => {
return Number.isNaN(ms) ? null : ms;
};
-const toWindow = (row: QuotaWindowRow | undefined, now: number): HeteroQuotaWindow | null => {
- if (!row) return null;
- // A window whose reset has already passed says nothing about current usage β€”
- // the quota refilled at `resetsAt`. Showing its last utilization paints a
- // spent window as if it were live (an exhausted 0%-left badge on a fresh
- // quota), so drop it and let the caller fall back to a live sample.
- const resetsAt = toMs(row.resetsAt);
- if (resetsAt !== null && resetsAt <= now) return null;
-
- // Displayed "used" is the latest reading; peak is the monotonic ceiling fallback.
- const usedPercent = Math.max(0, Math.min(100, row.lastUtilization ?? row.peakUtilization ?? 0));
- return {
- resetsAt,
- usedPercent,
- windowMinutes: Math.round((row.windowSeconds ?? 0) / 60),
- };
-};
-
-const isWeeklyAll = (row: QuotaWindowRow): boolean =>
- row.limitType === 'weekly_all' || (row.limitType.startsWith('weekly') && !row.scopeKey);
-
const identityOf = (account: QuotaAccountRow): ClaudeCodeAccountIdentity => ({
displayName: account.displayName ?? undefined,
email: account.email ?? undefined,
@@ -66,54 +38,91 @@ const identityOf = (account: QuotaAccountRow): ClaudeCodeAccountIdentity => ({
});
/**
- * Build the panel snapshot from the persisted DB windows β€” the primary display
- * source. The live Anthropic fetch is only used to refresh/ingest these rows, so
- * the panel keeps showing data even when that fetch fails.
+ * Newest persisted reading time (0 when none). Readings carry the sampling
+ * host's `capturedAt`, so this compares 1:1 against a live snapshot's readings
+ * β€” both are stamped by the same host.
*/
-export const buildClaudeSnapshotFromWindows = (
+export const newestCapturedAt = (readings: QuotaReadingRow[]): number =>
+ readings.reduce((max, r) => Math.max(max, r.capturedAt), 0);
+
+/**
+ * Whether a live sample provably describes the account on screen.
+ *
+ * Requiring a positive match (rather than only rejecting a mismatch) is what
+ * keeps an *unidentifiable* sample off a named account: `~/.claude.json` may
+ * carry no `oauthAccount` while the quota itself comes from the keychain, and
+ * with several logins on the machine the CLI's current one is not necessarily
+ * the account this panel is showing. Painting one account's numbers under
+ * another's name is worse than leaving a window unfilled. An account we cannot
+ * name either has nothing to be confused with, so it accepts any sample.
+ */
+const liveBelongsToAccount = (account: QuotaAccountRow, live: ClaudeCodeQuotaSnapshot): boolean => {
+ const accountId = account.externalAccountId;
+ if (!accountId) return true;
+ return live.identity?.externalAccountId === accountId;
+};
+
+/**
+ * The snapshot the panel renders: persisted readings, with an attributable live
+ * sample folded in. Pass `live = null` for the persisted-only view (the interim
+ * paint before a live refresh resolves).
+ *
+ * Readings rather than `agent_quota_windows`: a window is keyed by its
+ * `resets_at`, so a limit the provider reports without one (an untouched
+ * model-scoped weekly) has no window row at all, and a window whose reset has
+ * passed is not the live one. {@link buildClaudeQuotaWindows} covers both β€” a
+ * rolled-over window renders as refilled instead of vanishing from the panel.
+ *
+ * The merge happens at the *reading* level, so freshness is decided per limit β€”
+ * {@link buildClaudeQuotaWindows} keeps the newest reading in each bucket. A
+ * snapshot-level comparison would let one fresh bucket suppress newer live data
+ * for every other bucket (a session sampled at 12:00 discarding an 11:00 weekly
+ * that is newer than the persisted 10:00 one).
+ *
+ * A sample that carries windows but no readings (an older sampler build behind
+ * the device RPC) can still fill a limit the account has no reading for at all
+ * β€” otherwise the panel renders "this plan has no such limit" while holding a
+ * sample that has it.
+ */
+export const buildClaudePanelSnapshot = (
account: QuotaAccountRow,
- windows: QuotaWindowRow[],
+ persistedReadings: QuotaReadingRow[],
+ live: ClaudeCodeQuotaSnapshot | null,
now: number = Date.now(),
): ClaudeCodeQuotaSnapshot => {
- const session = windows.find((w) => w.limitType === 'session');
- const weekly = windows.find(isWeeklyAll);
- const scoped = windows.find((w) => w.limitType === 'weekly_scoped' && !!w.scopeKey);
- const scopedWindow = toWindow(scoped, now);
+ const sample = live?.status === 'ok' && liveBelongsToAccount(account, live) ? live : null;
+ const readings = sample?.readings?.length
+ ? [...persistedReadings, ...sample.readings]
+ : persistedReadings;
+ const windows = buildClaudeQuotaWindows(readings, now);
- // Freshness is based on when our server received the snapshot, not on the
- // sampling device's wall clock. Device timestamps remain on the windows for
- // history and cached-echo detection, but clock skew must not suppress or
- // accelerate browser refreshes.
- const updatedAt = toMs(account.updatedAt) ?? 0;
+ // Freshness is normally the server's receipt time β€” a device clock must not
+ // drive the refresh gates. But once a live sample has been consulted, the
+ // panel is at least as current as that sample, and reporting the older
+ // receipt would both mislabel the header and re-trip every staleness gate
+ // into refetching a quota we just fetched.
+ const receivedAt = toMs(account.updatedAt) ?? 0;
+ const updatedAt = sample ? Math.max(receivedAt, sample.updatedAt) : receivedAt;
return {
error: null,
identity: identityOf(account),
provider: 'claude-code',
- scopedWeekly:
- scoped && scopedWindow ? { modelName: scoped.scopeKey, window: scopedWindow } : null,
- session: toWindow(session, now),
+ scopedWeekly: windows.scopedWeekly ?? sample?.scopedWeekly ?? null,
+ session: windows.session ?? sample?.session ?? null,
status: 'ok',
updatedAt: updatedAt || now,
- weekly: toWindow(weekly, now),
+ weekly: windows.weekly ?? sample?.weekly ?? null,
};
};
/**
- * Newest persisted reading time across the windows (0 when none). `lastSeenAt`
- * is written from the readings' `capturedAt`, so this compares 1:1 against a
- * live snapshot's `capturedAt` values β€” both stamped by the desktop main
- * process.
- */
-export const newestSeenAt = (windows: QuotaWindowRow[]): number =>
- windows.reduce((max, w) => Math.max(max, toMs(w.lastSeenAt) ?? 0), 0);
-
-/**
- * Whether a built snapshot carries at least one window worth rendering. Callers
- * cannot infer this from the persisted row count: every row may describe a
- * window that has already reset, which {@link buildClaudeSnapshotFromWindows}
- * drops. Treating a non-empty row array as "we have data" would discard a live
- * sample in favour of an empty panel.
+ * Whether a built snapshot carries at least one window worth rendering.
+ * Callers cannot infer this from the persisted row count: an account may hold
+ * readings only for limits the panel does not render, which
+ * {@link buildClaudePanelSnapshot} maps to nothing. Treating a non-empty row
+ * array as "we have data" would discard a live sample in favour of an empty
+ * panel.
*/
export const hasRenderableWindow = (snapshot: ClaudeCodeQuotaSnapshot): boolean =>
!!snapshot.session || !!snapshot.weekly || !!snapshot.scopedWeekly;
diff --git a/src/services/agentQuota.ts b/src/services/agentQuota.ts
index be3d7405a96..2fd97e87e15 100644
--- a/src/services/agentQuota.ts
+++ b/src/services/agentQuota.ts
@@ -26,7 +26,13 @@ class AgentQuotaService {
listAccounts = async () => lambdaClient.agentQuota.listAccounts.query();
- getWindows = async (accountId: string) => lambdaClient.agentQuota.getWindows.query({ accountId });
+ /**
+ * Newest reading per limit bucket β€” what the panel renders. Windows are keyed
+ * by `resets_at`, so a limit reported without one (an untouched model-scoped
+ * weekly) only exists here.
+ */
+ getLatestReadings = async (accountId: string) =>
+ lambdaClient.agentQuota.getLatestReadings.query({ accountId });
listBindings = async (agentId: string) => lambdaClient.agentQuota.listBindings.query({ agentId });