Skip to content

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

🐛 fix(heterogeneous-agent): preserve quota cache by source (#16755)

AmAzing-c92f8e7ef55b
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index dcf391bdce1..0eb8099a9bb 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -267,6 +267,8 @@
"groupWizard.searchTemplates": "Search templates...",
"groupWizard.title": "Create Group",
"groupWizard.useTemplate": "Use Template",
+ "heteroAgent.claudeQuota.errorRateLimited": "Claude Code quota is temporarily rate limited. Please try again later.",
+ "heteroAgent.claudeQuota.refreshRateLimited": "Quota refresh is temporarily rate limited. Showing the last available data.",
"heteroAgent.claudeQuota.scopedWeekly": "Weekly ({{model}})",
"heteroAgent.claudeQuota.title": "Claude Code quota",
"heteroAgent.claudeQuota.tooltip": "View Claude Code quota",
@@ -341,6 +343,7 @@
"heteroAgent.quota.left": "{{percent}}% left",
"heteroAgent.quota.noData": "Quota is not available yet.",
"heteroAgent.quota.refresh": "Refresh quota",
+ "heteroAgent.quota.refreshFailed": "Couldn't refresh quota. Showing the last available data.",
"heteroAgent.quota.resetsIn": "Resets in {{duration}}",
"heteroAgent.quota.resetsSoon": "Resets soon",
"heteroAgent.quota.session": "Session",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 4f9ebed532b..447d940e454 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -267,6 +267,8 @@
"groupWizard.searchTemplates": "搜索模板…",
"groupWizard.title": "创建群组",
"groupWizard.useTemplate": "使用模板",
+ "heteroAgent.claudeQuota.errorRateLimited": "Claude Code 额度查询暂时被限流,请稍后再试。",
+ "heteroAgent.claudeQuota.refreshRateLimited": "额度刷新暂时被限流,当前显示上次获取的数据。",
"heteroAgent.claudeQuota.scopedWeekly": "每周({{model}})",
"heteroAgent.claudeQuota.title": "Claude Code 额度",
"heteroAgent.claudeQuota.tooltip": "查看 Claude Code 额度",
@@ -341,6 +343,7 @@
"heteroAgent.quota.left": "剩余 {{percent}}%",
"heteroAgent.quota.noData": "暂未获取到额度。",
"heteroAgent.quota.refresh": "刷新额度",
+ "heteroAgent.quota.refreshFailed": "暂时无法刷新额度,当前显示上次获取的数据。",
"heteroAgent.quota.resetsIn": "{{duration}}后重置",
"heteroAgent.quota.resetsSoon": "即将重置",
"heteroAgent.quota.session": "会话",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 5482d01fefd..de06d008c10 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -182,6 +182,10 @@ export default {
'heteroAgent.fullAccess.label': 'Full access',
'heteroAgent.fullAccess.tooltip':
'The local coding agent runs with full read/write access to the working directory. Switching permission modes is not available yet.',
+ 'heteroAgent.claudeQuota.errorRateLimited':
+ 'Claude Code quota is temporarily rate limited. Please try again later.',
+ 'heteroAgent.claudeQuota.refreshRateLimited':
+ 'Quota refresh is temporarily rate limited. Showing the last available data.',
'heteroAgent.claudeQuota.scopedWeekly': 'Weekly ({{model}})',
'heteroAgent.claudeQuota.title': 'Claude Code quota',
'heteroAgent.claudeQuota.tooltip': 'View Claude Code quota',
@@ -209,6 +213,7 @@ export default {
'heteroAgent.quota.left': '{{percent}}% left',
'heteroAgent.quota.noData': 'Quota is not available yet.',
'heteroAgent.quota.refresh': 'Refresh quota',
+ 'heteroAgent.quota.refreshFailed': "Couldn't refresh quota. Showing the last available data.",
'heteroAgent.quota.resetsIn': 'Resets in {{duration}}',
'heteroAgent.quota.resetsSoon': 'Resets soon',
'heteroAgent.quota.session': 'Session',
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ClaudeCodeQuotaMenu.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ClaudeCodeQuotaMenu.tsx
index ee2cbd1917e..0e678564245 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ClaudeCodeQuotaMenu.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ClaudeCodeQuotaMenu.tsx
@@ -6,7 +6,8 @@ import { useTranslation } from 'react-i18next';
import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
-import QuotaMenu, { type QuotaWindowItem } from './QuotaMenu';
+import type { QuotaWindowItem } from './QuotaMenu';
+import QuotaMenu, { createQuotaSourceKey } from './QuotaMenu';
const createErrorSnapshot = (error: unknown): ClaudeCodeQuotaSnapshot => ({
error: error instanceof Error ? error.message : String(error),
@@ -18,12 +19,15 @@ const createErrorSnapshot = (error: unknown): ClaudeCodeQuotaSnapshot => ({
weekly: null,
});
+const isRateLimitError = (quota: ClaudeCodeQuotaSnapshot) => quota.error?.includes('429') ?? false;
+
interface ClaudeCodeQuotaMenuProps {
env?: Record<string, string>;
}
const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ env }) => {
const { t } = useTranslation('chat');
+ const sourceKey = createQuotaSourceKey('claude-code', env);
const fetchQuota = useCallback(
() => heterogeneousAgentService.getClaudeCodeQuota({ env }),
@@ -69,12 +73,29 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ env }) => {
[t],
);
+ const getErrorText = useCallback(
+ (quota: ClaudeCodeQuotaSnapshot) => {
+ if (isRateLimitError(quota)) return t('heteroAgent.claudeQuota.errorRateLimited');
+ },
+ [t],
+ );
+
+ const getRefreshErrorText = useCallback(
+ (quota: ClaudeCodeQuotaSnapshot) => {
+ if (isRateLimitError(quota)) return t('heteroAgent.claudeQuota.refreshRateLimited');
+ },
+ [t],
+ );
+
return (
<QuotaMenu
createErrorSnapshot={createErrorSnapshot}
fetchQuota={fetchQuota}
+ getErrorText={getErrorText}
+ getRefreshErrorText={getRefreshErrorText}
getUnavailableText={getUnavailableText}
getWindows={getWindows}
+ sourceKey={sourceKey}
title={t('heteroAgent.claudeQuota.title')}
tooltip={t('heteroAgent.claudeQuota.tooltip')}
/>
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/CodexQuotaMenu.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/CodexQuotaMenu.tsx
index 234adb56093..c5f9d99e06a 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/CodexQuotaMenu.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/CodexQuotaMenu.tsx
@@ -9,7 +9,8 @@ import { useTranslation } from 'react-i18next';
import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
-import QuotaMenu, { type QuotaMenuHelpers, type QuotaWindowItem } from './QuotaMenu';
+import type { QuotaMenuHelpers, QuotaWindowItem } from './QuotaMenu';
+import QuotaMenu, { createQuotaSourceKey } from './QuotaMenu';
const styles = createStaticStyles(({ css }) => ({
resetCredits: css`
@@ -35,6 +36,7 @@ interface CodexQuotaMenuProps {
const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, env }) => {
const { t } = useTranslation('chat');
+ const sourceKey = createQuotaSourceKey('codex', command, env);
const fetchQuota = useCallback(
() => heterogeneousAgentService.getCodexQuota({ command, env }),
@@ -108,6 +110,7 @@ const CodexQuotaMenu = memo<CodexQuotaMenuProps>(({ command, env }) => {
getWindows={getWindows}
hasExtraData={hasExtraData}
renderFooter={renderFooter}
+ sourceKey={sourceKey}
title={t('heteroAgent.codexQuota.title')}
tooltip={t('heteroAgent.codexQuota.tooltip')}
/>
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx
index 72d1f0af3c1..95c5a746613 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx
@@ -2,7 +2,7 @@
* @vitest-environment happy-dom
*/
import type { ClaudeCodeQuotaSnapshot, CodexQuotaSnapshot } from '@lobechat/electron-client-ipc';
-import { fireEvent, render, screen } from '@testing-library/react';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -47,10 +47,20 @@ vi.mock('@lobehub/ui', () => ({
Icon: () => <svg />,
// Render the popover content unconditionally so window rows are assertable
// without driving the open/close interaction.
- Popover: ({ children, content }: { children?: ReactNode; content?: ReactNode }) => (
+ Popover: ({
+ children,
+ content,
+ onOpenChange,
+ }: {
+ children?: ReactNode;
+ content?: ReactNode;
+ onOpenChange?: (open: boolean) => void;
+ }) => (
<div>
<div data-testid="popover-content">{content}</div>
- {children}
+ <div data-testid="quota-trigger" onClick={() => onOpenChange?.(true)}>
+ {children}
+ </div>
</div>
),
Skeleton: { Button: () => <div data-testid="skeleton" /> },
@@ -83,7 +93,8 @@ const codexSnapshot = (overrides: Partial<CodexQuotaSnapshot> = {}): CodexQuotaS
});
beforeEach(() => {
- vi.clearAllMocks();
+ mockService.getClaudeCodeQuota.mockReset();
+ mockService.getCodexQuota.mockReset();
});
describe('ClaudeCodeQuotaMenu', () => {
@@ -127,19 +138,155 @@ describe('ClaudeCodeQuotaMenu', () => {
expect(screen.queryByText('raw main-process message')).toBeNull();
});
- it('shows the raw error for error snapshots and refetches on refresh', async () => {
+ it('shows a friendly rate-limit message for first-load 429 errors', async () => {
mockService.getClaudeCodeQuota.mockResolvedValue(
- claudeSnapshot({ error: 'usage API returned 429', status: 'error' }),
+ claudeSnapshot({ error: 'Anthropic usage API returned 429', status: 'error' }),
);
render(<ClaudeCodeQuotaMenu />);
- expect(await screen.findByText('usage API returned 429')).toBeTruthy();
+ expect(await screen.findByText('heteroAgent.claudeQuota.errorRateLimited')).toBeTruthy();
+ expect(screen.queryByText('Anthropic usage API returned 429')).toBeNull();
fireEvent.click(screen.getByTestId('refresh'));
expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(2);
});
+ it('renders an error snapshot when the quota request rejects', async () => {
+ const error = new Error('network failed');
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mockService.getClaudeCodeQuota.mockRejectedValueOnce(error);
+
+ try {
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('network failed')).toBeTruthy();
+ expect(consoleError).toHaveBeenCalledWith('Failed to fetch agent quota:', error);
+ } finally {
+ consoleError.mockRestore();
+ }
+ });
+
+ it('keeps the previous quota data when an automatic stale refresh is rate-limited', async () => {
+ const staleUpdatedAt = Date.now() - 61_000;
+
+ mockService.getClaudeCodeQuota
+ .mockResolvedValueOnce(
+ claudeSnapshot({
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ updatedAt: staleUpdatedAt,
+ }),
+ )
+ .mockResolvedValueOnce(
+ claudeSnapshot({ error: 'Anthropic usage API returned 429', status: 'error' }),
+ )
+ .mockResolvedValueOnce(
+ claudeSnapshot({
+ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 },
+ }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('heteroAgent.quota.left:92')).toBeTruthy();
+
+ fireEvent.click(screen.getByTestId('quota-trigger'));
+
+ await waitFor(() => expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(2));
+ expect(screen.getByText('heteroAgent.quota.left:92')).toBeTruthy();
+ expect(screen.queryByText('Anthropic usage API returned 429')).toBeNull();
+ expect(screen.queryByText('heteroAgent.claudeQuota.refreshRateLimited')).toBeNull();
+
+ fireEvent.click(screen.getByTestId('quota-trigger'));
+
+ expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps stale data and shows a friendly prompt when manual refresh is rate-limited', async () => {
+ mockService.getClaudeCodeQuota
+ .mockResolvedValueOnce(
+ claudeSnapshot({
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ }),
+ )
+ .mockResolvedValueOnce(
+ claudeSnapshot({ error: 'Anthropic usage API returned 429', status: 'error' }),
+ );
+
+ render(<ClaudeCodeQuotaMenu />);
+
+ expect(await screen.findByText('heteroAgent.quota.left:92')).toBeTruthy();
+
+ fireEvent.click(screen.getByTestId('refresh'));
+
+ await screen.findByText('heteroAgent.claudeQuota.refreshRateLimited');
+ expect(screen.getByText('heteroAgent.quota.left:92')).toBeTruthy();
+ expect(screen.queryByText('Anthropic usage API returned 429')).toBeNull();
+ });
+
+ it('does not preserve quota data after switching Claude Code credential source', async () => {
+ mockService.getClaudeCodeQuota
+ .mockResolvedValueOnce(
+ claudeSnapshot({
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ }),
+ )
+ .mockResolvedValueOnce(
+ claudeSnapshot({ error: 'Anthropic usage API returned 429', status: 'error' }),
+ );
+
+ const { rerender } = render(<ClaudeCodeQuotaMenu env={{ CLAUDE_CONFIG_DIR: '/profile-a' }} />);
+
+ expect(await screen.findByText('heteroAgent.quota.left:92')).toBeTruthy();
+
+ rerender(<ClaudeCodeQuotaMenu env={{ CLAUDE_CONFIG_DIR: '/profile-b' }} />);
+
+ await waitFor(() => expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(2));
+ expect(await screen.findByText('heteroAgent.claudeQuota.errorRateLimited')).toBeTruthy();
+ expect(screen.queryByText('heteroAgent.quota.left:92')).toBeNull();
+ });
+
+ it('ignores stale request loading updates after switching Claude Code credential source', async () => {
+ const requests: Array<(snapshot: ClaudeCodeQuotaSnapshot) => void> = [];
+ mockService.getClaudeCodeQuota.mockImplementation(
+ () =>
+ new Promise<ClaudeCodeQuotaSnapshot>((resolve) => {
+ requests.push(resolve);
+ }),
+ );
+
+ const { rerender } = render(<ClaudeCodeQuotaMenu env={{ CLAUDE_CONFIG_DIR: '/profile-a' }} />);
+
+ await waitFor(() => expect(requests).toHaveLength(1));
+
+ rerender(<ClaudeCodeQuotaMenu env={{ CLAUDE_CONFIG_DIR: '/profile-b' }} />);
+
+ await waitFor(() => expect(requests).toHaveLength(2));
+
+ await act(async () => {
+ requests[0](
+ claudeSnapshot({
+ session: { resetsAt: null, usedPercent: 8, windowMinutes: 300 },
+ }),
+ );
+ });
+
+ expect(screen.getAllByTestId('skeleton')).toHaveLength(3);
+ expect(screen.queryByText('heteroAgent.quota.noData')).toBeNull();
+ expect((screen.getByTestId('refresh') as HTMLButtonElement).disabled).toBe(true);
+
+ await act(async () => {
+ requests[1](
+ claudeSnapshot({
+ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 },
+ }),
+ );
+ });
+
+ expect(await screen.findByText('heteroAgent.quota.left:80')).toBeTruthy();
+ expect((screen.getByTestId('refresh') as HTMLButtonElement).disabled).toBe(false);
+ });
+
it('renders the empty state when the snapshot has no windows', async () => {
mockService.getClaudeCodeQuota.mockResolvedValue(claudeSnapshot());
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.tsx
index 5746f891d40..7f50d9e1b73 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.tsx
@@ -5,10 +5,11 @@ import { ActionIcon, Flexbox, Icon, Popover, Skeleton, Text, Tooltip } from '@lo
import { createStaticStyles, cssVar, cx } from 'antd-style';
import { ChevronDownIcon, GaugeIcon, RefreshCwIcon } from 'lucide-react';
import type { ReactNode } from 'react';
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
const QUOTA_STALE_MS = 60_000;
+const QUOTA_RETRY_COOLDOWN_MS = 60_000;
const styles = createStaticStyles(({ css }) => ({
emptyState: css`
@@ -26,6 +27,16 @@ const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorErrorBg};
`,
+ refreshNotice: css`
+ padding: 8px;
+ border: 1px solid ${cssVar.colorWarningBorder};
+ border-radius: ${cssVar.borderRadius};
+
+ font-size: 12px;
+ color: ${cssVar.colorWarningText};
+
+ background: ${cssVar.colorWarningBg};
+ `,
header: css`
padding-block-end: 8px;
border-block-end: 1px solid ${cssVar.colorBorderSecondary};
@@ -89,6 +100,17 @@ const styles = createStaticStyles(({ css }) => ({
const clampPercent = (value: number) => Math.min(100, Math.max(0, Math.round(value)));
+type QuotaSourcePart = Record<string, string | undefined> | string | null | undefined;
+
+const normalizeQuotaSourcePart = (part: QuotaSourcePart) => {
+ if (!part || typeof part === 'string') return part ?? null;
+
+ return Object.entries(part).sort(([left], [right]) => left.localeCompare(right));
+};
+
+export const createQuotaSourceKey = (...parts: QuotaSourcePart[]) =>
+ JSON.stringify(parts.map((part) => normalizeQuotaSourcePart(part)));
+
export interface QuotaSnapshotBase {
error: string | null;
status: 'error' | 'ok' | 'unavailable';
@@ -109,16 +131,25 @@ export interface QuotaMenuHelpers {
interface QuotaMenuProps<S extends QuotaSnapshotBase> {
createErrorSnapshot: (error: unknown) => S;
fetchQuota: () => Promise<S>;
+ /** Localized explanation for `status: 'error'`; falls back to `error`. */
+ getErrorText?: (quota: S) => string | undefined;
+ /** Localized explanation for a manual refresh error when stale data is preserved. */
+ getRefreshErrorText?: (quota: S) => string | undefined;
/** Localized explanation for `status: 'unavailable'`; falls back to `error`. */
getUnavailableText?: (quota: S) => string | undefined;
getWindows: (quota: S) => QuotaWindowItem[];
/** Extra agent-specific data (beyond windows) that makes the body worth rendering. */
hasExtraData?: (quota: S) => boolean;
renderFooter?: (quota: S, helpers: QuotaMenuHelpers) => ReactNode;
+ sourceKey?: string;
title: string;
tooltip: string;
}
+interface LoadQuotaOptions {
+ manual?: boolean;
+}
+
/**
* Shared quota popover for local CLI agents: gauge trigger with the most
* binding window's remaining percent, plus per-window progress bars and
@@ -127,10 +158,13 @@ interface QuotaMenuProps<S extends QuotaSnapshotBase> {
const QuotaMenu = <S extends QuotaSnapshotBase>({
createErrorSnapshot,
fetchQuota,
+ getErrorText,
+ getRefreshErrorText,
getUnavailableText,
getWindows,
hasExtraData,
renderFooter,
+ sourceKey = 'default',
title,
tooltip,
}: QuotaMenuProps<S>) => {
@@ -138,25 +172,94 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
const [quota, setQuota] = useState<S | null>(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 loadQuota = useCallback(async () => {
- setLoading(true);
-
- try {
- const nextQuota = await fetchQuota();
- setQuota(nextQuota);
- } catch (error) {
- console.error('Failed to fetch agent quota:', error);
- setQuota(createErrorSnapshot(error));
- } finally {
- setLoading(false);
- }
- }, [createErrorSnapshot, fetchQuota]);
+ const hasQuotaDataForSnapshot = useCallback(
+ (snapshot: S | null) => {
+ if (!snapshot) return false;
+
+ return getWindows(snapshot).some((item) => item.window) || !!hasExtraData?.(snapshot);
+ },
+ [getWindows, hasExtraData],
+ );
+
+ const setQuotaSnapshot = useCallback((nextQuota: S) => {
+ quotaRef.current = nextQuota;
+ setQuota(nextQuota);
+ }, []);
+
+ const isCurrentRequest = useCallback(
+ (requestId: number, requestSourceKey: string) =>
+ requestId === requestIdRef.current && requestSourceKey === sourceKeyRef.current,
+ [],
+ );
+
+ const applyQuotaResult = useCallback(
+ (
+ nextQuota: S,
+ options: LoadQuotaOptions = {},
+ requestId = requestIdRef.current,
+ requestSourceKey = sourceKeyRef.current,
+ ) => {
+ if (!isCurrentRequest(requestId, requestSourceKey)) return;
+
+ if (nextQuota.status === 'error') {
+ lastTransientErrorAtRef.current = Date.now();
+
+ if (hasQuotaDataForSnapshot(quotaRef.current)) {
+ if (options.manual) setRefreshError(nextQuota);
+ return;
+ }
+ } else {
+ lastTransientErrorAtRef.current = 0;
+ }
+
+ setRefreshError(null);
+ setQuotaSnapshot(nextQuota);
+ },
+ [hasQuotaDataForSnapshot, isCurrentRequest, setQuotaSnapshot],
+ );
+
+ const loadQuota = useCallback(
+ async (options: LoadQuotaOptions = {}) => {
+ const requestSourceKey = sourceKeyRef.current;
+ const requestId = requestIdRef.current + 1;
+ requestIdRef.current = requestId;
+
+ setRefreshError(null);
+ setLoading(true);
+
+ try {
+ const nextQuota = await fetchQuota();
+ applyQuotaResult(nextQuota, options, requestId, requestSourceKey);
+ } catch (error) {
+ console.error('Failed to fetch agent quota:', error);
+ applyQuotaResult(createErrorSnapshot(error), options, requestId, requestSourceKey);
+ } finally {
+ if (isCurrentRequest(requestId, requestSourceKey)) {
+ setLoading(false);
+ }
+ }
+ },
+ [applyQuotaResult, createErrorSnapshot, fetchQuota, isCurrentRequest],
+ );
+
+ useEffect(() => {
+ sourceKeyRef.current = sourceKey;
+ quotaRef.current = null;
+ lastTransientErrorAtRef.current = 0;
+ setQuota(null);
+ setRefreshError(null);
+ }, [sourceKey]);
useEffect(() => {
void loadQuota();
- }, [loadQuota]);
+ }, [loadQuota, sourceKey]);
useEffect(() => {
const interval = window.setInterval(() => setNow(Date.now()), QUOTA_STALE_MS);
@@ -213,14 +316,23 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
const windows = quota ? getWindows(quota) : [];
const firstWindow = windows.find((item) => item.window)?.window;
const compactLeftPercent = firstWindow ? clampPercent(100 - firstWindow.usedPercent) : undefined;
- const hasQuotaData = windows.some((item) => item.window) || (!!quota && !!hasExtraData?.(quota));
+ const hasQuotaData = hasQuotaDataForSnapshot(quota);
+ const refreshErrorText =
+ refreshError && (getRefreshErrorText?.(refreshError) || t('heteroAgent.quota.refreshFailed'));
const handleOpenChange = useCallback(
(nextOpen: boolean) => {
setOpen(nextOpen);
if (!nextOpen || loading) return;
- if (!quota || Date.now() - quota.updatedAt > QUOTA_STALE_MS) void loadQuota();
+ const currentTime = Date.now();
+ const recentlyFailed =
+ lastTransientErrorAtRef.current > 0 &&
+ currentTime - lastTransientErrorAtRef.current < QUOTA_RETRY_COOLDOWN_MS;
+
+ if ((!quota || currentTime - quota.updatedAt > QUOTA_STALE_MS) && !recentlyFailed) {
+ void loadQuota();
+ }
},
[loadQuota, loading, quota],
);
@@ -269,7 +381,7 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
disabled={loading}
icon={RefreshCwIcon}
size={'small'}
- onClick={() => void loadQuota()}
+ onClick={() => void loadQuota({ manual: true })}
/>
</Tooltip>
</Flexbox>
@@ -285,11 +397,14 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({
{getUnavailableText?.(quota) || quota.error || t('heteroAgent.quota.unavailable')}
</div>
) : quota?.status === 'error' ? (
- <div className={styles.error}>{quota.error || t('heteroAgent.quota.unavailable')}</div>
+ <div className={styles.error}>
+ {getErrorText?.(quota) || quota.error || t('heteroAgent.quota.unavailable')}
+ </div>
) : hasQuotaData ? (
<>
<Flexbox gap={10}>{windows.map((item) => renderQuotaWindow(item))}</Flexbox>
{quota && renderFooter?.(quota, { formatDuration, now })}
+ {refreshErrorText && <div className={styles.refreshNotice}>{refreshErrorText}</div>}
</>
) : (
<div className={styles.emptyState}>{t('heteroAgent.quota.noData')}</div>