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): make error-card retry reachable, effective, and visible (#18080)

Arvin Xua2dbb5947444
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 8a70445811e..77d91a0947f 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -778,6 +778,7 @@
"messageAction.interruptedHint": "What should I do instead?",
"messageAction.reaction": "Add Reaction",
"messageAction.regenerate": "Regenerate",
+ "messageAction.regenerateAlreadyRunning": "This message is already being regenerated.",
"messageAction.select": "Select",
"messageForward.bar.cancel": "Cancel",
"messageForward.bar.delete": "Delete",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index d431fe91ad5..4751284f952 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -778,6 +778,7 @@
"messageAction.interruptedHint": "ζŽ₯δΈ‹ζ₯ιœ€θ¦εšδ»€δΉˆοΌŸ",
"messageAction.reaction": "ζ·»εŠ θ‘¨ζƒ…",
"messageAction.regenerate": "ι‡ζ–°η”Ÿζˆ",
+ "messageAction.regenerateAlreadyRunning": "θ―₯ζΆˆζ―ζ­£εœ¨ι‡ζ–°η”ŸζˆδΈ­γ€‚",
"messageAction.select": "ε€šι€‰",
"messageForward.bar.cancel": "ε–ζΆˆ",
"messageForward.bar.delete": "εˆ ι™€",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index b329e8f9587..5985f3df855 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -594,6 +594,7 @@ export default {
'The current model doesn’t support continuing an assistant message. Try regenerating instead.',
'messageAction.copyOperationId': 'Copy Operation ID',
'messageAction.delAndRegenerate': 'Delete and Regenerate',
+ 'messageAction.regenerateAlreadyRunning': 'This message is already being regenerated.',
'messageAction.interrupted': 'Interrupted',
'messageAction.interruptedHint': 'What should I do instead?',
'messageAction.deleteDisabledByThreads': 'This message has a subtopic and can’t be deleted',
diff --git a/src/features/Conversation/ChatItem/components/ErrorContent.test.tsx b/src/features/Conversation/ChatItem/components/ErrorContent.test.tsx
index 851ed637648..6e0bcdadf4f 100644
--- a/src/features/Conversation/ChatItem/components/ErrorContent.test.tsx
+++ b/src/features/Conversation/ChatItem/components/ErrorContent.test.tsx
@@ -10,14 +10,18 @@ import ErrorContent from './ErrorContent';
const deleteMessageMock = vi.fn();
const updateMessageErrorMock = vi.fn();
let messageContent: string | undefined = '';
+let isRegenerating = false;
// Drive the Alert's `afterClose` directly via a click, so we exercise
// ErrorContent's dismiss branching without the real close animation.
vi.mock('@lobehub/ui', () => ({
- Alert: ({ afterClose }: { afterClose?: () => void }) => (
- <button type="button" onClick={() => afterClose?.()}>
- close
- </button>
+ Alert: ({ action, afterClose }: { action?: ReactNode; afterClose?: () => void }) => (
+ <div>
+ <button type="button" onClick={() => afterClose?.()}>
+ close
+ </button>
+ {action}
+ </div>
),
Skeleton: { Button: () => <div>loading</div> },
}));
@@ -34,6 +38,9 @@ vi.mock('@/features/Conversation/store', () => ({
dataSelectors: {
getDisplayMessageById: (id: string) => () => ({ content: messageContent, id }),
},
+ messageStateSelectors: {
+ isMessageRegenerating: () => () => isRegenerating,
+ },
useConversationStore: (selector: (s: unknown) => unknown) =>
selector({
deleteMessage: deleteMessageMock,
@@ -45,6 +52,7 @@ describe('ErrorContent dismiss behavior', () => {
beforeEach(() => {
deleteMessageMock.mockClear();
updateMessageErrorMock.mockClear();
+ isRegenerating = false;
});
it('clears only the error (keeps the message) when the turn already streamed content', () => {
@@ -66,4 +74,29 @@ describe('ErrorContent dismiss behavior', () => {
expect(deleteMessageMock).toHaveBeenCalledWith('msg-1');
expect(updateMessageErrorMock).not.toHaveBeenCalled();
});
+
+ // Regression: `regenerate` sits outside AI_RUNTIME_OPERATION_TYPES, so nothing
+ // else on the message reacts while a retry is in flight. Verified live: with a
+ // regenerate op genuinely running, the message showed zero loading affordance
+ // β€” the click read as "nothing happened" and invited a second one.
+ it('puts the retry button in a pending state while this message is regenerating', () => {
+ messageContent = '';
+ isRegenerating = true;
+ render(<ErrorContent error={{ message: 'boom' } as any} id="msg-1" onRegenerate={vi.fn()} />);
+
+ const button = screen.getByRole('button', { name: /regenerate/i });
+
+ expect(button).toBeDisabled();
+ expect(button).toHaveAttribute('aria-busy', 'true');
+ });
+
+ it('leaves the retry button idle when nothing is regenerating', () => {
+ messageContent = '';
+ render(<ErrorContent error={{ message: 'boom' } as any} id="msg-1" onRegenerate={vi.fn()} />);
+
+ const button = screen.getByRole('button', { name: /regenerate/i });
+
+ expect(button).not.toBeDisabled();
+ expect(button).not.toHaveAttribute('aria-busy');
+ });
});
diff --git a/src/features/Conversation/ChatItem/components/ErrorContent.tsx b/src/features/Conversation/ChatItem/components/ErrorContent.tsx
index 6d01e127b14..b3666283813 100644
--- a/src/features/Conversation/ChatItem/components/ErrorContent.tsx
+++ b/src/features/Conversation/ChatItem/components/ErrorContent.tsx
@@ -4,7 +4,11 @@ import { RotateCcw } from 'lucide-react';
import { memo, Suspense } from 'react';
import { useTranslation } from 'react-i18next';
-import { dataSelectors, useConversationStore } from '@/features/Conversation/store';
+import {
+ dataSelectors,
+ messageStateSelectors,
+ useConversationStore,
+} from '@/features/Conversation/store';
import { type ChatItemProps } from '../type';
@@ -24,6 +28,12 @@ const ErrorContent = memo<ErrorContentProps>(({ customErrorRender, error, id, on
const messageContent = useConversationStore((s) =>
id ? dataSelectors.getDisplayMessageById(id)(s)?.content : undefined,
);
+ // The retry can take a while to produce anything visible (branch switch plus a
+ // transport round trip), so the button has to own its own pending state β€”
+ // otherwise a click reads as "nothing happened" and invites a second one.
+ const retrying = useConversationStore((s) =>
+ id ? messageStateSelectors.isMessageRegenerating(id)(s) : false,
+ );
if (!error) return;
@@ -42,7 +52,14 @@ const ErrorContent = memo<ErrorContentProps>(({ customErrorRender, error, id, on
type={'secondary'}
action={
onRegenerate && (
- <Button icon={<RotateCcw size={14} />} size="small" type="fill" onClick={onRegenerate}>
+ <Button
+ disabled={retrying}
+ icon={<RotateCcw size={14} />}
+ loading={retrying}
+ size="small"
+ type="fill"
+ onClick={onRegenerate}
+ >
{t('regenerate')}
</Button>
)
diff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsx
index debc86274de..0a11a5f18af 100644
--- a/src/features/Conversation/Error/index.test.tsx
+++ b/src/features/Conversation/Error/index.test.tsx
@@ -16,6 +16,11 @@ const updateMessageErrorMock = vi.fn();
const dynamicComponentPropsMock = vi.hoisted(() => vi.fn());
const serverConfigMock = vi.hoisted(() => ({ enableBusinessFeatures: false }));
+const delAndRegenerateMessageMock = vi.hoisted(() => vi.fn());
+// Keyed by message id so a test can decide whether `data.id` is a top-level
+// displayMessage hanging off a user turn β€” the condition that decides whether a
+// self-contained retry can actually do anything.
+const displayMessageMock = vi.hoisted(() => new Map<string, { parentId?: string }>());
const missingTranslationKeys = vi.hoisted(() => new Set<string>());
const businessErrorContentMock = vi.hoisted(() =>
vi.fn(() => ({
@@ -95,10 +100,17 @@ vi.mock('@/business/client/hooks/useRenderBusinessChatErrorMessageExtra', () =>
}));
vi.mock('@/features/Conversation/ChatItem/components/ErrorContent', () => ({
- default: ({ error }: { error?: { extra?: ReactNode; message?: string } }) => (
+ default: ({
+ error,
+ onRegenerate,
+ }: {
+ error?: { extra?: ReactNode; message?: string };
+ onRegenerate?: () => void;
+ }) => (
<div>
<div>{error?.message}</div>
{error?.extra}
+ {onRegenerate && <button onClick={onRegenerate}>card-retry</button>}
</div>
),
}));
@@ -146,11 +158,11 @@ vi.mock('@/store/serverConfig', () => ({
vi.mock('@/features/Conversation/store', () => ({
dataSelectors: {
- getDisplayMessageById: () => () => undefined,
+ getDisplayMessageById: (id: string) => () => displayMessageMock.get(id),
},
useConversationStore: (selector: (state: unknown) => unknown) =>
selector({
- delAndRegenerateMessage: vi.fn(),
+ delAndRegenerateMessage: delAndRegenerateMessageMock,
deleteMessage: vi.fn(),
heteroOverloadRetryAttempts: {},
internal_beginHeteroOverloadWait: vi.fn(),
@@ -180,6 +192,70 @@ describe('ErrorMessageExtra', () => {
message: undefined,
});
updateMessageErrorMock.mockClear();
+ delAndRegenerateMessageMock.mockClear();
+ displayMessageMock.clear();
+ });
+
+ // Regression: the standalone surfaces (Assistant / Task / AgentCouncil) render
+ // this card through `customErrorRender` WITHOUT an `onRegenerate`, and the
+ // retry affordance used to be gated on that prop. Verified live: a plain
+ // assistant turn that failed showed a card reading "…or retry" whose only
+ // button was the close Γ—, while the identical error inside an assistantGroup
+ // offered a working retry.
+ describe('self-contained retry when no onRegenerate is supplied', () => {
+ it('renders a retry on a standalone message that has a parent user turn', () => {
+ displayMessageMock.set('msg-standalone', { parentId: 'user-1' });
+
+ render(
+ <ErrorMessageExtra
+ error={{ message: 'provider exploded' }}
+ data={{
+ error: { body: { provider: 'openai' }, type: 'ProviderBizError' } as any,
+ id: 'msg-standalone',
+ }}
+ />,
+ );
+
+ fireEvent.click(screen.getByText('card-retry'));
+
+ expect(delAndRegenerateMessageMock).toHaveBeenCalledWith('msg-standalone');
+ });
+
+ it('does not advertise a retry that could not do anything', () => {
+ // No entry in displayMessageMock: `data.id` is a nested block rather than a
+ // top-level displayMessage, so delete-and-regenerate would delete it and
+ // regenerate nothing.
+ render(
+ <ErrorMessageExtra
+ error={{ message: 'provider exploded' }}
+ data={{
+ error: { body: { provider: 'openai' }, type: 'ProviderBizError' } as any,
+ id: 'msg-orphan-block',
+ }}
+ />,
+ );
+
+ expect(screen.queryByText('card-retry')).toBeNull();
+ });
+
+ it('offers the trace-id report card a retry as well', () => {
+ serverConfigMock.enableBusinessFeatures = true;
+ displayMessageMock.set('msg-trace', { parentId: 'user-1' });
+
+ render(
+ <ErrorMessageExtra
+ error={{ message: 'unknown' }}
+ data={{
+ error: { body: { traceId: 'trace-abc' } } as any,
+ id: 'msg-trace',
+ }}
+ />,
+ );
+
+ fireEvent.click(screen.getByText('dynamic-retry'));
+
+ expect(delAndRegenerateMessageMock).toHaveBeenCalledWith('msg-trace');
+ });
});
it('keeps the localized message for known error types even when a traceId exists', () => {
diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsx
index e394bb11963..8d77391abca 100644
--- a/src/features/Conversation/Error/index.tsx
+++ b/src/features/Conversation/Error/index.tsx
@@ -294,14 +294,27 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(
const delAndRegenerateMessage = useConversationStore((s) => s.delAndRegenerateMessage);
const updateMessageError = useConversationStore((s) => s.updateMessageError);
const resetHeteroOverloadRetry = useConversationStore((s) => s.resetHeteroOverloadRetry);
+ // `data.id`'s own parent user message. Only present when `data.id` is a
+ // top-level displayMessage that hangs off a user turn β€” which is exactly the
+ // condition for the self-contained retry below to be able to do anything.
+ const ownParentId = useConversationStore(
+ (s) => dataSelectors.getDisplayMessageById(data.id)(s)?.parentId,
+ );
// 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,
- );
+ const resolvedScopeId = retryScopeId ?? ownParentId;
+
+ // The standalone surfaces (Assistant / Task / AgentCouncil) render this card
+ // through `customErrorRender` WITHOUT an `onRegenerate`, so gating the retry
+ // affordance on that prop left their error cards with no way to retry at all
+ // β€” while the very same error inside an assistantGroup offered one. Fall back
+ // to retrying this message on our own, but only advertise it when that can
+ // actually run: a block that isn't a top-level displayMessage, or one with no
+ // parent user turn, would delete itself and regenerate nothing.
+ const canRetry = canCreate && (!!onRegenerate || !!ownParentId);
const handleRetryAgentMessage = useCallback(() => {
- if (!canCreate) return;
+ if (!canRetry) return;
if (onRegenerate) {
onRegenerate();
return;
@@ -311,7 +324,7 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(
// 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]);
+ }, [canRetry, 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.
@@ -327,7 +340,7 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(
// the guide render below, so without it a provider/tool error rendering
// the normal card could be silently retried.
enabled:
- canCreate &&
+ canRetry &&
isHeterogeneousAgentStatusGuideError(sessionErrorBody) &&
sessionErrorBody.code === HeterogeneousAgentSessionErrorCode.Overloaded,
onRetry: handleRetryAgentMessage,
@@ -362,7 +375,9 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(
? {
isScheduled: activeTopicScheduled,
onCancel: () => void cancelHeteroContinuation(),
- onRunNow: () => void onRegenerate?.(),
+ // Same fallback as the retry button: `onRegenerate` is absent on the
+ // standalone surfaces, where a bare `onRegenerate?.()` was a no-op.
+ onRunNow: handleManualRetry,
onSchedule: () =>
void scheduleHeteroContinuation({
failedAssistantMessageId: data.id,
@@ -466,7 +481,7 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(
<TraceIdError
id={data.id}
traceId={traceId}
- onRetry={canCreate && onRegenerate ? handleManualRetry : undefined}
+ onRetry={canRetry ? handleManualRetry : undefined}
/>
);
}
@@ -488,7 +503,7 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(
</Highlighter>
) : undefined,
}}
- onRegenerate={canCreate ? onRegenerate : undefined}
+ onRegenerate={canRetry ? handleManualRetry : undefined}
/>
);
},
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx
index b1b1e78389c..f7c4cf5359f 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx
@@ -11,6 +11,7 @@ import ContentBlock from './ContentBlock';
const continueGenerationMock = vi.fn();
const deleteDBMessageMock = vi.fn();
const continueHeteroAfterErrorMock = vi.fn();
+const retryFailedAssistantStepMock = vi.fn();
const navigateMock = vi.fn();
let isInReasoningMock = false;
@@ -131,6 +132,7 @@ vi.mock('../../../store', () => ({
continueGeneration: continueGenerationMock,
continueHeteroAfterError: continueHeteroAfterErrorMock,
deleteDBMessage: deleteDBMessageMock,
+ retryFailedAssistantStep: retryFailedAssistantStepMock,
heteroOverloadRetryAttempts: {},
internal_beginHeteroOverloadWait: vi.fn(),
internal_endHeteroOverloadWait: vi.fn(),
@@ -146,11 +148,12 @@ describe('AssistantGroup ContentBlock', () => {
continueGenerationMock.mockClear();
deleteDBMessageMock.mockClear();
continueHeteroAfterErrorMock.mockClear();
+ retryFailedAssistantStepMock.mockClear();
navigateMock.mockClear();
isInReasoningMock = false;
});
- it('resumes the run (not the no-op continueGeneration) when retrying a heterogeneous error in a group', () => {
+ it('delegates a retry to the store instead of hand-rolling delete + continue', () => {
render(
<ContentBlock
assistantId="assistant-1"
@@ -173,10 +176,13 @@ describe('AssistantGroup ContentBlock', () => {
screen.getByRole('button', { name: 'guide-retry' }).click();
- // Retrying a grouped hetero turn resumes it from the GROUP id β€” dropping only
- // the failed step and picking the CLI session back up β€” instead of calling
- // continueGeneration, which is a no-op for hetero runtimes.
- expect(continueHeteroAfterErrorMock).toHaveBeenCalledWith('assistant-1');
+ // The component must not decide anything itself. It used to delete the failed
+ // block and then call `continueGeneration`, which could silently find nothing
+ // to continue and leave the turn deleted with nothing running. The store owns
+ // the routing (hetero resume / continue in place / replace the turn) because
+ // only it can guarantee a terminal outcome.
+ expect(retryFailedAssistantStepMock).toHaveBeenCalledWith('assistant-1', 'block-1');
+ expect(deleteDBMessageMock).not.toHaveBeenCalled();
expect(continueGenerationMock).not.toHaveBeenCalled();
});
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx
index 83e9595047f..b93b1e055f2 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx
@@ -3,10 +3,7 @@ import { memo, useCallback } from 'react';
import SafeBoundary from '@/components/ErrorBoundary';
import { LOADING_FLAT } from '@/const/message';
-import ErrorMessageExtra, {
- isHeterogeneousAgentStatusGuideError,
- useErrorContent,
-} from '@/features/Conversation/Error';
+import ErrorMessageExtra, { useErrorContent } from '@/features/Conversation/Error';
import ErrorContent from '../../../ChatItem/components/ErrorContent';
import { dataSelectors, messageStateSelectors, useConversationStore } from '../../../store';
@@ -37,45 +34,30 @@ const ContentBlock = memo<ContentBlockProps>(
}) => {
const errorContent = useErrorContent(error);
const showImageItems = !!imageList && imageList.length > 0;
- const [isReasoning, deleteMessage, continueGeneration, continueHeteroAfterError] =
- useConversationStore((s) => [
- messageStateSelectors.isMessageInReasoning(id)(s),
- s.deleteDBMessage,
- s.continueGeneration,
- s.continueHeteroAfterError,
- ]);
+ const [isReasoning, retryFailedAssistantStep] = useConversationStore((s) => [
+ messageStateSelectors.isMessageInReasoning(id)(s),
+ s.retryFailedAssistantStep,
+ ]);
// 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 = hasRenderableReasoning(reasoning) || (!reasoning && isReasoning);
const hasContent = !!content && content !== LOADING_FLAT;
const showMessageContent = hasContent || content === LOADING_FLAT || hasTools;
- const handleRegenerate = useCallback(async () => {
- // `continueGeneration` is a silent no-op for hetero CLIs (they have no
- // "continue a cut-off response" primitive), so an errored hetero turn goes
- // through its own path: drop just the failed step and resume the CLI
- // session, keeping every step that already succeeded. Routed through the
- // GROUP id β€” the child block id isn't a top-level displayMessage. It falls
- // back to a whole-turn regenerate when there's nothing left to resume.
- if (isHeteroError) {
- void continueHeteroAfterError(assistantId);
- return;
- }
- await deleteMessage(id);
- continueGeneration(assistantId);
- }, [
- assistantId,
- continueGeneration,
- continueHeteroAfterError,
- deleteMessage,
- id,
- isHeteroError,
- ]);
+ // The store owns the whole decision (resume a hetero session, continue the
+ // group in place, or replace the turn) because only it can guarantee a
+ // terminal outcome. Deleting the failed block here and then hoping
+ // `continueGeneration` still found something to continue is what silently
+ // ate the turn. Routed through the GROUP id β€” the child block id isn't a
+ // top-level displayMessage.
+ const handleRegenerate = useCallback(
+ () => retryFailedAssistantStep(assistantId, id),
+ [assistantId, id, retryFailedAssistantStep],
+ );
const errorBlock = error ? (
<ErrorContent
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/regenerate.test.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/regenerate.test.ts
new file mode 100644
index 00000000000..bf9fbf0f5ad
--- /dev/null
+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/regenerate.test.ts
@@ -0,0 +1,76 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import type { UIChatMessage } from '@lobechat/types';
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { MessageActionContext } from '../types';
+import { regenerateAction } from './regenerate';
+
+const regenerateUserMessage = vi.fn();
+const regenerateAssistantMessage = vi.fn();
+const delAndRegenerateMessage = vi.fn();
+const deleteMessage = vi.fn();
+
+vi.mock('../../../../store', () => ({
+ messageStateSelectors: {
+ isMessageRegenerating: () => () => false,
+ },
+ useConversationStore: (selector: (s: any) => any) =>
+ selector({
+ delAndRegenerateMessage,
+ deleteMessage,
+ regenerateAssistantMessage,
+ regenerateUserMessage,
+ }),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+const build = (
+ data: Partial<UIChatMessage>,
+ role: MessageActionContext['role'] = 'assistant',
+ id = 'msg-1',
+) =>
+ renderHook(() => regenerateAction.useBuild({ data: data as UIChatMessage, id, role })).result
+ .current!;
+
+describe('regenerateAction', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ // Regression: this used to fire `regenerateAssistantMessage` WITHOUT awaiting
+ // it and then call `deleteMessage` on the same tick. The unawaited regenerate
+ // computes its new branch index from the pre-delete child count, so the index
+ // lands out of range once the delete resolves; and the delete itself silently
+ // misses, because regenerate has already switched the branch away from the
+ // message it is trying to remove. `delAndRegenerateMessage` is the ordering
+ // that works β€” delete first, then regenerate.
+ it('replaces a failed assistant turn through the delete-first path', () => {
+ build({ error: { type: 'ProviderBizError' } } as any).handleClick!();
+
+ expect(delAndRegenerateMessage).toHaveBeenCalledWith('msg-1');
+ expect(regenerateAssistantMessage).not.toHaveBeenCalled();
+ expect(deleteMessage).not.toHaveBeenCalled();
+ });
+
+ it('regenerates a healthy assistant turn without deleting it', () => {
+ build({} as any).handleClick!();
+
+ expect(regenerateAssistantMessage).toHaveBeenCalledWith('msg-1');
+ expect(delAndRegenerateMessage).not.toHaveBeenCalled();
+ expect(deleteMessage).not.toHaveBeenCalled();
+ });
+
+ it('leaves the user-message path untouched', () => {
+ build({ error: { type: 'ProviderBizError' } } as any, 'user').handleClick!();
+
+ expect(regenerateUserMessage).toHaveBeenCalledWith('msg-1');
+ expect(deleteMessage).toHaveBeenCalledWith('msg-1');
+ expect(delAndRegenerateMessage).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/regenerate.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/regenerate.ts
index f75cc6bcd33..f503d907252 100644
--- a/src/features/Conversation/Messages/components/MessageActionBar/actions/regenerate.ts
+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/regenerate.ts
@@ -12,21 +12,40 @@ export const regenerateAction = defineAction({
const isRegenerating = useConversationStore(
messageStateSelectors.isMessageRegenerating(ctx.id),
);
- const [regenerateUserMessage, regenerateAssistantMessage, deleteMessage] = useConversationStore(
- (s) => [s.regenerateUserMessage, s.regenerateAssistantMessage, s.deleteMessage],
- );
+ const [
+ regenerateUserMessage,
+ regenerateAssistantMessage,
+ delAndRegenerateMessage,
+ deleteMessage,
+ ] = useConversationStore((s) => [
+ s.regenerateUserMessage,
+ s.regenerateAssistantMessage,
+ s.delAndRegenerateMessage,
+ s.deleteMessage,
+ ]);
return useMemo(
() => ({
disabled: isRegenerating,
handleClick: () => {
if (ctx.role === 'user') {
- regenerateUserMessage(ctx.id);
- if (ctx.data.error) deleteMessage(ctx.id);
- } else {
- regenerateAssistantMessage(ctx.id);
- if (ctx.data.error) deleteMessage(ctx.id);
+ void regenerateUserMessage(ctx.id);
+ if (ctx.data.error) void deleteMessage(ctx.id);
+ return;
}
+
+ // Retrying a FAILED assistant turn has to replace it, and
+ // `delAndRegenerateMessage` is the only ordering that works: it deletes
+ // first, then regenerates. Firing regenerate and delete concurrently
+ // (what this did before) is broken twice over β€” the unawaited
+ // regenerate computes its new branch index from the pre-delete child
+ // count, so the index lands out of range once the delete resolves; and
+ // the delete itself silently misses, because regenerate has already
+ // switched the branch away from the very message it is trying to
+ // remove. `delAndRegenerateMessage` carries that same reasoning in its
+ // own body comment.
+ if (ctx.data.error) void delAndRegenerateMessage(ctx.id);
+ else void regenerateAssistantMessage(ctx.id);
},
icon: RotateCcw,
key: 'regenerate',
@@ -41,6 +60,7 @@ export const regenerateAction = defineAction({
isRegenerating,
regenerateUserMessage,
regenerateAssistantMessage,
+ delAndRegenerateMessage,
deleteMessage,
],
);
diff --git a/src/features/Conversation/Messages/components/PendingRetryTurn.tsx b/src/features/Conversation/Messages/components/PendingRetryTurn.tsx
new file mode 100644
index 00000000000..e640b8008bd
--- /dev/null
+++ b/src/features/Conversation/Messages/components/PendingRetryTurn.tsx
@@ -0,0 +1,51 @@
+'use client';
+
+import { memo } from 'react';
+
+import { ChatItem } from '@/features/Conversation/ChatItem';
+
+import { useAgentMeta } from '../../hooks';
+import ContentLoading from './ContentLoading';
+import { usePendingRetryTurn } from './usePendingRetryTurn';
+
+interface PendingRetryTurnProps {
+ /** The user turn being retried β€” the retry operation is keyed to it. */
+ userMessageId: string;
+}
+
+/**
+ * Stand-in reply shown while a retry is in flight and the turn it replaces is
+ * already gone.
+ *
+ * A retry deletes the failed turn BEFORE the replacement exists (delete-first is
+ * deliberate β€” regenerating first switches the branch away and strands the failed
+ * attempt). Measured on the real app, that leaves ~250ms in which the user turn
+ * has no reply under it at all: the error card they clicked vanishes and nothing
+ * takes its place, so the click reads as "nothing happened".
+ *
+ * The message-level loading state cannot cover this β€” there is no message left to
+ * carry it. So the pending state belongs to the USER turn, which survives the
+ * whole window, and this renders the reply that is on its way.
+ */
+const PendingRetryTurn = memo<PendingRetryTurnProps>(({ userMessageId }) => {
+ const { agentId, showPendingTurn } = usePendingRetryTurn(userMessageId);
+ const avatar = useAgentMeta(agentId);
+
+ if (!showPendingTurn) return null;
+
+ return (
+ <ChatItem
+ loading
+ showTitle
+ avatar={avatar}
+ id={`${userMessageId}-pending-retry`}
+ placement={'left'}
+ >
+ <ContentLoading id={userMessageId} />
+ </ChatItem>
+ );
+});
+
+PendingRetryTurn.displayName = 'PendingRetryTurn';
+
+export default PendingRetryTurn;
diff --git a/src/features/Conversation/Messages/components/usePendingRetryTurn.test.ts b/src/features/Conversation/Messages/components/usePendingRetryTurn.test.ts
new file mode 100644
index 00000000000..dfbafdc85ff
--- /dev/null
+++ b/src/features/Conversation/Messages/components/usePendingRetryTurn.test.ts
@@ -0,0 +1,45 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { usePendingRetryTurn } from './usePendingRetryTurn';
+
+const state = vi.hoisted(() => ({ agentId: 'agt-1', hasNoReply: true, isRetrying: false }));
+
+vi.mock('../../store', () => ({
+ dataSelectors: {
+ getDisplayMessageById: () => () => ({ agentId: state.agentId }),
+ hasNoRenderedReply: () => () => state.hasNoReply,
+ },
+ messageStateSelectors: {
+ isMessageRegenerating: () => () => state.isRetrying,
+ },
+ useConversationStore: (selector: (s: any) => any) => selector({}),
+}));
+
+describe('usePendingRetryTurn', () => {
+ beforeEach(() => {
+ state.agentId = 'agt-1';
+ state.hasNoReply = true;
+ state.isRetrying = false;
+ });
+
+ // Regression: measured on the real app, `delAndRegenerateMessage` removes the
+ // failed reply ~457ms in while the replacement only appears ~712ms in. For that
+ // gap the user turn had nothing under it β€” the error card the user clicked just
+ // vanished. Message-level loading cannot cover it: there is no message left.
+ it('shows a stand-in while a retry runs and the old reply is already gone', () => {
+ state.isRetrying = true;
+
+ expect(usePendingRetryTurn('user-1')).toEqual({ agentId: 'agt-1', showPendingTurn: true });
+ });
+
+ it('stops as soon as the replacement reply exists', () => {
+ state.isRetrying = true;
+ state.hasNoReply = false;
+
+ expect(usePendingRetryTurn('user-1').showPendingTurn).toBe(false);
+ });
+
+ it('stays hidden when no retry is running', () => {
+ expect(usePendingRetryTurn('user-1').showPendingTurn).toBe(false);
+ });
+});
diff --git a/src/features/Conversation/Messages/components/usePendingRetryTurn.ts b/src/features/Conversation/Messages/components/usePendingRetryTurn.ts
new file mode 100644
index 00000000000..bf177692e21
--- /dev/null
+++ b/src/features/Conversation/Messages/components/usePendingRetryTurn.ts
@@ -0,0 +1,26 @@
+import { dataSelectors, messageStateSelectors, useConversationStore } from '../../store';
+
+/**
+ * Whether a stand-in reply should be shown under a user turn.
+ *
+ * A retry deletes the failed reply BEFORE its replacement exists (delete-first is
+ * deliberate β€” regenerating first switches the branch away and strands the failed
+ * attempt). Measured on the real app, that leaves ~250ms in which the user turn
+ * has no reply under it at all, so there is no message left to carry a loading
+ * state and the click reads as "nothing happened".
+ *
+ * True only inside that gap: a retry is running for this turn AND nothing is
+ * rendered beneath it yet. Once the replacement arrives it carries its own
+ * loading state, and two stacked bubbles would read as two separate replies.
+ */
+export const usePendingRetryTurn = (userMessageId: string) => {
+ const isRetrying = useConversationStore(
+ messageStateSelectors.isMessageRegenerating(userMessageId),
+ );
+ const hasNoReply = useConversationStore(dataSelectors.hasNoRenderedReply(userMessageId));
+ const agentId = useConversationStore(
+ (s) => dataSelectors.getDisplayMessageById(userMessageId)(s)?.agentId,
+ );
+
+ return { agentId, showPendingTurn: isRetrying && hasNoReply };
+};
diff --git a/src/features/Conversation/Messages/index.tsx b/src/features/Conversation/Messages/index.tsx
index 4fa363cd682..2c2b9c4c629 100644
--- a/src/features/Conversation/Messages/index.tsx
+++ b/src/features/Conversation/Messages/index.tsx
@@ -20,6 +20,7 @@ import AgentCouncilMessage from './AgentCouncil';
import AssistantMessage from './Assistant';
import AssistantGroupMessage from './AssistantGroup';
import type { WorkflowExpandLevelDefault } from './AssistantGroup/components/WorkflowCollapse';
+import PendingRetryTurn from './components/PendingRetryTurn';
import TextSelectionActionLayer from './components/TextSelectionActionLayer';
import CompressedGroupMessage from './CompressedGroup';
import GroupTasksMessage from './GroupTasks';
@@ -133,7 +134,15 @@ const MessageItem = memo<MessageItemProps>(
const renderContent = useCallback(() => {
switch (role) {
case 'user': {
- return <UserMessage disableEditing={disableEditing} id={id} index={index} />;
+ return (
+ <>
+ <UserMessage disableEditing={disableEditing} id={id} index={index} />
+ {/* A retry deletes the failed reply before its replacement exists.
+ The user turn outlives that window, so it carries the pending
+ state the deleted reply no longer can. */}
+ <PendingRetryTurn userMessageId={id} />
+ </>
+ );
}
case 'assistant': {
diff --git a/src/features/Conversation/store/slices/data/selectors.ts b/src/features/Conversation/store/slices/data/selectors.ts
index 45789191208..683c8e53b50 100644
--- a/src/features/Conversation/store/slices/data/selectors.ts
+++ b/src/features/Conversation/store/slices/data/selectors.ts
@@ -75,6 +75,16 @@ const findLastMessageIdRecursive = (node: UIChatMessage | undefined): string | u
return node.id;
};
+/**
+ * Whether a message currently has no reply rendered beneath it.
+ *
+ * True during the window a retry opens up: `delAndRegenerateMessage` removes the
+ * failed turn before the replacement exists, so for a beat the user turn stands
+ * alone with nothing under it and nothing to hang a loading state on.
+ */
+const hasNoRenderedReply = (id: string) => (s: State) =>
+ !s.displayMessages.some((message) => message.parentId === id);
+
/**
* Finds the last (deepest) message ID from a display message
* Recursively traverses children and tools to find the actual last message
@@ -242,6 +252,7 @@ export const dataSelectors = {
getGroupLatestMessageWithoutTools,
getToolInBlock,
getToolsInBlock,
+ hasNoRenderedReply,
isSecondLastMessageFromUser,
messagesInit,
pendingInterventions,
diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.ts
index 4961bf20808..fd1c4ec029f 100644
--- a/src/features/Conversation/store/slices/generation/action.test.ts
+++ b/src/features/Conversation/store/slices/generation/action.test.ts
@@ -24,6 +24,7 @@ const mockDeleteMessage = vi.fn();
const mockSwitchMessageBranch = vi.fn();
const mockStartOperation = vi.fn(() => ({ operationId: 'test-op-id' }));
const mockCompleteOperation = vi.fn();
+const mockAssociateMessageWithOperation = vi.fn();
const mockFailOperation = vi.fn();
const mockExecuteClientAgent = vi.fn();
const mockIsGatewayModeEnabled = vi.fn(() => false);
@@ -50,6 +51,7 @@ vi.mock('@/store/chat', () => ({
deleteMessage: mockDeleteMessage,
switchMessageBranch: mockSwitchMessageBranch,
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
executeClientAgent: mockExecuteClientAgent,
@@ -210,6 +212,7 @@ describe('Generation Actions', () => {
operations: {},
operationsByMessage: {},
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
executeClientAgent: mockExecuteClientAgent,
@@ -270,6 +273,7 @@ describe('Generation Actions', () => {
operations: {},
operationsByMessage: {},
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
executeClientAgent: mockExecuteClientAgent,
@@ -307,6 +311,7 @@ describe('Generation Actions', () => {
operations: {},
operationsByMessage: {},
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
executeClientAgent: mockExecuteClientAgent,
@@ -346,6 +351,7 @@ describe('Generation Actions', () => {
operations: {},
operationsByMessage: {},
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
executeClientAgent: mockExecuteClientAgent,
@@ -393,6 +399,7 @@ describe('Generation Actions', () => {
operations: {},
operationsByMessage: {},
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
executeClientAgent: mockExecuteClientAgent.mockResolvedValue(undefined),
@@ -438,6 +445,7 @@ describe('Generation Actions', () => {
operations: {},
operationsByMessage: {},
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
executeClientAgent: mockExecuteClientAgent,
@@ -469,6 +477,199 @@ describe('Generation Actions', () => {
});
});
+ // Retrying the failed step of a turn used to be "delete the block, then call
+ // continueGeneration and hope it still finds a group". Verified live: it did
+ // not. Both shapes below deleted the failed step and then created NO operation
+ // at all β€” the answer was gone and nothing was running, with no toast.
+ describe('retryFailedAssistantStep', () => {
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: 'topic-1',
+ threadId: null,
+ };
+
+ const mockChatStore = async () => {
+ const { useChatStore } = await import('@/store/chat');
+ vi.mocked(useChatStore.getState).mockReturnValue({
+ messagesMap: {},
+ dbMessagesMap: {},
+ operations: {},
+ operationsByMessage: {},
+ deleteMessage: mockDeleteMessage,
+ switchMessageBranch: mockSwitchMessageBranch,
+ startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
+ completeOperation: mockCompleteOperation,
+ failOperation: mockFailOperation,
+ executeClientAgent: mockExecuteClientAgent,
+ isGatewayModeEnabled: mockIsGatewayModeEnabled,
+ } as any);
+ };
+
+ it('replaces the whole turn when the failed block is the turn only step', async () => {
+ await mockChatStore();
+ const store = createStore({ context });
+ const deleteDBMessage = vi.fn();
+
+ act(() => {
+ store.setState({
+ deleteDBMessage,
+ displayMessages: [
+ { id: 'user-1', role: 'user', content: 'Hi' },
+ {
+ id: 'group-1',
+ role: 'assistantGroup',
+ content: '',
+ parentId: 'user-1',
+ children: [{ id: 'group-1', content: '...', error: { type: 'ProviderBizError' } }],
+ },
+ ],
+ } as any);
+ });
+
+ await act(async () => {
+ await store.getState().retryFailedAssistantStep('group-1', 'group-1');
+ });
+
+ // Never delete the only block speculatively β€” that is what destroyed the
+ // group and left continueGeneration with nothing to find.
+ expect(deleteDBMessage).not.toHaveBeenCalled();
+ // The turn is replaced instead: delete-then-regenerate from the user turn.
+ expect(mockDeleteMessage).toHaveBeenCalledWith('group-1', { operationId: 'test-op-id' });
+ expect(mockExecuteClientAgent).toHaveBeenCalled();
+ });
+
+ it('continues in place when the turn has earlier steps to keep', async () => {
+ await mockChatStore();
+ const store = createStore({ context });
+ const deleteDBMessage = vi.fn();
+
+ act(() => {
+ store.setState({
+ deleteDBMessage,
+ displayMessages: [
+ { id: 'user-1', role: 'user', content: 'Hi' },
+ {
+ id: 'group-1',
+ role: 'assistantGroup',
+ content: '',
+ parentId: 'user-1',
+ children: [
+ { id: 'block-1', content: 'step one' },
+ { id: 'block-2', content: '...', error: { type: 'ProviderBizError' } },
+ ],
+ },
+ ],
+ } as any);
+ });
+
+ await act(async () => {
+ await store.getState().retryFailedAssistantStep('group-1', 'block-2');
+ });
+
+ expect(deleteDBMessage).toHaveBeenCalledWith('block-2');
+ expect(mockStartOperation).toHaveBeenCalledWith({
+ context: { ...context, messageId: 'group-1' },
+ type: 'continue',
+ });
+ expect(mockExecuteClientAgent).toHaveBeenCalled();
+ });
+
+ it('falls back to replacing the turn when continuing turns out to be impossible', async () => {
+ await mockChatStore();
+ const store = createStore({ context });
+ // Deleting the failed block makes the turn stop resolving as a group β€”
+ // observed live, where continueGeneration then bailed on role !==
+ // 'assistantGroup' and left the turn dead.
+ const deleteDBMessage = vi.fn(async () => {
+ act(() => {
+ store.setState({
+ displayMessages: [
+ { id: 'user-1', role: 'user', content: 'Hi' },
+ { id: 'group-1', role: 'assistant', content: 'step one', parentId: 'user-1' },
+ ],
+ } as any);
+ });
+ });
+
+ act(() => {
+ store.setState({
+ deleteDBMessage,
+ displayMessages: [
+ { id: 'user-1', role: 'user', content: 'Hi' },
+ {
+ id: 'group-1',
+ role: 'assistantGroup',
+ content: '',
+ parentId: 'user-1',
+ children: [
+ { id: 'group-1', content: 'step one' },
+ { id: 'block-2', content: '...', error: { type: 'ProviderBizError' } },
+ ],
+ },
+ ],
+ } as any);
+ });
+
+ await act(async () => {
+ await store.getState().retryFailedAssistantStep('group-1', 'block-2');
+ });
+
+ expect(deleteDBMessage).toHaveBeenCalledWith('block-2');
+ // No `continue` op could be started …
+ expect(mockStartOperation).not.toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'continue' }),
+ );
+ // … so the turn must still end up regenerated rather than silently dead.
+ expect(mockStartOperation).toHaveBeenCalledWith({
+ context: { ...context, messageId: 'group-1' },
+ type: 'regenerate',
+ });
+ expect(mockExecuteClientAgent).toHaveBeenCalled();
+ });
+
+ it('routes a heterogeneous status error to the session-resuming path', async () => {
+ await mockChatStore();
+ const store = createStore({ context });
+ const deleteDBMessage = vi.fn();
+ const continueHeteroAfterError = vi.fn();
+
+ act(() => {
+ store.setState({
+ continueHeteroAfterError,
+ deleteDBMessage,
+ displayMessages: [
+ { id: 'user-1', role: 'user', content: 'Hi' },
+ {
+ id: 'group-1',
+ role: 'assistantGroup',
+ content: '',
+ parentId: 'user-1',
+ children: [
+ { id: 'block-1', content: 'step one' },
+ {
+ id: 'block-2',
+ content: '...',
+ error: {
+ type: 'ProviderBizError',
+ body: { agentType: 'claude-code', code: 'overloaded' },
+ },
+ },
+ ],
+ },
+ ],
+ } as any);
+ });
+
+ await act(async () => {
+ await store.getState().retryFailedAssistantStep('group-1', 'block-2');
+ });
+
+ expect(continueHeteroAfterError).toHaveBeenCalledWith('group-1');
+ expect(deleteDBMessage).not.toHaveBeenCalled();
+ });
+ });
+
describe('delAndRegenerateMessage', () => {
it('should create operation with context and pass operationId to deleteMessage', async () => {
// Re-setup mock to ensure all required functions are available
@@ -483,6 +684,7 @@ describe('Generation Actions', () => {
deleteMessage: mockDeleteMessage,
switchMessageBranch: mockSwitchMessageBranch,
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
executeClientAgent: mockExecuteClientAgent,
@@ -554,6 +756,7 @@ describe('Generation Actions', () => {
return Promise.resolve();
}),
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
executeClientAgent: vi.fn().mockImplementation(() => {
@@ -614,6 +817,7 @@ describe('Generation Actions', () => {
operationsByMessage: {},
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
deleteMessage: mockDeleteMessage,
} as any);
@@ -659,6 +863,7 @@ describe('Generation Actions', () => {
cancelOperations: mockCancelOperations,
cancelOperation: mockCancelOperation,
switchMessageBranch: mockSwitchMessageBranch,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
startOperation: vi.fn(() => {
const operationId = operationCount++ === 0 ? 'outer-op-id' : 'inner-op-id';
chatState.operations[operationId] = { id: operationId, status: 'running' };
@@ -756,6 +961,7 @@ describe('Generation Actions', () => {
failOperation: mockFailOperation,
isGatewayModeEnabled: mockIsGatewayModeEnabled,
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
switchMessageBranch: mockSwitchMessageBranch,
};
vi.mocked(useChatStore.getState).mockReturnValue(chatState);
@@ -808,6 +1014,7 @@ describe('Generation Actions', () => {
cancelOperation: mockCancelOperation,
deleteMessage: vi.fn().mockResolvedValue(undefined),
switchMessageBranch: mockSwitchMessageBranch,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
startOperation: vi.fn(() => {
const operationId = operationCount++ === 0 ? 'outer-op-id' : 'inner-op-id';
chatState.operations[operationId] = { id: operationId, status: 'running' };
@@ -864,6 +1071,7 @@ describe('Generation Actions', () => {
deleteMessage: mockDeleteMessage,
switchMessageBranch: mockSwitchMessageBranch,
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
executeClientAgent: mockExecuteClientAgent,
isGatewayModeEnabled: mockIsGatewayModeEnabled,
@@ -917,6 +1125,7 @@ describe('Generation Actions', () => {
deleteMessage: mockDeleteMessage,
switchMessageBranch: mockSwitchMessageBranch,
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
executeClientAgent: mockExecuteClientAgent,
@@ -975,6 +1184,7 @@ describe('Generation Actions', () => {
deleteMessage: mockDeleteMessage,
switchMessageBranch: mockSwitchMessageBranch,
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
executeClientAgent: mockExecuteClientAgent,
@@ -1026,6 +1236,7 @@ describe('Generation Actions', () => {
deleteMessage: mockDeleteMessage,
switchMessageBranch: mockSwitchMessageBranch,
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
executeClientAgent: mockExecuteClientAgent,
@@ -1074,6 +1285,7 @@ describe('Generation Actions', () => {
cancelOperation: mockCancelOperation,
deleteMessage: mockDeleteMessage,
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
executeClientAgent: mockExecuteClientAgent,
@@ -1122,6 +1334,7 @@ describe('Generation Actions', () => {
deleteMessage: mockDeleteMessage,
switchMessageBranch: mockSwitchMessageBranch,
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
executeClientAgent: mockExecuteClientAgent,
@@ -1191,6 +1404,7 @@ describe('Generation Actions', () => {
operationsByMessage: {},
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
isGatewayModeEnabled: vi.fn(() => true),
@@ -1223,11 +1437,18 @@ describe('Generation Actions', () => {
});
// Should call executeGatewayAgent with parentMessageId, original content, and onComplete
+ // β€” and, critically, the wrapper op id. `executeGatewayAgent` completes
+ // `parentOperationId` at phase-1 (child runtime op running), which is the
+ // only thing that keeps a WS drop before session end from stranding a
+ // running `regenerate` op on the user turn. The retry guard reads exactly
+ // that op type, so a stranded wrapper would brick retry for the turn
+ // permanently (Codex review P1 on this PR).
expect(mockExecuteGatewayAgent).toHaveBeenCalledWith(
expect.objectContaining({
context,
message: 'Hello world',
parentMessageId: 'msg-1',
+ parentOperationId: 'test-op-id',
onComplete: expect.any(Function),
}),
);
@@ -1235,7 +1456,9 @@ describe('Generation Actions', () => {
// Should NOT call client-mode executeClientAgent
expect(mockExecuteClientAgent).not.toHaveBeenCalled();
- // regenerate operation stays running until onComplete is called
+ // The flow itself must not settle the wrapper β€” phase-1 handoff belongs
+ // to executeGatewayAgent (mocked here), and double-settling would mask a
+ // missing handoff.
expect(mockCompleteOperation).not.toHaveBeenCalled();
// Simulate gateway session complete
@@ -1252,6 +1475,7 @@ describe('Generation Actions', () => {
operationsByMessage: {},
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
isGatewayModeEnabled: vi.fn(() => true),
@@ -1295,6 +1519,7 @@ describe('Generation Actions', () => {
operationsByMessage: {},
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
isGatewayModeEnabled: vi.fn(() => false),
@@ -1328,21 +1553,21 @@ describe('Generation Actions', () => {
expect(mockExecuteClientAgent).toHaveBeenCalled();
});
- it('should not regenerate if message is already loading', async () => {
- // Mock operation system to indicate message is processing
+ it('should not regenerate if the message already has a running regenerate op', async () => {
const { useChatStore } = await import('@/store/chat');
vi.mocked(useChatStore.getState).mockReturnValue({
messagesMap: {},
operations: {
'op-1': {
id: 'op-1',
- type: 'sendMessage',
+ type: 'regenerate',
status: 'running',
context: { messageIds: ['msg-1'] },
},
},
operationsByMessage: { 'msg-1': ['op-1'] },
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
} as any);
const context: ConversationContext = {
@@ -1367,6 +1592,58 @@ describe('Generation Actions', () => {
// Should not create operation if already regenerating
expect(mockStartOperation).not.toHaveBeenCalled();
});
+
+ // Regression: the guard used to be `isMessageProcessing` β€” ANY running op on
+ // the message. A stray op that outlived its run (a translate, or a gateway
+ // regenerate whose WS dropped non-terminally so `onComplete` never fired)
+ // then killed retry for that turn permanently, and silently.
+ it('regenerates despite an unrelated running op left on the message', async () => {
+ const { useChatStore } = await import('@/store/chat');
+ vi.mocked(useChatStore.getState).mockReturnValue({
+ messagesMap: {},
+ dbMessagesMap: {},
+ operations: {
+ 'stale-op': {
+ id: 'stale-op',
+ type: 'translate',
+ status: 'running',
+ context: { messageIds: ['msg-1'] },
+ },
+ },
+ operationsByMessage: { 'msg-1': ['stale-op'] },
+ startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
+ completeOperation: mockCompleteOperation,
+ failOperation: mockFailOperation,
+ switchMessageBranch: mockSwitchMessageBranch,
+ executeClientAgent: mockExecuteClientAgent,
+ isGatewayModeEnabled: mockIsGatewayModeEnabled,
+ } as any);
+
+ const context: ConversationContext = {
+ agentId: 'session-1',
+ topicId: null,
+ threadId: null,
+ };
+
+ const store = createStore({ context });
+
+ act(() => {
+ store.setState({
+ displayMessages: [{ id: 'msg-1', role: 'user', content: 'Hello' }],
+ } as any);
+ });
+
+ await act(async () => {
+ await store.getState().regenerateUserMessage('msg-1');
+ });
+
+ expect(mockStartOperation).toHaveBeenCalledWith({
+ context: { ...context, messageId: 'msg-1' },
+ type: 'regenerate',
+ });
+ expect(mockExecuteClientAgent).toHaveBeenCalled();
+ });
});
// ===========================================================================
@@ -1597,6 +1874,7 @@ describe('Generation Actions', () => {
operations: {},
operationsByMessage: {},
startOperation: mockStartOperation,
+ associateMessageWithOperation: mockAssociateMessageWithOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
executeClientAgent: mockExecuteClientAgent,
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.ts
index 386e99c13d7..b19d4c856f0 100644
--- a/src/features/Conversation/store/slices/generation/action.ts
+++ b/src/features/Conversation/store/slices/generation/action.ts
@@ -279,9 +279,17 @@ const regenerateUserMessageFromSource = async (
const { context, displayMessages, hooks, readDbMessages } = source;
const chatStore = useChatStore.getState();
- // Check if already regenerating via operation system
- const isRegenerating = operationSelectors.isMessageProcessing(messageId)(chatStore);
- if (isRegenerating) return;
+ // Block a genuine double-regenerate, and ONLY that. The guard used to be
+ // `isMessageProcessing`, i.e. "this message has any running operation at all" β€”
+ // so an unrelated op that outlived its run (a translate, a never-settled
+ // gateway regenerate whose WS dropped non-terminally) permanently and silently
+ // killed retry for that turn. Narrowing to the regenerate op keeps the
+ // duplicate-click protection without letting any stray op wedge the turn, and
+ // the toast means the refusal is never invisible again.
+ if (operationSelectors.isMessageRegenerating(messageId)(chatStore)) {
+ toast.info(t('messageAction.regenerateAlreadyRunning', { ns: 'chat' }));
+ return;
+ }
// Find the message in the captured conversation messages. The source remains
// bound to the initiating context even if StoreUpdater reuses this store for
@@ -362,8 +370,18 @@ const regenerateUserMessageFromSource = async (
// ── Gateway mode: trigger server-side regeneration ──
if (runtimeType === 'gateway') {
- // Keep the regenerate operation running until the gateway session completes,
- // so isMessageRegenerating stays true and duplicate clicks are blocked.
+ // Hand the wrapper op off at phase-1 (`executeGatewayAgent` completes
+ // `parentOperationId` once the child `execServerAgentRuntime` op is
+ // running) β€” the documented interim-op contract this branch used to
+ // deviate from by keeping the wrapper alive until session end. That
+ // deviation is what made a WS drop before `onComplete` leave a running
+ // `regenerate` op on the user turn FOREVER, and the retry guard reads
+ // exactly that op type β€” so one dropped socket permanently bricked
+ // retry for the turn. Forwarding the id also wires the wrapper's abort
+ // signal into the preflight round trip, so a Stop pressed there now
+ // actually aborts the request instead of being swallowed.
+ // `onComplete` still fires at session end for the UI hook; re-completing
+ // the already-settled wrapper is an idempotent no-op.
await chatStore.executeGatewayAgent({
context,
message: item.content,
@@ -372,6 +390,7 @@ const regenerateUserMessageFromSource = async (
hooks.onRegenerateComplete?.(messageId),
),
parentMessageId: messageId,
+ parentOperationId: operationId,
});
return;
@@ -458,14 +477,20 @@ export interface GenerationAction {
clearTranslate: (messageId: string) => Promise<void>;
/**
- * Continue generation from a message
+ * Continue generation from a message.
+ *
+ * Resolves `true` only when a generation actually started. Every bail-out
+ * (message gone, no longer a group, no block to continue from) resolves
+ * `false` so a caller that already mutated history can recover instead of
+ * silently leaving the turn dead β€” see {@link retryFailedAssistantStep}.
*/
- continueGeneration: (displayMessageId: string) => Promise<void>;
+ continueGeneration: (displayMessageId: string) => Promise<boolean>;
/**
- * Continue generation from a specific block
+ * Continue generation from a specific block. Resolves `true` only when a
+ * generation actually started; see {@link continueGeneration}.
*/
- continueGenerationMessage: (displayMessageId: string, messageId: string) => Promise<void>;
+ continueGenerationMessage: (displayMessageId: string, messageId: string) => Promise<boolean>;
/**
* Resume a heterogeneous (CC / Codex) run whose LAST step died on a status
@@ -552,6 +577,21 @@ export interface GenerationAction {
*/
resetHeteroOverloadRetry: (scopeId: string) => void;
+ /**
+ * Retry the failed step of an assistant turn, from the error card rendered on
+ * that step.
+ *
+ * Guarantees a terminal outcome: either a continuation actually starts, or the
+ * whole turn is regenerated. The previous call site deleted the failed block
+ * and then *hoped* `continueGeneration` still found a group to continue β€” when
+ * it didn't (single-step turn, or a turn that stops parsing as a group once the
+ * block is gone) the user was left with a deleted answer and nothing running.
+ *
+ * @param groupMessageId - the assistantGroup id (the turn)
+ * @param blockId - the child block that carries the error
+ */
+ retryFailedAssistantStep: (groupMessageId: string, blockId: string) => Promise<void>;
+
/**
* Save TTS metadata for a message
* @deprecated Temporary bridge to ChatStore
@@ -670,12 +710,12 @@ export const generationSlice: StateCreator<
// Find the message
const message = displayMessages.find((m) => m.id === groupMessageId);
- if (!message) return;
+ if (!message) return false;
// If it's an assistantGroup, find the last child's ID as blockId
let lastBlockId: string | undefined;
- if (message.role !== 'assistantGroup') return;
+ if (message.role !== 'assistantGroup') return false;
if (message.children && message.children.length > 0) {
const lastChild = message.children.at(-1);
@@ -685,9 +725,9 @@ export const generationSlice: StateCreator<
}
}
- if (!lastBlockId) return;
+ if (!lastBlockId) return false;
- await get().continueGenerationMessage(groupMessageId, lastBlockId);
+ return get().continueGenerationMessage(groupMessageId, lastBlockId);
},
continueGenerationMessage: async (displayMessageId: string, dbMessageId: string) => {
@@ -696,12 +736,12 @@ export const generationSlice: StateCreator<
// Find the message (blockId refers to the assistant message to continue from)
const message = displayMessages.find((m) => m.id === displayMessageId);
- if (!message) return;
+ if (!message) return false;
// ===== Hook: onBeforeContinue =====
if (hooks.onBeforeContinue) {
const shouldProceed = await hooks.onBeforeContinue(displayMessageId);
- if (shouldProceed === false) return;
+ if (shouldProceed === false) return false;
}
const { agencyConfig, workspaceScoped } = getEffectiveAgencyConfig(context.agentId);
@@ -717,7 +757,7 @@ export const generationSlice: StateCreator<
// β€” each prompt is a fresh user turn from their perspective. Bail out
// rather than synthesize a fake "please continue" turn that would pollute
// the session and confuse the model. The button is a no-op in this mode.
- if (runtimeType === 'hetero') return;
+ if (runtimeType === 'hetero') return false;
// Claude 4.6+/5 removed assistant prefill: a payload ending with an
// assistant turn is rejected (400), and the model runtime strips trailing
@@ -728,7 +768,7 @@ export const generationSlice: StateCreator<
const continueModel = getEffectiveConversationModel(context);
if (continueModel && shouldDropUnsupportedClaudeAssistantPrefill(continueModel)) {
toast.warning(t('messageAction.continueGenerationUnsupported', { ns: 'chat' }));
- return;
+ return false;
}
// Create continue operation with ConversationStore context (includes groupId)
@@ -752,7 +792,7 @@ export const generationSlice: StateCreator<
),
parentMessageId: dbMessageId,
});
- return;
+ return true;
}
// ── Client mode: run agent locally ──
@@ -767,6 +807,8 @@ export const generationSlice: StateCreator<
settleGenerationEntry(chatStore, operationId, () =>
hooks.onContinueComplete?.(displayMessageId),
);
+
+ return true;
} catch (error) {
chatStore.failOperation(operationId, {
message: error instanceof Error ? error.message : String(error),
@@ -1078,6 +1120,47 @@ export const generationSlice: StateCreator<
set({ heteroOverloadRetryAttempts: next }, false, 'resetHeteroOverloadRetry');
},
+ retryFailedAssistantStep: async (groupMessageId: string, blockId: string) => {
+ const { displayMessages } = get();
+
+ const group = displayMessages.find((m) => m.id === groupMessageId);
+ const erroredBlock = group?.children?.find((child) => child.id === blockId);
+
+ // A hetero status error (rate limit, upstream overload, auth, missing CLI)
+ // means the run died but its CLI session survives β€” that path resumes the
+ // session and already owns its own whole-turn fallback.
+ if (isHeterogeneousAgentStatusGuideError(erroredBlock?.error?.body)) {
+ await get().continueHeteroAfterError(groupMessageId);
+ return;
+ }
+
+ // Captured BEFORE any mutation: once the failed block is gone the turn may
+ // stop resolving as a group, and the parent user message is the only anchor
+ // left to regenerate from.
+ const parentUserId = group?.parentId;
+
+ // Nothing to continue from β€” the failed block IS the whole turn, so deleting
+ // it would destroy the group and leave `continueGeneration` with nothing to
+ // find. Replace the turn outright instead of deleting speculatively.
+ const hasEarlierSteps = (group?.children?.length ?? 0) > 1;
+ if (!hasEarlierSteps) {
+ await get().delAndRegenerateMessage(groupMessageId);
+ return;
+ }
+
+ await get().deleteDBMessage(blockId);
+
+ if (await get().continueGeneration(groupMessageId)) return;
+
+ // Continue turned out to be impossible after all (the turn stopped parsing
+ // as a group once the block was removed, the runtime has no continue
+ // primitive, ...). The failed block is already gone, so the only honest
+ // outcome left is replacing the whole turn β€” never a silent no-op.
+ const groupStillExists = get().displayMessages.some((m) => m.id === groupMessageId);
+ if (groupStillExists) await get().delAndRegenerateMessage(groupMessageId);
+ else if (parentUserId) await get().regenerateUserMessage(parentUserId);
+ },
+
regenerateAssistantMessage: async (messageId: string) => {
const { displayMessages } = get();
diff --git a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
index f75ee064eec..1940fd81e6d 100644
--- a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
+++ b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
@@ -46,6 +46,7 @@ vi.mock('@/store/chat/slices/operation/selectors', () => ({
operationSelectors: {
getOperationById: () => () => undefined,
isMessageProcessing: () => () => false,
+ isMessageRegenerating: () => () => false,
},
}));
diff --git a/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts b/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts
index fe5f35d4018..de26322d58d 100644
--- a/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts
+++ b/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts
@@ -35,6 +35,7 @@ vi.mock('@/store/chat/slices/operation/selectors', () => ({
operationSelectors: {
getOperationById: () => () => undefined,
isMessageProcessing: () => () => false,
+ isMessageRegenerating: () => () => false,
},
}));
diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.ts
index 3f6f4086dcb..3ca7cc03be1 100644
--- a/src/store/chat/slices/operation/types.ts
+++ b/src/store/chat/slices/operation/types.ts
@@ -477,11 +477,14 @@ export const INPUT_LOADING_OPERATION_TYPES: OperationType[] = [
// semantics and why they stay out of AI_RUNTIME_OPERATION_TYPES.
//
// Known limitation (accepted): this also makes Stop appear during the pre-
- // generation window. Because these gateway branches don't forward
- // `parentOperationId` to `executeGatewayAgent`, hitting Stop in that narrow
- // window doesn't actually abort the in-flight request (loading briefly
- // flickers, generation proceeds). No stuck state; wiring the abort handoff
- // through these branches is deferred.
+ // generation window. The approve/submit/skip gateway branches don't forward
+ // `parentOperationId` to `executeGatewayAgent`, so hitting Stop in that
+ // narrow window doesn't actually abort the in-flight request (loading
+ // briefly flickers, generation proceeds). No stuck state; wiring the abort
+ // handoff through those branches is deferred. The `regenerate` branch DOES
+ // forward it β€” an unsettled regenerate wrapper is what the retry guard
+ // reads, so it must never outlive phase-1 (a WS drop before session end
+ // would otherwise brick retry for that turn permanently).
...INTERIM_LOADING_OPERATION_TYPES,
];