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(hetero): resume device-bound runs on retry instead of wiping the turn (#21494)

Arvin Xu35fc2fa31b25
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.ts
index 26fd17a1b88..df08a89a107 100644
--- a/src/features/Conversation/store/slices/generation/action.ts
+++ b/src/features/Conversation/store/slices/generation/action.ts
@@ -1,41 +1,17 @@
import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';
-import { HETERO_CONTINUE_PROMPT, LOADING_FLAT } from '@lobechat/const';
-import {
- collectHeteroAttachedFiles,
- type HeteroAttachedFileRef,
-} from '@lobechat/heterogeneous-agents';
+import { collectHeteroAttachedFiles } from '@lobechat/heterogeneous-agents';
import { shouldDropUnsupportedClaudeAssistantPrefill } from '@lobechat/model-runtime/providers/anthropic/modelId';
-import type {
- ChatImageItem,
- ChatTopic,
- ConversationContext,
- HeterogeneousProviderConfig,
-} from '@lobechat/types';
-import { applyTopicModelToHeterogeneousProvider, resolveAgentAgencyConfig } from '@lobechat/types';
+import type { ConversationContext } from '@lobechat/types';
import { toast } from '@lobehub/ui';
import { t } from 'i18next';
import { type StateCreator } from 'zustand';
-import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { MESSAGE_CANCEL_FLAT } from '@/const/index';
import { saveDraft } from '@/features/ChatInput/draftStorage';
import { isHeterogeneousAgentStatusGuideError } from '@/features/Conversation/Error/heterogeneous';
import { getEffectiveConversationModel } from '@/features/Conversation/store/utils/effectiveModel';
-import {
- ensureAgentManagementAccess,
- getRuntimeCanManageAgent,
-} from '@/helpers/agentManagementAccess';
-import { resolveAgentWorkingDirectory } from '@/helpers/agentWorkingDirectory';
-import {
- applyTopicDeviceBinding,
- getTopicBoundDeviceId,
- resolveWorkspaceScoped,
-} from '@/helpers/executionTarget';
-import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';
import { messageService } from '@/services/message';
import { topicService } from '@/services/topic';
-import { getAgentStoreState } from '@/store/agent';
-import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
import { selectRuntimeType } from '@/store/chat/slices/agentRun/actions/dispatch/agentDispatcher';
@@ -44,25 +20,24 @@ import {
parseSelectedSkillsFromEditorData,
parseSelectedToolsFromEditorData,
} from '@/store/chat/slices/agentRun/actions/entries/commandBus';
-import {
- getNativeHeteroSessionBindingKey,
- resolveHeteroResume,
-} from '@/store/chat/slices/agentRun/actions/transports/hetero/heteroResume';
import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import { INPUT_LOADING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';
-import { resolveTopicHeteroPin } from '@/store/chat/slices/topic/selectors';
import {
mergeAgentRuntimeInitialContexts,
resolveActiveTopicDocumentInitialContext,
} from '@/store/chat/utils/activeTopicDocumentContext';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import { getElectronStoreState } from '@/store/electron';
-import { getUserStoreState } from '@/store/user';
-import { userProfileSelectors } from '@/store/user/selectors';
import { type Store as ConversationStore } from '../../action';
import { dataSelectors } from '../data/selectors';
+import { continueHeteroAfterError } from './continueHeteroAfterError';
import { MAX_HETERO_AUTO_RETRIES } from './heteroRetryConfig';
+import {
+ ensureEffectiveAgencyAccess,
+ getEffectiveAgencyConfig,
+ runHeterogeneousFromExistingMessage,
+ settleGenerationEntry,
+} from './heteroRun';
const buildRetryInitialContext = (editorData: Record<string, any> | null | undefined) => {
const normalizedEditorData = editorData ?? undefined;
@@ -93,286 +68,13 @@ const buildRetryInitialContext = (editorData: Record<string, any> | null | undef
};
};
-/**
- * Settle a regenerate / continue entry's OUTER tracking operation and fire its
- * thin UI completion hook (`onRegenerateComplete` / `onContinueComplete`).
- *
- * Each of these entries owns an outer tracking op distinct from the executor's
- * run op (`${messageKey}/${parentMessageId}`). The unified run lifecycle
- * (`buildRunLifecycle`, inside the executor) already drove the run-level terminal
- * side effects β€” title / queue drain / notification / complete signal β€” so the
- * entry only retires its own tracking op and broadcasts the UI hook. Five runtime
- * branches (regenerate Γ— client/gateway/hetero, continue Γ— client/gateway) shared
- * this identical two-line tail; centralized here so they converge on one adapter
- * instead of hand-rolling completion at each call site.
- */
-const settleGenerationEntry = (
- chatStore: ReturnType<typeof useChatStore.getState>,
- operationId: string,
- notify?: () => void,
-) => {
- chatStore.completeOperation(operationId);
- notify?.();
-};
-
-/**
- * Resolve management access from the server before `getEffectiveAgencyConfig`
- * runs on a cold cache (page reload straight into regenerate/continue) β€” an
- * admin must not be downgraded to member just because the picker's hook never
- * mounted. No-ops for authors, members-with-resolved-answers, and non-workspace
- * agents; a failed fetch falls back to authorship for this run.
- */
-export const ensureEffectiveAgencyAccess = async (agentId: string) => {
- const agentState = getAgentStoreState();
- const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
- await ensureAgentManagementAccess({
- agentId,
- agentUserId: agent?.userId,
- currentUserId: userProfileSelectors.userId(getUserStoreState()),
- visibility: agent?.visibility,
- workspaceId: agent?.workspaceId,
- });
-};
-
-/**
- * `topic` keeps the run on the machine that conversation already ran on β€” see
- * `applyTopicDeviceBinding`. Omit it for agent-level decisions only.
- */
-export const getEffectiveAgencyConfig = (agentId: string, topic?: ChatTopic | null) => {
- const agentState = getAgentStoreState();
- const sharedAgencyConfig = agentSelectors.getAgentConfigById(agentId)(agentState)?.agencyConfig;
- const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
- const currentUserId = userProfileSelectors.userId(getUserStoreState());
- // Author-or-admin, mirroring the picker (`useAgentManagementAccess`) and the
- // server (`isResourceAuthorOrAdmin`) β€” an admin's own override must survive
- // a `fixed` selection policy just like the author's does.
- const canManage = getRuntimeCanManageAgent({
- agentId,
- agentUserId: agent?.userId,
- currentUserId,
- });
- const usesWorkspaceMemberSelection =
- !!agent?.workspaceId && agent.visibility !== 'private' && !canManage;
- // Every workspace caller's override matters β€” a manager's / private owner's
- // `local` pick also lives in `agentDeviceOverrides` (the shared row must
- // never reference a personal device); `resolveAgentAgencyConfig` decides how
- // it applies per role.
- const deviceOverride = agent?.workspaceId
- ? getUserStoreState().workspaceUserPreference.agentDeviceOverrides?.[agentId]
- : undefined;
-
- const { agencyConfig, workspaceScoped } = applyTopicDeviceBinding(
- {
- agencyConfig: resolveAgentAgencyConfig(sharedAgencyConfig, deviceOverride, {
- canManage,
- visibility: agent?.visibility,
- workspaceId: agent?.workspaceId,
- }),
- workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),
- },
- getTopicBoundDeviceId(topic, agentId),
- getElectronStoreState().gatewayDeviceInfo?.deviceId,
- );
-
- return {
- agencyConfig,
- /** True workspace membership β€” stays true for the author, unlike `workspaceScoped`. */
- isWorkspaceAgent: !!agent?.workspaceId,
- workspaceScoped,
- };
-};
-
-/**
- * Prompt that resumes an interrupted hetero run instead of restarting it.
- *
- * 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.
- */
-/**
- * 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.
- */
-export const resolveHeteroRunContext = (
- chatStore: ReturnType<typeof useChatStore.getState>,
- context: ConversationContext,
- agentId: string,
- /** Topic row when the caller already holds it (the paginated store may not). */
- topicOverride?: ChatTopic,
-) => {
- const topic =
- topicOverride ??
- (context.topicId ? topicSelectors.getTopicById(context.topicId)(chatStore) : undefined);
- const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
- const agentState = getAgentStoreState();
- const desktopContext = globalAgentContextManager.getContext();
- const { agencyConfig, workspaceScoped } = getEffectiveAgencyConfig(agentId, topic);
- const agentWorkingDirectory = resolveAgentWorkingDirectory({
- agencyConfig,
- currentDeviceId,
- fallback: desktopContext?.desktopPath ?? desktopContext?.homePath,
- legacyAgentWorkingDirectory: agentState.localAgentWorkingDirectoryMap[agentId],
- workspaceScoped,
- });
- const workingDirectory = topic?.metadata?.workingDirectory || agentWorkingDirectory;
- const heterogeneousProvider = agencyConfig?.heterogeneousProvider;
- const providerBinding = heterogeneousProvider?.authMode === 'api';
-
- // 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, reason, resumeBindingKey, resumeSessionId } = resolveHeteroResume(
- topic?.metadata,
- workingDirectory,
- {
- currentBindingKey:
- heterogeneousProvider && !providerBinding
- ? getNativeHeteroSessionBindingKey(heterogeneousProvider.type)
- : undefined,
- providerBinding,
- },
- );
-
- return { cwdChanged, reason, resumeBindingKey, 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.
- */
-export const runHeterogeneousFromExistingMessage = async (
- chatStore: ReturnType<typeof useChatStore.getState>,
- params: {
- /** Non-image attachments from the original user message β€” forwarded to the CLI as download links */
- attachedFiles?: HeteroAttachedFileRef[];
- context: ConversationContext;
- heterogeneousProvider: HeterogeneousProviderConfig;
- /** Image attachments from the original user message β€” forwarded to the CLI for vision support */
- imageList?: ChatImageItem[];
- parentMessageId: string;
- parentOperationId: string;
- prompt: string;
- /**
- * Replay the topic's on-disk CLI transcript into this row instead of spawning the CLI
- * (desktop restart recovery). The saved session id must resolve, or there is nothing to read.
- */
- replayTranscript?: boolean;
- /** Claude profile root the interrupted run's transcript was written under. */
- replayTranscriptConfigDir?: string;
- /** ISO spawn time of the interrupted run; pins the replay to that run's own turn. */
- replayTranscriptStartedAt?: string;
- /** Topic row when the caller already holds it (not necessarily in the paginated store). */
- topic?: ChatTopic;
- workspaceId?: string | null; // where the caller's flow started; omitted = read now
- },
-): Promise<{
- assistantMessageId: string;
- replayComplete?: boolean;
- /** The executor persisted a terminal error instead of throwing. */
- terminalError?: boolean;
-}> => {
- const {
- attachedFiles,
- context,
- heterogeneousProvider,
- imageList,
- parentMessageId,
- parentOperationId,
- prompt,
- replayTranscript,
- replayTranscriptConfigDir,
- replayTranscriptStartedAt,
- topic: topicOverride,
- } = params;
- const agentId = context.agentId;
- if (!agentId) throw new Error('agentId is required for heterogeneous agent');
- const workspaceId = 'workspaceId' in params ? params.workspaceId : getActiveWorkspaceId();
- await ensureEffectiveAgencyAccess(agentId);
- const { cwdChanged, reason, resumeBindingKey, resumeSessionId, workingDirectory } =
- resolveHeteroRunContext(chatStore, context, agentId, topicOverride);
- if (replayTranscript && !resumeSessionId) {
- throw new Error('Transcript replay needs a resumable CLI session on the topic');
- }
- if (cwdChanged) toast.info(t('heteroAgent.resumeReset.cwdChanged', { ns: 'chat' }));
- else if (reason === 'binding_changed')
- toast.info(t('heteroAgent.resumeReset.bindingChanged', { ns: 'chat' }));
-
- const topicPin =
- (topicOverride ? resolveTopicHeteroPin(topicOverride) : undefined) ??
- (context.topicId
- ? topicSelectors.getTopicHeteroPinById(context.topicId)(chatStore)
- : undefined);
- const effectiveHeterogeneousProvider = applyTopicModelToHeterogeneousProvider(
- heterogeneousProvider,
- topicPin,
- );
-
- const assistantMsg = await messageService.createMessage({
- agentId,
- content: LOADING_FLAT,
- parentId: parentMessageId,
- // External CLIs own model selection; persist only the runtime provider up
- // front. The adapter backfills the actual model later if the CLI reports it.
- provider: heterogeneousProvider.type,
- role: 'assistant',
- threadId: context.threadId ?? undefined,
- topicId: context.topicId ?? undefined,
- });
-
- // Pull the new row into the store so the loading bubble shows while the executor
- // runs (it only dispatches updates, not creates). Scoped to THIS context: restart
- // recovery runs this for a topic the user may not be looking at, and an unscoped
- // refresh would leave the new row out, orphaning every step chained under it.
- await chatStore.refreshMessages(context);
-
- const { operationId: heteroOpId } = chatStore.startOperation({
- context,
- label: 'Heterogeneous Agent Execution',
- metadata: {
- heteroAutoRetryAvailable: !replayTranscript,
- heterogeneousType: heterogeneousProvider.type,
- },
- parentOperationId,
- type: 'execHeterogeneousAgent',
- });
- chatStore.associateMessageWithOperation(assistantMsg.id, heteroOpId);
-
- const { executeHeterogeneousAgent } =
- await import('@/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor');
- const outcome = await executeHeterogeneousAgent(() => useChatStore.getState(), {
- assistantMessageId: assistantMsg.id,
- attachedFiles: attachedFiles?.length ? attachedFiles : undefined,
- context,
- heterogeneousProvider: effectiveHeterogeneousProvider,
- imageList: imageList?.length ? imageList : undefined,
- message: prompt,
- operationId: heteroOpId,
- ...(replayTranscript
- ? { replayTranscript: true, replayTranscriptConfigDir, replayTranscriptStartedAt }
- : {}),
- resumeBindingKey,
- resumeSessionId,
- workingDirectory,
- workspaceId,
- });
-
- return {
- assistantMessageId: assistantMsg.id,
- replayComplete: outcome?.replay?.complete,
- terminalError: outcome?.terminalError,
- };
-};
+export {
+ ensureEffectiveAgencyAccess,
+ getEffectiveAgencyConfig,
+ resolveHeteroRunContext,
+ runHeterogeneousFromExistingMessage,
+ settleGenerationEntry,
+} from './heteroRun';
export interface HeteroContinuationScheduleParams {
failedAssistantMessageId: string;
@@ -1067,104 +769,8 @@ 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;
-
- await ensureEffectiveAgencyAccess(context.agentId);
- const { agencyConfig, isWorkspaceAgent, workspaceScoped } = getEffectiveAgencyConfig(
- context.agentId,
- context.topicId
- ? topicSelectors.getTopicById(context.topicId)(useChatStore.getState())
- : undefined,
- );
- const heterogeneousProvider = agencyConfig?.heterogeneousProvider;
- const runtimeType = selectRuntimeType({
- boundDeviceId: agencyConfig?.boundDeviceId,
- executionTarget: agencyConfig?.executionTarget,
- heterogeneousProvider,
- isGatewayMode: chatStore.isGatewayModeEnabled(context.agentId),
- isWorkspaceAgent,
- workspaceScoped,
- });
- 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;
- }
- },
+ continueHeteroAfterError: (groupMessageId: string) =>
+ continueHeteroAfterError(get, groupMessageId),
scheduleHeteroContinuation: async ({ failedAssistantMessageId, rateLimit }) => {
const { context, dbMessages } = get();
diff --git a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
index be3ef314b8f..4fe5fd2cca8 100644
--- a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
+++ b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
@@ -1,3 +1,4 @@
+import { HETERO_CONTINUE_PROMPT } from '@lobechat/const';
import { act } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -33,7 +34,9 @@ let mockAgentVisibility: 'private' | 'public' = 'public';
let mockIsWorkspaceAgent = false;
let mockSharedExecutionTarget: 'device' | 'local' = 'local';
let mockWorkspaceOverride: { boundDeviceId: string; executionTarget: 'local' } | undefined;
-let mockTopic: { id: string; model?: string; provider?: string } | undefined;
+let mockTopic:
+ | { id: string; metadata?: { heteroSessionId?: string }; model?: string; provider?: string }
+ | undefined;
vi.mock(
'@/store/chat/slices/agentRun/actions/transports/hetero/heteroResume',
async (importOriginal) => ({
@@ -309,9 +312,56 @@ describe('continueHeteroAfterError', () => {
expect(executorParams().workingDirectory).toBe('/Users/me/project');
});
- it('falls back through the gateway for a workspace shared-local target without an override', async () => {
+ // A device-bound Claude Code run (desktop `local` synced to a bound device, or
+ // web) routes through the gateway. Retrying its rate-limit card used to delete
+ // the whole group and regenerate from the user prompt, wiping every step.
+ it('resumes a gateway-dispatched run in place instead of replacing the turn', async () => {
+ mockSharedExecutionTarget = 'device';
+ mockTopic = { id: 'topic-1', metadata: { heteroSessionId: 'sess-remote' } };
+ 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).not.toHaveBeenCalled();
+ expect(mockRemoveMessages).toHaveBeenCalledWith(['step-2'], CONTEXT);
+ expect(mockExecuteHeterogeneousAgent).not.toHaveBeenCalled();
+ expect(mockExecuteGatewayAgent).toHaveBeenCalledTimes(1);
+ expect(mockExecuteGatewayAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: HETERO_CONTINUE_PROMPT,
+ parentMessageId: 'step-1',
+ parentOperationId: 'op-id',
+ }),
+ );
+ });
+
+ it('falls back to a whole-turn regenerate for a gateway run with no CLI session', async () => {
+ mockSharedExecutionTarget = 'device';
+ mockTopic = { id: 'topic-1' };
+ 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(mockExecuteGatewayAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ message: USER_MESSAGE.content }),
+ );
+ });
+
+ it('resumes through the gateway for a workspace shared-local target without an override', async () => {
mockIsWorkspaceAgent = true;
mockSharedExecutionTarget = 'local';
+ mockTopic = { id: 'topic-1', metadata: { heteroSessionId: 'sess-remote' } };
const store = buildGroupStore([
{ content: 'looking', id: 'step-1', tools: [{ id: 'call-1' }] },
{ content: '', error: HETERO_RATE_LIMIT, id: 'step-2' },
@@ -330,7 +380,7 @@ describe('continueHeteroAfterError', () => {
}),
);
expect(mockExecuteGatewayAgent).toHaveBeenCalledWith(
- expect.objectContaining({ message: USER_MESSAGE.content }),
+ expect.objectContaining({ message: HETERO_CONTINUE_PROMPT, parentMessageId: 'step-1' }),
);
expect(mockExecuteHeterogeneousAgent).not.toHaveBeenCalled();
});
diff --git a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.ts b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.ts
new file mode 100644
index 00000000000..9b9104f14bf
--- /dev/null
+++ b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.ts
@@ -0,0 +1,143 @@
+import { HETERO_CONTINUE_PROMPT, LOADING_FLAT } from '@lobechat/const';
+
+import { isHeterogeneousAgentStatusGuideError } from '@/features/Conversation/Error/heterogeneous';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { selectRuntimeType } from '@/store/chat/slices/agentRun/actions/dispatch/agentDispatcher';
+
+import { type Store as ConversationStore } from '../../action';
+import {
+ ensureEffectiveAgencyAccess,
+ getEffectiveAgencyConfig,
+ resolveHeteroRunContext,
+ runHeterogeneousFromExistingMessage,
+ settleGenerationEntry,
+} from './heteroRun';
+
+/**
+ * Resume a heterogeneous (CC / Codex) run whose LAST step died on a status
+ * error, keeping every step that succeeded before it. See
+ * `GenerationAction.continueHeteroAfterError`.
+ */
+export const continueHeteroAfterError = async (
+ get: () => ConversationStore,
+ 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;
+
+ await ensureEffectiveAgencyAccess(context.agentId);
+ const { agencyConfig, isWorkspaceAgent, workspaceScoped } = getEffectiveAgencyConfig(
+ context.agentId,
+ context.topicId
+ ? topicSelectors.getTopicById(context.topicId)(useChatStore.getState())
+ : undefined,
+ );
+ const heterogeneousProvider = agencyConfig?.heterogeneousProvider;
+ const runtimeType = selectRuntimeType({
+ boundDeviceId: agencyConfig?.boundDeviceId,
+ executionTarget: agencyConfig?.executionTarget,
+ heterogeneousProvider,
+ isGatewayMode: chatStore.isGatewayModeEnabled(context.agentId),
+ isWorkspaceAgent,
+ workspaceScoped,
+ });
+ const agentId = context.agentId;
+ const topic = context.topicId
+ ? topicSelectors.getTopicById(context.topicId)(useChatStore.getState())
+ : undefined;
+
+ // In-process runs resolve the resumable session against this desktop's cwd.
+ // A device/sandbox run (`gateway`) resolves it on the server against the
+ // executing device β€” the same path the scheduled rate-limit resume takes β€”
+ // so here it only matters that the topic has a session at all.
+ const hasResumableSession =
+ runtimeType === 'hetero'
+ ? !!agentId && !!resolveHeteroRunContext(chatStore, context, agentId).resumeSessionId
+ : runtimeType === 'gateway' && !!topic?.metadata?.heteroSessionId;
+
+ // 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 (!heterogeneousProvider || !hasEarlierSteps || !hasResumableSession) {
+ 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.
+ if (runtimeType === 'gateway') {
+ // `parentMessageId` makes the server resume the existing chain and the
+ // device's CLI session instead of starting a fresh user turn. Forwarding
+ // the wrapper op lets the gateway settle it at the phase-1 handoff and
+ // wire its abort signal β€” otherwise a socket that drops before
+ // `onComplete` leaves the turn stuck in `regenerate` and blocks retry.
+ await chatStore.executeGatewayAgent({
+ context,
+ message: HETERO_CONTINUE_PROMPT,
+ onComplete: () =>
+ settleGenerationEntry(chatStore, operationId, () =>
+ hooks.onRegenerateComplete?.(groupMessageId),
+ ),
+ parentMessageId: continueParentId,
+ parentOperationId: operationId,
+ });
+ return;
+ }
+
+ 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;
+ }
+};
diff --git a/src/features/Conversation/store/slices/generation/heteroRun.ts b/src/features/Conversation/store/slices/generation/heteroRun.ts
new file mode 100644
index 00000000000..397d1603c29
--- /dev/null
+++ b/src/features/Conversation/store/slices/generation/heteroRun.ts
@@ -0,0 +1,323 @@
+import { LOADING_FLAT } from '@lobechat/const';
+import { type HeteroAttachedFileRef } from '@lobechat/heterogeneous-agents';
+import type {
+ ChatImageItem,
+ ChatTopic,
+ ConversationContext,
+ HeterogeneousProviderConfig,
+} from '@lobechat/types';
+import { applyTopicModelToHeterogeneousProvider, resolveAgentAgencyConfig } from '@lobechat/types';
+import { toast } from '@lobehub/ui';
+import { t } from 'i18next';
+
+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import {
+ ensureAgentManagementAccess,
+ getRuntimeCanManageAgent,
+} from '@/helpers/agentManagementAccess';
+import { resolveAgentWorkingDirectory } from '@/helpers/agentWorkingDirectory';
+import {
+ applyTopicDeviceBinding,
+ getTopicBoundDeviceId,
+ resolveWorkspaceScoped,
+} from '@/helpers/executionTarget';
+import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';
+import { messageService } from '@/services/message';
+import { getAgentStoreState } from '@/store/agent';
+import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import {
+ getNativeHeteroSessionBindingKey,
+ resolveHeteroResume,
+} from '@/store/chat/slices/agentRun/actions/transports/hetero/heteroResume';
+import { resolveTopicHeteroPin } from '@/store/chat/slices/topic/selectors';
+import { getElectronStoreState } from '@/store/electron';
+import { getUserStoreState } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+/**
+ * Hetero (Claude Code / Codex) run helpers shared by the generation actions,
+ * continue-after-error and desktop restart recovery. Kept out of `action.ts`
+ * so modules the slice imports can use them without a circular import.
+ */
+/**
+ * Settle a regenerate / continue entry's OUTER tracking operation and fire its
+ * thin UI completion hook (`onRegenerateComplete` / `onContinueComplete`).
+ *
+ * Each of these entries owns an outer tracking op distinct from the executor's
+ * run op (`${messageKey}/${parentMessageId}`). The unified run lifecycle
+ * (`buildRunLifecycle`, inside the executor) already drove the run-level terminal
+ * side effects β€” title / queue drain / notification / complete signal β€” so the
+ * entry only retires its own tracking op and broadcasts the UI hook. Five runtime
+ * branches (regenerate Γ— client/gateway/hetero, continue Γ— client/gateway) shared
+ * this identical two-line tail; centralized here so they converge on one adapter
+ * instead of hand-rolling completion at each call site.
+ */
+export const settleGenerationEntry = (
+ chatStore: ReturnType<typeof useChatStore.getState>,
+ operationId: string,
+ notify?: () => void,
+) => {
+ chatStore.completeOperation(operationId);
+ notify?.();
+};
+
+/**
+ * Resolve management access from the server before `getEffectiveAgencyConfig`
+ * runs on a cold cache (page reload straight into regenerate/continue) β€” an
+ * admin must not be downgraded to member just because the picker's hook never
+ * mounted. No-ops for authors, members-with-resolved-answers, and non-workspace
+ * agents; a failed fetch falls back to authorship for this run.
+ */
+export const ensureEffectiveAgencyAccess = async (agentId: string) => {
+ const agentState = getAgentStoreState();
+ const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
+ await ensureAgentManagementAccess({
+ agentId,
+ agentUserId: agent?.userId,
+ currentUserId: userProfileSelectors.userId(getUserStoreState()),
+ visibility: agent?.visibility,
+ workspaceId: agent?.workspaceId,
+ });
+};
+
+/**
+ * `topic` keeps the run on the machine that conversation already ran on β€” see
+ * `applyTopicDeviceBinding`. Omit it for agent-level decisions only.
+ */
+export const getEffectiveAgencyConfig = (agentId: string, topic?: ChatTopic | null) => {
+ const agentState = getAgentStoreState();
+ const sharedAgencyConfig = agentSelectors.getAgentConfigById(agentId)(agentState)?.agencyConfig;
+ const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
+ const currentUserId = userProfileSelectors.userId(getUserStoreState());
+ // Author-or-admin, mirroring the picker (`useAgentManagementAccess`) and the
+ // server (`isResourceAuthorOrAdmin`) β€” an admin's own override must survive
+ // a `fixed` selection policy just like the author's does.
+ const canManage = getRuntimeCanManageAgent({
+ agentId,
+ agentUserId: agent?.userId,
+ currentUserId,
+ });
+ const usesWorkspaceMemberSelection =
+ !!agent?.workspaceId && agent.visibility !== 'private' && !canManage;
+ // Every workspace caller's override matters β€” a manager's / private owner's
+ // `local` pick also lives in `agentDeviceOverrides` (the shared row must
+ // never reference a personal device); `resolveAgentAgencyConfig` decides how
+ // it applies per role.
+ const deviceOverride = agent?.workspaceId
+ ? getUserStoreState().workspaceUserPreference.agentDeviceOverrides?.[agentId]
+ : undefined;
+
+ const { agencyConfig, workspaceScoped } = applyTopicDeviceBinding(
+ {
+ agencyConfig: resolveAgentAgencyConfig(sharedAgencyConfig, deviceOverride, {
+ canManage,
+ visibility: agent?.visibility,
+ workspaceId: agent?.workspaceId,
+ }),
+ workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),
+ },
+ getTopicBoundDeviceId(topic, agentId),
+ getElectronStoreState().gatewayDeviceInfo?.deviceId,
+ );
+
+ return {
+ agencyConfig,
+ /** True workspace membership β€” stays true for the author, unlike `workspaceScoped`. */
+ isWorkspaceAgent: !!agent?.workspaceId,
+ workspaceScoped,
+ };
+};
+
+/**
+ * Prompt that resumes an interrupted hetero run instead of restarting it.
+ *
+ * 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.
+ */
+/**
+ * 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.
+ */
+export const resolveHeteroRunContext = (
+ chatStore: ReturnType<typeof useChatStore.getState>,
+ context: ConversationContext,
+ agentId: string,
+ /** Topic row when the caller already holds it (the paginated store may not). */
+ topicOverride?: ChatTopic,
+) => {
+ const topic =
+ topicOverride ??
+ (context.topicId ? topicSelectors.getTopicById(context.topicId)(chatStore) : undefined);
+ const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
+ const agentState = getAgentStoreState();
+ const desktopContext = globalAgentContextManager.getContext();
+ const { agencyConfig, workspaceScoped } = getEffectiveAgencyConfig(agentId, topic);
+ const agentWorkingDirectory = resolveAgentWorkingDirectory({
+ agencyConfig,
+ currentDeviceId,
+ fallback: desktopContext?.desktopPath ?? desktopContext?.homePath,
+ legacyAgentWorkingDirectory: agentState.localAgentWorkingDirectoryMap[agentId],
+ workspaceScoped,
+ });
+ const workingDirectory = topic?.metadata?.workingDirectory || agentWorkingDirectory;
+ const heterogeneousProvider = agencyConfig?.heterogeneousProvider;
+ const providerBinding = heterogeneousProvider?.authMode === 'api';
+
+ // 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, reason, resumeBindingKey, resumeSessionId } = resolveHeteroResume(
+ topic?.metadata,
+ workingDirectory,
+ {
+ currentBindingKey:
+ heterogeneousProvider && !providerBinding
+ ? getNativeHeteroSessionBindingKey(heterogeneousProvider.type)
+ : undefined,
+ providerBinding,
+ },
+ );
+
+ return { cwdChanged, reason, resumeBindingKey, 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.
+ */
+export const runHeterogeneousFromExistingMessage = async (
+ chatStore: ReturnType<typeof useChatStore.getState>,
+ params: {
+ /** Non-image attachments from the original user message β€” forwarded to the CLI as download links */
+ attachedFiles?: HeteroAttachedFileRef[];
+ context: ConversationContext;
+ heterogeneousProvider: HeterogeneousProviderConfig;
+ /** Image attachments from the original user message β€” forwarded to the CLI for vision support */
+ imageList?: ChatImageItem[];
+ parentMessageId: string;
+ parentOperationId: string;
+ prompt: string;
+ /**
+ * Replay the topic's on-disk CLI transcript into this row instead of spawning the CLI
+ * (desktop restart recovery). The saved session id must resolve, or there is nothing to read.
+ */
+ replayTranscript?: boolean;
+ /** Claude profile root the interrupted run's transcript was written under. */
+ replayTranscriptConfigDir?: string;
+ /** ISO spawn time of the interrupted run; pins the replay to that run's own turn. */
+ replayTranscriptStartedAt?: string;
+ /** Topic row when the caller already holds it (not necessarily in the paginated store). */
+ topic?: ChatTopic;
+ workspaceId?: string | null; // where the caller's flow started; omitted = read now
+ },
+): Promise<{
+ assistantMessageId: string;
+ replayComplete?: boolean;
+ /** The executor persisted a terminal error instead of throwing. */
+ terminalError?: boolean;
+}> => {
+ const {
+ attachedFiles,
+ context,
+ heterogeneousProvider,
+ imageList,
+ parentMessageId,
+ parentOperationId,
+ prompt,
+ replayTranscript,
+ replayTranscriptConfigDir,
+ replayTranscriptStartedAt,
+ topic: topicOverride,
+ } = params;
+ const agentId = context.agentId;
+ if (!agentId) throw new Error('agentId is required for heterogeneous agent');
+ const workspaceId = 'workspaceId' in params ? params.workspaceId : getActiveWorkspaceId();
+ await ensureEffectiveAgencyAccess(agentId);
+ const { cwdChanged, reason, resumeBindingKey, resumeSessionId, workingDirectory } =
+ resolveHeteroRunContext(chatStore, context, agentId, topicOverride);
+ if (replayTranscript && !resumeSessionId) {
+ throw new Error('Transcript replay needs a resumable CLI session on the topic');
+ }
+ if (cwdChanged) toast.info(t('heteroAgent.resumeReset.cwdChanged', { ns: 'chat' }));
+ else if (reason === 'binding_changed')
+ toast.info(t('heteroAgent.resumeReset.bindingChanged', { ns: 'chat' }));
+
+ const topicPin =
+ (topicOverride ? resolveTopicHeteroPin(topicOverride) : undefined) ??
+ (context.topicId
+ ? topicSelectors.getTopicHeteroPinById(context.topicId)(chatStore)
+ : undefined);
+ const effectiveHeterogeneousProvider = applyTopicModelToHeterogeneousProvider(
+ heterogeneousProvider,
+ topicPin,
+ );
+
+ const assistantMsg = await messageService.createMessage({
+ agentId,
+ content: LOADING_FLAT,
+ parentId: parentMessageId,
+ // External CLIs own model selection; persist only the runtime provider up
+ // front. The adapter backfills the actual model later if the CLI reports it.
+ provider: heterogeneousProvider.type,
+ role: 'assistant',
+ threadId: context.threadId ?? undefined,
+ topicId: context.topicId ?? undefined,
+ });
+
+ // Pull the new row into the store so the loading bubble shows while the executor
+ // runs (it only dispatches updates, not creates). Scoped to THIS context: restart
+ // recovery runs this for a topic the user may not be looking at, and an unscoped
+ // refresh would leave the new row out, orphaning every step chained under it.
+ await chatStore.refreshMessages(context);
+
+ const { operationId: heteroOpId } = chatStore.startOperation({
+ context,
+ label: 'Heterogeneous Agent Execution',
+ metadata: {
+ heteroAutoRetryAvailable: !replayTranscript,
+ heterogeneousType: heterogeneousProvider.type,
+ },
+ parentOperationId,
+ type: 'execHeterogeneousAgent',
+ });
+ chatStore.associateMessageWithOperation(assistantMsg.id, heteroOpId);
+
+ const { executeHeterogeneousAgent } =
+ await import('@/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor');
+ const outcome = await executeHeterogeneousAgent(() => useChatStore.getState(), {
+ assistantMessageId: assistantMsg.id,
+ attachedFiles: attachedFiles?.length ? attachedFiles : undefined,
+ context,
+ heterogeneousProvider: effectiveHeterogeneousProvider,
+ imageList: imageList?.length ? imageList : undefined,
+ message: prompt,
+ operationId: heteroOpId,
+ ...(replayTranscript
+ ? { replayTranscript: true, replayTranscriptConfigDir, replayTranscriptStartedAt }
+ : {}),
+ resumeBindingKey,
+ resumeSessionId,
+ workingDirectory,
+ workspaceId,
+ });
+
+ return {
+ assistantMessageId: assistantMsg.id,
+ replayComplete: outcome?.replay?.complete,
+ terminalError: outcome?.terminalError,
+ };
+};