🤯 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
✨ feat(desktop): auto-retry Claude Code overloaded errors with in-place replace (#16277)
Arvin Xu84d963152053
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 3954c8da5b4..c94c5486c43 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -78,6 +78,10 @@"cliAuthGuide.runCommand": "Run this in Terminal","cliAuthGuide.title": "Sign in to {{name}}","cliOverloadedGuide.actions.retry": "Retry",+ "cliOverloadedGuide.autoRetry.actions.cancel": "Stop auto-retry",+ "cliOverloadedGuide.autoRetry.actions.retryNow": "Retry now",+ "cliOverloadedGuide.autoRetry.status": "Upstream is temporarily overloaded (not your usage limit) · retry {{attempt}}/{{max}} in {{seconds}}s",+ "cliOverloadedGuide.autoRetry.title": "{{name}} is busy — retrying automatically…","cliOverloadedGuide.desc": "{{name}}'s upstream model service is temporarily overloaded. This usually clears in a moment.","cliOverloadedGuide.errorDetails": "Error details","cliOverloadedGuide.retryHint": "Wait a few seconds and retry. If it keeps failing, the provider may be having a wider incident.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 398bb87f74b..ac5a1afaa54 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -78,6 +78,10 @@"cliAuthGuide.runCommand": "在终端执行","cliAuthGuide.title": "登录 {{name}}","cliOverloadedGuide.actions.retry": "重试",+ "cliOverloadedGuide.autoRetry.actions.cancel": "停止自动重试",+ "cliOverloadedGuide.autoRetry.actions.retryNow": "立即重试",+ "cliOverloadedGuide.autoRetry.status": "上游服务暂时过载(不是你的用量限制)· {{seconds}} 秒后重试(第 {{attempt}}/{{max}} 次)",+ "cliOverloadedGuide.autoRetry.title": "{{name}} 服务繁忙,正在自动重试…","cliOverloadedGuide.desc": "{{name}} 当前依赖的上游模型服务暂时过载,通常很快就能自动恢复。","cliOverloadedGuide.errorDetails": "错误详情","cliOverloadedGuide.retryHint": "稍等几秒重试即可。如果一直失败,可能是模型服务商出现了更大范围的故障。",diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.tsindex 8b1e54969c1..41b0e963e1e 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts@@ -152,6 +152,54 @@ describe('ClaudeCodeAdapter', () => {expect(events[1].data).toMatchObject({ code: 'overloaded', message: rawError });});+ it('replays a real session that streamed a turn then overloaded → overloaded + clears echo', () => {+ // Faithful transport-layer replay of a captured CC session shape: init →+ // a streamed assistant turn → the exact upstream throttle the user hit+ // (api_error_status 429 + the "not your usage limit" wording, alongside a+ // generic rate_limit_event with no reset window). This is how the+ // overloaded guide is driven without waiting on a real upstream outage.+ const adapter = new ClaudeCodeAdapter();+ const rawError =+ 'API Error: Server is temporarily limiting requests (not your usage limit) · Rate limited';++ adapter.adapt({+ model: 'claude-opus-4-8',+ session_id: 'sess_replay',+ subtype: 'init',+ type: 'system',+ });+ // A turn that already streamed content before the throttle landed.+ adapter.adapt({+ message: {+ content: [{ text: 'Let me read loadEvidence and the runner', type: 'text' }],+ id: 'msg_replay',+ role: 'assistant',+ },+ type: 'assistant',+ });+ adapter.adapt({+ rate_limit_info: { isUsingOverage: false, status: 'rejected' },+ type: 'rate_limit_event',+ });++ const events = adapter.adapt({+ api_error_status: 429,+ is_error: true,+ result: rawError,+ type: 'result',+ });++ const errorEvent = events.find((e) => e.type === 'error');+ expect(errorEvent?.data).toMatchObject({+ agentType: 'claude-code',+ // The UI keys auto-retry on this exact code; clearEchoedContent wipes+ // the half-streamed turn so the guide stands in for the whole bubble.+ clearEchoedContent: true,+ code: 'overloaded',+ message: rawError,+ });+ });+it('classifies a user quota limit from rateLimitType alone (no resetsAt)', () => {const adapter = new ClaudeCodeAdapter();const rawError = 'API Error: 429 · Rate limited';diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex a9bbd48699c..8f374bc5860 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -393,6 +393,11 @@ export default {'cliAuthGuide.runCommand': 'Run this in Terminal','cliAuthGuide.title': 'Sign in to {{name}}','cliOverloadedGuide.actions.retry': 'Retry',+ 'cliOverloadedGuide.autoRetry.actions.cancel': 'Stop auto-retry',+ 'cliOverloadedGuide.autoRetry.actions.retryNow': 'Retry now',+ 'cliOverloadedGuide.autoRetry.status':+ 'Upstream is temporarily overloaded (not your usage limit) · retry {{attempt}}/{{max}} in {{seconds}}s',+ 'cliOverloadedGuide.autoRetry.title': '{{name}} is busy — retrying automatically…','cliOverloadedGuide.desc':"{{name}}'s upstream model service is temporarily overloaded. This usually clears in a moment.",'cliOverloadedGuide.errorDetails': 'Error details',diff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsxindex 3dbbc492aad..2133770ae31 100644--- a/src/features/Conversation/Error/index.test.tsx+++ b/src/features/Conversation/Error/index.test.tsx@@ -113,10 +113,20 @@ vi.mock('@/store/serverConfig', () => ({}));vi.mock('@/features/Conversation/store', () => ({+ dataSelectors: {+ getDisplayMessageById: () => () => undefined,+ },useConversationStore: (selector: (state: unknown) => unknown) =>selector({+ delAndRegenerateMessage: vi.fn(),deleteMessage: vi.fn(),- regenerateAssistantMessage: vi.fn(),+ heteroOverloadRetryAttempts: {},+ internal_beginHeteroOverloadWait: vi.fn(),+ internal_endHeteroOverloadWait: vi.fn(),+ isHeteroOverloadWaitAborted: () => false,+ markHeteroOverloadRetryExhausted: vi.fn(),+ recordHeteroOverloadRetry: vi.fn(),+ resetHeteroOverloadRetry: vi.fn(),}),}));diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex ea433ac5812..e1e69893632 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -13,7 +13,7 @@ import useBusinessErrorAlertConfig from '@/business/client/hooks/useBusinessErroimport useBusinessErrorContent from '@/business/client/hooks/useBusinessErrorContent';import useRenderBusinessChatErrorMessageExtra from '@/business/client/hooks/useRenderBusinessChatErrorMessageExtra';import ErrorContent from '@/features/Conversation/ChatItem/components/ErrorContent';-import { useConversationStore } from '@/features/Conversation/store';+import { dataSelectors, useConversationStore } from '@/features/Conversation/store';import HeterogeneousAgentStatusGuide from '@/features/Electron/HeterogeneousAgent/StatusGuide';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { usePermission } from '@/hooks/usePermission';@@ -23,6 +23,7 @@ import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfiimport { getRuntimeErrorMessage } from '@/utils/locale/runtimeErrorMessage';import ChatInvalidAPIKey from './ChatInvalidApiKey';+import { useHeterogeneousAutoRetry } from './useHeterogeneousAutoRetry';interface ErrorMessageData {error?: ChatMessageError | null;@@ -155,7 +156,7 @@ const shouldShowTraceIdError = (return !hasLocalizedErrorMessage(errorType);};-const isHeterogeneousAgentStatusGuideError = (+export const isHeterogeneousAgentStatusGuideError = (value: unknown,): value is HeterogeneousAgentSessionError => {if (!value || typeof value !== 'object') return false;@@ -248,121 +249,164 @@ interface ErrorExtraProps {data: ErrorMessageData;error?: AlertProps;onRegenerate?: () => void;+ /**+ * Stable scope key for the overloaded auto-retry counter (the parent user+ * message id). The group surface must pass it explicitly because its+ * `data.id` is a nested child block, not a top-level displayMessage; the+ * standalone surface omits it and the parent is resolved from `data.id`.+ */+ retryScopeId?: string;}-const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data, onRegenerate }) => {- const error = data.error;- const navigate = useWorkspaceAwareNavigate();- const businessChatErrorMessageExtra = useRenderBusinessChatErrorMessageExtra(error, data.id);- const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);- const { allowed: canCreate } = usePermission('create_content');- const sessionErrorBody = error?.body;- const rawErrorMessage = getRawErrorMessage(error) || alertError?.message;-- const regenerateAssistantMessage = useConversationStore((s) => s.regenerateAssistantMessage);- const deleteMessage = useConversationStore((s) => s.deleteMessage);- const handleRetryAgentMessage = useCallback(() => {- if (!canCreate) return;- if (onRegenerate) {- onRegenerate();- return;- }- regenerateAssistantMessage(data.id);- if (data.error) deleteMessage(data.id);- }, [canCreate, data.error, data.id, deleteMessage, onRegenerate, regenerateAssistantMessage]);-- if (isHeterogeneousAgentStatusGuideError(sessionErrorBody)) {- return (- <HeterogeneousAgentStatusGuide- agentType={sessionErrorBody.agentType}- error={sessionErrorBody}- onOpenSystemTools={() => navigate('/settings/system-tools')}- onRetry={handleRetryAgentMessage}- />+const ErrorMessageExtra = memo<ErrorExtraProps>(+ ({ error: alertError, data, onRegenerate, retryScopeId }) => {+ const error = data.error;+ const navigate = useWorkspaceAwareNavigate();+ const businessChatErrorMessageExtra = useRenderBusinessChatErrorMessageExtra(error, data.id);+ const enableBusinessFeatures = useServerConfigStore(+ serverConfigSelectors.enableBusinessFeatures,+ );+ const { allowed: canCreate } = usePermission('create_content');+ const sessionErrorBody = error?.body;+ const rawErrorMessage = getRawErrorMessage(error) || alertError?.message;++ const delAndRegenerateMessage = useConversationStore((s) => s.delAndRegenerateMessage);+ const resetHeteroOverloadRetry = useConversationStore((s) => s.resetHeteroOverloadRetry);+ // Standalone surface: data.id is the top-level assistant message, so its+ // parentId is the user message. Group surface passes retryScopeId directly.+ const resolvedScopeId = useConversationStore(+ (s) => retryScopeId ?? dataSelectors.getDisplayMessageById(data.id)(s)?.parentId,);- }- if (enableBusinessFeatures && businessChatErrorMessageExtra) return businessChatErrorMessageExtra;-- switch (error?.type) {- // Lightweight fallbacks for cloud billing errors, used in builds without a- // business override (e.g. desktop). The business hook above takes- // precedence when installed.- case ChatErrorType.FreePlanLimit:- case ChatErrorType.SubscriptionPlanLimit:- case ChatErrorType.InsufficientBudgetForModel: {- if (enableBusinessFeatures)- return (- <PlanLimitCard- errorBody={error?.body}- errorType={error?.type}- onRetry={handleRetryAgentMessage}- />- );- break;+ const handleRetryAgentMessage = useCallback(() => {+ if (!canCreate) return;+ if (onRegenerate) {+ onRegenerate();+ return;+ }+ // Replace the failed attempt in place (delete-first, then regenerate) so+ // a transient overload/auto-retry doesn't pollute history with sibling+ // branches. Regenerate-first would switch the branch away before the+ // delete, leaving the failed attempt behind on each retry.+ void delAndRegenerateMessage(data.id);+ }, [canCreate, data.id, delAndRegenerateMessage, onRegenerate]);++ // A human-initiated retry restarts the auto-retry budget so the user isn't+ // stuck on the manual card after the cap was reached automatically.+ const handleManualRetry = useCallback(() => {+ if (resolvedScopeId) resetHeteroOverloadRetry(resolvedScopeId);+ handleRetryAgentMessage();+ }, [handleRetryAgentMessage, resetHeteroOverloadRetry, resolvedScopeId]);++ const autoRetry = useHeterogeneousAutoRetry({+ // Must be an actual heterogeneous-agent (CC / Codex) overloaded error —+ // not just any ChatMessageError whose body happens to carry+ // `code: 'overloaded'`. This guard runs before the same predicate gates+ // the guide render below, so without it a provider/tool error rendering+ // the normal card could be silently retried.+ enabled:+ canCreate &&+ isHeterogeneousAgentStatusGuideError(sessionErrorBody) &&+ sessionErrorBody.code === HeterogeneousAgentSessionErrorCode.Overloaded,+ onRetry: handleRetryAgentMessage,+ scopeId: resolvedScopeId,+ });++ if (isHeterogeneousAgentStatusGuideError(sessionErrorBody)) {+ return (+ <HeterogeneousAgentStatusGuide+ agentType={sessionErrorBody.agentType}+ autoRetry={autoRetry}+ error={sessionErrorBody}+ onOpenSystemTools={() => navigate('/settings/system-tools')}+ onRetry={handleManualRetry}+ />+ );}- case ChatErrorType.LobeHubModelDeprecated: {- if (enableBusinessFeatures)- return <DeprecatedModelError requestedModel={error?.body?.requestedModel} />;- break;- }+ if (enableBusinessFeatures && businessChatErrorMessageExtra)+ return businessChatErrorMessageExtra;++ switch (error?.type) {+ // Lightweight fallbacks for cloud billing errors, used in builds without a+ // business override (e.g. desktop). The business hook above takes+ // precedence when installed.+ case ChatErrorType.FreePlanLimit:+ case ChatErrorType.SubscriptionPlanLimit:+ case ChatErrorType.InsufficientBudgetForModel: {+ if (enableBusinessFeatures)+ return (+ <PlanLimitCard+ errorBody={error?.body}+ errorType={error?.type}+ onRetry={handleRetryAgentMessage}+ />+ );+ break;+ }- case AgentRuntimeErrorType.QuotaLimitReached:- case AgentRuntimeErrorType.RateLimitExceeded: {- if (enableBusinessFeatures) return <QuotaLimitError id={data.id} />;- break;- }+ case ChatErrorType.LobeHubModelDeprecated: {+ if (enableBusinessFeatures)+ return <DeprecatedModelError requestedModel={error?.body?.requestedModel} />;+ break;+ }- case AgentRuntimeErrorType.OllamaServiceUnavailable: {- return <OllamaSetupGuide id={data.id} />;- }+ case AgentRuntimeErrorType.QuotaLimitReached:+ case AgentRuntimeErrorType.RateLimitExceeded: {+ if (enableBusinessFeatures) return <QuotaLimitError id={data.id} />;+ break;+ }- case AgentRuntimeErrorType.OllamaBizError: {- return <OllamaBizError {...data} />;- }+ case AgentRuntimeErrorType.OllamaServiceUnavailable: {+ return <OllamaSetupGuide id={data.id} />;+ }- case AgentRuntimeErrorType.ExceededContextWindow: {- return <ExceededContextWindowError id={data.id} />;- }+ case AgentRuntimeErrorType.OllamaBizError: {+ return <OllamaBizError {...data} />;+ }++ case AgentRuntimeErrorType.ExceededContextWindow: {+ return <ExceededContextWindowError id={data.id} />;+ }- case AgentRuntimeErrorType.NoOpenAIAPIKey: {- {- return <ChatInvalidAPIKey id={data.id} provider={data.error?.body?.provider} />;+ case AgentRuntimeErrorType.NoOpenAIAPIKey: {+ {+ return <ChatInvalidAPIKey id={data.id} provider={data.error?.body?.provider} />;+ }}}- }- if (error?.type?.toString().includes('Invalid')) {- return <ChatInvalidAPIKey id={data.id} provider={data.error?.body?.provider} />;- }+ if (error?.type?.toString().includes('Invalid')) {+ return <ChatInvalidAPIKey id={data.id} provider={data.error?.body?.provider} />;+ }- // Show a report action for unknown or fallback-bucket traceable errors.- // Specific known error types keep their dedicated localized message below.- if (enableBusinessFeatures && shouldShowTraceIdError(error)) {- return <TraceIdError id={data.id} traceId={error.body.traceId} />;- }+ // Show a report action for unknown or fallback-bucket traceable errors.+ // Specific known error types keep their dedicated localized message below.+ if (enableBusinessFeatures && shouldShowTraceIdError(error)) {+ return <TraceIdError id={data.id} traceId={error.body.traceId} />;+ }- return (- <ErrorContent- id={data.id}- error={{- ...alertError,- ...(rawErrorMessage ? { message: rawErrorMessage } : {}),- extra: data.error?.body ? (- <Highlighter- actionIconSize={'small'}- language={'json'}- padding={8}- variant={'borderless'}- >- {JSON.stringify(data.error?.body, null, 2)}- </Highlighter>- ) : undefined,- }}- onRegenerate={canCreate ? onRegenerate : undefined}- />- );-});+ return (+ <ErrorContent+ id={data.id}+ error={{+ ...alertError,+ ...(rawErrorMessage ? { message: rawErrorMessage } : {}),+ extra: data.error?.body ? (+ <Highlighter+ actionIconSize={'small'}+ language={'json'}+ padding={8}+ variant={'borderless'}+ >+ {JSON.stringify(data.error?.body, null, 2)}+ </Highlighter>+ ) : undefined,+ }}+ onRegenerate={canCreate ? onRegenerate : undefined}+ />+ );+ },+);export default ErrorMessageExtra;diff --git a/src/features/Conversation/Error/useHeterogeneousAutoRetry.test.ts b/src/features/Conversation/Error/useHeterogeneousAutoRetry.test.tsnew file mode 100644index 00000000000..b630a413935--- /dev/null+++ b/src/features/Conversation/Error/useHeterogeneousAutoRetry.test.ts@@ -0,0 +1,199 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useHeterogeneousAutoRetry } from './useHeterogeneousAutoRetry';++// NOTE: every selected value must keep a STABLE identity across renders (the+// real store returns stable action refs). An inline arrow here would change+// each render → churn the effect and reset the countdown.+const storeMock = vi.hoisted(() => ({+ aborted: false,+ attempts: {} as Record<string, number>,+ internal_beginHeteroOverloadWait: vi.fn(),+ internal_endHeteroOverloadWait: vi.fn(),+ isHeteroOverloadWaitAborted: vi.fn(() => false),+ markHeteroOverloadRetryExhausted: vi.fn(),+ recordHeteroOverloadRetry: vi.fn(),+}));++vi.mock('@/features/Conversation/store', () => ({+ useConversationStore: (selector: (state: Record<string, unknown>) => unknown) =>+ selector({+ heteroOverloadRetryAttempts: storeMock.attempts,+ internal_beginHeteroOverloadWait: storeMock.internal_beginHeteroOverloadWait,+ internal_endHeteroOverloadWait: storeMock.internal_endHeteroOverloadWait,+ isHeteroOverloadWaitAborted: storeMock.isHeteroOverloadWaitAborted,+ markHeteroOverloadRetryExhausted: storeMock.markHeteroOverloadRetryExhausted,+ recordHeteroOverloadRetry: storeMock.recordHeteroOverloadRetry,+ }),+}));++const SCOPE = 'user-msg-1';++describe('useHeterogeneousAutoRetry', () => {+ beforeEach(() => {+ storeMock.attempts = {};+ storeMock.recordHeteroOverloadRetry.mockClear();+ storeMock.markHeteroOverloadRetryExhausted.mockClear();+ storeMock.internal_beginHeteroOverloadWait.mockClear();+ storeMock.internal_endHeteroOverloadWait.mockClear();+ storeMock.isHeteroOverloadWaitAborted.mockReset();+ storeMock.isHeteroOverloadWaitAborted.mockReturnValue(false);+ vi.useFakeTimers();+ // Neutralize jitter so backoff is exactly the base window.+ vi.spyOn(Math, 'random').mockReturnValue(0.5);+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it('schedules an auto-retry and fires it after the first backoff window', () => {+ const onRetry = vi.fn();+ const { result } = renderHook(() =>+ useHeterogeneousAutoRetry({ enabled: true, onRetry, scopeId: SCOPE }),+ );++ // first attempt: 2s window, shown as attempt 1 / 5+ expect(result.current?.attempt).toBe(1);+ expect(result.current?.maxAttempts).toBe(5);+ expect(result.current?.secondsLeft).toBe(2);+ expect(onRetry).not.toHaveBeenCalled();++ // A wait op is opened so the turn stays in its loading state while counting.+ expect(storeMock.internal_beginHeteroOverloadWait).toHaveBeenCalledWith(SCOPE);++ act(() => {+ vi.advanceTimersByTime(2000);+ });++ // Firing hands the wait off to the real attempt and bumps the counter.+ expect(storeMock.internal_endHeteroOverloadWait).toHaveBeenCalledWith(SCOPE);+ expect(storeMock.recordHeteroOverloadRetry).toHaveBeenCalledWith(SCOPE);+ expect(onRetry).toHaveBeenCalledTimes(1);+ });++ it('aborts the scheduled retry when the wait op was cancelled (global Stop)', () => {+ const onRetry = vi.fn();+ renderHook(() => useHeterogeneousAutoRetry({ enabled: true, onRetry, scopeId: SCOPE }));++ // Simulate the wait op being cancelled out from under us mid-countdown.+ storeMock.isHeteroOverloadWaitAborted.mockReturnValue(true);++ act(() => {+ vi.advanceTimersByTime(2000);+ });++ expect(onRetry).not.toHaveBeenCalled();+ expect(storeMock.recordHeteroOverloadRetry).not.toHaveBeenCalled();+ expect(storeMock.markHeteroOverloadRetryExhausted).toHaveBeenCalledWith(SCOPE);+ });++ it('uses a longer backoff window as attempts accrue', () => {+ storeMock.attempts = { [SCOPE]: 1 };+ const onRetry = vi.fn();+ const { result } = renderHook(() =>+ useHeterogeneousAutoRetry({ enabled: true, onRetry, scopeId: SCOPE }),+ );++ // second attempt: 5s window, shown as attempt 2 / 5+ expect(result.current?.attempt).toBe(2);+ expect(result.current?.secondsLeft).toBe(5);++ act(() => {+ vi.advanceTimersByTime(4000);+ });+ expect(onRetry).not.toHaveBeenCalled();++ act(() => {+ vi.advanceTimersByTime(1000);+ });+ expect(onRetry).toHaveBeenCalledTimes(1);+ });++ it('falls back to manual (returns undefined) once the cap is reached', () => {+ storeMock.attempts = { [SCOPE]: 5 };+ const onRetry = vi.fn();+ const { result } = renderHook(() =>+ useHeterogeneousAutoRetry({ enabled: true, onRetry, scopeId: SCOPE }),+ );++ expect(result.current).toBeUndefined();++ act(() => {+ vi.advanceTimersByTime(60_000);+ });+ expect(onRetry).not.toHaveBeenCalled();+ });++ it('does not schedule when disabled or without a scope', () => {+ const onRetry = vi.fn();+ const disabled = renderHook(() =>+ useHeterogeneousAutoRetry({ enabled: false, onRetry, scopeId: SCOPE }),+ );+ expect(disabled.result.current).toBeUndefined();++ const noScope = renderHook(() =>+ useHeterogeneousAutoRetry({ enabled: true, onRetry, scopeId: undefined }),+ );+ expect(noScope.result.current).toBeUndefined();++ act(() => {+ vi.advanceTimersByTime(60_000);+ });+ expect(onRetry).not.toHaveBeenCalled();+ });++ it('onRetryNow fires immediately and the scheduled timer cannot double-fire', () => {+ const onRetry = vi.fn();+ const { result } = renderHook(() =>+ useHeterogeneousAutoRetry({ enabled: true, onRetry, scopeId: SCOPE }),+ );++ act(() => {+ result.current?.onRetryNow();+ });+ expect(onRetry).toHaveBeenCalledTimes(1);+ expect(storeMock.recordHeteroOverloadRetry).toHaveBeenCalledTimes(1);++ // The pending timer must not retry a second time.+ act(() => {+ vi.advanceTimersByTime(10_000);+ });+ expect(onRetry).toHaveBeenCalledTimes(1);+ });++ it('onCancel pins the counter past the cap, ends the wait, and blocks a queued timer', () => {+ const onRetry = vi.fn();+ const { result } = renderHook(() =>+ useHeterogeneousAutoRetry({ enabled: true, onRetry, scopeId: SCOPE }),+ );++ act(() => {+ result.current?.onCancel();+ });+ expect(storeMock.markHeteroOverloadRetryExhausted).toHaveBeenCalledWith(SCOPE);+ expect(storeMock.internal_endHeteroOverloadWait).toHaveBeenCalledWith(SCOPE);++ // A timer callback that was already dequeued for this tick must not retry+ // after the user cancelled.+ act(() => {+ vi.advanceTimersByTime(10_000);+ });+ expect(onRetry).not.toHaveBeenCalled();+ });++ it('cleans up the pending timer on unmount', () => {+ const onRetry = vi.fn();+ const { unmount } = renderHook(() =>+ useHeterogeneousAutoRetry({ enabled: true, onRetry, scopeId: SCOPE }),+ );++ unmount();+ act(() => {+ vi.advanceTimersByTime(60_000);+ });+ expect(onRetry).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Conversation/Error/useHeterogeneousAutoRetry.ts b/src/features/Conversation/Error/useHeterogeneousAutoRetry.tsnew file mode 100644index 00000000000..fc92ce25857--- /dev/null+++ b/src/features/Conversation/Error/useHeterogeneousAutoRetry.ts@@ -0,0 +1,141 @@+import { useCallback, useEffect, useRef, useState } from 'react';++import { useConversationStore } from '../store';+import {+ HETERO_OVERLOAD_BACKOFF_JITTER,+ HETERO_OVERLOAD_BACKOFF_SECONDS,+ MAX_HETERO_AUTO_RETRIES,+} from '../store/slices/generation/heteroRetryConfig';++/**+ * View-model the overloaded guide renders while an auto-retry is pending. When+ * the hook returns `undefined` the guide falls back to its static manual-retry+ * card (auto-retry disabled, no scope, or the budget is exhausted/cancelled).+ */+export interface HeteroAutoRetryViewModel {+ /** 1-based index of the attempt about to run (e.g. "2 / 5"). */+ attempt: number;+ maxAttempts: number;+ /** Stop auto-retrying and fall back to the manual card. */+ onCancel: () => void;+ /** Skip the remaining wait and retry right now. */+ onRetryNow: () => void;+ /** Whole seconds left before the scheduled retry fires. */+ secondsLeft: number;+}++interface UseHeterogeneousAutoRetryParams {+ /** True only for the transient `overloaded` error code. */+ enabled: boolean;+ /** Fires the actual retry (delete failed turn + regenerate). */+ onRetry: () => void;+ /** Parent user message id — stable across the retry's delete+recreate. */+ scopeId?: string;+}++const backoffMs = (attemptsSpent: number): number => {+ const idx = Math.min(attemptsSpent, HETERO_OVERLOAD_BACKOFF_SECONDS.length - 1);+ const base = HETERO_OVERLOAD_BACKOFF_SECONDS[idx];+ // ± jitter so multiple sessions don't retry in lockstep against a struggling+ // upstream. Math.random is fine here (app runtime, not a workflow script).+ const jitter = base * HETERO_OVERLOAD_BACKOFF_JITTER * (Math.random() * 2 - 1);+ return Math.max(1, base + jitter) * 1000;+};++/**+ * Drives capped, backed-off auto-retry for heterogeneous "overloaded" errors.+ *+ * The attempt count lives in the store keyed by the parent user message id, so+ * it survives the unmount→remount cycle each retry triggers (the failed+ * assistant message is deleted and a fresh one is created). The timer itself+ * lives here: each mounted overloaded card schedules at most one retry, then+ * unmounts when the retry fires; if the next attempt also overloads, a fresh+ * card mounts, reads the incremented count, and schedules the next (longer)+ * backoff — until the cap is hit.+ *+ * While counting down, a long-lived `autoRetryPending` operation keeps the turn+ * in its loading/in-progress state (so the input stays busy and Stop works+ * across the wait, instead of the turn looking idle between attempts). A retry+ * fired after that operation was cancelled (Stop) aborts instead.+ */+export const useHeterogeneousAutoRetry = ({+ enabled,+ onRetry,+ scopeId,+}: UseHeterogeneousAutoRetryParams): HeteroAutoRetryViewModel | undefined => {+ const attemptsSpent = useConversationStore((s) =>+ scopeId ? (s.heteroOverloadRetryAttempts[scopeId] ?? 0) : 0,+ );+ const recordRetry = useConversationStore((s) => s.recordHeteroOverloadRetry);+ const markExhausted = useConversationStore((s) => s.markHeteroOverloadRetryExhausted);+ const beginWait = useConversationStore((s) => s.internal_beginHeteroOverloadWait);+ const endWait = useConversationStore((s) => s.internal_endHeteroOverloadWait);+ const isWaitAborted = useConversationStore((s) => s.isHeteroOverloadWaitAborted);++ const active = enabled && !!scopeId && attemptsSpent < MAX_HETERO_AUTO_RETRIES;++ const [secondsLeft, setSecondsLeft] = useState(0);+ // Keep the latest onRetry without re-arming the timer when it changes.+ const onRetryRef = useRef(onRetry);+ onRetryRef.current = onRetry;+ // Guards against a double-fire (timer + manual "retry now" racing).+ const firedRef = useRef(false);++ const fire = useCallback(() => {+ if (!scopeId || firedRef.current) return;+ firedRef.current = true;+ // Stop (or the cancel action) tore down the wait op while we were counting+ // — don't fire a retry the user asked to abort.+ if (isWaitAborted(scopeId)) {+ markExhausted(scopeId);+ return;+ }+ // Hand the wait off to the real retry attempt (its exec op takes over the+ // loading state), increment so the next card schedules the next backoff.+ endWait(scopeId);+ recordRetry(scopeId);+ onRetryRef.current();+ }, [endWait, isWaitAborted, markExhausted, recordRetry, scopeId]);++ useEffect(() => {+ if (!active || !scopeId) return;+ firedRef.current = false;+ beginWait(scopeId);++ const totalMs = backoffMs(attemptsSpent);+ const deadline = Date.now() + totalMs;+ setSecondsLeft(Math.ceil(totalMs / 1000));++ const ticker = setInterval(() => {+ setSecondsLeft(Math.max(0, Math.ceil((deadline - Date.now()) / 1000)));+ }, 250);+ const timer = setTimeout(fire, totalMs);++ return () => {+ clearTimeout(timer);+ clearInterval(ticker);+ // Unmounted/cancelled before firing → release the wait op so the turn+ // doesn't stay stuck in a loading state.+ if (!firedRef.current) endWait(scopeId);+ };+ }, [active, scopeId, attemptsSpent, fire, beginWait, endWait]);++ const onCancel = useCallback(() => {+ if (!scopeId) return;+ // Mark fired so a timer callback already dequeued for this tick can't slip+ // through and retry after the user cancelled.+ firedRef.current = true;+ endWait(scopeId);+ markExhausted(scopeId);+ }, [endWait, markExhausted, scopeId]);++ if (!active) return undefined;++ return {+ attempt: attemptsSpent + 1,+ maxAttempts: MAX_HETERO_AUTO_RETRIES,+ onCancel,+ onRetryNow: fire,+ secondsLeft,+ };+};diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsxindex 8be635ddb99..919bc9477fc 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx@@ -10,6 +10,7 @@ import ContentBlock from './ContentBlock';const continueGenerationMock = vi.fn();const deleteDBMessageMock = vi.fn();+const delAndRegenerateMessageMock = vi.fn();const navigateMock = vi.fn();vi.mock('@lobehub/ui', () => ({@@ -48,11 +49,28 @@ vi.mock('@/business/client/hooks/useRenderBusinessChatErrorMessageExtra', () =>}));vi.mock('@/features/Electron/HeterogeneousAgent/StatusGuide', () => ({- default: ({ agentType, error }: { agentType?: string; error?: { code?: string } }) => (- <div>{`guide:${agentType}:${error?.code}`}</div>+ default: ({+ agentType,+ error,+ onRetry,+ }: {+ agentType?: string;+ error?: { code?: string };+ onRetry?: () => void;+ }) => (+ <div>+ {`guide:${agentType}:${error?.code}`}+ <button type="button" onClick={onRetry}>+ guide-retry+ </button>+ </div>),}));+vi.mock('@/hooks/usePermission', () => ({+ usePermission: () => ({ allowed: true }),+}));+vi.mock('@/hooks/useProviderName', () => ({useProviderName: () => 'Mock Provider',}));@@ -99,13 +117,24 @@ vi.mock('./MessageContent', () => ({}));vi.mock('../../../store', () => ({+ dataSelectors: {+ getDisplayMessageById: () => () => ({ parentId: 'user-1' }),+ },messageStateSelectors: {isMessageInReasoning: () => () => false,},useConversationStore: (selector: (state: unknown) => unknown) =>selector({continueGeneration: continueGenerationMock,+ delAndRegenerateMessage: delAndRegenerateMessageMock,deleteDBMessage: deleteDBMessageMock,+ heteroOverloadRetryAttempts: {},+ internal_beginHeteroOverloadWait: vi.fn(),+ internal_endHeteroOverloadWait: vi.fn(),+ isHeteroOverloadWaitAborted: () => false,+ markHeteroOverloadRetryExhausted: vi.fn(),+ recordHeteroOverloadRetry: vi.fn(),+ resetHeteroOverloadRetry: vi.fn(),}),}));@@ -113,9 +142,40 @@ describe('AssistantGroup ContentBlock', () => {beforeEach(() => {continueGenerationMock.mockClear();deleteDBMessageMock.mockClear();+ delAndRegenerateMessageMock.mockClear();navigateMock.mockClear();});+ it('regenerates the whole turn (not continue) when retrying a heterogeneous error in a group', () => {+ render(+ <ContentBlock+ assistantId="assistant-1"+ content=""+ id="block-1"+ error={+ {+ body: {+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.Overloaded,+ message: 'API Error: 529 overloaded_error',+ stderr: 'API Error: 529 overloaded_error',+ },+ message: 'API Error: 529 overloaded_error',+ type: 'AgentRuntimeError',+ } as any+ }+ />,+ );++ screen.getByRole('button', { name: 'guide-retry' }).click();++ // The fix: a grouped hetero turn is replaced in place from the GROUP id via+ // the delete-first delAndRegenerateMessage (no sibling branch), instead of+ // the no-op continueGeneration.+ expect(delAndRegenerateMessageMock).toHaveBeenCalledWith('assistant-1');+ expect(continueGenerationMock).not.toHaveBeenCalled();+ });+it('uses the shared message error renderer for heterogeneous agent errors', () => {render(<ContentBlockdiff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsxindex 4c9611e7634..d12a6c6c52e 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx@@ -3,10 +3,13 @@ import { memo, useCallback } from 'react';import SafeBoundary from '@/components/ErrorBoundary';import { LOADING_FLAT } from '@/const/message';-import ErrorMessageExtra, { useErrorContent } from '@/features/Conversation/Error';+import ErrorMessageExtra, {+ isHeterogeneousAgentStatusGuideError,+ useErrorContent,+} from '@/features/Conversation/Error';import ErrorContent from '../../../ChatItem/components/ErrorContent';-import { messageStateSelectors, useConversationStore } from '../../../store';+import { dataSelectors, messageStateSelectors, useConversationStore } from '../../../store';import ImageFileListViewer from '../../components/ImageFileListViewer';import Reasoning from '../../components/Reasoning';import { Tools } from '../Tools';@@ -34,11 +37,19 @@ const ContentBlock = memo<ContentBlockProps>(}) => {const errorContent = useErrorContent(error);const showImageItems = !!imageList && imageList.length > 0;- const [isReasoning, deleteMessage, continueGeneration] = useConversationStore((s) => [- messageStateSelectors.isMessageInReasoning(id)(s),- s.deleteDBMessage,- s.continueGeneration,- ]);+ const [isReasoning, deleteMessage, continueGeneration, delAndRegenerateMessage] =+ useConversationStore((s) => [+ messageStateSelectors.isMessageInReasoning(id)(s),+ s.deleteDBMessage,+ s.continueGeneration,+ s.delAndRegenerateMessage,+ ]);+ // The group's parent user message id — the stable scope key for auto-retry+ // (survives the delete+recreate a retry performs) and the regenerate target.+ const groupParentId = useConversationStore(+ (s) => dataSelectors.getDisplayMessageById(assistantId)(s)?.parentId,+ );+ const isHeteroError = isHeterogeneousAgentStatusGuideError(error?.body);const hasTools = !!tools?.length;const showReasoning =(!!reasoning && reasoning.content?.trim() !== '') || (!reasoning && isReasoning);@@ -46,9 +57,27 @@ const ContentBlock = memo<ContentBlockProps>(const showMessageContent = hasContent || content === LOADING_FLAT || hasTools;const handleRegenerate = useCallback(async () => {+ // Hetero CLIs (CC / Codex) have no "continue a cut-off response"+ // primitive, so `continueGeneration` is a silent no-op for them and the+ // retry button does nothing. An errored hetero turn must instead be+ // regenerated from the user message — routed through the GROUP id (the+ // child block id isn't a top-level displayMessage). Use the delete-first+ // `delAndRegenerateMessage` so the failed turn is replaced in place rather+ // than accumulating a sibling branch on every (auto-)retry.+ if (isHeteroError) {+ void delAndRegenerateMessage(assistantId);+ return;+ }await deleteMessage(id);continueGeneration(assistantId);- }, [assistantId, continueGeneration, deleteMessage, id]);+ }, [+ assistantId,+ continueGeneration,+ delAndRegenerateMessage,+ deleteMessage,+ id,+ isHeteroError,+ ]);const errorBlock = error ? (<ErrorContent@@ -58,6 +87,7 @@ const ContentBlock = memo<ContentBlockProps>(<ErrorMessageExtradata={{ error, id }}error={alertError}+ retryScopeId={groupParentId}onRegenerate={handleRegenerate}/>)}diff --git a/src/features/Conversation/store/selectors.test.ts b/src/features/Conversation/store/selectors.test.tsindex 4b023707fcb..1ee4e03296d 100644--- a/src/features/Conversation/store/selectors.test.ts+++ b/src/features/Conversation/store/selectors.test.ts@@ -12,6 +12,8 @@ const createMockState = (overrides: Partial<State> = {}): State => ({inputMessage: '',// MessageState+ heteroOverloadRetryAttempts: {},+ heteroOverloadWaitOpIds: {},messageEditingIds: [],messageLoadingIds: [],pendingArgsUpdates: new Map(),diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.tsindex 88dbc4c7ea4..1043649041f 100644--- a/src/features/Conversation/store/slices/generation/action.test.ts+++ b/src/features/Conversation/store/slices/generation/action.test.ts@@ -10,6 +10,7 @@ import { INPUT_LOADING_OPERATION_TYPES } from '@/store/chat/slices/operation/typimport { type ConversationContext, type ConversationHooks } from '../../../types';import { createStore } from '../../index';+import { MAX_HETERO_AUTO_RETRIES } from './heteroRetryConfig';// Mock useChatStoreconst mockCancelOperations = vi.fn();@@ -1292,4 +1293,46 @@ describe('Generation Actions', () => {expect(mockExecuteGatewayAgent).not.toHaveBeenCalled();});});++ describe('heterogeneous overloaded auto-retry counter', () => {+ const context: ConversationContext = {+ agentId: 'session-1',+ threadId: null,+ topicId: 'topic-1',+ };++ it('increments the counter keyed by parent user message id', () => {+ const store = createStore({ context });++ act(() => {+ store.getState().recordHeteroOverloadRetry('user-1');+ store.getState().recordHeteroOverloadRetry('user-1');+ store.getState().recordHeteroOverloadRetry('user-2');+ });++ expect(store.getState().heteroOverloadRetryAttempts).toEqual({ 'user-1': 2, 'user-2': 1 });+ });++ it('resets a single scope without touching others', () => {+ const store = createStore({ context });++ act(() => {+ store.getState().recordHeteroOverloadRetry('user-1');+ store.getState().recordHeteroOverloadRetry('user-2');+ store.getState().resetHeteroOverloadRetry('user-1');+ });++ expect(store.getState().heteroOverloadRetryAttempts).toEqual({ 'user-2': 1 });+ });++ it('pins the counter to the cap when marked exhausted (cancel)', () => {+ const store = createStore({ context });++ act(() => {+ store.getState().markHeteroOverloadRetryExhausted('user-1');+ });++ expect(store.getState().heteroOverloadRetryAttempts['user-1']).toBe(MAX_HETERO_AUTO_RETRIES);+ });+ });});diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.tsindex e32f6e0428a..434904f7284 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -31,6 +31,7 @@ import {import { getElectronStoreState } from '@/store/electron';import { type Store as ConversationStore } from '../../action';+import { MAX_HETERO_AUTO_RETRIES } from './heteroRetryConfig';const buildRetryInitialContext = (editorData: Record<string, any> | null | undefined) => {const normalizedEditorData = editorData ?? undefined;@@ -223,12 +224,44 @@ export interface GenerationAction {*/delAndResendThreadMessage: (messageId: string) => Promise<void>;+ /**+ * Start (or reuse) the long-lived `autoRetryPending` operation for a turn so+ * the input/turn stays in its loading state during the auto-retry countdown.+ * Idempotent: reuses an existing still-running wait op for the scope.+ */+ internal_beginHeteroOverloadWait: (scopeId: string) => void;++ /**+ * End the `autoRetryPending` operation for a turn (the countdown handed off to+ * a real retry attempt, or the sequence ended).+ */+ internal_endHeteroOverloadWait: (scopeId: string) => void;++ /**+ * Whether the turn's `autoRetryPending` operation was cancelled out from under+ * us (e.g. the global Stop button) — the scheduled retry must then abort.+ */+ isHeteroOverloadWaitAborted: (scopeId: string) => boolean;++ /**+ * Pin the heterogeneous "overloaded" auto-retry counter past the cap so+ * scheduling stops and the guide falls back to manual retry (used by the+ * user's "cancel auto-retry" action).+ */+ markHeteroOverloadRetryExhausted: (scopeId: string) => void;+/*** Open thread creator* @deprecated Temporary bridge to ChatStore*/openThreadCreator: (messageId: string) => void;+ /**+ * Increment the heterogeneous "overloaded" auto-retry counter for a turn,+ * keyed by its parent user message id.+ */+ recordHeteroOverloadRetry: (scopeId: string) => void;+/*** Regenerate an assistant message*/@@ -250,6 +283,12 @@ export interface GenerationAction {*/resendThreadMessage: (messageId: string) => Promise<void>;+ /**+ * Clear the heterogeneous "overloaded" auto-retry counter for a turn so a+ * fresh auto-retry budget is granted (used when a human retries manually).+ */+ resetHeteroOverloadRetry: (scopeId: string) => void;+/*** Stop current generation*/@@ -455,6 +494,84 @@ export const generationSlice: StateCreator<await chatStore.reInvokeToolMessage(messageId);},+ internal_beginHeteroOverloadWait: (scopeId: string) => {+ const chatStore = useChatStore.getState();+ const existingId = get().heteroOverloadWaitOpIds[scopeId];+ // Reuse an existing wait op that's still running (effect re-runs / remounts).+ if (existingId && chatStore.operations[existingId]?.status === 'running') return;++ const { context } = get();+ const { operationId } = chatStore.startOperation({+ context: {+ agentId: context.agentId,+ messageId: scopeId,+ threadId: context.threadId ?? undefined,+ topicId: context.topicId ?? undefined,+ },+ label: 'Auto-retry pending',+ type: 'autoRetryPending',+ });+ set(+ { heteroOverloadWaitOpIds: { ...get().heteroOverloadWaitOpIds, [scopeId]: operationId } },+ false,+ 'internal_beginHeteroOverloadWait',+ );+ },++ internal_endHeteroOverloadWait: (scopeId: string) => {+ const opId = get().heteroOverloadWaitOpIds[scopeId];+ if (!opId) return;+ const chatStore = useChatStore.getState();+ // Only complete a still-running op; if it was already cancelled (Stop), leave+ // its terminal state intact.+ if (chatStore.operations[opId]?.status === 'running') chatStore.completeOperation(opId);+ const next = { ...get().heteroOverloadWaitOpIds };+ delete next[scopeId];+ set({ heteroOverloadWaitOpIds: next }, false, 'internal_endHeteroOverloadWait');+ },++ isHeteroOverloadWaitAborted: (scopeId: string) => {+ const opId = get().heteroOverloadWaitOpIds[scopeId];+ // A missing id means the wait was already torn down (cancel/Stop cleanup+ // can race the timer near the deadline) — treat that as aborted so a stale+ // queued retry doesn't run after the user asked to stop.+ if (!opId) return true;+ const op = useChatStore.getState().operations[opId];+ return !op || op.status !== 'running';+ },++ markHeteroOverloadRetryExhausted: (scopeId: string) => {+ set(+ {+ heteroOverloadRetryAttempts: {+ ...get().heteroOverloadRetryAttempts,+ [scopeId]: MAX_HETERO_AUTO_RETRIES,+ },+ },+ false,+ 'markHeteroOverloadRetryExhausted',+ );+ },++ recordHeteroOverloadRetry: (scopeId: string) => {+ const current = get().heteroOverloadRetryAttempts;+ set(+ {+ heteroOverloadRetryAttempts: { ...current, [scopeId]: (current[scopeId] ?? 0) + 1 },+ },+ false,+ 'recordHeteroOverloadRetry',+ );+ },++ resetHeteroOverloadRetry: (scopeId: string) => {+ const current = get().heteroOverloadRetryAttempts;+ if (!(scopeId in current)) return;+ const next = { ...current };+ delete next[scopeId];+ set({ heteroOverloadRetryAttempts: next }, false, 'resetHeteroOverloadRetry');+ },+regenerateAssistantMessage: async (messageId: string) => {const { displayMessages } = get();diff --git a/src/features/Conversation/store/slices/generation/heteroRetryConfig.ts b/src/features/Conversation/store/slices/generation/heteroRetryConfig.tsnew file mode 100644index 00000000000..a28e46a24c6--- /dev/null+++ b/src/features/Conversation/store/slices/generation/heteroRetryConfig.ts@@ -0,0 +1,22 @@+/**+ * Auto-retry policy for heterogeneous-agent (Claude Code / Codex) "overloaded"+ * errors. The upstream model service throttles transiently ("not your usage+ * limit") and clears on its own in moments, so instead of leaving the user to+ * click retry we schedule a capped, backed-off auto-retry. Only the+ * `overloaded` error code opts in — `auth_required` (needs a human) and+ * `rate_limit` (has a real reset window) never auto-retry.+ */++/** Maximum number of automatic retries before falling back to manual retry. */+export const MAX_HETERO_AUTO_RETRIES = 5;++/**+ * Backoff (seconds) before each auto-retry, indexed by the attempt count+ * already spent. The last value is reused if attempts exceed the array length.+ * Jitter is layered on at schedule time so concurrent sessions don't retry in+ * lockstep against an already-struggling upstream.+ */+export const HETERO_OVERLOAD_BACKOFF_SECONDS = [2, 5, 10, 20, 30] as const;++/** ±ratio of random jitter applied to each backoff window. */+export const HETERO_OVERLOAD_BACKOFF_JITTER = 0.2;diff --git a/src/features/Conversation/store/slices/messageState/initialState.ts b/src/features/Conversation/store/slices/messageState/initialState.tsindex 914eef7d70e..c5bbcb3005d 100644--- a/src/features/Conversation/store/slices/messageState/initialState.ts+++ b/src/features/Conversation/store/slices/messageState/initialState.ts@@ -2,6 +2,22 @@* Message UI state (editing, loading, etc.)*/export interface MessageStateState {+ /**+ * Consecutive auto-retry count for heterogeneous-agent "overloaded" errors,+ * keyed by the parent user message id (stable across the delete+recreate+ * cycle a retry performs). Drives the backoff schedule and the+ * exhausted→manual fallback; cancelling pins it past the cap.+ */+ heteroOverloadRetryAttempts: Record<string, number>;++ /**+ * Operation id of the in-flight "auto-retry pending" operation per turn+ * (keyed by parent user message id). This operation stays running for the+ * whole countdown so the turn keeps its loading/in-progress state between+ * attempts; cancelling it (Stop / guide cancel) tears the auto-retry down.+ */+ heteroOverloadWaitOpIds: Record<string, string>;+/*** IDs of messages currently being edited*/@@ -20,6 +36,8 @@ export interface MessageStateState {}export const messageStateInitialState: MessageStateState = {+ heteroOverloadRetryAttempts: {},+ heteroOverloadWaitOpIds: {},messageEditingIds: [],messageLoadingIds: [],pendingArgsUpdates: new Map(),diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/GuideShell.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/GuideShell.tsxindex 6df65a6acff..e2d3afcf5fd 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/GuideShell.tsx+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/GuideShell.tsx@@ -7,6 +7,12 @@ import type { HeterogeneousAgentStatusGuideVariant } from './types';interface GuideShellProps {actions?: ReactNode;children?: ReactNode;+ /**+ * Tighter spacing + smaller avatar/title. Used by transient states (e.g. the+ * overloaded auto-retry progress card) that should read as a lightweight+ * status, not a full error panel.+ */+ compact?: boolean;headerDescription?: ReactNode;icon: ReactNode;title: string;@@ -16,34 +22,43 @@ interface GuideShellProps {const GuideShell = ({actions,children,+ compact = false,headerDescription,icon,title,variant,}: GuideShellProps) => {const showHeader = variant !== 'embedded';+ // Compact cards keep the actions on the same row as the title/description+ // (right-aligned) so the whole status reads as a single tight line.+ const actionsInHeader = compact && showHeader;const content = (- <Flexbox gap={12}>+ <Flexbox gap={compact ? 8 : 12}>{showHeader ? (- <Flexbox horizontal align="center" gap={12}>- <Avatar- avatar={icon}- background={cssVar.colorFillQuaternary}- gap={12}- shape={'square'}- size={48}- />- <Flexbox gap={4}>- <Text style={{ fontSize: 16, fontWeight: 600 }}>{title}</Text>- {headerDescription}+ <Flexbox horizontal align="center" gap={compact ? 10 : 12} justify="space-between">+ <Flexbox horizontal align="center" gap={compact ? 10 : 12} style={{ minWidth: 0 }}>+ <Avatar+ avatar={icon}+ background={cssVar.colorFillQuaternary}+ gap={compact ? 8 : 12}+ shape={'square'}+ size={compact ? 32 : 48}+ />+ <Flexbox gap={2} style={{ minWidth: 0 }}>+ <Text ellipsis={compact} style={{ fontSize: compact ? 14 : 16, fontWeight: 600 }}>+ {title}+ </Text>+ {headerDescription}+ </Flexbox></Flexbox>+ {actionsInHeader && <Flexbox style={{ flexShrink: 0 }}>{actions}</Flexbox>}</Flexbox>) : (headerDescription)}{children}- {actions}+ {!actionsInHeader && actions}</Flexbox>);@@ -51,8 +66,8 @@ const GuideShell = ({return (<Block- gap={16}- padding={16}+ gap={compact ? 12 : 16}+ padding={compact ? 12 : 16}variant={'outlined'}style={{background: cssVar.colorBgElevated,diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.test.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.test.tsxindex 095e4efa919..adb7284711e 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.test.tsx+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.test.tsx@@ -26,6 +26,7 @@ vi.mock('@lobehub/ui', () => ({Highlighter: ({ children, style }: { children?: ReactNode; style?: React.CSSProperties }) => (<pre style={style}>{children}</pre>),+ Icon: () => <span>Icon</span>,Snippet: ({ children, style }: { children?: ReactNode; style?: React.CSSProperties }) => (<pre style={style}>{children}</pre>),@@ -40,7 +41,9 @@ vi.mock('antd-style', () => ({}));vi.mock('lucide-react', () => ({+ Ban: () => <span>Ban Icon</span>,ExternalLink: () => <span>ExternalLink Icon</span>,+ Loader2: () => <span>Loader Icon</span>,RotateCcw: () => <span>Retry Icon</span>,Settings2: () => <span>Settings Icon</span>,}));@@ -71,6 +74,11 @@ vi.mock('react-i18next', () => ({return `Resets in about ${options?.duration ?? ''}`;}+ if (key === 'cliOverloadedGuide.autoRetry.status') {+ const o = options as { attempt?: number; max?: number; seconds?: number };+ return `Upstream is temporarily overloaded (not your usage limit) · retry ${o?.attempt ?? 0}/${o?.max ?? 0} in ${o?.seconds ?? 0}s`;+ }+return (({@@ -83,6 +91,9 @@ vi.mock('react-i18next', () => ({'cliAuthGuide.runCommand': 'Run this in Terminal','cliAuthGuide.title': `Sign in to ${options?.name ?? ''}`,'cliOverloadedGuide.actions.retry': 'Retry',+ 'cliOverloadedGuide.autoRetry.actions.cancel': 'Stop auto-retry',+ 'cliOverloadedGuide.autoRetry.actions.retryNow': 'Retry now',+ 'cliOverloadedGuide.autoRetry.title': `${options?.name ?? ''} is busy — retrying automatically…`,'cliOverloadedGuide.desc': `${options?.name ?? ''}'s upstream model service is temporarily overloaded. This usually clears in a moment.`,'cliOverloadedGuide.errorDetails': 'Error details','cliOverloadedGuide.retryHint':@@ -299,6 +310,44 @@ describe('HeterogeneousAgentStatusGuide', () => {expect(onRetry).toHaveBeenCalledTimes(1);});+ it('renders the auto-retry progress state with countdown, retry-now and cancel', () => {+ const onRetryNow = vi.fn();+ const onCancel = vi.fn();+ render(+ <HeterogeneousAgentStatusGuide+ agentType={'claude-code'}+ autoRetry={{ attempt: 2, maxAttempts: 5, onCancel, onRetryNow, secondsLeft: 7 }}+ error={{+ agentType: 'claude-code',+ code: HeterogeneousAgentSessionErrorCode.Overloaded,+ message: 'API Error: 529 overloaded_error',+ stderr: 'API Error: 529 overloaded_error',+ }}+ onRetry={vi.fn()}+ />,+ );++ // Progress copy makes clear it's the upstream (not the user's quota), with+ // the countdown folded into the same line.+ expect(screen.getByText('Claude Code is busy — retrying automatically…')).toBeInTheDocument();+ expect(+ screen.getByText(+ 'Upstream is temporarily overloaded (not your usage limit) · retry 2/5 in 7s',+ ),+ ).toBeInTheDocument();++ // The static manual-retry card must NOT be shown while auto-retrying, and+ // the raw error details are hidden to keep the progress card lightweight.+ expect(screen.queryByText('Claude Code is temporarily overloaded')).not.toBeInTheDocument();+ expect(screen.queryByText('Error details')).not.toBeInTheDocument();++ screen.getByRole('button', { name: 'Retry now' }).click();+ expect(onRetryNow).toHaveBeenCalledTimes(1);++ screen.getByRole('button', { name: 'Stop auto-retry' }).click();+ expect(onCancel).toHaveBeenCalledTimes(1);+ });+it('formats reset time with the active i18n locale instead of the system locale', () => {vi.useFakeTimers();vi.setSystemTime(new Date('2026-04-23T13:27:00+08:00'));diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsxindex 8bd59d60ead..86a5c21dfde 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx@@ -11,12 +11,13 @@ import RateLimitState from './states/RateLimitState';import type { HeterogeneousAgentStatusGuideProps } from './types';const HeterogeneousAgentStatusGuide = memo<HeterogeneousAgentStatusGuideProps>(- ({ agentType = 'codex', error, onOpenSystemTools, onRetry, variant = 'inline' }) => {+ ({ agentType = 'codex', autoRetry, error, onOpenSystemTools, onRetry, variant = 'inline' }) => {const config = resolveHeterogeneousAgentGuideConfig({agentType,errorAgentType: error?.agentType,});const stateProps = {+ autoRetry,config,error,onOpenSystemTools,diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/OverloadedState.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/OverloadedState.tsxindex 1f3bb039147..c60293ed64d 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/OverloadedState.tsx+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/OverloadedState.tsx@@ -1,4 +1,5 @@-import { Flexbox, Highlighter, Text } from '@lobehub/ui';+import { Button, Flexbox, Highlighter, Icon, Text } from '@lobehub/ui';+import { Ban, Loader2, RotateCcw } from 'lucide-react';import { useTranslation } from 'react-i18next';import GuideActions from '../GuideActions';@@ -6,6 +7,7 @@ import GuideShell from '../GuideShell';import type { HeterogeneousAgentGuideStateProps } from '../types';const OverloadedState = ({+ autoRetry,config,error,onRetry,@@ -14,6 +16,40 @@ const OverloadedState = ({const { t } = useTranslation('chat');const rawErrorDetails = error?.stderr || error?.message;+ // Auto-retry pending: a lightweight progress card. Keep it compact — the+ // countdown is folded into the description line and the raw error details are+ // hidden (they stay on the manual/exhausted card below, where the user is+ // actually stuck and may want to copy them).+ if (autoRetry) {+ return (+ <GuideShell+ compact+ icon={<Icon spin icon={Loader2} size={18} />}+ title={t('cliOverloadedGuide.autoRetry.title', { name: config.title })}+ variant={variant}+ actions={+ <Flexbox horizontal gap={8} justify="flex-end" style={{ flexWrap: 'wrap' }}>+ <Button icon={<Ban size={14} />} size="small" type="text" onClick={autoRetry.onCancel}>+ {t('cliOverloadedGuide.autoRetry.actions.cancel')}+ </Button>+ <Button icon={<RotateCcw size={14} />} size="small" onClick={autoRetry.onRetryNow}>+ {t('cliOverloadedGuide.autoRetry.actions.retryNow')}+ </Button>+ </Flexbox>+ }+ headerDescription={+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('cliOverloadedGuide.autoRetry.status', {+ attempt: autoRetry.attempt,+ max: autoRetry.maxAttempts,+ seconds: autoRetry.secondsLeft,+ })}+ </Text>+ }+ />+ );+ }+return (<GuideShellicon={<config.icon size={24} />}@@ -40,11 +76,8 @@ const OverloadedState = ({actionIconSize={'small'}language={'log'}padding={12}+ style={{ maxHeight: 200, overflow: 'auto' }}variant={'outlined'}- style={{- maxHeight: 200,- overflow: 'auto',- }}>{rawErrorDetails}</Highlighter>diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.tsindex 1b52bf2fe61..db933a09232 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts@@ -3,8 +3,21 @@ import type { ComponentType } from 'react';export type HeterogeneousAgentStatusGuideVariant = 'compact' | 'embedded' | 'inline';+/**+ * Present while an `overloaded` error is auto-retrying. When absent, the+ * overloaded guide renders its static manual-retry card.+ */+export interface HeterogeneousAgentAutoRetryState {+ attempt: number;+ maxAttempts: number;+ onCancel: () => void;+ onRetryNow: () => void;+ secondsLeft: number;+}+export interface HeterogeneousAgentStatusGuideProps {agentType?: string;+ autoRetry?: HeterogeneousAgentAutoRetryState;error?: HeterogeneousAgentSessionError | null;onOpenSystemTools?: () => void;onRetry?: () => void;@@ -25,6 +38,7 @@ export interface HeterogeneousAgentGuideConfig {}export interface HeterogeneousAgentGuideStateProps {+ autoRetry?: HeterogeneousAgentAutoRetryState;config: HeterogeneousAgentGuideConfig;error?: HeterogeneousAgentSessionError | null;onOpenSystemTools?: () => void;diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex 0ec8d1bbc60..4e3ac7c2cfd 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -14,6 +14,7 @@ export type OperationType =| 'createTopic' // Auto create topic| 'regenerate' // Regenerate message| 'continue' // Continue generation+ | 'autoRetryPending' // Heterogeneous "overloaded" auto-retry waiting period (counting down to the next attempt). Keeps the turn in a loading/in-progress state between attempts; cancelled by Stop or the guide's cancel action.// === AI generation ===| 'execAgentRuntime' // Execute agent runtime (client-side, entire agent runtime execution)@@ -404,4 +405,7 @@ export const AI_RUNTIME_OPERATION_TYPES: OperationType[] = [export const INPUT_LOADING_OPERATION_TYPES: OperationType[] = [...AI_RUNTIME_OPERATION_TYPES,'sendMessage',+ // The auto-retry waiting period is part of the same in-progress turn — keep+ // the input in loading state (and let Stop target it) across the countdown.+ 'autoRetryPending',];