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-agent): mark tools still running at a stop as aborted (#22330)

AmAzing-fb7dfa247fb8
diff --git a/src/store/chat/agents/transports/ClientToolTransport.ts b/src/store/chat/agents/transports/ClientToolTransport.ts
index fde2605b515..682b8f1ddc9 100644
--- a/src/store/chat/agents/transports/ClientToolTransport.ts
+++ b/src/store/chat/agents/transports/ClientToolTransport.ts
@@ -19,7 +19,7 @@ const TOOL_PRICING: Record<string, number> = {
'lobe-web-browsing/search': 0.001,
};
-const CANCELLED_CONTENT = 'Tool execution was cancelled by user.';
+export const TOOL_CANCELLED_CONTENT = 'Tool execution was cancelled by user.';
/** Client tool adapter backed by optimistic messages and local tool executors. */
export class ClientToolTransport implements ToolTransport {
@@ -288,7 +288,7 @@ export class ClientToolTransport implements ToolTransport {
return {
attempts: 0,
interrupted: true,
- result: { content: CANCELLED_CONTENT, success: false },
+ result: { content: TOOL_CANCELLED_CONTENT, success: false },
resultPersisted: true,
toolMessageId,
};
@@ -307,7 +307,7 @@ export class ClientToolTransport implements ToolTransport {
private async markMessageCancelled(messageId: string, operationId: string) {
const store = this.get();
await Promise.all([
- store.optimisticUpdateMessageContent(messageId, CANCELLED_CONTENT, undefined, {
+ store.optimisticUpdateMessageContent(messageId, TOOL_CANCELLED_CONTENT, undefined, {
operationId,
}),
store.optimisticUpdateMessagePlugin(
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.cancel.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.cancel.test.ts
new file mode 100644
index 00000000000..985f82feb14
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.cancel.test.ts
@@ -0,0 +1,171 @@
+/** Stopping a heterogeneous run while a tool is still executing. */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { executeHeterogeneousAgent } from '../transports/hetero/heterogeneousAgentExecutor';
+import {
+ ccInit,
+ ccToolResult,
+ ccToolUse,
+ createMockStore,
+ defaultParams,
+ flush,
+ setupIpcCapture,
+} from './heterogeneousAgentExecutor.testUtils';
+
+const mockBatchMutate = vi.fn();
+const mockCreateMessage = vi.fn();
+const mockSendPrompt = vi.fn();
+const mockStartSession = vi.fn();
+
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ toast: { info: vi.fn() },
+}));
+
+vi.mock('@/services/message', () => ({
+ messageService: {
+ batchMutate: (...args: any[]) => mockBatchMutate(...args),
+ createMessage: (...args: any[]) => mockCreateMessage(...args),
+ getMessages: vi.fn(async () => []),
+ updateMessage: vi.fn(async () => undefined),
+ updateMessageError: vi.fn(async () => ({ success: false })),
+ updateToolMessage: vi.fn(async () => undefined),
+ },
+}));
+
+vi.mock('@/services/thread', () => ({
+ threadService: {
+ createThread: vi.fn(async (params: any) => params.id),
+ getThreads: vi.fn(async () => []),
+ updateThread: vi.fn(),
+ },
+}));
+
+vi.mock('@/services/electron/heterogeneousAgent', () => ({
+ heterogeneousAgentService: {
+ cancelSession: vi.fn(async () => undefined),
+ getClaudeCodeIdentity: vi.fn(async () => null),
+ getCodexQuota: vi.fn(async () => null),
+ getSessionInfo: vi.fn(async () => ({})),
+ sendPrompt: (...args: any[]) => mockSendPrompt(...args),
+ startSession: (...args: any[]) => mockStartSession(...args),
+ stopSession: vi.fn(async () => undefined),
+ },
+}));
+
+vi.mock('@/services/agentQuota', () => ({
+ agentQuotaService: {
+ recordUsage: vi.fn(async () => undefined),
+ selectAccountForAgent: vi.fn(async () => null),
+ },
+}));
+
+vi.mock('../transports/gateway/gatewayEventHandler', () => ({
+ createGatewayEventHandler: vi.fn(() => vi.fn()),
+}));
+
+describe('heterogeneousAgentExecutor cancellation', () => {
+ let ipc: ReturnType<typeof setupIpcCapture>;
+
+ /** Feed CC events while the prompt is in flight, optionally stopping before completion. */
+ const run = async (store: any, events: any[], beforeComplete?: () => void) => {
+ let resolvePrompt!: () => void;
+ mockSendPrompt.mockReturnValue(new Promise<void>((resolve) => (resolvePrompt = resolve)));
+ const executor = executeHeterogeneousAgent(() => store, defaultParams);
+ await flush();
+ for (const event of events) ipc.emitRawLine('ipc-sess-1', event);
+ await flush();
+ beforeComplete?.();
+ ipc.emitComplete('ipc-sess-1');
+ await flush();
+ resolvePrompt();
+ await executor;
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ ipc = setupIpcCapture();
+ mockStartSession.mockImplementation(async (params: any) => {
+ ipc.setAgentType('ipc-sess-1', params.agentType ?? 'claude-code');
+ return { sessionId: 'ipc-sess-1' };
+ });
+ mockCreateMessage.mockImplementation(async (params: any) => ({ id: params.id }));
+ mockBatchMutate.mockImplementation(async (operations: any[]) => {
+ for (const operation of operations) {
+ if (operation.type === 'createMessage') await mockCreateMessage(operation.message);
+ }
+ return {
+ results: operations.map((operation, index) => ({ index, success: true, ...operation })),
+ success: true,
+ };
+ });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ /**
+ * @example The user stops a run during `sleep 60`; the tool card must not show a success check.
+ */
+ it('marks tools still running at a stop as aborted and leaves finished tools alone', async () => {
+ // ROOT CAUSE:
+ //
+ // A stop aborts the operation first, so every later CLI event β€” including
+ // the adapter's own tool cleanup β€” is dropped. A tool that had not returned
+ // kept an empty row with no intervention, which renders as a finished
+ // (green check) call, and reloads showed no trace of the interruption.
+ //
+ // Before: the cancel path only stopped the CLI session.
+ // After: unfinished main-agent tools are persisted as cancelled + aborted.
+ const abortController = new AbortController();
+ const store = createMockStore({
+ onOperationCancel: vi.fn(),
+ operations: {
+ 'op-1': {
+ abortController,
+ context: { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },
+ metadata: { startTime: 0 },
+ },
+ },
+ optimisticUpdateMessageContent: vi.fn(async () => {}),
+ optimisticUpdateMessagePlugin: vi.fn(async () => {}),
+ });
+ await run(
+ store,
+ [
+ ccInit(),
+ ccToolUse('msg-1', 'tool-done', 'Read', { file_path: '/a' }),
+ ccToolResult('tool-done', 'file text'),
+ ccToolUse('msg-2', 'tool-running', 'Bash', { command: 'sleep' }),
+ ],
+ () => abortController.abort(),
+ );
+
+ const toolMessageId = (toolCallId: string) =>
+ mockCreateMessage.mock.calls.find(
+ ([message]) => message.role === 'tool' && message.tool_call_id === toolCallId,
+ )?.[0].id;
+ const runningId = toolMessageId('tool-running');
+ expect(runningId).toBeDefined();
+ expect(store.optimisticUpdateMessagePlugin.mock.calls).toEqual([
+ [runningId, { intervention: { status: 'aborted' } }, { operationId: 'op-1' }],
+ ]);
+ expect(store.optimisticUpdateMessageContent.mock.calls).toEqual([
+ [runningId, 'Tool execution was cancelled by user.', undefined, { operationId: 'op-1' }],
+ ]);
+ });
+
+ it('leaves tool rows untouched when the run was not stopped', async () => {
+ const store = createMockStore({
+ onOperationCancel: vi.fn(),
+ optimisticUpdateMessageContent: vi.fn(async () => {}),
+ optimisticUpdateMessagePlugin: vi.fn(async () => {}),
+ });
+ await run(store, [ccInit(), ccToolUse('msg-1', 'tool-open', 'Bash', { command: 'sleep' })]);
+
+ expect(store.optimisticUpdateMessagePlugin).not.toHaveBeenCalled();
+ expect(store.optimisticUpdateMessageContent).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
index 2830379770c..d084d52624f 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -2,8 +2,6 @@
import type * as LobeChatConst from '@lobechat/const';
import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';
-import type { AgentEventAdapter } from '@lobechat/heterogeneous-agents';
-import { createAdapter } from '@lobechat/heterogeneous-agents';
import type { ChatTopicMetadata, HeterogeneousProviderConfig } from '@lobechat/types';
import { ThreadStatus } from '@lobechat/types';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -14,9 +12,37 @@ import { useElectronStore } from '@/store/electron';
import { useUserStore } from '@/store/user';
import { createGatewayEventHandler } from '../transports/gateway/gatewayEventHandler';
-import type { HeterogeneousAgentExecutorParams } from '../transports/hetero/heterogeneousAgentExecutor';
import { executeHeterogeneousAgent } from '../transports/hetero/heterogeneousAgentExecutor';
import { resolveHeteroResume } from '../transports/hetero/heteroResume';
+import {
+ ccAssistant,
+ ccInit,
+ ccMessageDelta,
+ ccMessageStart,
+ ccResult,
+ ccSubagentSpawnResult,
+ ccSubagentText,
+ ccSubagentToolResult,
+ ccSubagentToolUse,
+ ccText,
+ ccThinking,
+ ccToolResult,
+ ccToolUse,
+ codexAgentMessage,
+ codexCommandCompleted,
+ codexCommandStarted,
+ codexSessionConfigured,
+ codexThreadStarted,
+ codexTodo,
+ codexTurnCompleted,
+ codexTurnStarted,
+ createMockStore,
+ defaultContext,
+ defaultParams,
+ flush,
+ flushFakeTimers,
+ setupIpcCapture,
+} from './heterogeneousAgentExecutor.testUtils';
// ─── Mocks ───
@@ -129,382 +155,6 @@ vi.mock('@/services/electron/completionSound', () => ({
},
}));
-// ─── Helpers ───
-
-function setupIpcCapture() {
- // Mock window.electron.ipcRenderer
- const listeners = new Map<string, (...args: any[]) => void>();
- (globalThis as any).window = {
- electron: {
- ipcRenderer: {
- on: vi.fn((channel: string, handler: (...args: any[]) => void) => {
- listeners.set(channel, handler);
- return () => {
- if (listeners.get(channel) === handler) listeners.delete(channel);
- };
- }),
- // A separately bridged callback does not preserve the listener proxy identity.
- removeListener: vi.fn(),
- },
- },
- };
-
- /** Mirror main's raw-output β†’ adapter β†’ event pipeline. */
- const adapters = new Map<string, AgentEventAdapter>();
- /**
- * IPC-session β†’ agent type. Defaults to `claude-code` so tests that don't
- * explicitly register codex still work; the multi-session resume test (and
- * any codex-only suite) registers explicitly via `setAgentType`.
- */
- const sessionAgentType = new Map<string, string>();
-
- const getAdapter = (sessionId: string) => {
- if (!adapters.has(sessionId)) {
- adapters.set(sessionId, createAdapter(sessionAgentType.get(sessionId) ?? 'claude-code'));
- }
- return adapters.get(sessionId)!;
- };
-
- return {
- getListeners: () => listeners,
- /** Register the agent type for an IPC session before emitting raw events. */
- setAgentType: (sessionId: string, type: string) => {
- sessionAgentType.set(sessionId, type);
- },
- /**
- * Look up the underlying adapter for an IPC session β€” used by the
- * `getSessionInfo` mock to mirror what main's `AgentStreamPipeline.sessionId`
- * returns to the renderer's post-prompt session-id sync.
- */
- getAdapterSessionId: (sessionId: string) => adapters.get(sessionId)?.sessionId,
- /**
- * Simulate the desktop main's per-stdout-line forwarding: feed `raw`
- * through the session's adapter, then broadcast each resulting
- * `AgentStreamEvent` over the `heteroAgentEvent` channel.
- */
- emitRawLine: (sessionId: string, raw: any) => {
- const handler = listeners.get('heteroAgentEvent');
- const adapter = getAdapter(sessionId);
- for (const event of adapter.adapt(raw)) {
- handler?.(null, {
- event: {
- data: event.data,
- operationId: defaultParams.operationId,
- stepIndex: event.stepIndex,
- timestamp: event.timestamp,
- type: event.type,
- },
- sessionId,
- });
- }
- },
- /** Emit an already-adapted AgentStreamEvent, matching main-process bridge events. */
- emitStreamEvent: (sessionId: string, event: Record<string, unknown>) => {
- const handler = listeners.get('heteroAgentEvent');
- handler?.(null, {
- event: {
- operationId: defaultParams.operationId,
- stepIndex: 0,
- timestamp: Date.now(),
- ...event,
- },
- sessionId,
- });
- },
- /** Simulate session completion */
- emitComplete: (sessionId: string) => {
- const handler = listeners.get('heteroAgentSessionComplete');
- handler?.(null, { sessionId });
- },
- /** Simulate session error */
- emitError: (sessionId: string, error: Record<string, unknown> | string) => {
- const handler = listeners.get('heteroAgentSessionError');
- handler?.(null, { error, sessionId });
- },
- };
-}
-
-function createMockStore(overrides: Record<string, any> = {}) {
- // Hand out a fresh AbortController + monotonically increasing sub-op id
- // for each subagent run, mirroring `startOperation`'s contract just
- // enough that the executor can build dispatchers + completion calls.
- let subOpCounter = 0;
- const store = {
- associateMessageWithOperation: vi.fn(),
- completeOperation: vi.fn(),
- dbMessagesMap: {},
- drainQueuedMessages: vi.fn(() => []),
- internal_dispatchMessage: vi.fn(),
- internal_toggleToolCallingStreaming: vi.fn(),
- markTopicUnread: vi.fn(),
- messagesMap: {},
- operations: {
- 'op-1': {
- context: { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },
- metadata: { startTime: 0 },
- },
- } as Record<string, any>,
- refreshMessages: vi.fn(async () => {}),
- refreshThreads: vi.fn(async () => {}),
- replaceMessages: vi.fn(),
- sendMessage: vi.fn(async () => {}),
- startOperation: vi.fn(() => {
- subOpCounter += 1;
- return {
- abortController: new AbortController(),
- operationId: `sub-op-${subOpCounter}`,
- };
- }),
- topicDataMap: {},
- updateTopicMetadata: vi.fn().mockResolvedValue(undefined),
- ...overrides,
- } as any;
-
- if (!store.updateOperationMetadata) {
- store.updateOperationMetadata = vi.fn((operationId: string, metadata: Record<string, any>) => {
- const operation = store.operations[operationId];
- if (!operation) return;
- operation.metadata = {
- ...operation.metadata,
- ...metadata,
- };
- });
- }
-
- return store;
-}
-
-const defaultContext = {
- agentId: 'agent-1',
- scope: 'main' as const,
- topicId: 'topic-1',
-};
-
-const defaultParams: HeterogeneousAgentExecutorParams = {
- assistantMessageId: 'ast-initial',
- context: defaultContext,
- heterogeneousProvider: { command: 'claude', type: 'claude-code' as const },
- message: 'test prompt',
- operationId: 'op-1',
-};
-
-/** Flush async queues */
-const flush = async () => {
- for (let i = 0; i < 10; i++) {
- await new Promise((r) => setTimeout(r, 10));
- }
-};
-
-const flushFakeTimers = async () => {
- for (let i = 0; i < 10; i++) {
- await vi.advanceTimersByTimeAsync(10);
- }
- await Promise.resolve();
-};
-
-// ─── CC stream-json event factories ───
-
-const ccInit = (sessionId = 'cc-sess-1') => ({
- model: 'claude-sonnet-4-6',
- session_id: sessionId,
- subtype: 'init',
- type: 'system',
-});
-
-const ccAssistant = (msgId: string, content: any[], extra?: { model?: string; usage?: any }) => ({
- message: {
- content,
- id: msgId,
- model: extra?.model || 'claude-sonnet-4-6',
- role: 'assistant',
- usage: extra?.usage,
- },
- type: 'assistant',
-});
-
-const ccToolUse = (msgId: string, toolId: string, name: string, input: any = {}) =>
- ccAssistant(msgId, [{ id: toolId, input, name, type: 'tool_use' }]);
-
-/**
- * CC subagent assistant event β€” carries `parent_tool_use_id` pointing back at
- * the outer `Task` tool_use. The adapter routes these through its subagent
- * handler which stamps `parentToolCallId` onto each tool payload.
- */
-const ccSubagentToolUse = (
- msgId: string,
- parentToolUseId: string,
- toolId: string,
- name: string,
- input: any = {},
-) => ({
- message: {
- content: [{ id: toolId, input, name, type: 'tool_use' }],
- id: msgId,
- role: 'assistant',
- },
- parent_tool_use_id: parentToolUseId,
- type: 'assistant',
-});
-
-/** Subagent assistant event with text content (closing summary-style turn). */
-const ccSubagentText = (msgId: string, parentToolUseId: string, text: string) => ({
- message: {
- content: [{ text, type: 'text' }],
- id: msgId,
- role: 'assistant',
- },
- parent_tool_use_id: parentToolUseId,
- type: 'assistant',
-});
-
-/** The main-agent tool_result for a spawn tool_use (end of a subagent run). */
-const ccSubagentSpawnResult = (spawnToolUseId: string, finalText: string) => ({
- message: {
- content: [{ content: finalText, tool_use_id: spawnToolUseId, type: 'tool_result' }],
- role: 'user',
- },
- type: 'user',
-});
-
-/**
- * Subagent INNER tool_result: a user event tagged with `parent_tool_use_id`,
- * which the adapter routes through its subagent path so the emitted
- * `tool_result` + `tool_end` events both carry the `subagent` peer field.
- */
-const ccSubagentToolResult = (
- toolUseId: string,
- parentToolUseId: string,
- content: string,
- isError = false,
-) => ({
- message: {
- content: [{ content, is_error: isError, tool_use_id: toolUseId, type: 'tool_result' }],
- role: 'user',
- },
- parent_tool_use_id: parentToolUseId,
- type: 'user',
-});
-
-const ccText = (msgId: string, text: string) => ccAssistant(msgId, [{ text, type: 'text' }]);
-
-const ccThinking = (msgId: string, thinking: string) =>
- ccAssistant(msgId, [{ thinking, type: 'thinking' }]);
-
-const ccToolResult = (toolUseId: string, content: string, isError = false) => ({
- message: {
- content: [{ content, is_error: isError, tool_use_id: toolUseId, type: 'tool_result' }],
- role: 'user',
- },
- type: 'user',
-});
-
-const ccResult = (isError = false, result = 'done') => ({
- is_error: isError,
- result,
- type: 'result',
-});
-
-/**
- * `stream_event: message_start` β€” primes adapter's in-flight message.id so a
- * following `message_delta` (which has no message.id of its own) can attach
- * its authoritative usage to the correct turn.
- */
-const ccMessageStart = (msgId: string, model = 'claude-sonnet-4-6') => ({
- event: { message: { id: msgId, model }, type: 'message_start' },
- type: 'stream_event',
-});
-
-/**
- * `stream_event: message_delta` β€” the authoritative per-turn usage under
- * `--include-partial-messages` (CC's `assistant` events only echo a stale
- * message_start snapshot, so turn_metadata is driven off this event).
- */
-const ccMessageDelta = (usage: {
- cache_creation_input_tokens?: number;
- cache_read_input_tokens?: number;
- input_tokens?: number;
- output_tokens?: number;
-}) => ({
- event: { type: 'message_delta', usage },
- type: 'stream_event',
-});
-
-// ─── Codex JSONL event factories ───
-
-const codexThreadStarted = (threadId = 'codex-thread-1') => ({
- thread_id: threadId,
- type: 'thread.started',
-});
-
-const codexSessionConfigured = (model = 'gpt-5.5') => ({
- model,
- type: 'session_configured',
-});
-
-const codexTurnStarted = () => ({
- type: 'turn.started',
-});
-
-const codexAgentMessage = (id: string, text: string) => ({
- item: {
- id,
- text,
- type: 'agent_message',
- },
- type: 'item.completed',
-});
-
-const codexCommandStarted = (id: string, command: string) => ({
- item: {
- aggregated_output: '',
- command,
- exit_code: null,
- id,
- status: 'in_progress',
- type: 'command_execution',
- },
- type: 'item.started',
-});
-
-const codexCommandCompleted = (id: string, command: string, aggregatedOutput: string) => ({
- item: {
- aggregated_output: aggregatedOutput,
- command,
- exit_code: 0,
- id,
- status: 'completed',
- type: 'command_execution',
- },
- type: 'item.completed',
-});
-
-const codexTodo = (
- lifecycle: 'item.completed' | 'item.started' | 'item.updated',
- completed: number,
-) => ({
- item: {
- id: 'todo-1',
- items: [
- { completed: completed >= 1, text: 'Inspect' },
- { completed: completed >= 2, text: 'Implement' },
- { completed: completed >= 3, text: 'Verify' },
- ],
- status: lifecycle === 'item.completed' ? 'completed' : 'in_progress',
- type: 'todo_list',
- },
- type: lifecycle,
-});
-
-const codexTurnCompleted = (usage?: {
- cached_input_tokens?: number;
- input_tokens?: number;
- output_tokens?: number;
- reasoning_output_tokens?: number;
-}) => ({
- ...(usage ? { usage } : {}),
- type: 'turn.completed',
-});
-
// ─── Tests ───
describe('heterogeneousAgentExecutor DB persistence', () => {
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.testUtils.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.testUtils.ts
new file mode 100644
index 00000000000..557c4b88740
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.testUtils.ts
@@ -0,0 +1,385 @@
+/** Shared harness for the heterogeneous agent executor scenario tests. */
+
+import type { AgentEventAdapter } from '@lobechat/heterogeneous-agents';
+import { createAdapter } from '@lobechat/heterogeneous-agents';
+import { vi } from 'vitest';
+
+import type { HeterogeneousAgentExecutorParams } from '../transports/hetero/heterogeneousAgentExecutor';
+
+export function setupIpcCapture() {
+ // Mock window.electron.ipcRenderer
+ const listeners = new Map<string, (...args: any[]) => void>();
+ (globalThis as any).window = {
+ electron: {
+ ipcRenderer: {
+ on: vi.fn((channel: string, handler: (...args: any[]) => void) => {
+ listeners.set(channel, handler);
+ return () => {
+ if (listeners.get(channel) === handler) listeners.delete(channel);
+ };
+ }),
+ // A separately bridged callback does not preserve the listener proxy identity.
+ removeListener: vi.fn(),
+ },
+ },
+ };
+
+ /** Mirror main's raw-output β†’ adapter β†’ event pipeline. */
+ const adapters = new Map<string, AgentEventAdapter>();
+ /**
+ * IPC-session β†’ agent type. Defaults to `claude-code` so tests that don't
+ * explicitly register codex still work; the multi-session resume test (and
+ * any codex-only suite) registers explicitly via `setAgentType`.
+ */
+ const sessionAgentType = new Map<string, string>();
+
+ const getAdapter = (sessionId: string) => {
+ if (!adapters.has(sessionId)) {
+ adapters.set(sessionId, createAdapter(sessionAgentType.get(sessionId) ?? 'claude-code'));
+ }
+ return adapters.get(sessionId)!;
+ };
+
+ return {
+ getListeners: () => listeners,
+ /** Register the agent type for an IPC session before emitting raw events. */
+ setAgentType: (sessionId: string, type: string) => {
+ sessionAgentType.set(sessionId, type);
+ },
+ /**
+ * Look up the underlying adapter for an IPC session β€” used by the
+ * `getSessionInfo` mock to mirror what main's `AgentStreamPipeline.sessionId`
+ * returns to the renderer's post-prompt session-id sync.
+ */
+ getAdapterSessionId: (sessionId: string) => adapters.get(sessionId)?.sessionId,
+ /**
+ * Simulate the desktop main's per-stdout-line forwarding: feed `raw`
+ * through the session's adapter, then broadcast each resulting
+ * `AgentStreamEvent` over the `heteroAgentEvent` channel.
+ */
+ emitRawLine: (sessionId: string, raw: any) => {
+ const handler = listeners.get('heteroAgentEvent');
+ const adapter = getAdapter(sessionId);
+ for (const event of adapter.adapt(raw)) {
+ handler?.(null, {
+ event: {
+ data: event.data,
+ operationId: defaultParams.operationId,
+ stepIndex: event.stepIndex,
+ timestamp: event.timestamp,
+ type: event.type,
+ },
+ sessionId,
+ });
+ }
+ },
+ /** Emit an already-adapted AgentStreamEvent, matching main-process bridge events. */
+ emitStreamEvent: (sessionId: string, event: Record<string, unknown>) => {
+ const handler = listeners.get('heteroAgentEvent');
+ handler?.(null, {
+ event: {
+ operationId: defaultParams.operationId,
+ stepIndex: 0,
+ timestamp: Date.now(),
+ ...event,
+ },
+ sessionId,
+ });
+ },
+ /** Simulate session completion */
+ emitComplete: (sessionId: string) => {
+ const handler = listeners.get('heteroAgentSessionComplete');
+ handler?.(null, { sessionId });
+ },
+ /** Simulate session error */
+ emitError: (sessionId: string, error: Record<string, unknown> | string) => {
+ const handler = listeners.get('heteroAgentSessionError');
+ handler?.(null, { error, sessionId });
+ },
+ };
+}
+
+export function createMockStore(overrides: Record<string, any> = {}) {
+ // Hand out a fresh AbortController + monotonically increasing sub-op id
+ // for each subagent run, mirroring `startOperation`'s contract just
+ // enough that the executor can build dispatchers + completion calls.
+ let subOpCounter = 0;
+ const store = {
+ associateMessageWithOperation: vi.fn(),
+ completeOperation: vi.fn(),
+ dbMessagesMap: {},
+ drainQueuedMessages: vi.fn(() => []),
+ internal_dispatchMessage: vi.fn(),
+ internal_toggleToolCallingStreaming: vi.fn(),
+ markTopicUnread: vi.fn(),
+ messagesMap: {},
+ operations: {
+ 'op-1': {
+ context: { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },
+ metadata: { startTime: 0 },
+ },
+ } as Record<string, any>,
+ refreshMessages: vi.fn(async () => {}),
+ refreshThreads: vi.fn(async () => {}),
+ replaceMessages: vi.fn(),
+ sendMessage: vi.fn(async () => {}),
+ startOperation: vi.fn(() => {
+ subOpCounter += 1;
+ return {
+ abortController: new AbortController(),
+ operationId: `sub-op-${subOpCounter}`,
+ };
+ }),
+ topicDataMap: {},
+ updateTopicMetadata: vi.fn().mockResolvedValue(undefined),
+ ...overrides,
+ } as any;
+
+ if (!store.updateOperationMetadata) {
+ store.updateOperationMetadata = vi.fn((operationId: string, metadata: Record<string, any>) => {
+ const operation = store.operations[operationId];
+ if (!operation) return;
+ operation.metadata = {
+ ...operation.metadata,
+ ...metadata,
+ };
+ });
+ }
+
+ return store;
+}
+
+export const defaultContext = {
+ agentId: 'agent-1',
+ scope: 'main' as const,
+ topicId: 'topic-1',
+};
+
+export const defaultParams: HeterogeneousAgentExecutorParams = {
+ assistantMessageId: 'ast-initial',
+ context: defaultContext,
+ heterogeneousProvider: { command: 'claude', type: 'claude-code' as const },
+ message: 'test prompt',
+ operationId: 'op-1',
+};
+
+/** Flush async queues */
+export const flush = async () => {
+ for (let i = 0; i < 10; i++) {
+ await new Promise((r) => setTimeout(r, 10));
+ }
+};
+
+export const flushFakeTimers = async () => {
+ for (let i = 0; i < 10; i++) {
+ await vi.advanceTimersByTimeAsync(10);
+ }
+ await Promise.resolve();
+};
+
+// ─── CC stream-json event factories ───
+
+export const ccInit = (sessionId = 'cc-sess-1') => ({
+ model: 'claude-sonnet-4-6',
+ session_id: sessionId,
+ subtype: 'init',
+ type: 'system',
+});
+
+export const ccAssistant = (
+ msgId: string,
+ content: any[],
+ extra?: { model?: string; usage?: any },
+) => ({
+ message: {
+ content,
+ id: msgId,
+ model: extra?.model || 'claude-sonnet-4-6',
+ role: 'assistant',
+ usage: extra?.usage,
+ },
+ type: 'assistant',
+});
+
+export const ccToolUse = (msgId: string, toolId: string, name: string, input: any = {}) =>
+ ccAssistant(msgId, [{ id: toolId, input, name, type: 'tool_use' }]);
+
+/**
+ * CC subagent assistant event β€” carries `parent_tool_use_id` pointing back at
+ * the outer `Task` tool_use. The adapter routes these through its subagent
+ * handler which stamps `parentToolCallId` onto each tool payload.
+ */
+export const ccSubagentToolUse = (
+ msgId: string,
+ parentToolUseId: string,
+ toolId: string,
+ name: string,
+ input: any = {},
+) => ({
+ message: {
+ content: [{ id: toolId, input, name, type: 'tool_use' }],
+ id: msgId,
+ role: 'assistant',
+ },
+ parent_tool_use_id: parentToolUseId,
+ type: 'assistant',
+});
+
+/** Subagent assistant event with text content (closing summary-style turn). */
+export const ccSubagentText = (msgId: string, parentToolUseId: string, text: string) => ({
+ message: {
+ content: [{ text, type: 'text' }],
+ id: msgId,
+ role: 'assistant',
+ },
+ parent_tool_use_id: parentToolUseId,
+ type: 'assistant',
+});
+
+/** The main-agent tool_result for a spawn tool_use (end of a subagent run). */
+export const ccSubagentSpawnResult = (spawnToolUseId: string, finalText: string) => ({
+ message: {
+ content: [{ content: finalText, tool_use_id: spawnToolUseId, type: 'tool_result' }],
+ role: 'user',
+ },
+ type: 'user',
+});
+
+/**
+ * Subagent INNER tool_result: a user event tagged with `parent_tool_use_id`,
+ * which the adapter routes through its subagent path so the emitted
+ * `tool_result` + `tool_end` events both carry the `subagent` peer field.
+ */
+export const ccSubagentToolResult = (
+ toolUseId: string,
+ parentToolUseId: string,
+ content: string,
+ isError = false,
+) => ({
+ message: {
+ content: [{ content, is_error: isError, tool_use_id: toolUseId, type: 'tool_result' }],
+ role: 'user',
+ },
+ parent_tool_use_id: parentToolUseId,
+ type: 'user',
+});
+
+export const ccText = (msgId: string, text: string) => ccAssistant(msgId, [{ text, type: 'text' }]);
+
+export const ccThinking = (msgId: string, thinking: string) =>
+ ccAssistant(msgId, [{ thinking, type: 'thinking' }]);
+
+export const ccToolResult = (toolUseId: string, content: string, isError = false) => ({
+ message: {
+ content: [{ content, is_error: isError, tool_use_id: toolUseId, type: 'tool_result' }],
+ role: 'user',
+ },
+ type: 'user',
+});
+
+export const ccResult = (isError = false, result = 'done') => ({
+ is_error: isError,
+ result,
+ type: 'result',
+});
+
+/**
+ * `stream_event: message_start` β€” primes adapter's in-flight message.id so a
+ * following `message_delta` (which has no message.id of its own) can attach
+ * its authoritative usage to the correct turn.
+ */
+export const ccMessageStart = (msgId: string, model = 'claude-sonnet-4-6') => ({
+ event: { message: { id: msgId, model }, type: 'message_start' },
+ type: 'stream_event',
+});
+
+/**
+ * `stream_event: message_delta` β€” the authoritative per-turn usage under
+ * `--include-partial-messages` (CC's `assistant` events only echo a stale
+ * message_start snapshot, so turn_metadata is driven off this event).
+ */
+export const ccMessageDelta = (usage: {
+ cache_creation_input_tokens?: number;
+ cache_read_input_tokens?: number;
+ input_tokens?: number;
+ output_tokens?: number;
+}) => ({
+ event: { type: 'message_delta', usage },
+ type: 'stream_event',
+});
+
+// ─── Codex JSONL event factories ───
+
+export const codexThreadStarted = (threadId = 'codex-thread-1') => ({
+ thread_id: threadId,
+ type: 'thread.started',
+});
+
+export const codexSessionConfigured = (model = 'gpt-5.5') => ({
+ model,
+ type: 'session_configured',
+});
+
+export const codexTurnStarted = () => ({
+ type: 'turn.started',
+});
+
+export const codexAgentMessage = (id: string, text: string) => ({
+ item: {
+ id,
+ text,
+ type: 'agent_message',
+ },
+ type: 'item.completed',
+});
+
+export const codexCommandStarted = (id: string, command: string) => ({
+ item: {
+ aggregated_output: '',
+ command,
+ exit_code: null,
+ id,
+ status: 'in_progress',
+ type: 'command_execution',
+ },
+ type: 'item.started',
+});
+
+export const codexCommandCompleted = (id: string, command: string, aggregatedOutput: string) => ({
+ item: {
+ aggregated_output: aggregatedOutput,
+ command,
+ exit_code: 0,
+ id,
+ status: 'completed',
+ type: 'command_execution',
+ },
+ type: 'item.completed',
+});
+
+export const codexTodo = (
+ lifecycle: 'item.completed' | 'item.started' | 'item.updated',
+ completed: number,
+) => ({
+ item: {
+ id: 'todo-1',
+ items: [
+ { completed: completed >= 1, text: 'Inspect' },
+ { completed: completed >= 2, text: 'Implement' },
+ { completed: completed >= 3, text: 'Verify' },
+ ],
+ status: lifecycle === 'item.completed' ? 'completed' : 'in_progress',
+ type: 'todo_list',
+ },
+ type: lifecycle,
+});
+
+export const codexTurnCompleted = (usage?: {
+ cached_input_tokens?: number;
+ input_tokens?: number;
+ output_tokens?: number;
+ reasoning_output_tokens?: number;
+}) => ({
+ ...(usage ? { usage } : {}),
+ type: 'turn.completed',
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/cancelledTools.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/cancelledTools.ts
new file mode 100644
index 00000000000..d66ffa49fc0
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/cancelledTools.ts
@@ -0,0 +1,42 @@
+import { TOOL_CANCELLED_CONTENT } from '@/store/chat/agents/transports/ClientToolTransport';
+import { type ChatStore } from '@/store/chat/store';
+
+interface RunToolCalls {
+ /** Main-agent tool calls whose final result already landed. */
+ completedCallIds: ReadonlySet<string>;
+ mainCallIds: ReadonlySet<string>;
+ messageIdByCallId: ReadonlyMap<string, string>;
+}
+
+/**
+ * A stop drops every later CLI event, so a tool still running never receives
+ * its result and its empty row would render as finished. Persist it as
+ * aborted, the same way a cancelled client tool is recorded.
+ */
+export const markUnfinishedToolsCancelled = async (
+ store: Pick<ChatStore, 'optimisticUpdateMessageContent' | 'optimisticUpdateMessagePlugin'>,
+ operationId: string,
+ { completedCallIds, mainCallIds, messageIdByCallId }: RunToolCalls,
+): Promise<void> => {
+ const messageIds = [...mainCallIds]
+ .filter((callId) => !completedCallIds.has(callId))
+ .map((callId) => messageIdByCallId.get(callId))
+ .filter((id): id is string => !!id);
+
+ await Promise.all(
+ messageIds.map((messageId) =>
+ Promise.all([
+ store.optimisticUpdateMessageContent(messageId, TOOL_CANCELLED_CONTENT, undefined, {
+ operationId,
+ }),
+ store.optimisticUpdateMessagePlugin(
+ messageId,
+ { intervention: { status: 'aborted' } },
+ { operationId },
+ ),
+ ]).catch((error) => {
+ console.error('[HeterogeneousAgent] Failed to mark cancelled tool:', error);
+ }),
+ ),
+ );
+};
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index 940e070ad88..03aa86af63f 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -92,10 +92,12 @@ import type { RunScope } from '../../lifecycle/types';
import { createGatewayEventHandler } from '../gateway/gatewayEventHandler';
import { isCompletedRuntimeEnd } from '../gateway/runtimeEndReason';
import { withHeteroContext } from '../viewedTaskPrompt';
+import { markUnfinishedToolsCancelled } from './cancelledTools';
import { getNativeHeteroSessionBindingKey, isRecoverableResumeError } from './heteroResume';
import { preserveSkippedIntervention } from './interventionAck';
import { createMessageWriteBatcher, type ToolMessageUpdateOperation } from './messageWriteBatcher';
import { createPendingCreateLedger } from './pendingCreateLedger';
+import { waitForPersistQueue } from './persistQueue';
import { resolveQuotaAccountSpawnPlan } from './resolveQuotaAccountEnv';
import {
buildEditedTopicPreviousConversation,
@@ -377,41 +379,8 @@ const subscribeBroadcasts = (
};
};
-const HETERO_TERMINAL_PERSIST_DRAIN_TIMEOUT_MS = 10_000;
const HETERO_TERMINAL_EVENT_GRACE_TIMEOUT_MS = 3_000;
-const waitForPersistQueue = async (
- queue: Promise<void>,
- label: string,
- timeoutMs = HETERO_TERMINAL_PERSIST_DRAIN_TIMEOUT_MS,
-): Promise<boolean> => {
- let timeoutId: ReturnType<typeof setTimeout> | undefined;
-
- const result = await Promise.race<
- { error: unknown; status: 'rejected' } | { status: 'resolved' } | { status: 'timeout' }
- >([
- queue.then(
- () => ({ status: 'resolved' }),
- (error) => ({ error, status: 'rejected' }),
- ),
- new Promise<{ status: 'timeout' }>((resolve) => {
- timeoutId = setTimeout(() => resolve({ status: 'timeout' }), timeoutMs);
- }),
- ]);
-
- if (timeoutId) clearTimeout(timeoutId);
-
- if (result.status === 'rejected') throw result.error;
- if (result.status === 'timeout') {
- console.warn(
- `[HeterogeneousAgent] persistQueue did not drain within ${timeoutMs}ms (${label}); continuing terminal flow.`,
- );
- return false;
- }
-
- return true;
-};
-
interface MessageBatchMutationResult {
results?: Array<{ error?: string; index: number; success: boolean }>;
success?: boolean;
@@ -2652,6 +2621,18 @@ export const executeHeterogeneousAgent = async (
}
} finally {
await waitForCompletionCallback();
+ if (isAborted() && !resumeFallbackTriggered) {
+ persistQueue = persistQueue.then(() => messageWriteBatcher.flush('cancel'));
+ await waitForPersistQueue(persistQueue, 'cancel')
+ .then(() =>
+ markUnfinishedToolsCancelled(get(), operationId, {
+ completedCallIds: completedToolStateCallIds,
+ mainCallIds: mainToolCallIds,
+ messageIdByCallId: toolMsgIdByCallId,
+ }),
+ )
+ .catch((err) => console.error('[HeterogeneousAgent] cancelled tool cleanup failed:', err));
+ }
unsubscribe?.();
// The desktop IPC session only owns this run's config and process handles.
// Multi-turn resume uses the native agentSessionId persisted above, so the
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/persistQueue.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/persistQueue.ts
new file mode 100644
index 00000000000..e089862f490
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/persistQueue.ts
@@ -0,0 +1,34 @@
+const HETERO_TERMINAL_PERSIST_DRAIN_TIMEOUT_MS = 10_000;
+
+/** Wait for queued persistence; `false` means it timed out and the caller continues anyway. */
+export const waitForPersistQueue = async (
+ queue: Promise<void>,
+ label: string,
+ timeoutMs = HETERO_TERMINAL_PERSIST_DRAIN_TIMEOUT_MS,
+): Promise<boolean> => {
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
+
+ const result = await Promise.race<
+ { error: unknown; status: 'rejected' } | { status: 'resolved' } | { status: 'timeout' }
+ >([
+ queue.then(
+ () => ({ status: 'resolved' }),
+ (error) => ({ error, status: 'rejected' }),
+ ),
+ new Promise<{ status: 'timeout' }>((resolve) => {
+ timeoutId = setTimeout(() => resolve({ status: 'timeout' }), timeoutMs);
+ }),
+ ]);
+
+ if (timeoutId) clearTimeout(timeoutId);
+
+ if (result.status === 'rejected') throw result.error;
+ if (result.status === 'timeout') {
+ console.warn(
+ `[HeterogeneousAgent] persistQueue did not drain within ${timeoutMs}ms (${label}); continuing terminal flow.`,
+ );
+ return false;
+ }
+
+ return true;
+};