π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(chat): resume a rate-limited hetero run instead of deleting the whole turn (#16974)
Arvin Xu95233b97c57b
diff --git a/src/features/Conversation/Error/heterogeneous.ts b/src/features/Conversation/Error/heterogeneous.tsindex 259d09dcb06..c6da4adc972 100644--- a/src/features/Conversation/Error/heterogeneous.ts+++ b/src/features/Conversation/Error/heterogeneous.ts@@ -2,6 +2,7 @@ import {type HeterogeneousAgentSessionError,HeterogeneousAgentSessionErrorCode,} from '@lobechat/electron-client-ipc';+import type { UIChatMessage } from '@lobechat/types';/*** Heterogeneous-agent (Claude Code / Codex) session errors that render the@@ -30,3 +31,27 @@ export const isHeterogeneousAgentStatusGuideError = (HETEROGENEOUS_AGENT_STATUS_GUIDE_ERROR_CODES.has(code));};++/**+ * Id of the single failed step at the tail of a heterogeneous run, when that+ * step can be dropped on its own without taking the rest of the run with it.+ *+ * A hetero (CC/Codex) turn renders as ONE `assistantGroup` bubble whose+ * `children` are the run's real steps, so acting on the group id acts on the+ * whole run. Returns undefined β meaning "operate on the whole group" β when:+ * - the message isn't a hetero run's group bubble;+ * - its tail step died on something other than a hetero status error (a generic+ * tool/provider failure isn't a resumable run);+ * - the tail step IS the group head, i.e. the run died on its first step. Its id+ * doubles as the group id, and no earlier work exists to preserve.+ */+export const resolveHeteroErroredStepId = (+ message: UIChatMessage | undefined,+): string | undefined => {+ if (message?.role !== 'assistantGroup') return;++ const tail = message.children?.at(-1);+ if (!tail || tail.id === message.id) return;++ return tail.error && isHeterogeneousAgentStatusGuideError(tail.error.body) ? tail.id : undefined;+};diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsxindex 919bc9477fc..899f71809a7 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx@@ -10,7 +10,7 @@ import ContentBlock from './ContentBlock';const continueGenerationMock = vi.fn();const deleteDBMessageMock = vi.fn();-const delAndRegenerateMessageMock = vi.fn();+const continueHeteroAfterErrorMock = vi.fn();const navigateMock = vi.fn();vi.mock('@lobehub/ui', () => ({@@ -126,7 +126,7 @@ vi.mock('../../../store', () => ({useConversationStore: (selector: (state: unknown) => unknown) =>selector({continueGeneration: continueGenerationMock,- delAndRegenerateMessage: delAndRegenerateMessageMock,+ continueHeteroAfterError: continueHeteroAfterErrorMock,deleteDBMessage: deleteDBMessageMock,heteroOverloadRetryAttempts: {},internal_beginHeteroOverloadWait: vi.fn(),@@ -142,11 +142,11 @@ describe('AssistantGroup ContentBlock', () => {beforeEach(() => {continueGenerationMock.mockClear();deleteDBMessageMock.mockClear();- delAndRegenerateMessageMock.mockClear();+ continueHeteroAfterErrorMock.mockClear();navigateMock.mockClear();});- it('regenerates the whole turn (not continue) when retrying a heterogeneous error in a group', () => {+ it('resumes the run (not the no-op continueGeneration) when retrying a heterogeneous error in a group', () => {render(<ContentBlockassistantId="assistant-1"@@ -169,10 +169,10 @@ describe('AssistantGroup ContentBlock', () => {screen.getByRole('button', { name: 'guide-retry' }).click();- // The fix: a grouped hetero turn is replaced in place from the GROUP id via- // the delete-first delAndRegenerateMessage (no sibling branch), instead of- // the no-op continueGeneration.- expect(delAndRegenerateMessageMock).toHaveBeenCalledWith('assistant-1');+ // 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');expect(continueGenerationMock).not.toHaveBeenCalled();});diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsxindex d12a6c6c52e..82932ad5d6a 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx@@ -37,12 +37,12 @@ const ContentBlock = memo<ContentBlockProps>(}) => {const errorContent = useErrorContent(error);const showImageItems = !!imageList && imageList.length > 0;- const [isReasoning, deleteMessage, continueGeneration, delAndRegenerateMessage] =+ const [isReasoning, deleteMessage, continueGeneration, continueHeteroAfterError] =useConversationStore((s) => [messageStateSelectors.isMessageInReasoning(id)(s),s.deleteDBMessage,s.continueGeneration,- s.delAndRegenerateMessage,+ s.continueHeteroAfterError,]);// 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.@@ -57,15 +57,14 @@ const ContentBlock = memo<ContentBlockProps>(const showMessageContent = hasContent || content === LOADING_FLAT || hasTools;const handleRegenerate = useCallback(async () => {- // Hetero CLIs (CC / Codex) have no "continue a cut-off response"- // primitive, so `continueGeneration` is a silent no-op for them and the- // retry button does nothing. An errored hetero turn must instead be- // regenerated from the user message β routed through the GROUP id (the- // child block id isn't a top-level displayMessage). Use the delete-first- // `delAndRegenerateMessage` so the failed turn is replaced in place rather- // than accumulating a sibling branch on every (auto-)retry.+ // `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 delAndRegenerateMessage(assistantId);+ void continueHeteroAfterError(assistantId);return;}await deleteMessage(id);@@ -73,7 +72,7 @@ const ContentBlock = memo<ContentBlockProps>(}, [assistantId,continueGeneration,- delAndRegenerateMessage,+ continueHeteroAfterError,deleteMessage,id,isHeteroError,diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/del.test.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/del.test.tsindex a10b01bb439..d5f2df262c0 100644--- a/src/features/Conversation/Messages/components/MessageActionBar/actions/del.test.ts+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/del.test.ts@@ -9,23 +9,28 @@ import type { MessageActionContext } from '../types';import { delAction } from './del';const deleteMessage = vi.fn();-const deleteDBMessage = vi.fn();+const deleteAssistantMessage = vi.fn();vi.mock('../../../../store', () => ({- useConversationStore: (selector: (s: any) => any) => selector({ deleteMessage, deleteDBMessage }),+ useConversationStore: (selector: (s: any) => any) =>+ selector({ deleteAssistantMessage, deleteMessage }),}));vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),}));+// A group's id IS its head child's id β the assistantGroup bubble is a virtual+// message built from the run's first assistant row. Fixtures mirror that.const build = (data: Partial<UIChatMessage>,role: MessageActionContext['role'] = 'group',- id = 'group-1',+ id = 'step-1',) =>renderHook(() => delAction.useBuild({ data: data as UIChatMessage, id, role })).result.current!;+const heteroError = { body: { agentType: 'claude-code', code: 'overloaded' } };+describe('delAction', () => {beforeEach(() => {vi.clearAllMocks();@@ -33,29 +38,42 @@ describe('delAction', () => {it('deletes only the errored tail step of a heterogeneous (CC/Codex) run', () => {const data = {- id: 'group-1',+ id: 'step-1',role: 'assistantGroup',children: [- { id: 'step-23', content: 'done' },- {- id: 'step-24',- error: { body: { agentType: 'claude-code', code: 'overloaded' } },- },+ { id: 'step-1', content: 'done' },+ { id: 'step-2', error: heteroError },],} as unknown as UIChatMessage;build(data).handleClick!();- // Must target the failed step's DB id (a child block), not the group id.- expect(deleteDBMessage).toHaveBeenCalledWith('step-24');+ // Must target the failed step's DB id (a child block), not the group id, and+ // go through the tool-aware delete so the step's tool rows don't orphan.+ expect(deleteAssistantMessage).toHaveBeenCalledWith('step-2');expect(deleteMessage).not.toHaveBeenCalled();});+ it('deletes the whole group when the errored step IS the group head', () => {+ // The run died on its first step: nothing succeeded before it, and the head's+ // id doubles as the group id β deleting it alone would strand the chain.+ const data = {+ id: 'step-1',+ role: 'assistantGroup',+ children: [{ id: 'step-1', error: heteroError }],+ } as unknown as UIChatMessage;++ build(data).handleClick!();++ expect(deleteMessage).toHaveBeenCalledWith('step-1');+ expect(deleteAssistantMessage).not.toHaveBeenCalled();+ });+it('deletes the whole group when the tail error is NOT a heterogeneous-agent error', () => {// A normal grouped reply that merely ends in a generic tool/provider error// keeps the whole-group delete.const data = {- id: 'group-1',+ id: 'step-1',role: 'assistantGroup',children: [{ id: 'step-1', content: 'done' },@@ -65,21 +83,24 @@ describe('delAction', () => {build(data).handleClick!();- expect(deleteMessage).toHaveBeenCalledWith('group-1');- expect(deleteDBMessage).not.toHaveBeenCalled();+ expect(deleteMessage).toHaveBeenCalledWith('step-1');+ expect(deleteAssistantMessage).not.toHaveBeenCalled();});it('deletes the whole group when no step errored', () => {const data = {- id: 'group-1',+ id: 'step-1',role: 'assistantGroup',- children: [{ id: 'step-23', content: 'done' }],+ children: [+ { id: 'step-1', content: 'done' },+ { id: 'step-2', content: 'done' },+ ],} as unknown as UIChatMessage;build(data).handleClick!();- expect(deleteMessage).toHaveBeenCalledWith('group-1');- expect(deleteDBMessage).not.toHaveBeenCalled();+ expect(deleteMessage).toHaveBeenCalledWith('step-1');+ expect(deleteAssistantMessage).not.toHaveBeenCalled();});it('deletes by message id for a non-group message', () => {@@ -90,6 +111,6 @@ describe('delAction', () => {).handleClick!();expect(deleteMessage).toHaveBeenCalledWith('msg-1');- expect(deleteDBMessage).not.toHaveBeenCalled();+ expect(deleteAssistantMessage).not.toHaveBeenCalled();});});diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/del.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/del.tsindex 472ddec7072..1c88e510b04 100644--- a/src/features/Conversation/Messages/components/MessageActionBar/actions/del.ts+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/del.ts@@ -2,7 +2,7 @@ import { Trash } from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { isHeterogeneousAgentStatusGuideError } from '@/features/Conversation/Error/heterogeneous';+import { resolveHeteroErroredStepId } from '@/features/Conversation/Error/heterogeneous';import { useConversationStore } from '../../../../store';import { defineAction } from '../defineAction';@@ -12,34 +12,24 @@ export const delAction = defineAction({useBuild: (ctx) => {const { t } = useTranslation('common');const deleteMessage = useConversationStore((s) => s.deleteMessage);- const deleteDBMessage = useConversationStore((s) => s.deleteDBMessage);+ const deleteAssistantMessage = useConversationStore((s) => s.deleteAssistantMessage);- // A heterogeneous (CC/Codex) turn renders as ONE assistantGroup bubble whose- // `children` are every real step in the run. Deleting the group id removes- // the ENTIRE run β including all the steps that succeeded before the tail- // failed. When the run's TAIL step is a heterogeneous-agent status error- // (upstream overload, rate limit, β¦), delete ONLY that step so the user- // keeps the work already done and can retry from there.+ // Deleting a heterogeneous (CC/Codex) run's group id removes the ENTIRE run,+ // including every step that succeeded before the tail failed. When only the+ // tail step died on a hetero status error, drop just that step.//- // Scope matters: a normal grouped reply that merely ends in a generic- // tool/provider error must keep the whole-group delete, so this is gated on- // the LAST child being a heterogeneous-agent status error β not any error.- // The errored step's id is a real DB message (a child block), not a- // top-level bubble, so it must go through `deleteDBMessage`;- // `deleteMessage`/`getDisplayMessageById` only resolve top-level display- // messages and would no-op on a child id.- const lastChild = ctx.role === 'group' ? ctx.data?.children?.at(-1) : undefined;- const erroredBlockId =- lastChild?.error && isHeterogeneousAgentStatusGuideError(lastChild.error.body)- ? lastChild.id- : undefined;+ // `deleteAssistantMessage` (not `deleteMessage`) resolves the child block+ // against `dbMessages` β `getDisplayMessageById` only sees top-level bubbles+ // and would no-op on a child id β and takes the step's tool result rows down+ // with it, which a bare single-id delete would leave orphaned.+ const erroredBlockId = resolveHeteroErroredStepId(ctx.data);return useMemo(() => ({danger: true,handleClick: () => {if (erroredBlockId) {- void deleteDBMessage(erroredBlockId);+ void deleteAssistantMessage(erroredBlockId);return;}deleteMessage(ctx.id);@@ -48,7 +38,7 @@ export const delAction = defineAction({key: 'del',label: t('delete'),}),- [t, ctx.id, deleteMessage, deleteDBMessage, erroredBlockId],+ [t, ctx.id, deleteMessage, deleteAssistantMessage, erroredBlockId],);},});diff --git a/src/features/Conversation/hooks/useChatItemContextMenu.tsx b/src/features/Conversation/hooks/useChatItemContextMenu.tsxindex 3688f11e3ff..3dcbf935c9d 100644--- a/src/features/Conversation/hooks/useChatItemContextMenu.tsx+++ b/src/features/Conversation/hooks/useChatItemContextMenu.tsx@@ -12,6 +12,7 @@ import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';import { MSG_CONTENT_CLASSNAME } from '@/features/Conversation/ChatItem/components/MessageContent';+import { resolveHeteroErroredStepId } from '@/features/Conversation/Error/heterogeneous';import { usePermission } from '@/hooks/usePermission';import { useSessionStore } from '@/store/session';import { sessionSelectors } from '@/store/session/selectors';@@ -92,6 +93,7 @@ export const useChatItemContextMenu = ({resendThreadMessage,delAndResendThreadMessage,toggleMessageCollapsed,+ deleteAssistantMessage,] = useConversationStore((s) => [s.toggleMessageEditing,s.deleteMessage,@@ -105,6 +107,7 @@ export const useChatItemContextMenu = ({s.resendThreadMessage,s.delAndResendThreadMessage,s.toggleMessageCollapsed,+ s.deleteAssistantMessage,]);const getMessage = useCallback(@@ -277,7 +280,11 @@ export const useChatItemContextMenu = ({}case 'del': {if (!canEdit) break;- deleteMessage(id);+ // Mirrors the action bar's `del`: on a heterogeneous run that only+ // failed on its tail step, drop that step instead of the whole run.+ const erroredStepId = resolveHeteroErroredStepId(item);+ if (erroredStepId) deleteAssistantMessage(erroredStepId);+ else deleteMessage(id);break;}case 'regenerate': {@@ -324,6 +331,7 @@ export const useChatItemContextMenu = ({copyMessage,canCreate,canEdit,+ deleteAssistantMessage,deleteMessage,delAndRegenerateMessage,delAndResendThreadMessage,diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.tsindex 267ea1ce8af..a9fc7d1f8ff 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -10,6 +10,7 @@ import { type StateCreator } from 'zustand';import { message as antdMessage } from '@/components/AntdStaticMethods';import { MESSAGE_CANCEL_FLAT } from '@/const/index';+import { isHeterogeneousAgentStatusGuideError } from '@/features/Conversation/Error/heterogeneous';import { messageService } from '@/services/message';import { getAgentStoreState } from '@/store/agent';import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';@@ -85,13 +86,56 @@ const settleGenerationEntry = (};/**- * Branch a hetero (Claude Code / Codex) turn off an existing user message.+ * Prompt that resumes an interrupted hetero run instead of restarting it.*- * Used by regenerate (parent = user msg, prompt = original user content).- * Pre-creates the assistant row so `executeHeterogeneousAgent` has a stable- * `assistantMessageId` to stream into, then runs an `execHeterogeneousAgent`- * op as a child of the caller's parent op so Stop cancels the executor- * without killing the parent op early.+ * Neither CLI exposes a "keep going, no new input" primitive β `claude --resume`+ * and `codex exec resume` both require a prompt β so continuing necessarily adds+ * one user turn to the CLI's own transcript. That transcript already holds every+ * completed step (we resume the same session id), so the instruction only has to+ * stop the model from redoing them. Not localized: it is model input, not UI.+ */+const HETERO_CONTINUE_PROMPT =+ 'Continue the task from where it stopped. The transcript above shows the work already completed β do not redo it.';++/**+ * Where a hetero (Claude Code / Codex) run should execute, and whether it can+ * pick up the topic's existing CLI session.+ *+ * `workingDirectory`: the topic-level pin (set when bound to a project) wins+ * over the agent-level default, so regenerate/continue stay on the same project+ * as the original turn.+ */+const resolveHeteroRunContext = (+ chatStore: ReturnType<typeof useChatStore.getState>,+ context: ConversationContext,+ agentId: string,+) => {+ const topic = context.topicId+ ? topicSelectors.getTopicById(context.topicId)(chatStore)+ : undefined;+ const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;+ const agentWorkingDirectory = agentByIdSelectors.getAgentWorkingDirectoryById(+ agentId,+ currentDeviceId,+ )(getAgentStoreState());+ const workingDirectory = topic?.metadata?.workingDirectory || agentWorkingDirectory;++ // Drops the saved sessionId when its bound cwd disagrees with the current+ // one β without this CC emits "No conversation found with session ID".+ const { cwdChanged, resumeSessionId } = resolveHeteroResume(topic?.metadata, workingDirectory);++ return { cwdChanged, resumeSessionId, workingDirectory };+};++/**+ * Branch a hetero (Claude Code / Codex) turn off an existing message.+ *+ * Used by regenerate (parent = user msg, prompt = original user content) and by+ * continue-after-error (parent = the run's chain tail, prompt = a continuation+ * instruction). Pre-creates the assistant row so `executeHeterogeneousAgent` has+ * a stable `assistantMessageId` to stream into, then runs an+ * `execHeterogeneousAgent` op as a child of the caller's parent op so Stop+ * cancels the executor without killing the parent op early.*/const runHeterogeneousFromExistingMessage = async (chatStore: ReturnType<typeof useChatStore.getState>,@@ -110,22 +154,11 @@ const runHeterogeneousFromExistingMessage = async (const agentId = context.agentId;if (!agentId) throw new Error('agentId is required for heterogeneous agent');- // Resolve workingDirectory: topic-level pin (set when bound to a project)- // wins over the agent-level default. Mirrors the sendMessage hetero branch- // so regenerate stays on the same project as the original turn.- const topic = context.topicId- ? topicSelectors.getTopicById(context.topicId)(chatStore)- : undefined;- const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;- const agentWorkingDirectory = agentByIdSelectors.getAgentWorkingDirectoryById(+ const { cwdChanged, resumeSessionId, workingDirectory } = resolveHeteroRunContext(+ chatStore,+ context,agentId,- currentDeviceId,- )(getAgentStoreState());- const workingDirectory = topic?.metadata?.workingDirectory || agentWorkingDirectory;-- // Drops the saved sessionId when its bound cwd disagrees with the current- // one β without this CC emits "No conversation found with session ID".- const { cwdChanged, resumeSessionId } = resolveHeteroResume(topic?.metadata, workingDirectory);+ );if (cwdChanged) antdMessage.info(t('heteroAgent.resumeReset.cwdChanged', { ns: 'chat' }));const assistantMsg = await messageService.createMessage({@@ -214,6 +247,16 @@ export interface GenerationAction {*/continueGenerationMessage: (displayMessageId: string, messageId: string) => Promise<void>;+ /**+ * Resume a heterogeneous (CC / Codex) run whose LAST step died on a status+ * error (rate limit, upstream overload, ...), keeping every step that+ * succeeded before it. Falls back to `delAndRegenerateMessage` when there is+ * nothing to keep or no CLI session left to resume.+ *+ * @param groupMessageId - the assistantGroup id of the failed run+ */+ continueHeteroAfterError: (groupMessageId: string) => Promise<void>;+/*** Delete and regenerate a message*/@@ -444,6 +487,104 @@ export const generationSlice: StateCreator<}},+ continueHeteroAfterError: async (groupMessageId: string) => {+ const { context, dbMessages, displayMessages, hooks } = get();+ const chatStore = useChatStore.getState();++ const group = displayMessages.find((m) => m.id === groupMessageId);+ const erroredStep = group?.children?.at(-1);+ if (!erroredStep) return;++ // Only the dedicated hetero status errors (rate limit, upstream overload,+ // auth, missing CLI) mean "the run died but its session survives". A generic+ // tool/provider error on a grouped reply is not resumable this way.+ if (!isHeterogeneousAgentStatusGuideError(erroredStep.error?.body)) return;++ const agentConfig = agentSelectors.getAgentConfigById(context.agentId)(getAgentStoreState());+ const heterogeneousProvider = agentConfig?.agencyConfig?.heterogeneousProvider;+ const runtimeType = selectRuntimeType({+ boundDeviceId: agentConfig?.agencyConfig?.boundDeviceId,+ executionTarget: agentConfig?.agencyConfig?.executionTarget,+ heterogeneousProvider,+ isGatewayMode: chatStore.isGatewayModeEnabled(context.agentId),+ // Workspace agents never run in-process on this member's desktop β a+ // local/unset target coerces to sandbox/device. Omitting this would+ // classify the retry as local hetero and spawn the CLI on the wrong+ // machine; with it, gateway-routed runs take the whole-turn fallback.+ isWorkspaceAgent: agentByIdSelectors.isWorkspaceAgentById(context.agentId)(+ getAgentStoreState(),+ ),+ });+ const agentId = context.agentId;++ const resumeSessionId = agentId+ ? resolveHeteroRunContext(chatStore, context, agentId).resumeSessionId+ : undefined;++ // Nothing to continue from: the failed step IS the group's head (the run+ // died before producing a second step, so no work was preserved anyway), or+ // the topic has no CLI session left to resume (never started, or its cwd+ // moved). Both degrade to replacing the whole turn.+ const hasEarlierSteps = erroredStep.id !== groupMessageId;+ if (+ runtimeType !== 'hetero' ||+ !heterogeneousProvider ||+ !hasEarlierSteps ||+ !resumeSessionId+ ) {+ await get().delAndRegenerateMessage(groupMessageId);+ return;+ }++ // A step that streamed content or landed tool calls before dying is worth+ // keeping: clear its error and chain the continuation onto it. A step that+ // carries nothing but the error (its content echo was suppressed) would+ // render as an empty block, so drop it and chain onto its parent instead.+ const hasSalvageableWork =+ !!erroredStep.tools?.length ||+ (!!erroredStep.content && erroredStep.content !== LOADING_FLAT);++ const continueParentId = hasSalvageableWork+ ? erroredStep.id+ : dbMessages.find((m) => m.id === erroredStep.id)?.parentId;+ if (!continueParentId) {+ await get().delAndRegenerateMessage(groupMessageId);+ return;+ }++ const { operationId } = chatStore.startOperation({+ context: { ...context, messageId: groupMessageId },+ type: 'regenerate',+ });++ try {+ if (hasSalvageableWork) await get().updateMessageError(erroredStep.id, null);+ else await get().deleteAssistantMessage(erroredStep.id);++ // Chaining off the run's tail (not off the user message) keeps the new+ // steps inside the same assistantGroup, so the bubble grows instead of+ // being replaced.+ await runHeterogeneousFromExistingMessage(chatStore, {+ context,+ heterogeneousProvider,+ parentMessageId: continueParentId,+ parentOperationId: operationId,+ prompt: HETERO_CONTINUE_PROMPT,+ });++ settleGenerationEntry(chatStore, operationId, () =>+ hooks.onRegenerateComplete?.(groupMessageId),+ );+ } catch (error) {+ // Settle the wrapper op on failure β see delAndRegenerateMessage.+ chatStore.failOperation(operationId, {+ message: error instanceof Error ? error.message : String(error),+ type: 'RegenerateError',+ });+ throw error;+ }+ },+delAndRegenerateMessage: async (messageId: string) => {const { context, displayMessages } = get();const chatStore = useChatStore.getState();diff --git a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.tsnew file mode 100644index 00000000000..35a3a106864--- /dev/null+++ b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts@@ -0,0 +1,270 @@+import { act } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { type ConversationContext } from '../../../types';+import { createStore } from '../../index';++// ββ Mock the hetero runtime seam ββ+// `continueHeteroAfterError` re-creates ONE assistant row chained onto the run's+// surviving tail, then delegates to `executeHeterogeneousAgent` with the topic's+// resumable CLI session. We spy on that boundary to assert what the new turn is+// parented to and which prompt it carries β a continuation instruction, not the+// original user prompt (which would restart the whole task).+const mockExecuteHeterogeneousAgent = vi.fn();+vi.mock(+ '@/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor',+ () => ({+ executeHeterogeneousAgent: (...args: any[]) => mockExecuteHeterogeneousAgent(...args),+ }),+);++// Mirrors the real routing rule that matters here: a workspace-scoped agent's+// local/unset target coerces away from in-process execution (β gateway), so the+// test fails if `continueHeteroAfterError` stops passing `isWorkspaceAgent`.+const mockSelectRuntimeType = vi.fn((ctx: any) => (ctx?.isWorkspaceAgent ? 'gateway' : 'hetero'));+vi.mock('@/store/chat/slices/agentRun/actions/dispatch/agentDispatcher', () => ({+ selectRuntimeType: (ctx: any) => mockSelectRuntimeType(ctx),+}));++let mockResumeSessionId: string | undefined = 'sess-1';+let mockIsWorkspaceAgent = false;+vi.mock('@/store/chat/slices/agentRun/actions/transports/hetero/heteroResume', () => ({+ resolveHeteroResume: () => ({ cwdChanged: false, resumeSessionId: mockResumeSessionId }),+}));++vi.mock('@/store/chat/utils/activeTopicDocumentContext', () => ({+ mergeAgentRuntimeInitialContexts: () => undefined,+ resolveActiveTopicDocumentInitialContext: async () => undefined,+}));++vi.mock('@/store/chat/slices/operation/selectors', () => ({+ operationSelectors: {+ getOperationById: () => () => undefined,+ isMessageProcessing: () => () => false,+ },+}));++const mockCreateMessage = vi.fn(async () => ({ id: 'assistant-new' }));+const mockUpdateMessage = vi.fn(async () => ({ success: false }));+const mockRemoveMessages = vi.fn(async () => ({ success: false }));+vi.mock('@/services/message', () => ({+ messageService: {+ createMessage: (...args: any[]) => mockCreateMessage(...(args as [])),+ removeMessages: (...args: any[]) => mockRemoveMessages(...(args as [])),+ updateMessage: (...args: any[]) => mockUpdateMessage(...(args as [])),+ },+}));++vi.mock('@/store/agent', () => ({ getAgentStoreState: () => ({}) }));++vi.mock('@/store/agent/selectors', () => ({+ agentByIdSelectors: {+ getAgentWorkingDirectoryById: () => () => '/work/dir',+ isWorkspaceAgentById: () => () => mockIsWorkspaceAgent,+ },+ agentSelectors: {+ getAgentConfigById: () => () => ({+ agencyConfig: {+ executionTarget: 'local',+ heterogeneousProvider: { type: 'claude-code' },+ },+ }),+ },+}));++vi.mock('@/store/chat/selectors', () => ({+ topicSelectors: { getTopicById: () => () => undefined },+}));++vi.mock('@/store/electron', () => ({+ getElectronStoreState: () => ({ gatewayDeviceInfo: { deviceId: 'device-1' } }),+}));++vi.mock('@/components/AntdStaticMethods', () => ({+ message: { info: vi.fn() },+}));++const mockChatDeleteMessage = vi.fn(async () => {});+const mockExecuteGatewayAgent = vi.fn(async () => {});+const noop = vi.fn();+vi.mock('@/store/chat', () => ({+ useChatStore: {+ getState: vi.fn(() => ({+ operations: {},+ operationsByMessage: {},++ associateMessageWithOperation: noop,+ completeOperation: noop,+ deleteMessage: (...args: any[]) => mockChatDeleteMessage(...(args as [])),+ executeGatewayAgent: (...args: any[]) => mockExecuteGatewayAgent(...(args as [])),+ failOperation: noop,+ internal_updateTopicLoading: noop,+ isGatewayModeEnabled: () => false,+ refreshMessages: vi.fn(async () => {}),+ startOperation: vi.fn(() => ({ operationId: 'op-id' })),+ switchMessageBranch: vi.fn(async () => {}),+ })),+ setState: vi.fn(),+ },+}));++const CONTEXT: ConversationContext = { agentId: 'agent-1', threadId: null, topicId: 'topic-1' };++const HETERO_RATE_LIMIT = { body: { agentType: 'claude-code', code: 'rate_limit' } };++const USER_MESSAGE = { content: 'clean up worktrees', id: 'user-1', role: 'user' };++/**+ * A finished-then-failed run: step-1 did real work (a tool call), step-2 opened+ * and immediately died on the usage limit. `step-1` is also the group id.+ */+const buildGroupStore = (children: any[], dbMessages?: any[]) => {+ const store = createStore({ context: CONTEXT });+ act(() => {+ store.setState({+ dbMessages: dbMessages ?? [+ USER_MESSAGE,+ { content: '', id: 'step-1', parentId: 'user-1', role: 'assistant' },+ { content: '', id: 'step-2', parentId: 'step-1', role: 'assistant' },+ ],+ displayMessages: [+ USER_MESSAGE,+ { children, content: '', id: 'step-1', parentId: 'user-1', role: 'assistantGroup' },+ ],+ } as any);+ });+ return store;+};++const executorParams = () => mockExecuteHeterogeneousAgent.mock.calls[0][1];++describe('continueHeteroAfterError', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockResumeSessionId = 'sess-1';+ mockIsWorkspaceAgent = false;+ });++ it('keeps a tail step that did work: clears its error and chains the continuation onto it', async () => {+ const store = buildGroupStore([+ { content: 'looking', id: 'step-1', tools: [{ id: 'call-1' }] },+ { content: '', error: HETERO_RATE_LIMIT, id: 'step-2', tools: [{ id: 'call-2' }] },+ ]);++ await act(async () => {+ await store.getState().continueHeteroAfterError('step-1');+ });++ // The failed step survives, minus its error.+ expect(mockUpdateMessage).toHaveBeenCalledWith('step-2', { error: null }, CONTEXT);+ expect(mockRemoveMessages).not.toHaveBeenCalled();+ // The whole turn must NOT be deleted.+ expect(mockChatDeleteMessage).not.toHaveBeenCalled();++ // New assistant row chains onto the tail, keeping it inside the same group.+ expect(mockCreateMessage).toHaveBeenCalledWith(expect.objectContaining({ parentId: 'step-2' }));++ expect(mockExecuteHeterogeneousAgent).toHaveBeenCalledTimes(1);+ expect(executorParams()).toMatchObject({+ assistantMessageId: 'assistant-new',+ resumeSessionId: 'sess-1',+ });+ expect(executorParams().message).toContain('Continue the task from where it stopped');+ expect(executorParams().message).not.toBe(USER_MESSAGE.content);+ });++ it('drops an error-only tail step and chains the continuation onto its parent', async () => {+ // The terminal-error echo suppressor cleared the step's content, so it has+ // nothing to render β keeping it would leave an empty block in the bubble.+ const store = buildGroupStore([+ { content: 'looking', id: 'step-1', tools: [{ id: 'call-1' }] },+ { content: '', error: HETERO_RATE_LIMIT, id: 'step-2' },+ ]);++ await act(async () => {+ await store.getState().continueHeteroAfterError('step-1');+ });++ expect(mockRemoveMessages).toHaveBeenCalledWith(['step-2'], CONTEXT);+ expect(mockUpdateMessage).not.toHaveBeenCalled();+ expect(mockChatDeleteMessage).not.toHaveBeenCalled();+ expect(mockCreateMessage).toHaveBeenCalledWith(expect.objectContaining({ parentId: 'step-1' }));+ });++ it('falls back to a whole-turn regenerate when the failed step is the group head', async () => {+ // Nothing ran before the failure, so there is no work to keep β and the+ // head's id doubles as the group id.+ const store = buildGroupStore(+ [{ content: '', error: HETERO_RATE_LIMIT, id: 'step-1' }],+ [USER_MESSAGE, { content: '', id: 'step-1', parentId: 'user-1', role: 'assistant' }],+ );++ await act(async () => {+ await store.getState().continueHeteroAfterError('step-1');+ });++ expect(mockChatDeleteMessage).toHaveBeenCalledWith('step-1', { operationId: 'op-id' });+ // Regenerated from the original user prompt, not the continuation prompt.+ expect(executorParams().message).toBe(USER_MESSAGE.content);+ });++ it('falls back to a whole-turn regenerate when no CLI session survives to resume', async () => {+ mockResumeSessionId = undefined;+ const store = buildGroupStore([+ { content: 'looking', id: 'step-1', tools: [{ id: 'call-1' }] },+ { content: '', error: HETERO_RATE_LIMIT, id: 'step-2' },+ ]);++ await act(async () => {+ await store.getState().continueHeteroAfterError('step-1');+ });++ expect(mockChatDeleteMessage).toHaveBeenCalledWith('step-1', { operationId: 'op-id' });+ expect(mockRemoveMessages).not.toHaveBeenCalled();+ expect(executorParams().message).toBe(USER_MESSAGE.content);+ });++ it('routes a workspace-scoped agent through the whole-turn fallback, never the local executor', async () => {+ // Workspace agents never execute in-process on this member's desktop:+ // selectRuntimeType must see the workspace scope (β gateway) so the retry+ // neither mutates the preserved steps locally nor spawns the local CLI.+ mockIsWorkspaceAgent = true;+ const store = buildGroupStore([+ { content: 'looking', id: 'step-1', tools: [{ id: 'call-1' }] },+ { content: '', error: HETERO_RATE_LIMIT, id: 'step-2' },+ ]);++ await act(async () => {+ await store.getState().continueHeteroAfterError('step-1');+ });++ // The routing decision saw the workspace scope.+ expect(mockSelectRuntimeType).toHaveBeenCalledWith(+ expect.objectContaining({ isWorkspaceAgent: true }),+ );+ // No local mutation of the failed run's steps.+ expect(mockUpdateMessage).not.toHaveBeenCalled();+ expect(mockRemoveMessages).not.toHaveBeenCalled();+ // Whole-turn fallback: the turn is replaced and regenerated via the+ // gateway with the ORIGINAL user prompt β the local executor never runs.+ expect(mockChatDeleteMessage).toHaveBeenCalledWith('step-1', { operationId: 'op-id' });+ expect(mockExecuteGatewayAgent).toHaveBeenCalledWith(+ expect.objectContaining({ message: USER_MESSAGE.content }),+ );+ expect(mockExecuteHeterogeneousAgent).not.toHaveBeenCalled();+ });++ it('ignores a tail error that is not a heterogeneous-agent status error', async () => {+ const store = buildGroupStore([+ { content: 'looking', id: 'step-1', tools: [{ id: 'call-1' }] },+ { content: '', error: { body: { message: 'boom' }, type: 'PluginError' }, id: 'step-2' },+ ]);++ await act(async () => {+ await store.getState().continueHeteroAfterError('step-1');+ });++ expect(mockChatDeleteMessage).not.toHaveBeenCalled();+ expect(mockExecuteHeterogeneousAgent).not.toHaveBeenCalled();+ });+});