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.

♻️ refactor(agent-quota): move quota menus, account manager and calendar onto @lobechat/replica (#21301)

Arvin Xubbfbaf9a6ed0
diff --git a/src/features/AgentQuotaCalendar/QuotaCalendarModal.tsx b/src/features/AgentQuotaCalendar/QuotaCalendarModal.tsx
index a638d1c6f83..b36ddacbcb9 100644
--- a/src/features/AgentQuotaCalendar/QuotaCalendarModal.tsx
+++ b/src/features/AgentQuotaCalendar/QuotaCalendarModal.tsx
@@ -15,11 +15,9 @@ import dayjs from 'dayjs';
import type { TFunction } from 'i18next';
import { t as i18nT } from 'i18next';
import { BanIcon, ChevronLeftIcon, ChevronRightIcon, InfoIcon, RotateCcwIcon } from 'lucide-react';
-import { memo, useEffect, useMemo, useState } from 'react';
+import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { agentQuotaService } from '@/services/agentQuota';
-
import {
buildBurnSeries,
buildDailyBurn,
@@ -38,7 +36,6 @@ import {
projectBurnout,
type QuotaSeriesKey,
type QuotaWindowSpan,
- selectProviderQuotaAccount,
seriesId,
SESSION_SERIES,
shouldShowHeatDot,
@@ -49,6 +46,7 @@ import {
windowSeriesIdOf,
type WindowStat,
} from './quotaCalendarModel';
+import { useQuotaCalendarHistory } from './useQuotaCalendarHistory';
const styles = createStaticStyles(({ css }) => ({
calendarGrid: css`
@@ -333,8 +331,6 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-type WindowRow = Awaited<ReturnType<typeof agentQuotaService.getWindows>>[number];
-
const toMs = (value: Date | number | string | null | undefined): number | null =>
value == null ? null : new Date(value).getTime();
@@ -362,7 +358,6 @@ const normalizeWindows = (rows: WindowLike[]): NormalizedWindow[] =>
const CHART_W = 640;
const CHART_H = 120;
-const HISTORY_DAYS = 90;
const RING_RADIUS = 22;
const RING_CIRCUMFERENCE = 2 * Math.PI * RING_RADIUS;
@@ -775,44 +770,15 @@ const MONTHLY_LABEL_KEYS: Record<
const QuotaCalendar = memo<QuotaCalendarProps>(({ externalAccountId, provider }) => {
const { t } = useTranslation('chat');
- const [accountUnavailable, setAccountUnavailable] = useState(false);
- const [loading, setLoading] = useState(true);
- const [readings, setReadings] = useState<QuotaLimitReading[]>([]);
- const [turns, setTurns] = useState<UsageTurn[]>([]);
- const [windows, setWindows] = useState<NormalizedWindow[]>([]);
+ const { accountUnavailable, loading, readings, turns, windowRows } = useQuotaCalendarHistory(
+ provider,
+ externalAccountId,
+ );
+ const windows = useMemo(() => normalizeWindows(windowRows as WindowLike[]), [windowRows]);
const [series, setSeries] = useState<QuotaSeriesKey>(SESSION_SERIES);
const [month, setMonth] = useState(() => dayjs().startOf('month'));
const now = Date.now();
- useEffect(() => {
- let cancelled = false;
- (async () => {
- const accounts = await agentQuotaService.listAccounts().catch(() => []);
- const account = selectProviderQuotaAccount(accounts, provider, externalAccountId);
- if (!account) {
- if (!cancelled) setAccountUnavailable(true);
- return;
- }
- setAccountUnavailable(false);
-
- const [windowRows, snapshotSeries, usageTurns] = await Promise.all([
- agentQuotaService.getWindows(account.id, 200).catch(() => [] as WindowRow[]),
- agentQuotaService
- .listSnapshots(account.id, HISTORY_DAYS)
- .catch(() => [] as QuotaLimitReading[]),
- agentQuotaService.listUsageTurns(account.id, HISTORY_DAYS).catch(() => [] as UsageTurn[]),
- ]);
- if (cancelled) return;
- setWindows(normalizeWindows(windowRows));
- setReadings(snapshotSeries);
- setTurns(usageTurns);
- })().finally(() => setLoading(false));
-
- return () => {
- cancelled = true;
- };
- }, [externalAccountId, provider]);
-
// The session window comes first: it is the window an agent actually
// works inside, and the one that stops a run mid-task. Codex reports one
// primary bucket per rate-limit scope, so each discovered bucket gets its
diff --git a/src/features/AgentQuotaCalendar/useQuotaCalendarHistory.test.ts b/src/features/AgentQuotaCalendar/useQuotaCalendarHistory.test.ts
new file mode 100644
index 00000000000..c43f001d99a
--- /dev/null
+++ b/src/features/AgentQuotaCalendar/useQuotaCalendarHistory.test.ts
@@ -0,0 +1,139 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type PropsWithChildren } from 'react';
+import { SWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { useAgentQuotaStore } from '@/store/agentQuota';
+import { initialState } from '@/store/agentQuota/initialState';
+
+import { useQuotaCalendarHistory } from './useQuotaCalendarHistory';
+
+const mockQuotaService = vi.hoisted(() => ({
+ getWindows: vi.fn(),
+ listAccounts: vi.fn(),
+ listSnapshots: vi.fn(),
+ listUsageTurns: vi.fn(),
+}));
+
+vi.mock('@/services/agentQuota', () => ({ agentQuotaService: mockQuotaService }));
+
+const claudeAccount = {
+ externalAccountId: 'ext-1',
+ id: 'acc-1',
+ provider: 'claude-code',
+ updatedAt: new Date(),
+};
+
+const reading = {
+ capturedAt: Date.now() - 60_000,
+ limitType: 'session',
+ resetsAt: Date.now() + 2 * 3_600_000,
+ scopeKey: '',
+ utilization: 40,
+};
+
+const pending = () => new Promise<never>(() => {});
+
+/** Each mount gets its own request cache, like a reopened app. */
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
+
+const open = () => renderHook(() => useQuotaCalendarHistory('claude-code'), { wrapper });
+
+/** A reload: memory is gone, storage keeps what the last session persisted. */
+const reload = () => act(() => useAgentQuotaStore.setState(initialState, false));
+
+describe('useQuotaCalendarHistory', () => {
+ let scope = '';
+
+ beforeEach(() => {
+ scope = `quota-calendar-${Math.random().toString(36).slice(2)}:personal`;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ reload();
+ mockQuotaService.listAccounts.mockReset().mockResolvedValue([claudeAccount]);
+ mockQuotaService.getWindows.mockReset().mockResolvedValue([]);
+ mockQuotaService.listSnapshots.mockReset().mockResolvedValue([reading]);
+ mockQuotaService.listUsageTurns.mockReset().mockResolvedValue([]);
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ });
+
+ it('reopens on the last history after a reload before the network answers', async () => {
+ const first = open();
+ await waitFor(() => expect(first.result.current.readings).toHaveLength(1));
+ first.unmount();
+
+ reload();
+ mockQuotaService.listAccounts.mockImplementation(pending);
+ mockQuotaService.getWindows.mockImplementation(pending);
+ mockQuotaService.listSnapshots.mockImplementation(pending);
+ mockQuotaService.listUsageTurns.mockImplementation(pending);
+ const { result } = open();
+
+ await waitFor(() => expect(result.current.readings).toHaveLength(1));
+ expect(result.current.loading).toBe(false);
+ });
+
+ it('keeps loading over an empty local history until the server confirms it', async () => {
+ mockQuotaService.listSnapshots.mockResolvedValue([]);
+ const first = open();
+ await waitFor(() => expect(first.result.current.loading).toBe(false));
+ first.unmount();
+
+ reload();
+ let release!: (value: unknown[]) => void;
+ mockQuotaService.getWindows.mockImplementation(
+ () => new Promise((resolve) => (release = resolve)),
+ );
+ const { result } = open();
+
+ await waitFor(() =>
+ expect(useAgentQuotaStore.getState().quotaHistoryMap['acc-1']).toBeDefined(),
+ );
+ expect(result.current.loading).toBe(true);
+
+ await act(async () => release([]));
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.readings).toEqual([]);
+ });
+
+ it('does not call the account unavailable while only an outdated local list says so', async () => {
+ mockQuotaService.listAccounts.mockResolvedValue([]);
+ const first = open();
+ await waitFor(() => expect(first.result.current.accountUnavailable).toBe(true));
+ first.unmount();
+
+ reload();
+ let release!: (value: unknown[]) => void;
+ mockQuotaService.listAccounts.mockImplementation(
+ () => new Promise((resolve) => (release = resolve)),
+ );
+ const { result } = open();
+
+ await waitFor(() => expect(useAgentQuotaStore.getState().quotaAccountsMap.all).toEqual([]));
+ expect(result.current.accountUnavailable).toBe(false);
+ expect(result.current.loading).toBe(true);
+
+ // The server knows the account the local copy predates.
+ await act(async () => release([claudeAccount]));
+ await waitFor(() => expect(result.current.readings).toHaveLength(1));
+ expect(result.current.accountUnavailable).toBe(false);
+ });
+
+ it('shows the account as unavailable when the first account read fails', async () => {
+ mockQuotaService.listAccounts.mockRejectedValue(new Error('offline'));
+ const { result } = open();
+
+ await waitFor(() => expect(result.current.accountUnavailable).toBe(true));
+ expect(result.current.loading).toBe(false);
+ });
+});
diff --git a/src/features/AgentQuotaCalendar/useQuotaCalendarHistory.ts b/src/features/AgentQuotaCalendar/useQuotaCalendarHistory.ts
new file mode 100644
index 00000000000..7dab18c1b18
--- /dev/null
+++ b/src/features/AgentQuotaCalendar/useQuotaCalendarHistory.ts
@@ -0,0 +1,64 @@
+import type { QuotaLimitReading } from '@lobechat/heterogeneous-agents/quota';
+import { useMemo } from 'react';
+
+import { cacheScope } from '@/libs/replica';
+import { agentQuotaSelectors, type QuotaWindowRow, useAgentQuotaStore } from '@/store/agentQuota';
+
+import { selectProviderQuotaAccount, type UsageTurn } from './quotaCalendarModel';
+
+const EMPTY_READINGS: QuotaLimitReading[] = [];
+const EMPTY_TURNS: UsageTurn[] = [];
+const EMPTY_WINDOW_ROWS: QuotaWindowRow[] = [];
+
+export interface QuotaCalendarHistory {
+ /** The server (or a failed first read) says the provider has no such account. */
+ accountUnavailable: boolean;
+ /** Nothing to draw yet: no account resolved, or no history the server has settled. */
+ loading: boolean;
+ readings: QuotaLimitReading[];
+ turns: UsageTurn[];
+ windowRows: QuotaWindowRow[];
+}
+
+/**
+ * The calendar's account and 90-day history, read from the agentQuota
+ * replicas: a reopen (or a reload) paints the last-seen history at once and
+ * revalidates it in the background.
+ */
+export const useQuotaCalendarHistory = (
+ provider: string,
+ externalAccountId?: string,
+): QuotaCalendarHistory => {
+ const scope = cacheScope.use();
+ const [useFetchQuotaAccounts, useFetchQuotaHistory] = useAgentQuotaStore((s) => [
+ s.useFetchQuotaAccounts,
+ s.useFetchQuotaHistory,
+ ]);
+ const { error: accountsError } = useFetchQuotaAccounts();
+ const accounts = useAgentQuotaStore(agentQuotaSelectors.accounts);
+ const accountsConfirmed = useAgentQuotaStore(agentQuotaSelectors.isAccountsConfirmed(scope));
+ const account = useMemo(
+ () =>
+ accounts ? selectProviderQuotaAccount(accounts, provider, externalAccountId) : undefined,
+ [accounts, externalAccountId, provider],
+ );
+ const { error: historyError } = useFetchQuotaHistory(account?.id);
+ const history = useAgentQuotaStore(agentQuotaSelectors.history(account?.id));
+ const historyConfirmed = useAgentQuotaStore(
+ agentQuotaSelectors.isHistoryConfirmed(scope, account?.id),
+ );
+
+ // A hydrated account list may predate the account, so "no account" waits for
+ // the server (or a failed first read, which the old fetch also showed as none).
+ const accountUnavailable = !account && (accountsConfirmed || !!accountsError);
+ const readings = (history?.snapshots as QuotaLimitReading[] | undefined) ?? EMPTY_READINGS;
+ const turns = (history?.usageTurns as UsageTurn[] | undefined) ?? EMPTY_TURNS;
+ const windowRows = history?.windows ?? EMPTY_WINDOW_ROWS;
+ const hasHistoryData = readings.length > 0 || windowRows.length > 0;
+ // An empty local copy is not an answer yet: keep the skeleton until the
+ // server (or a failure) settles it.
+ const loading =
+ !accountUnavailable && (!account || (!hasHistoryData && !historyConfirmed && !historyError));
+
+ return { accountUnavailable, loading, readings, turns, windowRows };
+};
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx
index 70a30060474..b0441606b06 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx
@@ -8,6 +8,7 @@ import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
import { useSingleton } from '@/hooks/useSingleton';
import { agentQuotaService } from '@/services/agentQuota';
import { fetchClaudeCodeQuotaSnapshot } from '@/services/heteroAgentQuota';
+import { getAgentQuotaStoreState } from '@/store/agentQuota';
import QuotaAccountSwitcher from './QuotaAccountSwitcher';
import type { FetchQuotaOptions, QuotaWindowItem } from './QuotaMenu';
@@ -57,6 +58,7 @@ const unavailableSnapshot = (
*/
type ClaudeCodePanelSnapshot = ClaudeCodeQuotaSnapshot & {
refreshUnavailableReason?: ClaudeCodeQuotaSnapshot['reason'];
+ sampleFailed?: boolean;
};
const isRateLimitError = (quota: ClaudeCodeQuotaSnapshot) => quota.error?.includes('429') ?? false;
@@ -70,7 +72,7 @@ interface ClaudeCodeQuotaMenuProps {
const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) => {
const { t } = useTranslation('chat');
const agentId = useAgentId();
- const sourceKey = createQuotaSourceKey('claude-code', deviceId ?? 'local', env);
+ const sourceKey = createQuotaSourceKey('claude-code', agentId, deviceId ?? 'local', env);
// A persisted account becomes eligible for a device only after this mounted
// menu has observed that device return the same external account identity.
// This avoids painting another machine's pinned/first account on a device
@@ -90,11 +92,12 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =
options?: FetchQuotaOptions<ClaudeCodePanelSnapshot>,
): Promise<ClaudeCodePanelSnapshot> => {
const force = !!options?.force;
+ const quotaStore = getAgentQuotaStoreState();
// 1) Resolve the account to display — pinned for this agent, else the first.
const [initialAccounts, bindings] = await Promise.all([
- agentQuotaService.listAccounts().catch(() => []),
- agentId ? agentQuotaService.listBindings(agentId).catch(() => []) : [],
+ quotaStore.readQuotaAccounts().catch(() => []),
+ agentId ? quotaStore.readQuotaBindings(agentId).catch(() => []) : [],
]);
let accounts = initialAccounts;
let claude = accounts.filter((a) => a.provider === 'claude-code');
@@ -103,13 +106,12 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =
let account = deviceId
? claude.find((a) => a.externalAccountId === trustedExternalAccountId)
: (claude.find((a) => a.id === pinnedId) ?? claude[0]);
- let readings = account
- ? await agentQuotaService.getLatestReadings(account.id).catch(() => [])
- : [];
+ let readings = account ? await quotaStore.readQuotaReadings(account.id).catch(() => []) : [];
// 2) Throttled live refresh + ingest. Paint the persisted windows before
// awaiting the live fetch so the panel never blocks on it.
let live: ClaudeCodeQuotaSnapshot | null = null;
+ let liveFailed = false;
if (
force ||
options?.revalidate ||
@@ -120,7 +122,10 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =
const interim = buildClaudePanelSnapshot(account, readings, null);
if (hasRenderableWindow(interim)) options?.onInterim?.(interim);
}
- live = await fetchClaudeCodeQuotaSnapshot({ deviceId, env, force }).catch(() => null);
+ live = await fetchClaudeCodeQuotaSnapshot({ deviceId, env, force }).catch(() => {
+ liveFailed = true;
+ return null;
+ });
const externalAccountId = live?.identity?.externalAccountId;
if (live?.status === 'ok' && externalAccountId && live.readings?.length) {
@@ -135,7 +140,7 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =
(candidate) => candidate.externalAccountId === externalAccountId,
);
const matchingReadings = matchingAccount
- ? await agentQuotaService.getLatestReadings(matchingAccount.id).catch(() => [])
+ ? await quotaStore.readQuotaReadings(matchingAccount.id).catch(() => [])
: [];
const isCachedEcho =
!!matchingAccount && liveCapturedAt <= newestCapturedAt(matchingReadings);
@@ -144,14 +149,16 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =
await agentQuotaService
.ingestClaudeSnapshot({ deviceId, identity: live.identity!, readings: live.readings })
.catch(() => {});
- accounts = await agentQuotaService.listAccounts().catch(() => accounts);
+ accounts = await quotaStore.readQuotaAccounts({ fresh: true }).catch(() => accounts);
claude = accounts.filter((a) => a.provider === 'claude-code');
account =
claude.find((a) => a.externalAccountId === externalAccountId) ??
claude.find((a) => a.id === pinnedId) ??
claude[0];
readings = account
- ? await agentQuotaService.getLatestReadings(account.id).catch(() => readings)
+ ? await quotaStore
+ .readQuotaReadings(account.id, { fresh: true })
+ .catch(() => readings)
: readings;
} else {
account = matchingAccount;
@@ -171,6 +178,9 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =
? { ...merged, refreshUnavailableReason: live.reason }
: merged;
}
+ // A failed live fetch with nothing to show still reads as "unavailable",
+ // but flagged, so the panel keeps the last snapshot it already shows.
+ if (!live && liveFailed) return { ...unavailableSnapshot(), sampleFailed: true };
return live ?? merged ?? unavailableSnapshot();
},
[agentId, deviceId, env, trustedDeviceAccounts],
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.test.tsx
new file mode 100644
index 00000000000..c7391e8fd93
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.test.tsx
@@ -0,0 +1,140 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentQuotaService } from '@/services/agentQuota';
+import { useAgentQuotaStore } from '@/store/agentQuota';
+import {
+ QUOTA_ACCOUNTS_KEY,
+ type QuotaAccount,
+ type QuotaBinding,
+} from '@/store/agentQuota/projection';
+
+import QuotaAccountManager from './QuotaAccountManagerModal';
+import { isolateQuotaReplica } from './testUtils';
+
+const account = (id: string) =>
+ ({
+ email: `${id}@example.com`,
+ externalAccountId: `ext-${id}`,
+ id,
+ label: null,
+ provider: 'claude-code',
+ }) as unknown as QuotaAccount;
+
+/** The label of the option the radio group shows as selected. */
+const checkedOption = () =>
+ screen.getByRole('radio', { checked: true }).closest('label')?.textContent;
+
+const binding = (id: string, accountId: string, role: string) =>
+ ({ accountId, agentId: 'agent-1', id, role }) as unknown as QuotaBinding;
+
+describe('QuotaAccountManager', () => {
+ beforeEach(() => {
+ isolateQuotaReplica();
+ vi.spyOn(agentQuotaService, 'listAccounts').mockResolvedValue([account('a1')]);
+ vi.spyOn(agentQuotaService, 'getLatestReadings').mockResolvedValue([]);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('shows no "no account" hint and keeps the controls disabled until the bindings load', async () => {
+ let answerBindings!: (rows: QuotaBinding[]) => void;
+ vi.spyOn(agentQuotaService, 'listBindings').mockImplementation(
+ () => new Promise((resolve) => (answerBindings = resolve)),
+ );
+ // The account pool painted from the replica; this agent's bindings did not.
+ act(() =>
+ useAgentQuotaStore.setState({ quotaAccountsMap: { [QUOTA_ACCOUNTS_KEY]: [account('a1')] } }),
+ );
+
+ render(<QuotaAccountManager agentId={'agent-1'} />);
+
+ expect(screen.getByText('[email protected]')).toBeTruthy();
+ expect(screen.queryByText('heteroAgent.claudeQuota.manage.autoNoAccount')).toBeNull();
+ expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(true);
+ expect(screen.queryByRole('radio', { checked: true })).toBeNull();
+
+ await act(async () => answerBindings([binding('b1', 'a1', 'pool')]));
+
+ expect(screen.queryByText('heteroAgent.claudeQuota.manage.autoNoAccount')).toBeNull();
+ expect(screen.getByText(/heteroAgent\.claudeQuota\.manage\.autoRoutingTo/)).toBeTruthy();
+ expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(false);
+ // Auto is the confirmed mode now, and the group shows it.
+ expect(checkedOption()).toContain('heteroAgent.claudeQuota.manage.modeAuto');
+ });
+
+ it('selects the pinned account once the bindings load', async () => {
+ let answerBindings!: (rows: QuotaBinding[]) => void;
+ vi.spyOn(agentQuotaService, 'listBindings').mockImplementation(
+ () => new Promise((resolve) => (answerBindings = resolve)),
+ );
+ act(() =>
+ useAgentQuotaStore.setState({ quotaAccountsMap: { [QUOTA_ACCOUNTS_KEY]: [account('a1')] } }),
+ );
+
+ render(<QuotaAccountManager agentId={'agent-1'} />);
+ await act(async () => answerBindings([binding('b1', 'a1', 'pinned')]));
+
+ expect(checkedOption()).toContain('[email protected]');
+ });
+
+ it('shows hydrated bindings but takes writes only after the server confirms them', async () => {
+ let answerBindings!: (rows: QuotaBinding[]) => void;
+ vi.spyOn(agentQuotaService, 'listBindings').mockImplementation(
+ () => new Promise((resolve) => (answerBindings = resolve)),
+ );
+ // Restored from storage: a1 pinned, but another device has since moved it to the pool.
+ act(() =>
+ useAgentQuotaStore.setState({
+ quotaAccountsMap: { [QUOTA_ACCOUNTS_KEY]: [account('a1')] },
+ quotaBindingsMap: { 'agent-1': [binding('b1', 'a1', 'pinned')] },
+ }),
+ );
+
+ render(<QuotaAccountManager agentId={'agent-1'} />);
+
+ expect(checkedOption()).toContain('[email protected]');
+ expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(true);
+ for (const radio of screen.getAllByRole('radio'))
+ expect(radio.getAttribute('aria-disabled')).toBe('true');
+
+ await act(async () => answerBindings([binding('b1', 'a1', 'pool')]));
+
+ expect(checkedOption()).toContain('heteroAgent.claudeQuota.manage.modeAuto');
+ expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(false);
+ expect(
+ screen
+ .getByRole('radio', { name: /heteroAgent\.claudeQuota\.manage\.modeAuto/ })
+ .getAttribute('aria-disabled'),
+ ).not.toBe('true');
+ });
+
+ it('offers Remove for a hydrated binding only after the server confirms it', async () => {
+ let answerBindings!: (rows: QuotaBinding[]) => void;
+ vi.spyOn(agentQuotaService, 'listBindings').mockImplementation(
+ () => new Promise((resolve) => (answerBindings = resolve)),
+ );
+ act(() =>
+ useAgentQuotaStore.setState({
+ quotaAccountsMap: { [QUOTA_ACCOUNTS_KEY]: [account('a1')] },
+ quotaBindingsMap: { 'agent-1': [binding('stale', 'a1', 'pool')] },
+ }),
+ );
+ const removeItem = () =>
+ screen.findByRole('menuitem', { name: /heteroAgent\.claudeQuota\.manage\.remove/ });
+
+ render(<QuotaAccountManager agentId={'agent-1'} />);
+ fireEvent.click(screen.getByRole('button', { name: 'heteroAgent.claudeQuota.manage.more' }));
+
+ expect((await removeItem()).getAttribute('aria-disabled')).toBe('true');
+
+ await act(async () => answerBindings([binding('b1', 'a1', 'pool')]));
+
+ expect((await removeItem()).getAttribute('aria-disabled')).not.toBe('true');
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx
index c2f4c23d9b4..ea637041c4b 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountManagerModal.tsx
@@ -21,10 +21,17 @@ import {
XIcon,
ZapIcon,
} from 'lucide-react';
-import { memo, type MouseEvent, useCallback, useEffect, useMemo, useState } from 'react';
+import { memo, type MouseEvent, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { agentQuotaService } from '@/services/agentQuota';
+import { cacheScope } from '@/libs/replica';
+import {
+ agentQuotaSelectors,
+ type QuotaAccount,
+ type QuotaBinding,
+ type QuotaLatestReading,
+ useAgentQuotaStore,
+} from '@/store/agentQuota';
const styles = createStaticStyles(({ css }) => ({
footer: css`
@@ -76,9 +83,12 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-type Account = Awaited<ReturnType<typeof agentQuotaService.listAccounts>>[number];
-type Binding = Awaited<ReturnType<typeof agentQuotaService.listBindings>>[number];
-type QuotaReading = Awaited<ReturnType<typeof agentQuotaService.getLatestReadings>>[number];
+type Account = QuotaAccount;
+type Binding = QuotaBinding;
+type QuotaReading = QuotaLatestReading;
+
+const EMPTY_ACCOUNTS: Account[] = [];
+const EMPTY_BINDINGS: Binding[] = [];
const AUTO = 'auto';
@@ -96,11 +106,64 @@ const weeklyLeftOf = (readings: QuotaReading[], now = Date.now()): number | unde
const accountName = (a: Account) => a.label || a.email || a.externalAccountId;
+/** Keeps one account's newest readings in sync while its row is listed. */
+const AccountReadingsSync = memo<{ accountId: string }>(({ accountId }) => {
+ const useFetchQuotaReadings = useAgentQuotaStore((s) => s.useFetchQuotaReadings);
+ useFetchQuotaReadings(accountId);
+ return null;
+});
+
+AccountReadingsSync.displayName = 'AccountReadingsSync';
+
const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
const { t } = useTranslation('chat');
- const [accounts, setAccounts] = useState<Account[]>([]);
- const [bindings, setBindings] = useState<Binding[]>([]);
- const [weeklyById, setWeeklyById] = useState<Record<string, number | undefined>>({});
+ const [
+ useFetchQuotaAccounts,
+ useFetchQuotaBindings,
+ bindQuotaAccount,
+ renameQuotaAccount,
+ switchQuotaAccount,
+ unbindQuotaAccount,
+ ] = useAgentQuotaStore((s) => [
+ s.useFetchQuotaAccounts,
+ s.useFetchQuotaBindings,
+ s.bindQuotaAccount,
+ s.renameQuotaAccount,
+ s.switchQuotaAccount,
+ s.unbindQuotaAccount,
+ ]);
+ const scope = cacheScope.use();
+ const { error: accountsError } = useFetchQuotaAccounts();
+ useFetchQuotaBindings(agentId);
+ // A hydrated empty list may be an outdated snapshot: only the server's answer
+ // (or a failed first read) settles "no accounts yet".
+ const accountsConfirmed = useAgentQuotaStore(agentQuotaSelectors.isAccountsConfirmed(scope));
+ // The replica paints the last-known pool on open; the server confirms behind it.
+ const accounts = useAgentQuotaStore(agentQuotaSelectors.accounts) ?? EMPTY_ACCOUNTS;
+ const loadedBindings = useAgentQuotaStore(agentQuotaSelectors.bindings(agentId));
+ const bindings = loadedBindings ?? EMPTY_BINDINGS;
+ // Until this agent's bindings are on screen, every row would read as "off"
+ // and Auto as routing to nobody: keep the mode and per-account controls
+ // disabled and show no routing hint instead of acting on that guess.
+ const bindingsLoaded = loadedBindings !== undefined;
+ // A hydrated row may be outdated (changed in another tab or on another
+ // device): show it, but take writes only once the server confirmed it, so a
+ // change is computed against the bindings the server actually holds.
+ const bindingsConfirmed = useAgentQuotaStore(
+ agentQuotaSelectors.isBindingsConfirmed(scope, agentId),
+ );
+ const canEditBindings = bindingsLoaded && bindingsConfirmed;
+ const readingsMap = useAgentQuotaStore((s) => s.quotaReadingsMap);
+ const weeklyById = useMemo(
+ () =>
+ Object.fromEntries(
+ accounts.map((a) => {
+ const readings = readingsMap[a.id];
+ return [a.id, readings ? weeklyLeftOf(readings) : undefined] as const;
+ }),
+ ) as Record<string, number | undefined>,
+ [accounts, readingsMap],
+ );
const [busy, setBusy] = useState(false);
// Staged account selection — applied only when the user confirms.
const [pending, setPending] = useState<string | null>(null);
@@ -108,29 +171,6 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
const [editingId, setEditingId] = useState<string | null>(null);
const [editLabel, setEditLabel] = useState('');
- const load = useCallback(async () => {
- const [accs, binds] = await Promise.all([
- agentQuotaService.listAccounts(),
- agentQuotaService.listBindings(agentId),
- ]);
- setAccounts(accs);
- setBindings(binds);
-
- const entries = await Promise.all(
- accs.map(async (a) => {
- const readings = await agentQuotaService
- .getLatestReadings(a.id)
- .catch(() => [] as QuotaReading[]);
- return [a.id, weeklyLeftOf(readings)] as const;
- }),
- );
- setWeeklyById(Object.fromEntries(entries));
- }, [agentId]);
-
- useEffect(() => {
- void load().catch(() => {});
- }, [load]);
-
const roleOf = useCallback(
(accountId: string) => bindings.find((b) => b.accountId === accountId)?.role,
[bindings],
@@ -152,18 +192,15 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
const selected = pending ?? current;
const dirty = pending !== null && pending !== current;
- const run = useCallback(
- async (fn: () => Promise<unknown>) => {
- setBusy(true);
- try {
- await fn();
- await load();
- } finally {
- setBusy(false);
- }
- },
- [load],
- );
+ // Every write lands on the replica optimistically and re-reads its entry.
+ const run = useCallback(async (fn: () => Promise<unknown>) => {
+ setBusy(true);
+ try {
+ await fn();
+ } finally {
+ setBusy(false);
+ }
+ }, []);
// Preview which account Auto would route to (most weekly headroom in the pool).
const routeId = useMemo(() => {
@@ -180,32 +217,33 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
const value = pending;
if (value === null) return;
if (value === AUTO) {
- if (pinnedId) await agentQuotaService.bindAccount(agentId, pinnedId, 'pool');
+ if (pinnedId) await bindQuotaAccount(agentId, pinnedId, 'pool');
} else {
if (!bindings.some((b) => b.accountId === value)) {
- await agentQuotaService.bindAccount(agentId, value, 'pool');
+ await bindQuotaAccount(agentId, value, 'pool');
}
- await agentQuotaService.switchAccount(agentId, value);
+ await switchQuotaAccount(agentId, value);
}
}).then(() => setPending(null)),
- [agentId, bindings, pending, pinnedId, run],
+ [agentId, bindQuotaAccount, bindings, pending, pinnedId, run, switchQuotaAccount],
);
const setRotation = useCallback(
(accountId: string, next: boolean) =>
- run(() => agentQuotaService.bindAccount(agentId, accountId, next ? 'pool' : 'disabled')),
- [agentId, run],
+ run(() => bindQuotaAccount(agentId, accountId, next ? 'pool' : 'disabled')),
+ [agentId, bindQuotaAccount, run],
);
const remove = useCallback(
(accountId: string) => {
- const b = bindingOf(accountId);
+ // An unconfirmed (hydrated) binding id may already be gone on the server.
+ const b = canEditBindings ? bindingOf(accountId) : undefined;
if (!b) return;
// Removing the account currently staged for switch cancels the stage.
if (pending === accountId) setPending(null);
- return run(() => agentQuotaService.unbindAccount(b.id));
+ return run(() => unbindQuotaAccount(agentId, b.id));
},
- [bindingOf, pending, run],
+ [agentId, bindingOf, canEditBindings, pending, run, unbindQuotaAccount],
);
const startEdit = useCallback((a: Account) => {
@@ -214,10 +252,10 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
}, []);
const saveEdit = useCallback(
(accountId: string) =>
- run(() =>
- agentQuotaService.updateAccount(accountId, { label: editLabel.trim() || undefined }),
- ).then(() => setEditingId(null)),
- [editLabel, run],
+ run(() => renameQuotaAccount(accountId, editLabel.trim() || undefined)).then(() =>
+ setEditingId(null),
+ ),
+ [editLabel, renameQuotaAccount, run],
);
const preventRadioSelection = useCallback((event: MouseEvent) => {
@@ -227,18 +265,25 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
return (
<Flexbox gap={2}>
+ {accounts.map((a) => (
+ <AccountReadingsSync accountId={a.id} key={a.id} />
+ ))}
<RadioGroup
className={styles.radioGroup}
gap={2}
horizontal={false}
- value={selected}
+ // Which mode is active is unknown until the bindings are on screen. The
+ // group mounts again once they are, so it starts controlled by the
+ // confirmed mode instead of staying uncontrolled with nothing selected.
+ key={bindingsLoaded ? 'bindings-loaded' : 'bindings-loading'}
+ value={bindingsLoaded ? selected : undefined}
options={[
{
- disabled: busy,
+ disabled: busy || !canEditBindings,
label: (
<Flexbox className={styles.row} gap={4}>
<Text style={{ fontSize: 13 }}>{t('heteroAgent.claudeQuota.manage.modeAuto')}</Text>
- {selected === AUTO && (
+ {bindingsLoaded && selected === AUTO && (
<Flexbox horizontal align={'center'} className={styles.routing} gap={6}>
<Icon icon={ZapIcon} size={14} />
{routeAccount
@@ -266,7 +311,7 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
{ type: 'divider' as const },
{
danger: true,
- disabled: !bindingOf(a.id),
+ disabled: !canEditBindings || !bindingOf(a.id),
icon: <Icon icon={Trash2Icon} />,
key: 'remove',
label: t('heteroAgent.claudeQuota.manage.remove'),
@@ -275,7 +320,7 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
];
return {
- disabled: busy || !rotate || isEditing,
+ disabled: busy || !canEditBindings || !rotate || isEditing,
label: (
<Flexbox
horizontal
@@ -333,7 +378,7 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
<span className={styles.interactive} onClick={preventRadioSelection}>
<Switch
checked={rotate}
- disabled={busy}
+ disabled={busy || !canEditBindings}
size={'small'}
onChange={(v) => void setRotation(a.id, v)}
/>
@@ -358,7 +403,7 @@ const QuotaAccountManager = memo<{ agentId: string }>(({ agentId }) => {
onChange={setPending}
/>
- {accounts.length === 0 && (
+ {accounts.length === 0 && (accountsConfirmed || !!accountsError) && (
<Text className={styles.hint}>{t('heteroAgent.claudeQuota.manage.empty')}</Text>
)}
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
index 2ae9a5377e8..d833a3e33a0 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
@@ -8,11 +8,23 @@ import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { openQuotaCalendarModal } from '@/features/AgentQuotaCalendar';
+import { cacheScope } from '@/libs/replica';
+import { hashQuotaSourceKey, quotaPanelResource } from '@/store/agentQuota/projection';
import ClaudeCodeQuotaMenu from './ClaudeCodeQuotaMenu';
import CodexQuotaMenu from './CodexQuotaMenu';
import KimiCodeQuotaMenu from './KimiCodeQuotaMenu';
-import { codexSnapshot, kimiCodeSnapshot } from './testUtils';
+import { createQuotaSourceKey } from './QuotaMenu';
+import {
+ claudeSnapshot,
+ codexSnapshot,
+ isolateQuotaReplica,
+ kimiCodeSnapshot,
+ liveSessionReading,
+ persistedAccount,
+ persistedSessionReading,
+ waitForQuotaIdle,
+} from './testUtils';
const mockService = vi.hoisted(() => ({
consumeCodexRateLimitResetCredit: vi.fn(),
@@ -180,55 +192,8 @@ vi.mock('@lobehub/ui', async (importOriginal) => {
return merged;
});
-const claudeSnapshot = (
- overrides: Partial<ElectronClientIpcModule.ClaudeCodeQuotaSnapshot> = {},
-): ElectronClientIpcModule.ClaudeCodeQuotaSnapshot => ({
- error: null,
- provider: 'claude-code',
- scopedWeekly: null,
- session: null,
- status: 'ok',
- updatedAt: Date.now(),
- weekly: null,
- ...overrides,
-});
-
-const persistedAccount = (updatedAt = Date.now()) => ({
- externalAccountId: 'ext-1',
- id: 'acc-1',
- provider: 'claude-code',
- updatedAt: new Date(updatedAt),
-});
-
-/** The account's newest persisted session reading, captured at `capturedAt`. */
-const persistedSessionReading = (capturedAt: number) => ({
- capturedAt,
- limitType: 'session',
- resetsAt: null,
- scopeKey: '',
- utilization: 8,
-});
-
-/** A live session reading as fossilized by the desktop sampler at `capturedAt`. */
-const liveSessionReading = (capturedAt: number) => ({
- capturedAt,
- isActive: true,
- limitType: 'session',
- resetsAt: null,
- scopeKey: '',
- utilization: 8,
-});
-
-/** Persisted quota can render before the initial load finishes; focus is ignored while loading. */
-const waitForQuotaIdle = async () => {
- await waitFor(() => expect(screen.getByTestId('refresh').hasAttribute('disabled')).toBe(false));
- // Let the focus listener's effect observe loading=false before dispatching focus.
- await act(async () => {
- await Promise.resolve();
- });
-};
-
beforeEach(() => {
+ isolateQuotaReplica();
confirmModalMock.mockReset();
mockService.consumeCodexRateLimitResetCredit.mockReset();
mockService.getClaudeCodeQuota.mockReset();
@@ -244,11 +209,35 @@ beforeEach(() => {
mockQuotaService.getLatestReadings.mockResolvedValue([]);
mockQuotaService.ingestClaudeSnapshot.mockClear();
mockQuotaService.ingestKimiCodeSnapshot.mockClear();
- mockQuotaService.listAccounts.mockResolvedValue([]);
- mockQuotaService.listBindings.mockResolvedValue([]);
+ mockQuotaService.listAccounts.mockClear().mockResolvedValue([]);
+ mockQuotaService.listBindings.mockClear().mockResolvedValue([]);
vi.mocked(openQuotaCalendarModal).mockClear();
});
+describe('quota panels sharing the account pool', () => {
+ it('send one account / binding read when several panels mount together', async () => {
+ const live = { session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 } };
+ mockService.getClaudeCodeQuota.mockResolvedValue(claudeSnapshot(live));
+ mockService.getCodexQuota.mockResolvedValue(codexSnapshot(live));
+ mockService.getKimiCodeQuota.mockResolvedValue(kimiCodeSnapshot(live));
+
+ render(
+ <>
+ <ClaudeCodeQuotaMenu />
+ <CodexQuotaMenu />
+ <KimiCodeQuotaMenu />
+ </>,
+ );
+
+ for (const name of ['claudeQuota', 'codexQuota', 'kimiCodeQuota']) {
+ const trigger = screen.getByRole('button', { name: `heteroAgent.${name}.tooltip` });
+ await waitFor(() => expect(trigger.textContent).toContain('compactLeft:92'));
+ }
+ expect(mockQuotaService.listAccounts).toHaveBeenCalledTimes(1);
+ expect(mockQuotaService.listBindings).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('KimiCodeQuotaMenu', () => {
it('renders all four windows and the Extra Usage footer from the snapshot', async () => {
mockService.getKimiCodeQuota.mockResolvedValue(
@@ -286,6 +275,64 @@ describe('KimiCodeQuotaMenu', () => {
expect(mockService.getKimiCodeQuota).toHaveBeenCalledWith({ env: undefined });
});
+ it('paints the last snapshot on a remount before the sampler answers', async () => {
+ const live = { session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 } };
+ mockService.getKimiCodeQuota.mockResolvedValueOnce(kimiCodeSnapshot(live));
+ const badge = () => screen.getByRole('button', { name: 'heteroAgent.kimiCodeQuota.tooltip' });
+ const first = render(<KimiCodeQuotaMenu />);
+ await waitFor(() => expect(badge().textContent).toContain('compactLeft:92'));
+ first.unmount();
+
+ // The next sample never answers: the badge can only come from the replica.
+ mockService.getKimiCodeQuota.mockImplementation(() => new Promise(() => {}));
+ render(<KimiCodeQuotaMenu />);
+ await waitFor(() => expect(badge().textContent).toContain('compactLeft:92'));
+ });
+
+ it('keeps the stored snapshot when a reload samples an error before hydration', async () => {
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ const storage = quotaPanelResource.storage!;
+ const sourceKey = createQuotaSourceKey('kimi-code', 'agent-1', undefined, undefined);
+ await storage.set(
+ { queryKey: hashQuotaSourceKey(sourceKey), scope: cacheScope.get() },
+ {
+ data: kimiCodeSnapshot({
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ }),
+ updatedAt: 1,
+ },
+ );
+
+ // Cold reload, offline: the sampler fails while IndexedDB is still answering.
+ let releaseStorage!: () => void;
+ const storageReady = new Promise<void>((resolve) => {
+ releaseStorage = resolve;
+ });
+ const read = storage.get.bind(storage);
+ vi.spyOn(storage, 'get').mockImplementation(async (key) => {
+ await storageReady;
+ return read(key);
+ });
+ mockService.getKimiCodeQuota.mockRejectedValue(new Error('offline'));
+ const badge = () => screen.getByRole('button', { name: 'heteroAgent.kimiCodeQuota.tooltip' });
+
+ render(<KimiCodeQuotaMenu />);
+ await waitFor(() => expect(mockService.getKimiCodeQuota).toHaveBeenCalled());
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ releaseStorage();
+
+ await waitFor(() => expect(badge().textContent).toContain('compactLeft:92'));
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ vi.mocked(storage.get).mockRestore();
+ expect(
+ await storage.get({ queryKey: hashQuotaSourceKey(sourceKey), scope: cacheScope.get() }),
+ ).toMatchObject({ data: { session: { usedPercent: 8 }, status: 'ok' } });
+ });
+
it('omits the monthly cap line when the charge limit is disabled', async () => {
mockService.getKimiCodeQuota.mockResolvedValue(
kimiCodeSnapshot({
@@ -880,6 +927,27 @@ describe('ClaudeCodeQuotaMenu', () => {
expect(mockService.getClaudeCodeQuota).not.toHaveBeenCalled();
});
+ it('keeps the stored snapshot when a cold load of a device fails to sample', async () => {
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ const storage = quotaPanelResource.storage!;
+ const sourceKey = createQuotaSourceKey('claude-code', 'agent-1', 'remote-device', undefined);
+ const row = { queryKey: hashQuotaSourceKey(sourceKey), scope: cacheScope.get() };
+ await storage.set(row, {
+ data: claudeSnapshot({ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 } }),
+ updatedAt: 1,
+ });
+ // No trusted device account yet on a cold load, and the device RPC fails.
+ mockLambdaClaudeQuota.mockRejectedValue(new Error('device offline'));
+
+ render(<ClaudeCodeQuotaMenu deviceId="remote-device" />);
+
+ await waitFor(() => expect(mockLambdaClaudeQuota).toHaveBeenCalled());
+ await waitForQuotaIdle();
+ expect(screen.getAllByText('92%').length).toBeGreaterThan(0);
+ expect(screen.queryByText('heteroAgent.quota.unavailable')).toBeNull();
+ expect(await storage.get(row)).toMatchObject({ data: { status: 'ok' } });
+ });
+
it('does not reuse another device account when the newly selected device is unavailable', async () => {
const capturedAt = Date.now();
const account = persistedAccount();
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx
index f46d1ac8266..dc372233e30 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx
@@ -19,6 +19,12 @@ import type { ReactNode } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import {
+ agentQuotaSelectors,
+ getAgentQuotaStoreState,
+ useAgentQuotaStore,
+} from '@/store/agentQuota';
+
const QUOTA_STALE_MS = 60_000;
const QUOTA_RETRY_COOLDOWN_MS = 60_000;
@@ -162,6 +168,11 @@ export const createQuotaSourceKey = (...parts: QuotaSourcePart[]) =>
export interface QuotaSnapshotBase {
error: string | null;
+ /**
+ * The live sample failed (transport / IPC) instead of reporting a state: the
+ * panel treats it like an error and keeps the last good snapshot.
+ */
+ sampleFailed?: boolean;
status: 'error' | 'ok' | 'unavailable';
updatedAt: number;
}
@@ -240,6 +251,14 @@ interface LoadQuotaOptions {
revalidate?: boolean;
}
+interface PendingQuotaError<S> {
+ nextQuota: S;
+ options: LoadQuotaOptions;
+ requestContext?: string;
+ requestId: number;
+ requestSourceKey: string;
+}
+
/**
* Shared quota popover for local CLI agents: gauge trigger with the tightest
* remaining percent in each compact group, plus per-window progress bars and
@@ -265,13 +284,27 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
const { t } = useTranslation('chat');
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
- const [quota, setQuota] = useState<S | null>(null);
+ // The last snapshot of this source lives in the agentQuota replica: a reload
+ // or a remount paints it (with its "updated N ago" line) before the sampler
+ // answers, and every applied sample is written back to it.
+ const useHydrateQuotaPanel = useAgentQuotaStore((s) => s.useHydrateQuotaPanel);
+ const { isHydrated } = useHydrateQuotaPanel(sourceKey);
+ const quota = (useAgentQuotaStore(agentQuotaSelectors.panel(sourceKey)) as S | undefined) ?? null;
const [refreshError, setRefreshError] = useState<S | null>(null);
const [now, setNow] = useState(() => Date.now());
const lastTransientErrorAtRef = useRef(0);
- const quotaRef = useRef<S | null>(null);
const requestIdRef = useRef(0);
const sourceKeyRef = useRef(sourceKey);
+ const isHydratedRef = useRef(isHydrated);
+ /** An error sampled before the stored snapshot hydrated, applied once it has. */
+ const pendingErrorRef = useRef<PendingQuotaError<S> | null>(null);
+
+ /** What the panel of `key` shows now, read outside render. */
+ const readQuota = useCallback(
+ (key: string) =>
+ (agentQuotaSelectors.panel(key)(getAgentQuotaStoreState()) as S | undefined) ?? null,
+ [],
+ );
const hasQuotaDataForSnapshot = useCallback(
(snapshot: S | null) => {
@@ -282,10 +315,12 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
[getWindows, hasExtraData],
);
- const setQuotaSnapshot = useCallback((nextQuota: S) => {
- quotaRef.current = nextQuota;
- setQuota(nextQuota);
- }, []);
+ const setQuotaSnapshot = useCallback(
+ (nextQuota: S, key: string = sourceKeyRef.current, context?: string) => {
+ getAgentQuotaStoreState().setQuotaPanel(key, nextQuota, context);
+ },
+ [],
+ );
const applyQuota = useCallback(
(nextQuota: S) => {
@@ -313,13 +348,29 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
options: LoadQuotaOptions = {},
requestId = requestIdRef.current,
requestSourceKey = sourceKeyRef.current,
+ requestContext?: string,
) => {
if (!isCurrentRequest(requestId, requestSourceKey)) return;
- if (nextQuota.status === 'error') {
+ if (nextQuota.status === 'error' || nextQuota.sampleFailed) {
lastTransientErrorAtRef.current = Date.now();
- if (hasQuotaDataForSnapshot(quotaRef.current)) {
+ // Writing the error before the stored snapshot hydrated would make the
+ // replica ignore that snapshot and drop its stored row: hold the error
+ // until hydration settles, then judge it against what was restored.
+ if (!isHydratedRef.current) {
+ pendingErrorRef.current = {
+ nextQuota,
+ options,
+ requestId,
+ requestContext,
+ requestSourceKey,
+ };
+ return;
+ }
+
+ // A failed refresh keeps the last good snapshot on screen (and in storage).
+ if (hasQuotaDataForSnapshot(readQuota(requestSourceKey))) {
if (options.manual) setRefreshError(nextQuota);
return;
}
@@ -328,14 +379,17 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
}
setRefreshError(null);
- setQuotaSnapshot(nextQuota);
+ setQuotaSnapshot(nextQuota, requestSourceKey, requestContext);
},
- [hasQuotaDataForSnapshot, isCurrentRequest, setQuotaSnapshot],
+ [hasQuotaDataForSnapshot, isCurrentRequest, readQuota, setQuotaSnapshot],
);
const loadQuota = useCallback(
async (options: LoadQuotaOptions = {}) => {
const requestSourceKey = sourceKeyRef.current;
+ // A sample started under one identity (or before a user-data reset) must
+ // not land in another data context's replica.
+ const requestContext = getAgentQuotaStoreState().getQuotaContext();
const requestId = requestIdRef.current + 1;
requestIdRef.current = requestId;
@@ -350,13 +404,19 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
// Progressive paint: show the fast (persisted) snapshot while the
// live refresh continues; requestId still guards stale sources.
if (!isCurrentRequest(requestId, requestSourceKey)) return;
- setQuotaSnapshot(interimQuota);
+ setQuotaSnapshot(interimQuota, requestSourceKey, requestContext);
},
});
- applyQuotaResult(nextQuota, options, requestId, requestSourceKey);
+ applyQuotaResult(nextQuota, options, requestId, requestSourceKey, requestContext);
} catch (error) {
console.error('Failed to fetch agent quota:', error);
- applyQuotaResult(createErrorSnapshot(error), options, requestId, requestSourceKey);
+ applyQuotaResult(
+ createErrorSnapshot(error),
+ options,
+ requestId,
+ requestSourceKey,
+ requestContext,
+ );
} finally {
if (isCurrentRequest(requestId, requestSourceKey)) {
setLoading(false);
@@ -368,9 +428,7 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
useEffect(() => {
sourceKeyRef.current = sourceKey;
- quotaRef.current = null;
lastTransientErrorAtRef.current = 0;
- setQuota(null);
setRefreshError(null);
}, [sourceKey]);
@@ -378,6 +436,20 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
void loadQuota();
}, [loadQuota, sourceKey]);
+ useEffect(() => {
+ isHydratedRef.current = isHydrated;
+ const pending = pendingErrorRef.current;
+ if (!isHydrated || !pending) return;
+ pendingErrorRef.current = null;
+ applyQuotaResult(
+ pending.nextQuota,
+ pending.options,
+ pending.requestId,
+ pending.requestSourceKey,
+ pending.requestContext,
+ );
+ }, [applyQuotaResult, isHydrated]);
+
useEffect(() => {
const interval = window.setInterval(() => setNow(Date.now()), QUOTA_STALE_MS);
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/testUtils.ts b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/testUtils.ts
index a22ae52f16e..b5a34ca30bd 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/testUtils.ts
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/testUtils.ts
@@ -1,5 +1,22 @@
import type * as ElectronClientIpcModule from '@lobechat/electron-client-ipc';
import type { KimiCodeQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';
+import { act, screen, waitFor } from '@testing-library/react';
+import { expect, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { useAgentQuotaStore } from '@/store/agentQuota';
+import { initialState } from '@/store/agentQuota/initialState';
+
+/**
+ * Start a case like a first launch: its own identity partition and an empty
+ * in-memory replica, so no panel snapshot leaks between cases.
+ */
+export const isolateQuotaReplica = () => {
+ const scope = `quota-menu-${Math.random().toString(36).slice(2)}:personal`;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ act(() => useAgentQuotaStore.setState(initialState, false));
+};
export const codexSnapshot = (
overrides: Partial<ElectronClientIpcModule.CodexQuotaSnapshot> = {},
@@ -28,3 +45,51 @@ export const kimiCodeSnapshot = (
weekly: null,
...overrides,
});
+
+export const claudeSnapshot = (
+ overrides: Partial<ElectronClientIpcModule.ClaudeCodeQuotaSnapshot> = {},
+): ElectronClientIpcModule.ClaudeCodeQuotaSnapshot => ({
+ error: null,
+ provider: 'claude-code',
+ scopedWeekly: null,
+ session: null,
+ status: 'ok',
+ updatedAt: Date.now(),
+ weekly: null,
+ ...overrides,
+});
+
+export const persistedAccount = (updatedAt = Date.now()) => ({
+ externalAccountId: 'ext-1',
+ id: 'acc-1',
+ provider: 'claude-code',
+ updatedAt: new Date(updatedAt),
+});
+
+/** The account's newest persisted session reading, captured at `capturedAt`. */
+export const persistedSessionReading = (capturedAt: number) => ({
+ capturedAt,
+ limitType: 'session',
+ resetsAt: null,
+ scopeKey: '',
+ utilization: 8,
+});
+
+/** A live session reading as fossilized by the desktop sampler at `capturedAt`. */
+export const liveSessionReading = (capturedAt: number) => ({
+ capturedAt,
+ isActive: true,
+ limitType: 'session',
+ resetsAt: null,
+ scopeKey: '',
+ utilization: 8,
+});
+
+/** Persisted quota can render before the initial load finishes; focus is ignored while loading. */
+export const waitForQuotaIdle = async () => {
+ await waitFor(() => expect(screen.getByTestId('refresh').hasAttribute('disabled')).toBe(false));
+ // Let the focus listener's effect observe loading=false before dispatching focus.
+ await act(async () => {
+ await Promise.resolve();
+ });
+};
diff --git a/src/services/codexQuota.test.ts b/src/services/codexQuota.test.ts
index 30378191789..cc94218d481 100644
--- a/src/services/codexQuota.test.ts
+++ b/src/services/codexQuota.test.ts
@@ -1,5 +1,8 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { useAgentQuotaStore } from '@/store/agentQuota';
+import { initialState } from '@/store/agentQuota/initialState';
+
import { agentQuotaService } from './agentQuota';
import { createCodexQuotaReader } from './codexQuota';
import { heterogeneousAgentService } from './electron/heterogeneousAgent';
@@ -44,6 +47,9 @@ const sample = {
beforeEach(() => {
vi.resetAllMocks();
+ // Reads go through the global quota replica: start every case without the
+ // previous case's accounts / readings (they would answer inside the dedupe window).
+ useAgentQuotaStore.setState(initialState, false);
vi.mocked(agentQuotaService.listAccounts).mockResolvedValue([account] as never);
vi.mocked(agentQuotaService.listBindings).mockResolvedValue([]);
vi.mocked(agentQuotaService.getLatestReadings).mockResolvedValue([reading]);
@@ -117,4 +123,21 @@ describe('account-scoped Codex quota', () => {
expect(result.identity?.externalAccountId).toBe('external-b');
expect(result.session?.usedPercent).toBe(80);
});
+
+ it('refreshes the quota replica after accepting a local snapshot', async () => {
+ const first = createCodexQuotaReader({});
+ expect((await first({})).session?.usedPercent).toBe(23);
+
+ // A reset lands locally and is ingested; the server now holds the new reading.
+ const resetReading = { ...reading, capturedAt: Date.now() + 1, utilization: 0 };
+ vi.mocked(agentQuotaService.getLatestReadings).mockResolvedValue([resetReading]);
+ await first.acceptLocalSnapshot({
+ ...sample,
+ readings: [resetReading],
+ session: { ...sample.session, usedPercent: 0 },
+ });
+
+ // A reader mounted right after (inside the dedupe window) must not repaint the old reading.
+ expect((await createCodexQuotaReader({})({})).session?.usedPercent).toBe(0);
+ });
});
diff --git a/src/services/codexQuota.ts b/src/services/codexQuota.ts
index 21b2caf02e0..ac3708947d5 100644
--- a/src/services/codexQuota.ts
+++ b/src/services/codexQuota.ts
@@ -1,5 +1,7 @@
import type { CodexQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';
+import { getAgentQuotaStoreState } from '@/store/agentQuota';
+
import { agentQuotaService } from './agentQuota';
import { buildCodexPanelSnapshot } from './codexQuotaViewModel';
import { heterogeneousAgentService } from './electron/heterogeneousAgent';
@@ -19,6 +21,8 @@ interface FetchOptions {
revalidate?: boolean;
}
+const quotaReads = () => getAgentQuotaStoreState();
+
const readPersisted = async <T>(request: Promise<T>, fallback: T): Promise<T> => {
try {
return await request;
@@ -34,8 +38,8 @@ export const createCodexQuotaReader = (source: CodexQuotaSource) => {
let lastLive: CodexQuotaSnapshot | null = null;
const readQuota = async (options: FetchOptions = {}): Promise<CodexQuotaSnapshot> => {
const [allAccounts, bindings] = await Promise.all([
- readPersisted(agentQuotaService.listAccounts(), []),
- source.agentId ? readPersisted(agentQuotaService.listBindings(source.agentId), []) : [],
+ readPersisted(quotaReads().readQuotaAccounts(), []),
+ source.agentId ? readPersisted(quotaReads().readQuotaBindings(source.agentId), []) : [],
]);
const accounts = allAccounts.filter((account) => account.provider === 'codex');
const pinnedId = bindings.find((binding) => binding.role === 'pinned')?.accountId;
@@ -46,7 +50,7 @@ export const createCodexQuotaReader = (source: CodexQuotaSource) => {
accounts.find((item) => item.id === pinnedId) ??
accounts[0]);
let readings = account
- ? await readPersisted(agentQuotaService.getLatestReadings(account.id), [])
+ ? await readPersisted(quotaReads().readQuotaReadings(account.id), [])
: [];
const persisted =
account && readings.length ? buildCodexPanelSnapshot(account, readings, lastLive) : null;
@@ -75,13 +79,12 @@ export const createCodexQuotaReader = (source: CodexQuotaSource) => {
throw error;
}
if (live?.status === 'ok') lastLive = live;
+ let ingested = false;
const externalAccountId = live?.identity?.externalAccountId;
if (live?.status === 'ok' && externalAccountId) {
trustedAccountId = externalAccountId;
account = accounts.find((item) => item.externalAccountId === externalAccountId);
- readings = account
- ? await readPersisted(agentQuotaService.getLatestReadings(account.id), [])
- : [];
+ readings = account ? await readPersisted(quotaReads().readQuotaReadings(account.id), []) : [];
const fresh = live.readings?.filter(
(reading) =>
!readings.some(
@@ -93,21 +96,29 @@ export const createCodexQuotaReader = (source: CodexQuotaSource) => {
);
if (!source.deviceId && fresh?.length) {
try {
+ ingested = true;
account = await agentQuotaService.ingestCodexSnapshot({
identity: live.identity!,
readings: fresh,
});
+ // The ingest moved the account's `updatedAt` (and may have created it).
+ void readPersisted(quotaReads().readQuotaAccounts({ fresh: true }), []);
} catch (error) {
console.error('[codexQuota:ingest]', error);
}
}
if (source.deviceId && !account) {
- account = (await readPersisted(agentQuotaService.listAccounts(), [])).find(
+ account = (await readPersisted(quotaReads().readQuotaAccounts({ fresh: true }), [])).find(
(item) => item.provider === 'codex' && item.externalAccountId === externalAccountId,
);
}
+ // The device sampler ingests server-side, and a local ingest just wrote
+ // new readings: both make the replica's copy outdated.
if (account)
- readings = await readPersisted(agentQuotaService.getLatestReadings(account.id), []);
+ readings = await readPersisted(
+ quotaReads().readQuotaReadings(account.id, { fresh: !!source.deviceId || ingested }),
+ [],
+ );
} else if (live?.status === 'ok') {
// A successful but unidentified login must not inherit the previous account.
trustedAccountId = undefined;
@@ -136,10 +147,18 @@ export const createCodexQuotaReader = (source: CodexQuotaSource) => {
snapshot.readings?.length
) {
trustedAccountId = snapshot.identity.externalAccountId;
- await agentQuotaService.ingestCodexSnapshot({
+ const account = await agentQuotaService.ingestCodexSnapshot({
identity: snapshot.identity,
readings: snapshot.readings,
});
+ // The replica still holds the pre-ingest account / readings: refresh both,
+ // so a reader mounted inside the dedupe window does not paint them again.
+ await Promise.all([
+ readPersisted(quotaReads().readQuotaAccounts({ fresh: true }), []),
+ account?.id
+ ? readPersisted(quotaReads().readQuotaReadings(account.id, { fresh: true }), [])
+ : undefined,
+ ]);
}
},
});
diff --git a/src/services/kimiCodeQuota.test.ts b/src/services/kimiCodeQuota.test.ts
index f83d2b8d6a8..49fc4556730 100644
--- a/src/services/kimiCodeQuota.test.ts
+++ b/src/services/kimiCodeQuota.test.ts
@@ -1,5 +1,8 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { useAgentQuotaStore } from '@/store/agentQuota';
+import { initialState } from '@/store/agentQuota/initialState';
+
import { agentQuotaService } from './agentQuota';
import { heterogeneousAgentService } from './electron/heterogeneousAgent';
import { createKimiCodeQuotaReader } from './kimiCodeQuota';
@@ -47,6 +50,9 @@ const sample = {
beforeEach(() => {
vi.resetAllMocks();
+ // Reads go through the global quota replica: start every case without the
+ // previous case's accounts / readings (they would answer inside the dedupe window).
+ useAgentQuotaStore.setState(initialState, false);
vi.mocked(agentQuotaService.listAccounts).mockResolvedValue([account] as never);
vi.mocked(agentQuotaService.listBindings).mockResolvedValue([]);
vi.mocked(agentQuotaService.getLatestReadings).mockResolvedValue([reading]);
@@ -158,4 +164,21 @@ describe('account-scoped Kimi Code quota', () => {
expect(result.identity?.externalAccountId).toBe('external-b');
expect(result.session?.usedPercent).toBe(80);
});
+
+ it('refreshes the quota replica after accepting a local snapshot', async () => {
+ const first = createKimiCodeQuotaReader({});
+ expect((await first({})).session?.usedPercent).toBe(23);
+
+ // A reset lands locally and is ingested; the server now holds the new reading.
+ const resetReading = { ...reading, capturedAt: Date.now() + 1, utilization: 0 };
+ vi.mocked(agentQuotaService.getLatestReadings).mockResolvedValue([resetReading]);
+ await first.acceptLocalSnapshot({
+ ...sample,
+ readings: [resetReading],
+ session: { ...sample.session, usedPercent: 0 },
+ });
+
+ // A reader mounted right after (inside the dedupe window) must not repaint the old reading.
+ expect((await createKimiCodeQuotaReader({})({})).session?.usedPercent).toBe(0);
+ });
});
diff --git a/src/services/kimiCodeQuota.ts b/src/services/kimiCodeQuota.ts
index 18e3013d7ee..bb86f533b15 100644
--- a/src/services/kimiCodeQuota.ts
+++ b/src/services/kimiCodeQuota.ts
@@ -1,5 +1,7 @@
import type { KimiCodeQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';
+import { getAgentQuotaStoreState } from '@/store/agentQuota';
+
import { agentQuotaService } from './agentQuota';
import { heterogeneousAgentService } from './electron/heterogeneousAgent';
import { buildKimiCodePanelSnapshot } from './kimiCodeQuotaViewModel';
@@ -18,6 +20,8 @@ interface FetchOptions {
revalidate?: boolean;
}
+const quotaReads = () => getAgentQuotaStoreState();
+
const readPersisted = async <T>(request: Promise<T>, fallback: T): Promise<T> => {
try {
return await request;
@@ -33,8 +37,8 @@ export const createKimiCodeQuotaReader = (source: KimiCodeQuotaSource) => {
let lastLive: KimiCodeQuotaSnapshot | null = null;
const readQuota = async (options: FetchOptions = {}): Promise<KimiCodeQuotaSnapshot> => {
const [allAccounts, bindings] = await Promise.all([
- readPersisted(agentQuotaService.listAccounts(), []),
- source.agentId ? readPersisted(agentQuotaService.listBindings(source.agentId), []) : [],
+ readPersisted(quotaReads().readQuotaAccounts(), []),
+ source.agentId ? readPersisted(quotaReads().readQuotaBindings(source.agentId), []) : [],
]);
const accounts = allAccounts.filter((account) => account.provider === 'kimi-code');
const pinnedId = bindings.find((binding) => binding.role === 'pinned')?.accountId;
@@ -45,7 +49,7 @@ export const createKimiCodeQuotaReader = (source: KimiCodeQuotaSource) => {
accounts.find((item) => item.id === pinnedId) ??
accounts[0]);
let readings = account
- ? await readPersisted(agentQuotaService.getLatestReadings(account.id), [])
+ ? await readPersisted(quotaReads().readQuotaReadings(account.id), [])
: [];
const persisted =
account && readings.length ? buildKimiCodePanelSnapshot(account, readings, lastLive) : null;
@@ -72,13 +76,12 @@ export const createKimiCodeQuotaReader = (source: KimiCodeQuotaSource) => {
throw error;
}
if (live?.status === 'ok') lastLive = live;
+ let ingested = false;
const externalAccountId = live?.identity?.externalAccountId;
if (live?.status === 'ok' && externalAccountId) {
trustedAccountId = externalAccountId;
account = accounts.find((item) => item.externalAccountId === externalAccountId);
- readings = account
- ? await readPersisted(agentQuotaService.getLatestReadings(account.id), [])
- : [];
+ readings = account ? await readPersisted(quotaReads().readQuotaReadings(account.id), []) : [];
const fresh = live.readings?.filter(
(reading) =>
!readings.some(
@@ -92,22 +95,30 @@ export const createKimiCodeQuotaReader = (source: KimiCodeQuotaSource) => {
// moves independently of the limit windows.
if (!source.deviceId && (fresh?.length || live.extraUsage)) {
try {
+ ingested = true;
account = await agentQuotaService.ingestKimiCodeSnapshot({
extraUsage: live.extraUsage,
identity: live.identity!,
readings: fresh ?? [],
});
+ // The ingest moved the account's `updatedAt` (and may have created it).
+ void readPersisted(quotaReads().readQuotaAccounts({ fresh: true }), []);
} catch (error) {
console.error('[kimiCodeQuota:ingest]', error);
}
}
if (source.deviceId && !account) {
- account = (await readPersisted(agentQuotaService.listAccounts(), [])).find(
+ account = (await readPersisted(quotaReads().readQuotaAccounts({ fresh: true }), [])).find(
(item) => item.provider === 'kimi-code' && item.externalAccountId === externalAccountId,
);
}
+ // The device sampler ingests server-side, and a local ingest just wrote
+ // new readings: both make the replica's copy outdated.
if (account)
- readings = await readPersisted(agentQuotaService.getLatestReadings(account.id), []);
+ readings = await readPersisted(
+ quotaReads().readQuotaReadings(account.id, { fresh: !!source.deviceId || ingested }),
+ [],
+ );
} else if (live?.status === 'ok') {
// A successful but unidentified login must not inherit the previous account.
trustedAccountId = undefined;
@@ -143,11 +154,19 @@ export const createKimiCodeQuotaReader = (source: KimiCodeQuotaSource) => {
snapshot.readings?.length
) {
trustedAccountId = snapshot.identity.externalAccountId;
- await agentQuotaService.ingestKimiCodeSnapshot({
+ const account = await agentQuotaService.ingestKimiCodeSnapshot({
extraUsage: snapshot.extraUsage,
identity: snapshot.identity,
readings: snapshot.readings,
});
+ // The replica still holds the pre-ingest account / readings: refresh both,
+ // so a reader mounted inside the dedupe window does not paint them again.
+ await Promise.all([
+ readPersisted(quotaReads().readQuotaAccounts({ fresh: true }), []),
+ account?.id
+ ? readPersisted(quotaReads().readQuotaReadings(account.id, { fresh: true }), [])
+ : undefined,
+ ]);
}
},
});
diff --git a/src/store/agentQuota/action.ts b/src/store/agentQuota/action.ts
new file mode 100644
index 00000000000..eaf3a3c018f
--- /dev/null
+++ b/src/store/agentQuota/action.ts
@@ -0,0 +1,433 @@
+import isEqual from 'fast-deep-equal';
+import { type StateCreator } from 'zustand';
+
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
+import { agentQuotaService } from '@/services/agentQuota';
+import { type StoreSetter } from '@/store/types';
+import { flattenActions } from '@/store/utils/flattenActions';
+
+import { initialState, type State } from './initialState';
+import {
+ hashQuotaSourceKey,
+ QUOTA_ACCOUNTS_KEY,
+ QUOTA_HISTORY_DAYS,
+ QUOTA_HISTORY_WINDOW_LIMIT,
+ type QuotaAccount,
+ quotaAccountsResource,
+ type QuotaBinding,
+ quotaBindingsResource,
+ type QuotaHistory,
+ type QuotaHistoryFetched,
+ quotaHistoryResource,
+ type QuotaLatestReading,
+ quotaPanelResource,
+ type QuotaPanelSnapshot,
+ quotaReadingsResource,
+ toPersistedQuotaAccounts,
+ toPersistedQuotaPanel,
+} from './projection';
+
+export type Action = Pick<ActionImpl, keyof ActionImpl>;
+export type Store = State & Action;
+
+type Setter = StoreSetter<Store>;
+
+/**
+ * Panels, the account manager and the calendar all read the same account list
+ * and readings. A read inside this window answers from the replica instead of
+ * sending another request; writes and explicit refreshes pass `fresh`.
+ */
+export const QUOTA_READ_DEDUPE_MS = 10_000;
+
+type QuotaResourceName = 'accounts' | 'bindings' | 'history' | 'readings';
+
+interface ReadOptions {
+ /** Skip the dedupe window and retire older requests (after a write / ingest). */
+ fresh?: boolean;
+}
+
+/** Where a settled server answer was captured (`ReplicaEffects` context). */
+interface SettleContext {
+ key: string;
+ scope: string;
+}
+
+export const quotaConfirmedKey = (scope: string, resource: QuotaResourceName, key: string) =>
+ `${scope}|${resource}|${key}`;
+
+const sameValue = <T>(incoming: T, confirmed: T | undefined) =>
+ isEqual(incoming, confirmed) ? undefined : incoming;
+
+const upsertBinding = (bindings: QuotaBinding[], row: QuotaBinding) =>
+ bindings.some((binding) => binding.id === row.id || binding.accountId === row.accountId)
+ ? bindings.map((binding) =>
+ binding.id === row.id || binding.accountId === row.accountId ? row : binding,
+ )
+ : [...bindings, row];
+
+/**
+ * Agent quota (coding agent subscription accounts): the account pool, each
+ * agent's bindings, each account's newest readings and calendar history, plus
+ * the last snapshot every quota panel rendered. All of it paints from the
+ * local replica on a reload and converges on the server in the background.
+ */
+export class ActionImpl {
+ readonly #get: () => Store;
+ readonly #set: Setter;
+ readonly #accounts;
+ readonly #bindings;
+ readonly #readings;
+ readonly #history;
+ readonly #panel;
+ /** When each `<scope>|<resource>|<key>` last applied a server answer. */
+ readonly #appliedAt = new Map<string, number>();
+ /** Advanced by every `reset()`, so a live panel sample from before it is dropped. */
+ #resetGeneration = 0;
+
+ constructor(set: Setter, get: () => Store, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+
+ const confirmOn = (resource: QuotaResourceName) => ({
+ onApplied: (_data: unknown, _params: unknown, context: SettleContext) =>
+ this.#markApplied(resource, context),
+ });
+
+ this.#accounts = createReplicaSlice(quotaAccountsResource, {
+ actionPrefix: 'quotaAccounts',
+ effects: confirmOn('accounts'),
+ fetcher: () => agentQuotaService.listAccounts(),
+ get,
+ merge: sameValue,
+ set,
+ stateKey: 'quotaAccountsReplica',
+ toPersisted: toPersistedQuotaAccounts,
+ view: recordLens<Store, QuotaAccount[]>('quotaAccountsMap'),
+ });
+ this.#bindings = createReplicaSlice(quotaBindingsResource, {
+ actionPrefix: 'quotaBindings',
+ effects: confirmOn('bindings'),
+ fetcher: (agentId) => agentQuotaService.listBindings(agentId),
+ get,
+ merge: sameValue,
+ set,
+ stateKey: 'quotaBindingsReplica',
+ view: recordLens<Store, QuotaBinding[]>('quotaBindingsMap'),
+ });
+ this.#readings = createReplicaSlice(quotaReadingsResource, {
+ actionPrefix: 'quotaReadings',
+ effects: confirmOn('readings'),
+ fetcher: (accountId) => agentQuotaService.getLatestReadings(accountId),
+ get,
+ merge: sameValue,
+ set,
+ stateKey: 'quotaReadingsReplica',
+ view: recordLens<Store, QuotaLatestReading[]>('quotaReadingsMap'),
+ });
+ this.#history = createReplicaSlice(quotaHistoryResource, {
+ actionPrefix: 'quotaHistory',
+ effects: confirmOn('history'),
+ fetcher: async (accountId): Promise<QuotaHistoryFetched> => {
+ const [windows, snapshots, usageTurns] = await Promise.allSettled([
+ agentQuotaService.getWindows(accountId, QUOTA_HISTORY_WINDOW_LIMIT),
+ agentQuotaService.listSnapshots(accountId, QUOTA_HISTORY_DAYS),
+ agentQuotaService.listUsageTurns(accountId, QUOTA_HISTORY_DAYS),
+ ]);
+ // Nothing answered: fail the refresh so the last history stays on screen.
+ if ([windows, snapshots, usageTurns].every((result) => result.status === 'rejected'))
+ throw (windows as PromiseRejectedResult).reason;
+ // A part that failed stays `undefined`; `merge` keeps its last confirmed value.
+ return {
+ snapshots: snapshots.status === 'fulfilled' ? snapshots.value : undefined,
+ usageTurns: usageTurns.status === 'fulfilled' ? usageTurns.value : undefined,
+ windows: windows.status === 'fulfilled' ? windows.value : undefined,
+ };
+ },
+ get,
+ // One part failing keeps the parts that answered, and that part's last
+ // confirmed value (or nothing on a first read).
+ merge: (incoming, confirmed) =>
+ sameValue<QuotaHistory>(
+ {
+ snapshots: incoming.snapshots ?? confirmed?.snapshots ?? [],
+ usageTurns: incoming.usageTurns ?? confirmed?.usageTurns ?? [],
+ windows: incoming.windows ?? confirmed?.windows ?? [],
+ },
+ confirmed,
+ ),
+ set,
+ stateKey: 'quotaHistoryReplica',
+ view: recordLens<Store, QuotaHistory>('quotaHistoryMap'),
+ });
+ this.#panel = createReplicaSlice(quotaPanelResource, {
+ actionPrefix: 'quotaPanel',
+ get,
+ set,
+ stateKey: 'quotaPanelReplica',
+ toPersisted: toPersistedQuotaPanel,
+ view: recordLens<Store, QuotaPanelSnapshot>('quotaPanelMap'),
+ });
+ }
+
+ // ---- sync hooks (fetch orchestration only; data comes from selectors) ----
+
+ useFetchQuotaAccounts = (enabled = true): ReplicaSyncResult =>
+ this.#accounts.useSync(
+ enabled ? QUOTA_ACCOUNTS_KEY : null,
+ this.#syncOptions('accounts', QUOTA_ACCOUNTS_KEY),
+ );
+
+ useFetchQuotaBindings = (agentId?: string | null): ReplicaSyncResult =>
+ this.#bindings.useSync(agentId || null, this.#syncOptions('bindings', agentId));
+
+ useFetchQuotaReadings = (accountId?: string | null): ReplicaSyncResult =>
+ this.#readings.useSync(accountId || null, this.#syncOptions('readings', accountId));
+
+ useFetchQuotaHistory = (accountId?: string | null): ReplicaSyncResult =>
+ this.#history.useSync(accountId || null, this.#syncOptions('history', accountId));
+
+ /**
+ * Hydrate the last snapshot a quota panel rendered for `sourceKey`. The panel
+ * samples live quota itself (desktop IPC / device RPC), so this replica has
+ * no fetcher: it only paints from storage and persists what the panel writes
+ * back through `setQuotaPanel`.
+ */
+ useHydrateQuotaPanel = (sourceKey: string): ReplicaSyncResult =>
+ this.#panel.useSync(hashQuotaSourceKey(sourceKey));
+
+ /**
+ * The data context a panel sample is captured under: the identity (user +
+ * workspace) plus the reset generation, since a desktop `refreshUserData` /
+ * `disconnectRemoteServer` can change the context without changing the scope.
+ */
+ getQuotaContext = (): string => `${quotaPanelResource.scope.get()}\u0000${this.#resetGeneration}`;
+
+ /** Record what a panel now shows; a sample started under another data context is dropped. */
+ setQuotaPanel = (
+ sourceKey: string,
+ snapshot: QuotaPanelSnapshot,
+ context = this.getQuotaContext(),
+ ): void => {
+ if (context !== this.getQuotaContext()) return;
+ this.#panel.update(hashQuotaSourceKey(sourceKey), () => snapshot);
+ };
+
+ // ---- reads for the live samplers (no view mounted) ----
+
+ readQuotaAccounts = (options?: ReadOptions): Promise<QuotaAccount[]> =>
+ this.#read('accounts', this.#accounts, QUOTA_ACCOUNTS_KEY, 'quotaAccountsMap', options);
+
+ readQuotaBindings = (agentId: string, options?: ReadOptions): Promise<QuotaBinding[]> =>
+ this.#read('bindings', this.#bindings, agentId, 'quotaBindingsMap', options);
+
+ /**
+ * A `fresh` readings read follows an ingest (local, device-side or a reset),
+ * which also appended to the account's snapshot series and windows: refresh a
+ * loaded calendar history too instead of leaving it a dedupe window behind.
+ */
+ readQuotaReadings = (accountId: string, options?: ReadOptions): Promise<QuotaLatestReading[]> => {
+ if (options?.fresh && this.#get().quotaHistoryMap[accountId] !== undefined)
+ void this.#refresh(this.#history, accountId);
+ return this.#read('readings', this.#readings, accountId, 'quotaReadingsMap', options);
+ };
+
+ // ---- writes (account manager) ----
+
+ /** Pin one account for an agent (Manual mode); any previous pin drops back to the pool. */
+ switchQuotaAccount = async (agentId: string, accountId: string): Promise<void> => {
+ const loading = this.#ensureBindings(agentId);
+ if (loading) await loading;
+ await this.#bindings.optimistic(
+ agentId,
+ (bindings) =>
+ bindings.map((binding) =>
+ binding.accountId === accountId
+ ? { ...binding, role: 'pinned' }
+ : binding.role === 'pinned'
+ ? { ...binding, role: 'pool' }
+ : binding,
+ ),
+ () => agentQuotaService.switchAccount(agentId, accountId),
+ );
+ await this.#refresh(this.#bindings, agentId);
+ };
+
+ /** Add an account to an agent's pool, or change its role there. */
+ bindQuotaAccount = async (
+ agentId: string,
+ accountId: string,
+ role: 'pinned' | 'pool' | 'disabled',
+ ): Promise<void> => {
+ const loading = this.#ensureBindings(agentId);
+ if (loading) await loading;
+ await this.#bindings.optimistic(
+ agentId,
+ (bindings) =>
+ bindings.map((binding) =>
+ binding.accountId === accountId ? { ...binding, role } : binding,
+ ),
+ () => agentQuotaService.bindAccount(agentId, accountId, role),
+ {
+ // The upserted row is the confirmed value, also for an account that had no binding yet.
+ confirm: (row) => (bindings) => (row ? upsertBinding(bindings, row) : bindings),
+ },
+ );
+ await this.#refresh(this.#bindings, agentId);
+ };
+
+ /** Drop an account from an agent's pool; the row leaves the replica and its stored copy. */
+ unbindQuotaAccount = async (agentId: string, bindingId: string): Promise<void> => {
+ const loading = this.#ensureBindings(agentId);
+ if (loading) await loading;
+ await this.#bindings.optimistic(
+ agentId,
+ (bindings) => bindings.filter((binding) => binding.id !== bindingId),
+ () => agentQuotaService.unbindAccount(bindingId),
+ );
+ await this.#refresh(this.#bindings, agentId);
+ };
+
+ /** Rename an account (an empty label falls back to its email / external id). */
+ renameQuotaAccount = async (accountId: string, label: string | undefined): Promise<void> => {
+ await this.#accounts.optimistic(
+ QUOTA_ACCOUNTS_KEY,
+ (accounts) =>
+ accounts.map((account) =>
+ account.id === accountId ? { ...account, label: label ?? null } : account,
+ ),
+ () => agentQuotaService.updateAccount(accountId, { label }),
+ );
+ await this.#refresh(this.#accounts, QUOTA_ACCOUNTS_KEY);
+ };
+
+ /**
+ * Drop every quota view and confirmation when the data context changes
+ * (desktop `refreshUserData` / `disconnectRemoteServer`), even when the next
+ * context derives the same scope string.
+ * `clear()` advances each replica's clear generation, so a read still in
+ * flight from the previous context is discarded instead of repopulating (and
+ * persisting) what was just dropped; it also deletes that context's rows.
+ * Mounted syncs then refetch from empty.
+ */
+ reset = (): void => {
+ // A mounted manager / calendar keeps its sync key across the reset, so
+ // nothing would refetch until a focus or remount: revalidate once cleared.
+ for (const slice of [this.#accounts, this.#bindings, this.#readings, this.#history])
+ void slice.clear().then(() => slice.revalidate());
+ void this.#panel.clear();
+ this.#appliedAt.clear();
+ // Live panel samples are not replica fetches, so `clear()` cannot retire them.
+ this.#resetGeneration += 1;
+ this.#set({ ...initialState }, false, 'resetAgentQuotaStore');
+ };
+
+ // ---- internals ----
+
+ /**
+ * A sampler read (`readQuota*`) seeds the sync cache, but SWR still
+ * revalidates a seeded entry on mount: a panel opened right after the menu
+ * sampled would send the same request again. Inside the dedupe window of a
+ * server answer, mount from the replica instead; explicit, post-write and
+ * later mounts refresh as usual.
+ */
+ #syncOptions = (resource: QuotaResourceName, key?: string | null) => {
+ const appliedAt = key
+ ? this.#appliedAt.get(quotaConfirmedKey(quotaAccountsResource.scope.get(), resource, key))
+ : undefined;
+ const recent = appliedAt !== undefined && Date.now() - appliedAt < QUOTA_READ_DEDUPE_MS;
+ return {
+ dedupingInterval: QUOTA_READ_DEDUPE_MS,
+ revalidateOnFocus: false,
+ ...(recent && { revalidateIfStale: false }),
+ };
+ };
+
+ /**
+ * An optimistic write (and its confirmation) only lands on a loaded view, so
+ * load the agent's bindings first: a write made while the persisted accounts
+ * already painted but the bindings read is still out would otherwise reach
+ * the server and never reach the replica. A loaded view returns nothing, so
+ * the optimistic update still paints in the same tick as the click.
+ */
+ #ensureBindings = (agentId: string): Promise<unknown> | undefined =>
+ this.#get().quotaBindingsMap[agentId] === undefined
+ ? this.readQuotaBindings(agentId)
+ : undefined;
+
+ #markApplied = (resource: QuotaResourceName, { key, scope }: SettleContext) => {
+ const id = quotaConfirmedKey(scope, resource, key);
+ this.#appliedAt.set(id, Date.now());
+ if (this.#get().quotaConfirmed[id]) return;
+ this.#set(
+ (state) => ({ quotaConfirmed: { ...state.quotaConfirmed, [id]: true } }),
+ false,
+ 'quotaConfirmed',
+ );
+ };
+
+ /** Re-read an entry after a write; the optimistic value already holds if it fails. */
+ #refresh = async (
+ slice: { fetch: (params: string, options?: ReadOptions) => Promise<unknown> },
+ key: string,
+ ) => {
+ try {
+ await slice.fetch(key, { fresh: true });
+ } catch (error) {
+ console.error('[agentQuota:refresh]', error);
+ }
+ };
+
+ #read = async <T>(
+ resource: QuotaResourceName,
+ slice: {
+ ensureScope: (scope: string) => void;
+ fetch: (params: string, options?: ReadOptions) => Promise<{ applied: boolean; data: T }>;
+ },
+ key: string,
+ field: 'quotaAccountsMap' | 'quotaBindingsMap' | 'quotaReadingsMap',
+ { fresh = false }: ReadOptions = {},
+ retried = false,
+ ): Promise<T> => {
+ const scope = quotaAccountsResource.scope.get();
+ // The samplers read with no view mounted: drop a previous identity's
+ // entries first, so neither the dedupe nor the failure fallback below can
+ // answer with them.
+ slice.ensureScope(scope);
+ const cached = (this.#get()[field] as Record<string, T>)[key];
+ const appliedAt = this.#appliedAt.get(quotaConfirmedKey(scope, resource, key));
+ if (
+ !fresh &&
+ cached !== undefined &&
+ appliedAt !== undefined &&
+ Date.now() - appliedAt < QUOTA_READ_DEDUPE_MS
+ )
+ return cached;
+
+ let result: { applied: boolean; data: T };
+ try {
+ result = await slice.fetch(key, fresh ? { fresh: true } : undefined);
+ } catch (error) {
+ // A failed refresh keeps answering with the last value the replica still
+ // holds for this identity. Re-read it rather than reuse `cached`: a reset
+ // may have cleared it, or a fresh read landed a newer value, meanwhile.
+ const current = (this.#get()[field] as Record<string, T>)[key];
+ if (current !== undefined && quotaAccountsResource.scope.get() === scope) return current;
+ throw error;
+ }
+ if (result.applied) return result.data;
+
+ // The replica dropped this answer: a write's `fresh` read superseded it, the
+ // entry was removed, or the identity changed. Answer with what the replica
+ // now holds (e.g. the switched pin) instead of the outdated response.
+ const current = (this.#get()[field] as Record<string, T>)[key];
+ if (current !== undefined && quotaAccountsResource.scope.get() === scope) return current;
+ if (retried) throw new Error(`[agentQuota] ${resource} read for "${key}" was superseded`);
+ return this.#read(resource, slice, key, field, { fresh: true }, true);
+ };
+}
+
+export const store: StateCreator<Store> = (...parameters: Parameters<StateCreator<Store>>) => ({
+ ...initialState,
+ ...flattenActions<Action>([new ActionImpl(...parameters)]),
+});
diff --git a/src/store/agentQuota/agentQuota.replica.test.ts b/src/store/agentQuota/agentQuota.replica.test.ts
new file mode 100644
index 00000000000..fe63e4510bb
--- /dev/null
+++ b/src/store/agentQuota/agentQuota.replica.test.ts
@@ -0,0 +1,711 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * Agent quota replicas: the account pool, bindings, readings, calendar history
+ * and the last quota-panel snapshot paint from IndexedDB on a reload, then
+ * converge on the server (or the live sampler) in the background.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope, REPLICA_INDEX_KEY } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { agentQuotaService } from '@/services/agentQuota';
+import { stores } from '@/store/utils/userDataStores';
+
+import { QUOTA_READ_DEDUPE_MS } from './action';
+import { agentQuotaSelectors, useAgentQuotaStore } from './index';
+import { initialState } from './initialState';
+import {
+ hashQuotaSourceKey,
+ QUOTA_ACCOUNTS_KEY,
+ type QuotaAccount,
+ quotaAccountsResource,
+ type QuotaBinding,
+ quotaBindingsResource,
+ type QuotaHistory,
+ quotaHistoryResource,
+ quotaPanelResource,
+ type QuotaPanelSnapshot,
+} from './projection';
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const account = (id: string, overrides: Partial<QuotaAccount> = {}): QuotaAccount =>
+ ({
+ credentialMode: 'referenced',
+ credentialRef: { path: '/Users/me/.claude/.credentials.json' },
+ email: `${id}@example.com`,
+ externalAccountId: `ext-${id}`,
+ id,
+ label: null,
+ metadata: null,
+ provider: 'claude-code',
+ tokenExpiresAt: new Date(0),
+ updatedAt: new Date(1),
+ ...overrides,
+ }) as unknown as QuotaAccount;
+
+const binding = (id: string, accountId: string, role: string): QuotaBinding =>
+ ({ accountId, agentId: 'agent-1', id, role }) as unknown as QuotaBinding;
+
+const panel = (usedPercent: number, overrides: Record<string, unknown> = {}) =>
+ ({
+ error: null,
+ provider: 'claude-code',
+ session: { resetsAt: null, usedPercent, windowMinutes: 300 },
+ status: 'ok',
+ updatedAt: 1000,
+ ...overrides,
+ }) as QuotaPanelSnapshot;
+
+/** Never-resolving request: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const tick = () => new Promise((resolve) => setTimeout(resolve, 30));
+
+describe('agent quota replicas', () => {
+ let scope = '';
+
+ const storedRow = async <T>(
+ resource: { storage?: { get: (key: any) => Promise<any> } },
+ queryKey: string,
+ inScope = scope,
+ ) => (await resource.storage!.get({ queryKey, scope: inScope }))?.data as T | undefined;
+
+ const persistRow = (
+ resource: { storage?: { set: (key: any, row: any) => Promise<unknown> } },
+ queryKey: string,
+ data: unknown,
+ inScope = scope,
+ ) => resource.storage!.set({ queryKey, scope: inScope }, { data, updatedAt: 1 });
+
+ /** A fresh store: what a reload starts from. */
+ const reload = () => act(() => useAgentQuotaStore.setState(initialState, false));
+
+ beforeEach(() => {
+ scope = `quota-user-${randomUUID()}:personal`;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ reload();
+ });
+
+ afterEach(async () => {
+ cleanup();
+ for (const resource of [
+ quotaAccountsResource,
+ quotaBindingsResource,
+ quotaHistoryResource,
+ quotaPanelResource,
+ ] as { storage?: { remove: (key: any) => Promise<unknown> } }[]) {
+ await resource.storage!.remove({ queryKey: REPLICA_INDEX_KEY, scope });
+ }
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ describe('quota panel snapshot', () => {
+ const SOURCE = JSON.stringify(['claude-code', 'agent-1', 'local', [['TOKEN', 'sk-secret']]]);
+
+ it('paints the last snapshot after a reload before the sampler answers, then replaces it', async () => {
+ await persistRow(quotaPanelResource, hashQuotaSourceKey(SOURCE), panel(30));
+
+ renderHook(() => useAgentQuotaStore.getState().useHydrateQuotaPanel(SOURCE), { wrapper });
+
+ await waitFor(() =>
+ expect(agentQuotaSelectors.panel(SOURCE)(useAgentQuotaStore.getState())).toMatchObject({
+ session: { usedPercent: 30 },
+ }),
+ );
+
+ act(() =>
+ useAgentQuotaStore.getState().setQuotaPanel(SOURCE, panel(55, { updatedAt: 2000 })),
+ );
+
+ expect(agentQuotaSelectors.panel(SOURCE)(useAgentQuotaStore.getState())).toMatchObject({
+ session: { usedPercent: 55 },
+ });
+ await waitFor(async () =>
+ expect(
+ await storedRow<QuotaPanelSnapshot>(quotaPanelResource, hashQuotaSourceKey(SOURCE)),
+ ).toMatchObject({ session: { usedPercent: 55 }, updatedAt: 2000 }),
+ );
+ });
+
+ it('keys storage by a digest, so an env secret in the source never reaches it', async () => {
+ renderHook(() => useAgentQuotaStore.getState().useHydrateQuotaPanel(SOURCE), { wrapper });
+ act(() => useAgentQuotaStore.getState().setQuotaPanel(SOURCE, panel(10)));
+
+ await waitFor(async () =>
+ expect(await storedRow(quotaPanelResource, hashQuotaSourceKey(SOURCE))).toBeDefined(),
+ );
+ const index = await storedRow<string[]>(quotaPanelResource, REPLICA_INDEX_KEY);
+ expect(index).toEqual([hashQuotaSourceKey(SOURCE)]);
+ expect(JSON.stringify(index)).not.toContain('sk-secret');
+ });
+
+ it('persists only successful snapshots, without a session-only refresh notice', async () => {
+ renderHook(() => useAgentQuotaStore.getState().useHydrateQuotaPanel(SOURCE), { wrapper });
+ act(() =>
+ useAgentQuotaStore
+ .getState()
+ .setQuotaPanel(SOURCE, panel(10, { refreshUnavailableReason: 'request-blocked' })),
+ );
+ await waitFor(async () =>
+ expect(await storedRow(quotaPanelResource, hashQuotaSourceKey(SOURCE))).toBeDefined(),
+ );
+ expect(
+ await storedRow<Record<string, unknown>>(quotaPanelResource, hashQuotaSourceKey(SOURCE)),
+ ).not.toHaveProperty('refreshUnavailableReason');
+
+ // An error / unavailable state is a current fact: it never replays after a reload.
+ act(() =>
+ useAgentQuotaStore
+ .getState()
+ .setQuotaPanel(SOURCE, panel(0, { error: 'boom', session: null, status: 'error' })),
+ );
+ await waitFor(async () =>
+ expect(await storedRow(quotaPanelResource, hashQuotaSourceKey(SOURCE))).toBeUndefined(),
+ );
+ });
+
+ it('drops a sample captured under the previous identity', async () => {
+ renderHook(() => useAgentQuotaStore.getState().useHydrateQuotaPanel(SOURCE), { wrapper });
+ const previousContext = useAgentQuotaStore.getState().getQuotaContext();
+ scope = `quota-user-${randomUUID()}:personal`;
+
+ act(() => useAgentQuotaStore.getState().setQuotaPanel(SOURCE, panel(10), previousContext));
+
+ expect(agentQuotaSelectors.panel(SOURCE)(useAgentQuotaStore.getState())).toBeUndefined();
+ });
+
+ it('drops a sample started before a user-data reset that kept the same scope', async () => {
+ renderHook(() => useAgentQuotaStore.getState().useHydrateQuotaPanel(SOURCE), { wrapper });
+ const previousContext = useAgentQuotaStore.getState().getQuotaContext();
+
+ // Desktop refreshUserData / disconnect: same scope string, new data context.
+ act(() => stores.reset());
+ act(() => useAgentQuotaStore.getState().setQuotaPanel(SOURCE, panel(10), previousContext));
+
+ expect(agentQuotaSelectors.panel(SOURCE)(useAgentQuotaStore.getState())).toBeUndefined();
+ await tick();
+ expect(await storedRow(quotaPanelResource, hashQuotaSourceKey(SOURCE))).toBeUndefined();
+ });
+ });
+
+ describe('account pool', () => {
+ it('paints persisted accounts before the network answers, then takes the server list', async () => {
+ await persistRow(quotaAccountsResource, QUOTA_ACCOUNTS_KEY, [account('a1')]);
+ let release!: (value: QuotaAccount[]) => void;
+ vi.spyOn(agentQuotaService, 'listAccounts').mockImplementation(
+ () => new Promise((resolve) => (release = resolve)),
+ );
+
+ renderHook(() => useAgentQuotaStore.getState().useFetchQuotaAccounts(), { wrapper });
+
+ await waitFor(() =>
+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())?.[0]?.id).toBe('a1'),
+ );
+ // Painted from storage only: "no accounts" is not settled yet.
+ expect(agentQuotaSelectors.isAccountsConfirmed(scope)(useAgentQuotaStore.getState())).toBe(
+ false,
+ );
+
+ await act(async () => release([account('a2')]));
+ await waitFor(() =>
+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())?.[0]?.id).toBe('a2'),
+ );
+ expect(agentQuotaSelectors.isAccountsConfirmed(scope)(useAgentQuotaStore.getState())).toBe(
+ true,
+ );
+ });
+
+ it('persists accounts without their credential reference', async () => {
+ vi.spyOn(agentQuotaService, 'listAccounts').mockResolvedValue([account('a1')]);
+
+ renderHook(() => useAgentQuotaStore.getState().useFetchQuotaAccounts(), { wrapper });
+
+ await waitFor(async () =>
+ expect(
+ (await storedRow<QuotaAccount[]>(quotaAccountsResource, QUOTA_ACCOUNTS_KEY))?.[0]?.id,
+ ).toBe('a1'),
+ );
+ const [row] = (await storedRow<Record<string, unknown>[]>(
+ quotaAccountsResource,
+ QUOTA_ACCOUNTS_KEY,
+ ))!;
+ expect(row).not.toHaveProperty('credentialRef');
+ expect(row).not.toHaveProperty('tokenExpiresAt');
+ expect(row.email).toBe('[email protected]');
+ });
+
+ it('does not show the previous identity its accounts after a switch', async () => {
+ const listAccounts = vi
+ .spyOn(agentQuotaService, 'listAccounts')
+ .mockResolvedValueOnce([account('mine')])
+ .mockImplementation(pending);
+
+ const { rerender } = renderHook(() => useAgentQuotaStore.getState().useFetchQuotaAccounts(), {
+ wrapper,
+ });
+ await waitFor(() =>
+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())?.[0]?.id).toBe('mine'),
+ );
+
+ scope = `quota-user-${randomUUID()}:personal`;
+ rerender();
+
+ await waitFor(() => expect(listAccounts).toHaveBeenCalledTimes(2));
+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())).toBeUndefined();
+ });
+
+ it('shares one request between the samplers and dedupes reads inside the window', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ const listAccounts = vi
+ .spyOn(agentQuotaService, 'listAccounts')
+ .mockResolvedValue([account('a1')]);
+ const state = useAgentQuotaStore.getState();
+
+ // Three panels mounting together (Claude, Codex, Kimi) join one request.
+ const results = await Promise.all([
+ state.readQuotaAccounts(),
+ state.readQuotaAccounts(),
+ state.readQuotaAccounts(),
+ ]);
+ expect(results.map((list) => list[0].id)).toEqual(['a1', 'a1', 'a1']);
+ expect(listAccounts).toHaveBeenCalledTimes(1);
+
+ // A later read inside the window answers from the replica.
+ await state.readQuotaAccounts();
+ expect(listAccounts).toHaveBeenCalledTimes(1);
+
+ // After an ingest the caller asks for a fresh read.
+ await state.readQuotaAccounts({ fresh: true });
+ expect(listAccounts).toHaveBeenCalledTimes(2);
+
+ vi.advanceTimersByTime(QUOTA_READ_DEDUPE_MS + 1);
+ await state.readQuotaAccounts();
+ expect(listAccounts).toHaveBeenCalledTimes(3);
+ });
+
+ it('does not refetch on a panel mount right after a sampler read answered', async () => {
+ const listAccounts = vi
+ .spyOn(agentQuotaService, 'listAccounts')
+ .mockResolvedValue([account('a1')]);
+ const { rerender } = renderHook(
+ ({ enabled }) => useAgentQuotaStore.getState().useFetchQuotaAccounts(enabled),
+ { initialProps: { enabled: false }, wrapper },
+ );
+
+ // The menu's sampler reads first; the account manager opens a moment later.
+ await useAgentQuotaStore.getState().readQuotaAccounts();
+ rerender({ enabled: true });
+ await tick();
+
+ expect(listAccounts).toHaveBeenCalledTimes(1);
+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())?.map((a) => a.id)).toEqual(
+ ['a1'],
+ );
+ });
+
+ it('keeps answering with the last accounts when a refresh fails', async () => {
+ vi.spyOn(agentQuotaService, 'listAccounts')
+ .mockResolvedValueOnce([account('a1')])
+ .mockRejectedValue(new Error('offline'));
+ const state = useAgentQuotaStore.getState();
+
+ await state.readQuotaAccounts();
+ await expect(state.readQuotaAccounts({ fresh: true })).resolves.toMatchObject([{ id: 'a1' }]);
+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())?.[0]?.id).toBe('a1');
+ });
+
+ it('never answers a new identity with the previous identity its accounts', async () => {
+ vi.spyOn(agentQuotaService, 'listAccounts')
+ .mockResolvedValueOnce([account('theirs')])
+ .mockRejectedValue(new Error('offline'));
+ await useAgentQuotaStore.getState().readQuotaAccounts();
+
+ // Switch identity; the new identity's first read fails.
+ scope = `quota-user-${randomUUID()}:personal`;
+ await expect(useAgentQuotaStore.getState().readQuotaAccounts()).rejects.toThrow('offline');
+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())).toBeUndefined();
+ });
+
+ it('renames an account in the replica and its stored copy', async () => {
+ vi.spyOn(agentQuotaService, 'listAccounts')
+ .mockResolvedValueOnce([account('a1')])
+ .mockRejectedValue(new Error('offline'));
+ vi.spyOn(agentQuotaService, 'updateAccount').mockResolvedValue(undefined as never);
+ renderHook(() => useAgentQuotaStore.getState().useFetchQuotaAccounts(), { wrapper });
+ await waitFor(() =>
+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())).toBeDefined(),
+ );
+
+ await act(() => useAgentQuotaStore.getState().renameQuotaAccount('a1', 'Work'));
+
+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())?.[0]?.label).toBe('Work');
+ await waitFor(async () =>
+ expect(
+ (await storedRow<QuotaAccount[]>(quotaAccountsResource, QUOTA_ACCOUNTS_KEY))?.[0]?.label,
+ ).toBe('Work'),
+ );
+ });
+ });
+
+ describe('user-data reset', () => {
+ it('drops every quota view and the dedupe window, so the next read asks the server', async () => {
+ const listAccounts = vi
+ .spyOn(agentQuotaService, 'listAccounts')
+ .mockResolvedValueOnce([account('a1')])
+ .mockResolvedValueOnce([account('a2')]);
+ await useAgentQuotaStore.getState().readQuotaAccounts();
+ expect(agentQuotaSelectors.isAccountsConfirmed(scope)(useAgentQuotaStore.getState())).toBe(
+ true,
+ );
+
+ // Same scope string, new data context (desktop refreshUserData / disconnect).
+ act(() => stores.reset());
+
+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())).toBeUndefined();
+ expect(agentQuotaSelectors.isAccountsConfirmed(scope)(useAgentQuotaStore.getState())).toBe(
+ false,
+ );
+ const accounts = await useAgentQuotaStore.getState().readQuotaAccounts();
+ expect(listAccounts).toHaveBeenCalledTimes(2);
+ expect(accounts.map((a) => a.id)).toEqual(['a2']);
+ });
+
+ it('refetches a mounted query after the reset instead of leaving it empty', async () => {
+ const listAccounts = vi
+ .spyOn(agentQuotaService, 'listAccounts')
+ .mockResolvedValueOnce([account('a1')])
+ .mockResolvedValueOnce([account('a2')]);
+ renderHook(() => useAgentQuotaStore.getState().useFetchQuotaAccounts(), { wrapper });
+ await waitFor(() =>
+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())?.[0]?.id).toBe('a1'),
+ );
+
+ // Same scope string, new data context; the manager stays mounted.
+ act(() => stores.reset());
+
+ await waitFor(() =>
+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())?.[0]?.id).toBe('a2'),
+ );
+ expect(listAccounts).toHaveBeenCalledTimes(2);
+ });
+
+ it('discards a read still in flight from the previous data context', async () => {
+ let answer!: (rows: QuotaAccount[]) => void;
+ vi.spyOn(agentQuotaService, 'listAccounts')
+ // The re-read for the new context stays offline here.
+ .mockRejectedValue(new Error('offline'))
+ .mockImplementationOnce(() => new Promise((resolve) => (answer = resolve)));
+ const read = useAgentQuotaStore.getState().readQuotaAccounts();
+
+ act(() => stores.reset());
+ answer([account('old')]);
+ await read.catch(() => undefined);
+ await tick();
+
+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())).toBeUndefined();
+ expect(await storedRow<QuotaAccount[]>(quotaAccountsResource, QUOTA_ACCOUNTS_KEY)).toBe(
+ undefined,
+ );
+ });
+ it('does not answer a read that fails after the reset with the previous context', async () => {
+ let fail!: (error: Error) => void;
+ vi.spyOn(agentQuotaService, 'listAccounts')
+ .mockResolvedValueOnce([account('old')])
+ .mockImplementationOnce(() => new Promise((_, reject) => (fail = reject)));
+ await useAgentQuotaStore.getState().readQuotaAccounts();
+ const read = useAgentQuotaStore.getState().readQuotaAccounts({ fresh: true });
+
+ act(() => stores.reset());
+ fail(new Error('offline'));
+
+ await expect(read).rejects.toThrow('offline');
+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())).toBeUndefined();
+ });
+ });
+
+ describe('bindings', () => {
+ const seedBindings = async (rows: QuotaBinding[]) => {
+ vi.spyOn(agentQuotaService, 'listBindings').mockResolvedValueOnce(rows);
+ await useAgentQuotaStore.getState().readQuotaBindings('agent-1');
+ };
+
+ it('removes an unbound account from storage, so a reload cannot bring it back', async () => {
+ await seedBindings([binding('b1', 'a1', 'pinned'), binding('b2', 'a2', 'pool')]);
+ vi.spyOn(agentQuotaService, 'unbindAccount').mockResolvedValue(undefined as never);
+ // The follow-up refresh fails: the write must not depend on it.
+ vi.spyOn(agentQuotaService, 'listBindings').mockRejectedValue(new Error('offline'));
+
+ await act(() => useAgentQuotaStore.getState().unbindQuotaAccount('agent-1', 'b2'));
+
+ expect(
+ agentQuotaSelectors
+ .bindings('agent-1')(useAgentQuotaStore.getState())
+ ?.map((b) => b.id),
+ ).toEqual(['b1']);
+ await waitFor(async () =>
+ expect(
+ (await storedRow<QuotaBinding[]>(quotaBindingsResource, 'agent-1'))?.map((b) => b.id),
+ ).toEqual(['b1']),
+ );
+
+ reload();
+ vi.spyOn(agentQuotaService, 'listBindings').mockImplementation(pending);
+ renderHook(() => useAgentQuotaStore.getState().useFetchQuotaBindings('agent-1'), {
+ wrapper,
+ });
+ await waitFor(() =>
+ expect(
+ agentQuotaSelectors.bindings('agent-1')(useAgentQuotaStore.getState()),
+ ).toBeDefined(),
+ );
+ expect(
+ agentQuotaSelectors
+ .bindings('agent-1')(useAgentQuotaStore.getState())
+ ?.map((b) => b.id),
+ ).toEqual(['b1']);
+ });
+
+ it('switches the pin on screen at once and rolls back when the server rejects', async () => {
+ await seedBindings([binding('b1', 'a1', 'pinned'), binding('b2', 'a2', 'pool')]);
+ let reject!: (error: Error) => void;
+ vi.spyOn(agentQuotaService, 'switchAccount').mockImplementation(
+ () => new Promise((_, fail) => (reject = fail)),
+ );
+
+ let switching!: Promise<void>;
+ act(() => {
+ switching = useAgentQuotaStore.getState().switchQuotaAccount('agent-1', 'a2');
+ });
+ const roles = () =>
+ agentQuotaSelectors
+ .bindings('agent-1')(useAgentQuotaStore.getState())
+ ?.map((b) => `${b.accountId}:${b.role}`);
+ expect(roles()).toEqual(['a1:pool', 'a2:pinned']);
+
+ await act(async () => {
+ reject(new Error('denied'));
+ await expect(switching).rejects.toThrow('denied');
+ });
+ expect(roles()).toEqual(['a1:pinned', 'a2:pool']);
+ });
+
+ it('lands a newly bound account from the upserted row', async () => {
+ await seedBindings([binding('b1', 'a1', 'pinned')]);
+ vi.spyOn(agentQuotaService, 'bindAccount').mockResolvedValue(
+ binding('b9', 'a9', 'pool') as never,
+ );
+ vi.spyOn(agentQuotaService, 'listBindings').mockRejectedValue(new Error('offline'));
+
+ await act(() => useAgentQuotaStore.getState().bindQuotaAccount('agent-1', 'a9', 'pool'));
+
+ expect(
+ agentQuotaSelectors
+ .bindings('agent-1')(useAgentQuotaStore.getState())
+ ?.map((b) => b.id),
+ ).toEqual(['b1', 'b9']);
+ });
+
+ it('answers a read a fresh read superseded with the replica value, not the outdated response', async () => {
+ let answerStale!: (rows: QuotaBinding[]) => void;
+ let answerFresh!: (rows: QuotaBinding[]) => void;
+ vi.spyOn(agentQuotaService, 'listBindings')
+ .mockImplementationOnce(() => new Promise((resolve) => (answerStale = resolve)))
+ .mockImplementationOnce(() => new Promise((resolve) => (answerFresh = resolve)));
+
+ // A sampler read is out when a write's fresh refresh starts.
+ const samplerRead = useAgentQuotaStore.getState().readQuotaBindings('agent-1');
+ const writeRefresh = useAgentQuotaStore
+ .getState()
+ .readQuotaBindings('agent-1', { fresh: true });
+ answerFresh([binding('b1', 'a1', 'pool'), binding('b2', 'a2', 'pinned')]);
+ await writeRefresh;
+ answerStale([binding('b1', 'a1', 'pinned'), binding('b2', 'a2', 'pool')]);
+
+ expect((await samplerRead).map((b) => `${b.accountId}:${b.role}`)).toEqual([
+ 'a1:pool',
+ 'a2:pinned',
+ ]);
+ });
+
+ it('answers a failed read a fresh read overtook with the replica value, not its own snapshot', async () => {
+ let fail!: (error: Error) => void;
+ let answerFresh!: (rows: QuotaBinding[]) => void;
+ vi.spyOn(agentQuotaService, 'listBindings')
+ .mockResolvedValueOnce([binding('b1', 'a1', 'pinned'), binding('b2', 'a2', 'pool')])
+ .mockImplementationOnce(() => new Promise((_, reject) => (fail = reject)))
+ .mockImplementationOnce(() => new Promise((resolve) => (answerFresh = resolve)));
+ await useAgentQuotaStore.getState().readQuotaBindings('agent-1');
+
+ // A sampler re-read is out when a write's fresh refresh lands the switched pin.
+ const samplerRead = useAgentQuotaStore
+ .getState()
+ .readQuotaBindings('agent-1', { fresh: true });
+ const writeRefresh = useAgentQuotaStore
+ .getState()
+ .readQuotaBindings('agent-1', { fresh: true });
+ answerFresh([binding('b1', 'a1', 'pool'), binding('b2', 'a2', 'pinned')]);
+ await writeRefresh;
+ fail(new Error('offline'));
+
+ expect((await samplerRead).map((b) => `${b.accountId}:${b.role}`)).toEqual([
+ 'a1:pool',
+ 'a2:pinned',
+ ]);
+ });
+
+ it('loads the bindings before a write made while they were still unloaded', async () => {
+ // Persisted accounts painted, but this agent's bindings never loaded.
+ expect(
+ agentQuotaSelectors.bindings('agent-1')(useAgentQuotaStore.getState()),
+ ).toBeUndefined();
+ vi.spyOn(agentQuotaService, 'listBindings')
+ .mockResolvedValueOnce([binding('b1', 'a1', 'pinned')])
+ // The follow-up refresh fails: the confirmed row must still land.
+ .mockRejectedValue(new Error('offline'));
+ vi.spyOn(agentQuotaService, 'bindAccount').mockResolvedValue(
+ binding('b9', 'a9', 'pool') as never,
+ );
+
+ await act(() => useAgentQuotaStore.getState().bindQuotaAccount('agent-1', 'a9', 'pool'));
+
+ expect(
+ agentQuotaSelectors
+ .bindings('agent-1')(useAgentQuotaStore.getState())
+ ?.map((b) => `${b.accountId}:${b.role}`),
+ ).toEqual(['a1:pinned', 'a9:pool']);
+ });
+ });
+
+ describe('calendar history', () => {
+ it('treats a hydrated empty history as unconfirmed until the server answers', async () => {
+ const empty: QuotaHistory = { snapshots: [], usageTurns: [], windows: [] };
+ await persistRow(quotaHistoryResource, 'a1', empty);
+ let release!: (value: unknown[]) => void;
+ vi.spyOn(agentQuotaService, 'getWindows').mockImplementation(
+ () => new Promise((resolve) => (release = resolve)) as never,
+ );
+ vi.spyOn(agentQuotaService, 'listSnapshots').mockResolvedValue([]);
+ vi.spyOn(agentQuotaService, 'listUsageTurns').mockResolvedValue([]);
+
+ renderHook(() => useAgentQuotaStore.getState().useFetchQuotaHistory('a1'), { wrapper });
+
+ await waitFor(() =>
+ expect(agentQuotaSelectors.history('a1')(useAgentQuotaStore.getState())).toEqual(empty),
+ );
+ await tick();
+ expect(
+ agentQuotaSelectors.isHistoryConfirmed(scope, 'a1')(useAgentQuotaStore.getState()),
+ ).toBe(false);
+
+ await act(async () => release([]));
+ await waitFor(() =>
+ expect(
+ agentQuotaSelectors.isHistoryConfirmed(scope, 'a1')(useAgentQuotaStore.getState()),
+ ).toBe(true),
+ );
+ });
+
+ it('keeps the parts that answered when one history request fails', async () => {
+ const snapshot = { capturedAt: 1, limitType: 'session', scopeKey: '', utilization: 5 };
+ const turn = { occurredAt: 1 };
+ await persistRow(quotaHistoryResource, 'a1', {
+ snapshots: [],
+ usageTurns: [turn],
+ windows: [],
+ });
+ let release!: (value: unknown[]) => void;
+ vi.spyOn(agentQuotaService, 'getWindows').mockImplementation(
+ () => new Promise((resolve) => (release = resolve)) as never,
+ );
+ vi.spyOn(agentQuotaService, 'listSnapshots').mockResolvedValue([snapshot] as never);
+ vi.spyOn(agentQuotaService, 'listUsageTurns').mockRejectedValue(new Error('flaky'));
+
+ const { result } = renderHook(
+ () => useAgentQuotaStore.getState().useFetchQuotaHistory('a1'),
+ { wrapper },
+ );
+ await waitFor(() =>
+ expect(agentQuotaSelectors.history('a1')(useAgentQuotaStore.getState())).toBeDefined(),
+ );
+ await act(async () => release([{ id: 'w1' }]));
+
+ await waitFor(() =>
+ expect(agentQuotaSelectors.history('a1')(useAgentQuotaStore.getState())).toEqual({
+ snapshots: [snapshot],
+ // The failed part keeps its last confirmed value.
+ usageTurns: [turn],
+ windows: [{ id: 'w1' }],
+ }),
+ );
+ expect(result.current.error).toBeFalsy();
+ expect(
+ agentQuotaSelectors.isHistoryConfirmed(scope, 'a1')(useAgentQuotaStore.getState()),
+ ).toBe(true);
+ });
+
+ it('refreshes a loaded history when an ingest re-reads the readings', async () => {
+ const before = { snapshots: [], usageTurns: [], windows: [{ id: 'w-old' }] };
+ vi.spyOn(agentQuotaService, 'getWindows')
+ .mockResolvedValueOnce(before.windows as never)
+ .mockResolvedValue([{ id: 'w-new' }] as never);
+ vi.spyOn(agentQuotaService, 'listSnapshots').mockResolvedValue([]);
+ vi.spyOn(agentQuotaService, 'listUsageTurns').mockResolvedValue([]);
+ vi.spyOn(agentQuotaService, 'getLatestReadings').mockResolvedValue([]);
+ renderHook(() => useAgentQuotaStore.getState().useFetchQuotaHistory('a1'), { wrapper });
+ await waitFor(() =>
+ expect(agentQuotaSelectors.history('a1')(useAgentQuotaStore.getState())).toEqual(before),
+ );
+
+ await useAgentQuotaStore.getState().readQuotaReadings('a1', { fresh: true });
+
+ await waitFor(() =>
+ expect(agentQuotaSelectors.history('a1')(useAgentQuotaStore.getState())?.windows).toEqual([
+ { id: 'w-new' },
+ ]),
+ );
+ });
+
+ it('keeps the last history on screen when a refresh fails', async () => {
+ const history = {
+ snapshots: [{ capturedAt: 1, limitType: 'session', scopeKey: '', utilization: 5 }],
+ usageTurns: [],
+ windows: [],
+ } as unknown as QuotaHistory;
+ await persistRow(quotaHistoryResource, 'a1', history);
+ vi.spyOn(agentQuotaService, 'getWindows').mockRejectedValue(new Error('offline'));
+ vi.spyOn(agentQuotaService, 'listSnapshots').mockRejectedValue(new Error('offline'));
+ vi.spyOn(agentQuotaService, 'listUsageTurns').mockRejectedValue(new Error('offline'));
+
+ const { result } = renderHook(
+ () => useAgentQuotaStore.getState().useFetchQuotaHistory('a1'),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(agentQuotaSelectors.history('a1')(useAgentQuotaStore.getState())).toEqual(history);
+ });
+ });
+});
diff --git a/src/store/agentQuota/index.ts b/src/store/agentQuota/index.ts
new file mode 100644
index 00000000000..082ff490a33
--- /dev/null
+++ b/src/store/agentQuota/index.ts
@@ -0,0 +1,30 @@
+'use client';
+
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import { createDevtools } from '@/store/middleware/createDevtools';
+import { expose } from '@/store/middleware/expose';
+
+import { type Store, store } from './action';
+
+export type { State } from './initialState';
+export type {
+ QuotaAccount,
+ QuotaBinding,
+ QuotaHistory,
+ QuotaLatestReading,
+ QuotaPanelSnapshot,
+ QuotaUsageTurn,
+ QuotaWindowRow,
+} from './projection';
+
+const devtools = createDevtools('agentQuota');
+
+export const useAgentQuotaStore = createWithEqualityFn<Store>()(devtools(store), shallow);
+
+expose('agentQuota', useAgentQuotaStore);
+
+export const getAgentQuotaStoreState = () => useAgentQuotaStore.getState();
+
+export { agentQuotaSelectors } from './selectors';
diff --git a/src/store/agentQuota/initialState.ts b/src/store/agentQuota/initialState.ts
new file mode 100644
index 00000000000..74ad20eb959
--- /dev/null
+++ b/src/store/agentQuota/initialState.ts
@@ -0,0 +1,53 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+import type {
+ QuotaAccount,
+ QuotaBinding,
+ QuotaHistory,
+ QuotaLatestReading,
+ QuotaPanelSnapshot,
+} from './projection';
+
+export interface State {
+ /** Replica view of the quota account list (one entry, `QUOTA_ACCOUNTS_KEY`). */
+ quotaAccountsMap: Record<string, QuotaAccount[]>;
+ /** Replica bookkeeping of `quotaAccountsMap`. */
+ quotaAccountsReplica: ReplicaState<QuotaAccount[]>;
+ /** Replica view of each agent's account bindings, keyed by agent id. */
+ quotaBindingsMap: Record<string, QuotaBinding[]>;
+ /** Replica bookkeeping of `quotaBindingsMap`. */
+ quotaBindingsReplica: ReplicaState<QuotaBinding[]>;
+ /**
+ * Entries the server answered for in this session, keyed
+ * `<scope>|<resource>|<key>`. A value hydrated from storage may be an empty
+ * or outdated snapshot, so "no account" / "no history" is only shown once
+ * the matching flag is set.
+ */
+ quotaConfirmed: Record<string, true>;
+ /** Replica view of each account's calendar history, keyed by account id. */
+ quotaHistoryMap: Record<string, QuotaHistory>;
+ /** Replica bookkeeping of `quotaHistoryMap`. */
+ quotaHistoryReplica: ReplicaState<QuotaHistory>;
+ /** Replica view of the last panel snapshot per quota source (hashed source key). */
+ quotaPanelMap: Record<string, QuotaPanelSnapshot>;
+ /** Replica bookkeeping of `quotaPanelMap`. */
+ quotaPanelReplica: ReplicaState<QuotaPanelSnapshot>;
+ /** Replica view of each account's newest readings, keyed by account id. */
+ quotaReadingsMap: Record<string, QuotaLatestReading[]>;
+ /** Replica bookkeeping of `quotaReadingsMap`. */
+ quotaReadingsReplica: ReplicaState<QuotaLatestReading[]>;
+}
+
+export const initialState: State = {
+ quotaAccountsMap: {},
+ quotaAccountsReplica: createReplicaState(),
+ quotaBindingsMap: {},
+ quotaBindingsReplica: createReplicaState(),
+ quotaConfirmed: {},
+ quotaHistoryMap: {},
+ quotaHistoryReplica: createReplicaState(),
+ quotaPanelMap: {},
+ quotaPanelReplica: createReplicaState(),
+ quotaReadingsMap: {},
+ quotaReadingsReplica: createReplicaState(),
+};
diff --git a/src/store/agentQuota/projection.ts b/src/store/agentQuota/projection.ts
new file mode 100644
index 00000000000..42ef76f19e0
--- /dev/null
+++ b/src/store/agentQuota/projection.ts
@@ -0,0 +1,136 @@
+import type { QuotaLimitReading } from '@lobechat/heterogeneous-agents/quota';
+
+import { defineReplica } from '@/libs/replica';
+import type { agentQuotaService } from '@/services/agentQuota';
+
+export type QuotaAccount = Awaited<ReturnType<typeof agentQuotaService.listAccounts>>[number];
+export type QuotaBinding = Awaited<ReturnType<typeof agentQuotaService.listBindings>>[number];
+export type QuotaLatestReading = Awaited<
+ ReturnType<typeof agentQuotaService.getLatestReadings>
+>[number];
+export type QuotaWindowRow = Awaited<ReturnType<typeof agentQuotaService.getWindows>>[number];
+export type QuotaUsageTurn = Awaited<ReturnType<typeof agentQuotaService.listUsageTurns>>[number];
+
+/** The calendar reads 90 days of history: complete data for this month and the last. */
+export const QUOTA_HISTORY_DAYS = 90;
+/** Concrete windows the calendar asks for, newest reset first. */
+export const QUOTA_HISTORY_WINDOW_LIMIT = 200;
+
+/** One account's calendar history: windows, the reading series and per-turn spend. */
+export interface QuotaHistory {
+ snapshots: QuotaLimitReading[];
+ usageTurns: QuotaUsageTurn[];
+ windows: QuotaWindowRow[];
+}
+
+/** A history read: a part whose request failed is `undefined`. */
+export type QuotaHistoryFetched = { [K in keyof QuotaHistory]: QuotaHistory[K] | undefined };
+
+/**
+ * The account list is one entry for the whole scope: every panel, the account
+ * manager and the calendar resolve their account from it.
+ */
+export const QUOTA_ACCOUNTS_KEY = 'all';
+
+/**
+ * Persist the account rows without credential references. The server already
+ * strips the encrypted credentials; the reference (keychain / file pointer)
+ * and token expiry only matter to the server-side refresh worker.
+ */
+export const toPersistedQuotaAccounts = (accounts: QuotaAccount[]): QuotaAccount[] =>
+ accounts.map((account) => {
+ const lean = { ...account } as Partial<QuotaAccount>;
+ delete lean.credentialRef;
+ delete lean.credentialMode;
+ delete lean.tokenExpiresAt;
+ return lean as QuotaAccount;
+ });
+
+export const quotaAccountsResource = defineReplica<string, QuotaAccount[]>({
+ key: (key) => key,
+ name: 'agentQuotaAccounts',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** One agent's account bindings (pinned / pool / disabled), keyed by agent id. */
+export const quotaBindingsResource = defineReplica<string, QuotaBinding[]>({
+ key: (agentId) => agentId,
+ name: 'agentQuotaBindings',
+ persist: { maxEntries: 50 },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** The newest reading per limit bucket of one account, keyed by account id. */
+export const quotaReadingsResource = defineReplica<string, QuotaLatestReading[]>({
+ key: (accountId) => accountId,
+ name: 'agentQuotaReadings',
+ persist: { maxEntries: 30 },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * One account's 90-day calendar history. The reading series is the heaviest
+ * payload of the domain, so only the most recently opened accounts persist.
+ */
+export const quotaHistoryResource = defineReplica<string, QuotaHistory, QuotaHistoryFetched>({
+ key: (accountId) => accountId,
+ name: 'agentQuotaHistory',
+ persist: { maxEntries: 5 },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** What every quota panel snapshot shares (see `QuotaMenu`). */
+export interface QuotaPanelSnapshot {
+ error: string | null;
+ status: 'error' | 'ok' | 'unavailable';
+ updatedAt: number;
+}
+
+/**
+ * The last snapshot a quota panel rendered for one source (provider, agent,
+ * device / local login, command and environment), so a reload paints the
+ * badge and its "updated N ago" line before the live sampler answers.
+ *
+ * Fed by the panel's own sampler (desktop IPC / device RPC + persisted DB
+ * readings), not by a fetcher: the replica only hydrates and persists.
+ */
+export const quotaPanelResource = defineReplica<string, QuotaPanelSnapshot>({
+ key: (sourceKey) => sourceKey,
+ name: 'agentQuotaPanel',
+ persist: { maxEntries: 20 },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * Only a successful snapshot is worth replaying after a reload. An error or
+ * an unavailable login is a current fact the sampler must confirm again, and
+ * a "could not refresh" notice belongs to the session that saw it.
+ */
+export const toPersistedQuotaPanel = (snapshot: QuotaPanelSnapshot): QuotaPanelSnapshot | null => {
+ if (snapshot.status !== 'ok') return null;
+ if (!('refreshUnavailableReason' in snapshot)) return snapshot;
+
+ const lean = { ...snapshot } as QuotaPanelSnapshot & { refreshUnavailableReason?: unknown };
+ delete lean.refreshUnavailableReason;
+ return lean;
+};
+
+/**
+ * FNV-1a over the source description. A source key may carry the agent's
+ * environment (API keys included), so only this digest reaches storage.
+ */
+export const hashQuotaSourceKey = (source: string): string => {
+ let h1 = 0x81_1c_9d_c5;
+ let h2 = 0x01_00_01_93;
+ for (let index = 0; index < source.length; index++) {
+ const code = source.charCodeAt(index);
+ h1 = Math.imul(h1 ^ code, 0x01_00_01_93);
+ h2 = Math.imul(h2 ^ code, 0x05_bd_1e_95);
+ }
+ return `${(h1 >>> 0).toString(16).padStart(8, '0')}${(h2 >>> 0).toString(16).padStart(8, '0')}`;
+};
diff --git a/src/store/agentQuota/selectors.ts b/src/store/agentQuota/selectors.ts
new file mode 100644
index 00000000000..68920aec640
--- /dev/null
+++ b/src/store/agentQuota/selectors.ts
@@ -0,0 +1,38 @@
+import { quotaConfirmedKey, type Store } from './action';
+import { hashQuotaSourceKey, QUOTA_ACCOUNTS_KEY } from './projection';
+
+const accounts = (s: Store) => s.quotaAccountsMap[QUOTA_ACCOUNTS_KEY];
+
+const bindings = (agentId?: string | null) => (s: Store) =>
+ agentId ? s.quotaBindingsMap[agentId] : undefined;
+
+const readings = (accountId?: string | null) => (s: Store) =>
+ accountId ? s.quotaReadingsMap[accountId] : undefined;
+
+const history = (accountId?: string | null) => (s: Store) =>
+ accountId ? s.quotaHistoryMap[accountId] : undefined;
+
+const panel = (sourceKey: string) => (s: Store) => s.quotaPanelMap[hashQuotaSourceKey(sourceKey)];
+
+/** The server answered for the account list in `scope` during this session. */
+const isAccountsConfirmed = (scope: string) => (s: Store) =>
+ !!s.quotaConfirmed[quotaConfirmedKey(scope, 'accounts', QUOTA_ACCOUNTS_KEY)];
+
+/** The server answered for one agent's bindings in `scope` during this session. */
+const isBindingsConfirmed = (scope: string, agentId?: string | null) => (s: Store) =>
+ !!agentId && !!s.quotaConfirmed[quotaConfirmedKey(scope, 'bindings', agentId)];
+
+/** The server answered for one account's calendar history in `scope` during this session. */
+const isHistoryConfirmed = (scope: string, accountId?: string | null) => (s: Store) =>
+ !!accountId && !!s.quotaConfirmed[quotaConfirmedKey(scope, 'history', accountId)];
+
+export const agentQuotaSelectors = {
+ accounts,
+ bindings,
+ history,
+ isAccountsConfirmed,
+ isBindingsConfirmed,
+ isHistoryConfirmed,
+ panel,
+ readings,
+};
diff --git a/src/store/utils/userDataStores.test.ts b/src/store/utils/userDataStores.test.ts
index cacd9dd4c9b..3bacdecb742 100644
--- a/src/store/utils/userDataStores.test.ts
+++ b/src/store/utils/userDataStores.test.ts
@@ -20,6 +20,7 @@ vi.mock('@/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry', (
}));
vi.mock('@/store/agent', () => ({ useAgentStore: fakeStore() }));
vi.mock('@/store/agentGroup', () => ({ useAgentGroupStore: fakeStore() }));
+vi.mock('@/store/agentQuota', () => ({ useAgentQuotaStore: fakeStore() }));
vi.mock('@/store/chat', () => ({ useChatStore: fakeStore() }));
vi.mock('@/store/discover', () => ({ useDiscoverStore: fakeStore() }));
vi.mock('@/store/document', () => ({ useDocumentStore: fakeStore() }));
@@ -61,7 +62,7 @@ describe('stores.reset', () => {
stores.reset();
expect(resetGatewayMuxRegistry).toHaveBeenCalledTimes(1);
- expect(storeResets).toHaveLength(18);
+ expect(storeResets).toHaveLength(19);
expect(pageReset).toHaveBeenCalledTimes(1);
// Confirmed manage grants and the memory-only collaborator roster must not
// outlive the data context, even when the next one reuses the scope string.
diff --git a/src/store/utils/userDataStores.ts b/src/store/utils/userDataStores.ts
index 5bd7689d445..762c9d35af9 100644
--- a/src/store/utils/userDataStores.ts
+++ b/src/store/utils/userDataStores.ts
@@ -3,6 +3,7 @@ import { unstable_batchedUpdates } from 'react-dom';
import { useAgentStore } from '@/store/agent';
import { agentDocumentActions } from '@/store/agentDocument';
import { useAgentGroupStore } from '@/store/agentGroup';
+import { useAgentQuotaStore } from '@/store/agentQuota';
import { useChatStore } from '@/store/chat';
import { resetGatewayMuxRegistry } from '@/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry';
import { useDiscoverStore } from '@/store/discover';
@@ -33,6 +34,7 @@ interface ResetableStoreApi {
const resetableStores: ResetableStoreApi[] = [
useAgentGroupStore,
+ useAgentQuotaStore,
useAgentStore,
useChatStore,
useDiscoverStore,