🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(quota): tell a network-blocked Claude quota sample apart from an expired login (#20844)
Arvin Xu21930468acd9
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 1fa4b67e27d..e6d9ff2690d 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1284,6 +1284,7 @@"heteroAgent.claudeQuota.unavailableExpired": "Claude Code login has expired. Start a Claude Code conversation or run claude in a terminal, then refresh.","heteroAgent.claudeQuota.unavailableExternalAuth": "This agent uses an API key / custom endpoint, so subscription quota does not apply.","heteroAgent.claudeQuota.unavailableNotFound": "No Claude Code login found. Run claude in a terminal to sign in first.",+ "heteroAgent.claudeQuota.unavailableRequestBlocked": "Anthropic refused the quota request from this machine's network (usually a region restriction). Check the machine's network proxy, then refresh.","heteroAgent.claudeSdkRuntime.state.closed": "SDK closed","heteroAgent.claudeSdkRuntime.state.closing": "SDK closing","heteroAgent.claudeSdkRuntime.state.error": "SDK error",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex d8e2c1b2ac8..cd497088d5e 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1284,6 +1284,7 @@"heteroAgent.claudeQuota.unavailableExpired": "Claude Code 登录已过期,发起一次 Claude Code 对话或在终端运行 claude 后再刷新。","heteroAgent.claudeQuota.unavailableExternalAuth": "当前 Agent 使用 API Key / 自定义接入点运行,订阅额度不适用。","heteroAgent.claudeQuota.unavailableNotFound": "未找到 Claude Code 登录凭证,请先在终端运行 claude 完成登录。",+ "heteroAgent.claudeQuota.unavailableRequestBlocked": "Anthropic 拒绝了来自该设备网络的额度请求(通常是地区限制),请检查该设备的网络代理后再刷新。","heteroAgent.claudeSdkRuntime.state.closed": "SDK 已关闭","heteroAgent.claudeSdkRuntime.state.closing": "SDK 正在关闭","heteroAgent.claudeSdkRuntime.state.error": "SDK 异常",diff --git a/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.tsindex a13760ac468..aa1f21789eb 100644--- a/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts+++ b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.test.ts@@ -415,6 +415,34 @@ describe('fetchClaudeCodeQuota', () => {expect(result.error).toContain('401');});+ it('reports a network-blocked 403 as request-blocked, not an expired login', async () => {+ setPlatform('linux');+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));+ vi.mocked(fetch).mockResolvedValue({+ json: async () => ({ error: { message: 'Request not allowed', type: 'forbidden' } }),+ ok: false,+ status: 403,+ } as Response);++ const result = await fetchClaudeCodeQuota();++ expect(result).toMatchObject({ reason: 'request-blocked', status: 'unavailable' });+ });++ it('keeps a token-rejecting 403 as an expired login', async () => {+ setPlatform('linux');+ vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));+ vi.mocked(fetch).mockResolvedValue({+ json: async () => ({ error: { message: 'OAuth token revoked', type: 'permission_error' } }),+ ok: false,+ status: 403,+ } as Response);++ const result = await fetchClaudeCodeQuota();++ expect(result).toMatchObject({ reason: 'credentials-expired', status: 'unavailable' });+ });+it('surfaces a 429 as a transient error', async () => {setPlatform('linux');vi.mocked(readFile).mockResolvedValue(credentialsJson(FRESH_EXPIRES_AT));diff --git a/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.tsindex b9ab22620b3..282fb5dc2df 100644--- a/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts+++ b/packages/heterogeneous-agents/src/quota-sampler/claudeCodeQuota.ts@@ -106,6 +106,21 @@ const unavailableSnapshot = (status: 'unavailable',});+/**+ * Anthropic answers a request from a blocked network or region with a 403+ * `forbidden` error ("Request not allowed") before it ever looks at the token,+ * so it says nothing about the login. A 403 for a bad token carries an auth /+ * permission error type instead.+ */+const isRequestBlocked = async (response: Response) => {+ try {+ const body = (await response.json()) as { error?: { type?: unknown } };+ return body?.error?.type === 'forbidden';+ } catch {+ return false;+ }+};+const parseCredentialsJson = (raw: string): ClaudeOAuthCredentials | null => {try {const parsed = JSON.parse(raw) as {@@ -266,6 +281,13 @@ export const fetchClaudeCodeQuota = async (signal: controller.signal,});+ if (response.status === 403 && (await isRequestBlocked(response))) {+ return unavailableSnapshot(+ 'request-blocked',+ 'Anthropic usage API blocked the request from this network (403)',+ );+ }+if (response.status === 401 || response.status === 403) {return unavailableSnapshot('credentials-expired',diff --git a/packages/heterogeneous-agents/src/quota/snapshot.ts b/packages/heterogeneous-agents/src/quota/snapshot.tsindex 3cbe181c693..5ee5d64af9c 100644--- a/packages/heterogeneous-agents/src/quota/snapshot.ts+++ b/packages/heterogeneous-agents/src/quota/snapshot.ts@@ -62,10 +62,12 @@ export type CodexRateLimitResetOutcome =/*** Why the quota can't be shown. `external-auth` means the agent is configured* with an API key / custom base url, so subscription quota does not apply;- * the credential reasons mean no fresh OAuth login was found on this machine.+ * the credential reasons mean no fresh OAuth login was found on this machine;+ * `request-blocked` means Anthropic refused the sampling machine's network+ * (region / missing proxy) before checking the login.*/export type ClaudeCodeQuotaUnavailableReason =- 'credentials-expired' | 'credentials-not-found' | 'external-auth';+ 'credentials-expired' | 'credentials-not-found' | 'external-auth' | 'request-blocked';export interface ClaudeCodeScopedWeekly {/** Display name of the model the window is scoped to, e.g. "Fable". */diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex de9b4fe3ac6..ab557db93fd 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -626,6 +626,8 @@ export default {'This agent uses an API key / custom endpoint, so subscription quota does not apply.','heteroAgent.claudeQuota.unavailableNotFound':'No Claude Code login found. Run claude in a terminal to sign in first.',+ 'heteroAgent.claudeQuota.unavailableRequestBlocked':+ "Anthropic refused the quota request from this machine's network (usually a region restriction). Check the machine's network proxy, then refresh.",'heteroAgent.claudeSdkRuntime.state.closed': 'SDK closed','heteroAgent.claudeSdkRuntime.state.closing': 'SDK closing','heteroAgent.claudeSdkRuntime.state.error': 'SDK error',diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsxindex b7d2fc5d5f1..70a30060474 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/ClaudeCodeQuotaMenu.tsx@@ -51,6 +51,14 @@ const unavailableSnapshot = (weekly: null,});+/**+ * Persisted windows merged with a live sample that came back unavailable keep+ * the live reason, so the panel can say why the windows stopped refreshing.+ */+type ClaudeCodePanelSnapshot = ClaudeCodeQuotaSnapshot & {+ refreshUnavailableReason?: ClaudeCodeQuotaSnapshot['reason'];+};+const isRateLimitError = (quota: ClaudeCodeQuotaSnapshot) => quota.error?.includes('429') ?? false;interface ClaudeCodeQuotaMenuProps {@@ -79,8 +87,8 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =*/const fetchQuota = useCallback(async (- options?: FetchQuotaOptions<ClaudeCodeQuotaSnapshot>,- ): Promise<ClaudeCodeQuotaSnapshot> => {+ options?: FetchQuotaOptions<ClaudeCodePanelSnapshot>,+ ): Promise<ClaudeCodePanelSnapshot> => {const force = !!options?.force;// 1) Resolve the account to display — pinned for this agent, else the first.@@ -158,7 +166,11 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =// reading wins. With no account resolved at all there is nothing to// attribute the sample to, so the live snapshot stands on its own.const merged = account ? buildClaudePanelSnapshot(account, readings, live) : null;- if (merged && hasRenderableWindow(merged)) return merged;+ if (merged && hasRenderableWindow(merged)) {+ return live?.status === 'unavailable' && live.reason+ ? { ...merged, refreshUnavailableReason: live.reason }+ : merged;+ }return live ?? merged ?? unavailableSnapshot();},[agentId, deviceId, env, trustedDeviceAccounts],@@ -197,9 +209,9 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =[t],);- const getUnavailableText = useCallback(- (quota: ClaudeCodeQuotaSnapshot) => {- switch (quota.reason) {+ const getReasonText = useCallback(+ (reason: ClaudeCodeQuotaSnapshot['reason']) => {+ switch (reason) {case 'credentials-expired': {return t('heteroAgent.claudeQuota.unavailableExpired');}@@ -209,6 +221,9 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =case 'external-auth': {return t('heteroAgent.claudeQuota.unavailableExternalAuth');}+ case 'request-blocked': {+ return t('heteroAgent.claudeQuota.unavailableRequestBlocked');+ }default: {return undefined;}@@ -217,6 +232,17 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =[t],);+ const getUnavailableText = useCallback(+ (quota: ClaudeCodeQuotaSnapshot) => getReasonText(quota.reason),+ [getReasonText],+ );++ const getStaleNotice = useCallback(+ (quota: ClaudeCodePanelSnapshot) =>+ quota.refreshUnavailableReason ? getReasonText(quota.refreshUnavailableReason) : undefined,+ [getReasonText],+ );+const getErrorText = useCallback((quota: ClaudeCodeQuotaSnapshot) => {if (isRateLimitError(quota)) return t('heteroAgent.claudeQuota.errorRateLimited');@@ -241,6 +267,7 @@ const ClaudeCodeQuotaMenu = memo<ClaudeCodeQuotaMenuProps>(({ deviceId, env }) =fetchQuota={fetchQuota}getErrorText={getErrorText}getRefreshErrorText={getRefreshErrorText}+ getStaleNotice={getStaleNotice}getUnavailableText={getUnavailableText}getWindows={getWindows}sourceKey={sourceKey}diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsxindex b4dd18ea773..d761dcd040e 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx@@ -657,6 +657,37 @@ describe('ClaudeCodeQuotaMenu', () => {expect(screen.queryByText('raw main-process message')).toBeNull();});+ it('explains a network-blocked sample instead of reporting an expired login', async () => {+ mockService.getClaudeCodeQuota.mockResolvedValue(+ claudeSnapshot({ error: 'blocked (403)', reason: 'request-blocked', status: 'unavailable' }),+ );++ render(<ClaudeCodeQuotaMenu />);++ expect(+ await screen.findByText('heteroAgent.claudeQuota.unavailableRequestBlocked'),+ ).toBeTruthy();+ expect(screen.queryByText('heteroAgent.claudeQuota.unavailableExpired')).toBeNull();+ });++ it('keeps the unavailable explanation on screen while a retry is in flight', async () => {+ mockService.getClaudeCodeQuota.mockResolvedValueOnce(+ claudeSnapshot({ error: 'expired', reason: 'credentials-expired', status: 'unavailable' }),+ );++ render(<ClaudeCodeQuotaMenu />);++ expect(await screen.findByText('heteroAgent.claudeQuota.unavailableExpired')).toBeTruthy();++ mockService.getClaudeCodeQuota.mockImplementation(() => new Promise(() => {}));+ fireEvent.click(screen.getByTestId('refresh'));++ await waitFor(() => expect(mockService.getClaudeCodeQuota).toHaveBeenCalledTimes(2));+ expect((screen.getByTestId('refresh') as HTMLButtonElement).disabled).toBe(true);+ expect(screen.queryByTestId('skeleton')).toBeNull();+ expect(screen.getByText('heteroAgent.claudeQuota.unavailableExpired')).toBeTruthy();+ });+it('shows a friendly rate-limit message for first-load 429 errors', async () => {mockService.getClaudeCodeQuota.mockResolvedValue(claudeSnapshot({ error: 'Anthropic usage API returned 429', status: 'error' }),@@ -974,6 +1005,23 @@ describe('ClaudeCodeQuotaMenu', () => {);});+ it('explains a blocked live refresh under the persisted windows it could not update', async () => {+ mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 31 * 60_000)]);+ mockQuotaService.getLatestReadings.mockResolvedValue([+ persistedSessionReading(Date.now() - 31 * 60_000),+ ]);+ mockService.getClaudeCodeQuota.mockResolvedValue(+ claudeSnapshot({ error: 'blocked (403)', reason: 'request-blocked', status: 'unavailable' }),+ );++ render(<ClaudeCodeQuotaMenu />);++ expect(+ await screen.findByText('heteroAgent.claudeQuota.unavailableRequestBlocked'),+ ).toBeTruthy();+ expect(screen.getByText('92%')).toBeTruthy();+ });+it('paints persisted windows while a stale live refresh is still in flight', async () => {mockQuotaService.listAccounts.mockResolvedValue([persistedAccount(Date.now() - 31 * 60_000)]);mockQuotaService.getLatestReadings.mockResolvedValue([diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsxindex dc6cd28b201..039ae7059a7 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.tsx@@ -2,7 +2,7 @@import type { HeteroQuotaWindow } from '@lobechat/electron-client-ipc';import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';-import { ActionIcon, Skeleton, Text } from '@lobehub/ui/base-ui';+import { ActionIcon, Alert, Skeleton, Text } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';import { ChevronDownIcon, GaugeIcon, RefreshCwIcon } from 'lucide-react';import type { ReactNode } from 'react';@@ -43,16 +43,6 @@ 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: 6px;border-block-end: 1px solid ${cssVar.colorBorderSecondary};@@ -217,6 +207,11 @@ interface QuotaMenuProps<S extends QuotaSnapshotBase> {getErrorText?: (quota: S) => string | undefined;/** Localized explanation for a manual refresh error when stale data is preserved. */getRefreshErrorText?: (quota: S) => string | undefined;+ /**+ * Localized notice for a snapshot that still renders preserved windows but+ * whose latest live refresh could not run (e.g. the network was blocked).+ */+ getStaleNotice?: (quota: S) => string | undefined;/** Localized explanation for `status: 'unavailable'`; falls back to `error`. */getUnavailableText?: (quota: S) => string | undefined;getWindows: (quota: S) => QuotaWindowItem[];@@ -247,6 +242,7 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({fetchQuota,getErrorText,getRefreshErrorText,+ getStaleNotice,getUnavailableText,getWindows,hasExtraData,@@ -491,7 +487,11 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({quota?.status === 'error' && hasQuotaData? getRefreshErrorText?.(quota) || t('heteroAgent.quota.refreshFailed'): undefined;- const refreshErrorText = manualRefreshErrorText || staleSnapshotErrorText;+ const staleNoticeText = quota && hasQuotaData ? getStaleNotice?.(quota) : undefined;+ const refreshErrorText = manualRefreshErrorText || staleSnapshotErrorText || staleNoticeText;+ // An unavailable / error explanation stays readable while a retry runs;+ // swapping it for a skeleton every poll made it look like data was loading.+ const hasStatusMessage = quota?.status === 'unavailable' || quota?.status === 'error';const handleOpenChange = useCallback((nextOpen: boolean) => {@@ -578,12 +578,13 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({disabled={loading}icon={RefreshCwIcon}size={'small'}+ spin={loading}onClick={() => void loadQuota({ manual: true })}/></Tooltip></Flexbox>- {loading && !hasQuotaData ? (+ {loading && !hasQuotaData && !hasStatusMessage ? (<Flexbox gap={8}><Skeleton height={18} /><Skeleton height={18} />@@ -602,7 +603,16 @@ const QuotaMenu = <S extends QuotaSnapshotBase>({{quota && renderHeader?.(quota, { applyQuota, formatDuration, now })}<Flexbox gap={10}>{windows.map((item) => renderQuotaWindow(item))}</Flexbox>{quota && renderFooter?.(quota, { applyQuota, formatDuration, now })}- {refreshErrorText && <div className={styles.refreshNotice}>{refreshErrorText}</div>}+ {refreshErrorText && (+ // Stale windows stay the subject; the notice only annotates them.+ <Alert+ showIcon+ styles={{ title: { color: cssVar.colorTextSecondary, fontSize: 12 } }}+ title={refreshErrorText}+ type={'warning'}+ variant={'plain'}+ />+ )}</>) : (<div className={styles.emptyState}>{t('heteroAgent.quota.noData')}</div>