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(chat): require a one-use grant before heterogeneous auto-retry (#20653)

Neko4183bce23e5c
diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsx
index f5c1577671e..56691cad9df 100644
--- a/src/features/Conversation/Error/index.tsx
+++ b/src/features/Conversation/Error/index.tsx
@@ -391,6 +391,7 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(
canRetry &&
isHeterogeneousAgentStatusGuideError(sessionErrorBody) &&
sessionErrorBody.code === HeterogeneousAgentSessionErrorCode.Overloaded,
+ messageId: data.id,
onRetry: handleRetryAgentMessage,
scopeId: resolvedScopeId,
});
diff --git a/src/features/Conversation/Error/useHeterogeneousAutoRetry.test.ts b/src/features/Conversation/Error/useHeterogeneousAutoRetry.test.ts
index b630a413935..3fd5b5b5d4c 100644
--- a/src/features/Conversation/Error/useHeterogeneousAutoRetry.test.ts
+++ b/src/features/Conversation/Error/useHeterogeneousAutoRetry.test.ts
@@ -8,6 +8,8 @@ import { useHeterogeneousAutoRetry } from './useHeterogeneousAutoRetry';
// each render → churn the effect and reset the countdown.
const storeMock = vi.hoisted(() => ({
aborted: false,
+ retryAvailable: true,
+ hasOperation: true,
attempts: {} as Record<string, number>,
internal_beginHeteroOverloadWait: vi.fn(),
internal_endHeteroOverloadWait: vi.fn(),
@@ -28,11 +30,42 @@ vi.mock('@/features/Conversation/store', () => ({
}),
}));
+const runtimeMock = {
+ abortController: new AbortController(),
+ id: 'runtime-1',
+ metadata: {
+ get heteroAutoRetryAvailable() {
+ return storeMock.retryAvailable;
+ },
+ },
+ status: 'completed',
+ type: 'execServerAgentRuntime',
+};
+const chatState = {
+ messageOperationMap: { 'failed-step': 'runtime-1' },
+ get operations() {
+ return storeMock.hasOperation ? { 'runtime-1': runtimeMock } : {};
+ },
+ updateOperationMetadata: (_id: string, metadata: { heteroAutoRetryAvailable: boolean }) => {
+ storeMock.retryAvailable = metadata.heteroAutoRetryAvailable;
+ },
+};
+vi.mock('@/store/chat', () => ({
+ useChatStore: Object.assign(
+ (selector: (state: typeof chatState) => unknown) => selector(chatState),
+ {
+ getState: () => chatState,
+ },
+ ),
+}));
+
const SCOPE = 'user-msg-1';
describe('useHeterogeneousAutoRetry', () => {
beforeEach(() => {
storeMock.attempts = {};
+ storeMock.retryAvailable = true;
+ storeMock.hasOperation = true;
storeMock.recordHeteroOverloadRetry.mockClear();
storeMock.markHeteroOverloadRetryExhausted.mockClear();
storeMock.internal_beginHeteroOverloadWait.mockClear();
@@ -52,7 +85,12 @@ describe('useHeterogeneousAutoRetry', () => {
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 }),
+ useHeterogeneousAutoRetry({
+ enabled: true,
+ onRetry,
+ messageId: 'failed-step',
+ scopeId: SCOPE,
+ }),
);
// first attempt: 2s window, shown as attempt 1 / 5
@@ -76,7 +114,14 @@ describe('useHeterogeneousAutoRetry', () => {
it('aborts the scheduled retry when the wait op was cancelled (global Stop)', () => {
const onRetry = vi.fn();
- renderHook(() => useHeterogeneousAutoRetry({ enabled: true, onRetry, scopeId: SCOPE }));
+ renderHook(() =>
+ useHeterogeneousAutoRetry({
+ enabled: true,
+ onRetry,
+ messageId: 'failed-step',
+ scopeId: SCOPE,
+ }),
+ );
// Simulate the wait op being cancelled out from under us mid-countdown.
storeMock.isHeteroOverloadWaitAborted.mockReturnValue(true);
@@ -94,7 +139,12 @@ describe('useHeterogeneousAutoRetry', () => {
storeMock.attempts = { [SCOPE]: 1 };
const onRetry = vi.fn();
const { result } = renderHook(() =>
- useHeterogeneousAutoRetry({ enabled: true, onRetry, scopeId: SCOPE }),
+ useHeterogeneousAutoRetry({
+ enabled: true,
+ onRetry,
+ messageId: 'failed-step',
+ scopeId: SCOPE,
+ }),
);
// second attempt: 5s window, shown as attempt 2 / 5
@@ -116,7 +166,12 @@ describe('useHeterogeneousAutoRetry', () => {
storeMock.attempts = { [SCOPE]: 5 };
const onRetry = vi.fn();
const { result } = renderHook(() =>
- useHeterogeneousAutoRetry({ enabled: true, onRetry, scopeId: SCOPE }),
+ useHeterogeneousAutoRetry({
+ enabled: true,
+ onRetry,
+ messageId: 'failed-step',
+ scopeId: SCOPE,
+ }),
);
expect(result.current).toBeUndefined();
@@ -130,12 +185,22 @@ describe('useHeterogeneousAutoRetry', () => {
it('does not schedule when disabled or without a scope', () => {
const onRetry = vi.fn();
const disabled = renderHook(() =>
- useHeterogeneousAutoRetry({ enabled: false, onRetry, scopeId: SCOPE }),
+ useHeterogeneousAutoRetry({
+ enabled: false,
+ onRetry,
+ messageId: 'failed-step',
+ scopeId: SCOPE,
+ }),
);
expect(disabled.result.current).toBeUndefined();
const noScope = renderHook(() =>
- useHeterogeneousAutoRetry({ enabled: true, onRetry, scopeId: undefined }),
+ useHeterogeneousAutoRetry({
+ enabled: true,
+ onRetry,
+ messageId: 'failed-step',
+ scopeId: undefined,
+ }),
);
expect(noScope.result.current).toBeUndefined();
@@ -148,7 +213,12 @@ describe('useHeterogeneousAutoRetry', () => {
it('onRetryNow fires immediately and the scheduled timer cannot double-fire', () => {
const onRetry = vi.fn();
const { result } = renderHook(() =>
- useHeterogeneousAutoRetry({ enabled: true, onRetry, scopeId: SCOPE }),
+ useHeterogeneousAutoRetry({
+ enabled: true,
+ onRetry,
+ messageId: 'failed-step',
+ scopeId: SCOPE,
+ }),
);
act(() => {
@@ -167,7 +237,12 @@ describe('useHeterogeneousAutoRetry', () => {
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 }),
+ useHeterogeneousAutoRetry({
+ enabled: true,
+ onRetry,
+ messageId: 'failed-step',
+ scopeId: SCOPE,
+ }),
);
act(() => {
@@ -187,7 +262,12 @@ describe('useHeterogeneousAutoRetry', () => {
it('cleans up the pending timer on unmount', () => {
const onRetry = vi.fn();
const { unmount } = renderHook(() =>
- useHeterogeneousAutoRetry({ enabled: true, onRetry, scopeId: SCOPE }),
+ useHeterogeneousAutoRetry({
+ enabled: true,
+ onRetry,
+ messageId: 'failed-step',
+ scopeId: SCOPE,
+ }),
);
unmount();
@@ -196,4 +276,87 @@ describe('useHeterogeneousAutoRetry', () => {
});
expect(onRetry).not.toHaveBeenCalled();
});
+ // ROOT CAUSE:
+ // Persisted overloaded cards used their mount as permission to execute again.
+ // Looking at an old branch or reloading reset the budget and reran shell steps.
+ // A live local run now grants one claim; hydration and consumed claims grant none.
+ /** @example Loading historical failure data never dispatches a native run. */
+ it('keeps hydrated historical failures manual when there is no local run', () => {
+ storeMock.hasOperation = false;
+ const onRetry = vi.fn();
+ const { result } = renderHook(() =>
+ useHeterogeneousAutoRetry({
+ enabled: true,
+ messageId: 'failed-step',
+ onRetry,
+ scopeId: SCOPE,
+ }),
+ );
+ act(() => vi.advanceTimersByTime(60_000));
+ /** @example No countdown and no implicit retry for loaded history. */
+ expect(result.current).toBeUndefined();
+ expect(onRetry).not.toHaveBeenCalled();
+ });
+
+ /** @example Returning to an already retried branch cannot consume another attempt. */
+ it('does not rearm the same failed run after navigating away and back', () => {
+ const onRetry = vi.fn();
+ const renderFailure = () =>
+ renderHook(() =>
+ useHeterogeneousAutoRetry({
+ enabled: true,
+ messageId: 'failed-step',
+ onRetry,
+ scopeId: SCOPE,
+ }),
+ );
+ const first = renderFailure();
+ act(() => vi.advanceTimersByTime(2000));
+ first.unmount();
+ const historical = renderFailure();
+ act(() => vi.advanceTimersByTime(60_000));
+ /** @example Only the original live error can schedule this run's retry. */
+ expect(onRetry).toHaveBeenCalledTimes(1);
+ expect(historical.result.current).toBeUndefined();
+ });
+
+ /** @example Stop followed directly by a fresh page load stays stopped. */
+ it('does not restart a cancelled countdown after reload clears the local budget', () => {
+ const onRetry = vi.fn();
+ const renderFailure = () =>
+ renderHook(() =>
+ useHeterogeneousAutoRetry({
+ enabled: true,
+ messageId: 'failed-step',
+ onRetry,
+ scopeId: SCOPE,
+ }),
+ );
+ const first = renderFailure();
+ act(() => first.result.current?.onCancel());
+ first.unmount();
+ storeMock.attempts = {};
+ storeMock.hasOperation = false;
+ renderFailure();
+ act(() => vi.advanceTimersByTime(60_000));
+ /** @example Refreshing does not imply a Retry action. */
+ expect(onRetry).not.toHaveBeenCalled();
+ });
+
+ /** @example Reconnecting an existing run only observes it, without retry permission. */
+ it('keeps reconnected runs manual unless a new run granted retry permission', () => {
+ storeMock.retryAvailable = false;
+ const onRetry = vi.fn();
+ renderHook(() =>
+ useHeterogeneousAutoRetry({
+ enabled: true,
+ messageId: 'failed-step',
+ onRetry,
+ scopeId: SCOPE,
+ }),
+ );
+ act(() => vi.advanceTimersByTime(60_000));
+ /** @example A server operation id alone cannot authorize replay. */
+ expect(onRetry).not.toHaveBeenCalled();
+ });
});
diff --git a/src/features/Conversation/Error/useHeterogeneousAutoRetry.ts b/src/features/Conversation/Error/useHeterogeneousAutoRetry.ts
index fc92ce25857..b6a3e9939b0 100644
--- a/src/features/Conversation/Error/useHeterogeneousAutoRetry.ts
+++ b/src/features/Conversation/Error/useHeterogeneousAutoRetry.ts
@@ -1,5 +1,8 @@
import { useCallback, useEffect, useRef, useState } from 'react';
+import { useChatStore } from '@/store/chat';
+import { operationSelectors } from '@/store/chat/slices/operation/selectors';
+
import { useConversationStore } from '../store';
import {
HETERO_OVERLOAD_BACKOFF_JITTER,
@@ -27,6 +30,8 @@ export interface HeteroAutoRetryViewModel {
interface UseHeterogeneousAutoRetryParams {
/** True only for the transient `overloaded` error code. */
enabled: boolean;
+ /** Failed assistant step; one locally initiated run may grant one automatic retry. */
+ messageId: string;
/** Fires the actual retry (delete failed turn + regenerate). */
onRetry: () => void;
/** Parent user message id — stable across the retry's delete+recreate. */
@@ -43,12 +48,29 @@ const backoffMs = (attemptsSpent: number): number => {
};
/**
- * Drives capped, backed-off auto-retry for heterogeneous "overloaded" errors.
+ * Drives capped, backed-off auto-retry for live heterogeneous "overloaded" errors.
+ *
+ * Use when:
+ * - Rendering the failed step of a locally initiated agent run.
+ *
+ * Expects:
+ * - The runtime operation is associated with the failed message and grants one retry.
+ *
+ * Returns:
+ * - A countdown for an admitted live failure; persisted history remains manual.
+ *
+ * Call stack:
+ *
+ * ErrorMessageExtra
+ * -> {@link useHeterogeneousAutoRetry}
+ * -> internal_beginHeteroOverloadWait
+ * -> onRetry (continueHeteroAfterError or regenerate)
+ *
*
* 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
+ * lives here: each eligible live error 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.
@@ -60,6 +82,7 @@ const backoffMs = (attemptsSpent: number): number => {
*/
export const useHeterogeneousAutoRetry = ({
enabled,
+ messageId,
onRetry,
scopeId,
}: UseHeterogeneousAutoRetryParams): HeteroAutoRetryViewModel | undefined => {
@@ -72,7 +95,36 @@ export const useHeterogeneousAutoRetry = ({
const endWait = useConversationStore((s) => s.internal_endHeteroOverloadWait);
const isWaitAborted = useConversationStore((s) => s.isHeteroOverloadWaitAborted);
- const active = enabled && !!scopeId && attemptsSpent < MAX_HETERO_AUTO_RETRIES;
+ // Loading persisted messages must not authorize shell execution. Only a run
+ // explicitly started in this client grants a one-use retry; reconnect merely
+ // observes the server run. Consuming its grant survives card remounts, while
+ // a page reload has no grants at all and therefore stays on manual Retry.
+ const availableRunId = useChatStore((s) => {
+ const operationId = s.messageOperationMap[messageId];
+ if (!operationId) return undefined;
+ const operation = operationSelectors.findRootRuntimeOperation(operationId)(s);
+ return operation?.metadata.heteroAutoRetryAvailable && !operation.abortController.signal.aborted
+ ? operation.id
+ : undefined;
+ });
+ const [admittedMessageId, setAdmittedMessageId] = useState<string>();
+ useEffect(() => {
+ if (!enabled || !scopeId || !availableRunId || attemptsSpent >= MAX_HETERO_AUTO_RETRIES) return;
+ const chatStore = useChatStore.getState();
+ const operation = chatStore.operations[availableRunId];
+ // Multiple surfaces may render the same error; claim synchronously so only
+ // one countdown can own the run, including React's effect replay.
+ if (!operation?.metadata.heteroAutoRetryAvailable || operation.abortController.signal.aborted)
+ return;
+ chatStore.updateOperationMetadata(availableRunId, { heteroAutoRetryAvailable: false });
+ setAdmittedMessageId(messageId);
+ }, [availableRunId, enabled, messageId, scopeId, attemptsSpent]);
+
+ const active =
+ enabled &&
+ !!scopeId &&
+ admittedMessageId === messageId &&
+ attemptsSpent < MAX_HETERO_AUTO_RETRIES;
const [secondsLeft, setSecondsLeft] = useState(0);
// Keep the latest onRetry without re-arming the timer when it changes.
@@ -84,6 +136,7 @@ export const useHeterogeneousAutoRetry = ({
const fire = useCallback(() => {
if (!scopeId || firedRef.current) return;
firedRef.current = true;
+ setAdmittedMessageId(undefined);
// 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)) {
@@ -125,6 +178,7 @@ export const useHeterogeneousAutoRetry = ({
// Mark fired so a timer callback already dequeued for this tick can't slip
// through and retry after the user cancelled.
firedRef.current = true;
+ setAdmittedMessageId(undefined);
endWait(scopeId);
markExhausted(scopeId);
}, [endWait, markExhausted, scopeId]);
diff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.ts
index 7509143880e..0b603d89996 100644
--- a/src/features/Conversation/store/slices/data/action.test.ts
+++ b/src/features/Conversation/store/slices/data/action.test.ts
@@ -1819,6 +1819,44 @@ describe('DataSlice', () => {
});
describe('switchMessageBranch', () => {
+ // ROOT CAUSE:
+ // MessageBranch calls this conversation action, which persists metadata
+ // directly rather than delegating to ChatStore.switchMessageBranch.
+ /** @example Leaving a live branch revokes retry before the UI swaps replies. */
+ it('revokes automatic recovery through the branch button action', async () => {
+ const store = createTestStore();
+ const context = store.getState().context;
+ const { operationId } = useChatStore.getState().startOperation({
+ context,
+ metadata: { heteroAutoRetryAvailable: true },
+ type: 'execServerAgentRuntime',
+ });
+ store.setState({
+ dbMessages: [
+ {
+ id: 'live-reply',
+ parentId: 'parent-user',
+ role: 'assistant',
+ content: '',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ },
+ ],
+ });
+ const update = vi
+ .spyOn(store.getState(), 'updateMessageMetadata')
+ .mockImplementation(async () => {
+ /** @example Even an error not yet rendered loses its automatic retry grant. */
+ expect(
+ useChatStore.getState().operations[operationId].metadata.heteroAutoRetryAvailable,
+ ).toBe(false);
+ });
+ await store.getState().switchMessageBranch('live-reply', 0);
+ /** @example The normal parent branch selection still persists. */
+ expect(update).toHaveBeenCalledWith('parent-user', { activeBranchIndex: 0 });
+ update.mockRestore();
+ });
+
it('should call updateMessageMetadata on parent message with branch index', async () => {
const store = createTestStore();
diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.ts
index 64f994f102a..f50d8e2e8f1 100644
--- a/src/features/Conversation/store/slices/data/action.ts
+++ b/src/features/Conversation/store/slices/data/action.ts
@@ -556,6 +556,9 @@ export const dataSlice: StateCreator<
const message = dataSelectors.getDbMessageById(messageId)(state);
if (!message || !message.parentId) return;
+ // Invalidate pending automatic recovery before a historical error can mount.
+ getChatStoreState().revokeHeteroAutoRetry(state.context);
+
// Update the parent's metadata.activeBranchIndex
// because the branch indicator is on the child message,
// but the activeBranchIndex is stored on the parent
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.ts
index ea39aab56da..17b391321f7 100644
--- a/src/features/Conversation/store/slices/generation/action.ts
+++ b/src/features/Conversation/store/slices/generation/action.ts
@@ -333,7 +333,10 @@ export const runHeterogeneousFromExistingMessage = async (
const { operationId: heteroOpId } = chatStore.startOperation({
context,
label: 'Heterogeneous Agent Execution',
- metadata: { heterogeneousType: heterogeneousProvider.type },
+ metadata: {
+ heteroAutoRetryAvailable: !replayTranscript,
+ heterogeneousType: heterogeneousProvider.type,
+ },
parentOperationId,
type: 'execHeterogeneousAgent',
});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
index fc7287a913b..017d62c2bf7 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
@@ -522,6 +522,39 @@ describe('ConversationControl actions', () => {
});
describe('switchMessageBranch', () => {
+ // ROOT CAUSE:
+ // An unclaimed retry grant could outlive its visible branch. Selecting old
+ // history must revoke that grant before a newly mounted error card sees it.
+ /** @example Branch selection revokes only the selected conversation's grants. */
+ it('revokes unclaimed auto retries before displaying another branch', async () => {
+ const context = { agentId: 'retry-agent', topicId: 'retry-topic', threadId: null };
+ const otherContext = { agentId: 'retry-agent', topicId: 'other-topic', threadId: null };
+ const current = useChatStore.getState().startOperation({
+ context,
+ metadata: { heteroAutoRetryAvailable: true },
+ type: 'execServerAgentRuntime',
+ });
+ const unrelated = useChatStore.getState().startOperation({
+ context: otherContext,
+ metadata: { heteroAutoRetryAvailable: true },
+ type: 'execServerAgentRuntime',
+ });
+ vi.spyOn(useChatStore.getState(), 'optimisticUpdateMessageMetadata').mockImplementation(
+ async () => {
+ /** @example Revocation happens before the asynchronous branch replacement. */
+ expect(
+ useChatStore.getState().operations[current.operationId].metadata
+ .heteroAutoRetryAvailable,
+ ).toBe(false);
+ },
+ );
+ await useChatStore.getState().switchMessageBranch('parent-user', 1, { context });
+ /** @example Other topics retain their live recovery intent. */
+ expect(
+ useChatStore.getState().operations[unrelated.operationId].metadata.heteroAutoRetryAvailable,
+ ).toBe(true);
+ });
+
it('should switch to a different message branch', async () => {
const { result } = renderHook(() => useChatStore());
const messageId = TEST_IDS.MESSAGE_ID;
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index b59bbb657d3..2b3de128163 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -987,6 +987,37 @@ describe('GatewayActionImpl', () => {
expect(connectToGateway).toHaveBeenCalled();
});
+ /** @example A run dispatched by this client may recover from one live overloaded error. */
+ it('grants one automatic heterogeneous retry to a run started from this client', async () => {
+ const { action, startOperation } = createExecuteTestAction();
+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({
+ agentId: 'agent-1',
+ assistantMessageId: 'assistant-1',
+ autoStarted: true,
+ createdAt: new Date().toISOString(),
+ message: 'ok',
+ operationId: 'server-op-1',
+ status: 'created',
+ success: true,
+ timestamp: new Date().toISOString(),
+ token: 'token',
+ topicId: 'topic-1',
+ userMessageId: 'user-1',
+ });
+
+ await action.executeGatewayAgent({
+ context: { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },
+ message: 'run it',
+ });
+
+ expect(startOperation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: expect.objectContaining({ heteroAutoRetryAvailable: true }),
+ type: 'execServerAgentRuntime',
+ }),
+ );
+ });
+
const precreatedInterventionResult: ExecAgentResult = {
agentId: 'agent-1',
assistantMessageId: 'ast-resumed',
@@ -3847,6 +3878,23 @@ describe('GatewayActionImpl', () => {
);
});
+ // ROOT CAUSE:
+ // Reconnecting only observes a server run that another client or an earlier
+ // page load started; it must not authorize re-executing its tool steps.
+ /** @example Reconnect never grants an automatic heterogeneous retry. */
+ it('does not grant automatic retry to a reconnected run', async () => {
+ const { action, startOperation } = createReconnectTestAction({ id: 'ast-1' });
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ const [[params]] = startOperation.mock.calls as unknown as [[{ metadata: object }]];
+ expect(params.metadata).not.toHaveProperty('heteroAutoRetryAvailable');
+ });
+
it('shares one attempt between concurrent reconnects to the same run', async () => {
const { action, startOperation } = createReconnectTestAction({ id: 'ast-1' });
const params = {
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
index 006eab9933d..4c0bd9f8654 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts
@@ -679,6 +679,11 @@ export class ConversationControlActionImpl {
branchIndex: number,
context?: OptimisticUpdateContext,
): Promise<void> => {
+ const store = this.#get();
+ const messageContext = store.internal_getConversationContext(context);
+ // A branch change only changes the displayed reply; it does not authorize
+ // recovery of an old failure when its card mounts.
+ store.revokeHeteroAutoRetry(messageContext);
await this.#get().optimisticUpdateMessageMetadata(
messageId,
{ activeBranchIndex: branchIndex },
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index ca3082f5d65..910f53d50bd 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -1730,7 +1730,7 @@ export class ConversationLifecycleActionImpl {
const { operationId: heteroOpId } = this.#get().startOperation({
context: heteroExecutionContext,
label: 'Heterogeneous Agent Execution',
- metadata: { heterogeneousType: heterogeneousProvider.type },
+ metadata: { heteroAutoRetryAvailable: true, heterogeneousType: heterogeneousProvider.type },
parentOperationId: operationId,
type: 'execHeterogeneousAgent',
});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index ad7e72857af..97e6466ef81 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -1592,7 +1592,7 @@ export class GatewayActionImpl {
// without needing an out-of-band lookup.
const { operationId: gatewayOpId } = this.#get().startOperation({
context: resolvedMessageContext,
- metadata: { serverOperationId: result.operationId },
+ metadata: { heteroAutoRetryAvailable: true, serverOperationId: result.operationId },
parentOperationId,
type: 'execServerAgentRuntime',
});
diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.ts
index f006faaf64a..69dee56b0af 100644
--- a/src/store/chat/slices/operation/actions.ts
+++ b/src/store/chat/slices/operation/actions.ts
@@ -49,6 +49,32 @@ export class OperationActionsImpl {
this.#get = get;
}
+ /**
+ * Abandons unclaimed automatic recovery when a conversation changes branches.
+ *
+ * Use when:
+ * - Either conversation surface selects another persisted reply.
+ *
+ * Expects:
+ * - The full message context, including thread and share scopes.
+ *
+ * Returns:
+ * - No value; unrelated conversations and explicit Retry remain unchanged.
+ *
+ * Call stack:
+ *
+ * switchMessageBranch (conversation or chat store)
+ * -> {@link OperationActionsImpl.revokeHeteroAutoRetry}
+ * -> {@link OperationActionsImpl.updateOperationMetadata}
+ */
+ revokeHeteroAutoRetry = (context: MessageMapKeyInput): void => {
+ for (const operation of operationSelectors.getOperationsByContext(context)(this.#get())) {
+ if (operation.metadata.heteroAutoRetryAvailable) {
+ this.updateOperationMetadata(operation.id, { heteroAutoRetryAvailable: false });
+ }
+ }
+ };
+
internal_getConversationContext = (reference?: {
context?: MessageMapKeyInput;
operationId?: string;
diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.ts
index 0d9b539be05..82cffb4efa8 100644
--- a/src/store/chat/slices/operation/types.ts
+++ b/src/store/chat/slices/operation/types.ts
@@ -142,6 +142,13 @@ export interface OperationMetadata {
details?: any;
};
+ /**
+ * One-use automatic retry grant for a run explicitly dispatched by this client.
+ * Consumed by the error card; absent for restored/reconnected operations.
+ * @default undefined
+ */
+ heteroAutoRetryAvailable?: boolean;
+
// UI state (for sendMessage operation)
inputEditorTempState?: any | null; // Editor state snapshot for cancel restoration