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(agent): prevent Codex resume writer races (#18872)

Neko31e0aa510894
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.ts
index 08ee9c00237..76782908a91 100644
--- a/apps/cli/src/commands/hetero.test.ts
+++ b/apps/cli/src/commands/hetero.test.ts
@@ -1173,6 +1173,8 @@ describe('hetero exec command', () => {
'cc-stale',
'--operation-id',
'op-fallback',
+ '--topic',
+ 'topic-fallback',
]);
} finally {
await rm(dir, { force: true, recursive: true });
@@ -1185,6 +1187,13 @@ describe('hetero exec command', () => {
});
expect(mockSpawnAgent.mock.calls[1][0]).toMatchObject({ prompt: fallbackPrompt });
expect(mockSpawnAgent.mock.calls[1][0].resumeSessionId).toBeUndefined();
+ expect(mockHeteroFinishMutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ operationId: 'op-fallback',
+ resumeSessionInvalidated: true,
+ topicId: 'topic-fallback',
+ }),
+ );
});
it('does not consume the recovery prompt when native resume succeeds', async () => {
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index 15ca346677c..2315c261c8b 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -990,6 +990,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
try {
await sink.finish({
error: finishError,
+ resumeSessionInvalidated: first.resumeNotFound || undefined,
result: runResult,
sessionId,
});
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index cd753863935..0403cacc544 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -1022,6 +1022,14 @@ export default class GatewayConnectionCtr extends ControllerModule {
private async cancelHeteroTask(args: { signal?: string; taskId: string }): Promise<string> {
const { signal = 'SIGINT', taskId } = args;
+ const localExec = await this.heterogeneousAgentCtr.cancelLhHeteroExec({
+ operationId: taskId,
+ signal: signal as NodeJS.Signals,
+ });
+ if (localExec) {
+ return JSON.stringify({ ...localExec, taskId });
+ }
+
const entry = this.platformTasks.get(taskId);
if (!entry) {
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
index ecad0854927..9f142518d01 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
@@ -1,6 +1,7 @@
import type { RemoteServerAuth } from '@/modules/heterogeneousAgent/fileStorePort';
import type HeterogeneousAgentImplementation from './HeterogeneousAgentImpl';
+import type { LhHeteroExecCancellationResult } from './HeterogeneousAgentImpl';
import { ControllerModule, IpcMethod } from './index';
import RemoteServerConfigCtr from './RemoteServerConfigCtr';
@@ -115,4 +116,24 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
implementation.spawnLhHeteroExec(...args),
);
}
+
+ /**
+ * Cancels a gateway CLI wrapper through the lazy implementation boundary.
+ *
+ * Use when:
+ * - A server interrupt must stop a device-hosted heterogeneous run.
+ *
+ * Expects:
+ * - The operation id belongs to a wrapper started by this desktop process.
+ *
+ * Returns:
+ * - The wrapper cancellation result, or `undefined` when no wrapper is registered.
+ */
+ cancelLhHeteroExec(
+ ...args: Parameters<Implementation['cancelLhHeteroExec']>
+ ): Promise<LhHeteroExecCancellationResult | undefined> {
+ return this.getImplementation().then((implementation) =>
+ implementation.cancelLhHeteroExec(...args),
+ );
+ }
}
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index 6fcfdf4ad9d..6a0f291bd59 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -403,6 +403,22 @@ interface CliTraceSession {
writeQueue: Promise<void>;
}
+/** Result of cancelling a device-gateway CLI wrapper. */
+export interface LhHeteroExecCancellationResult {
+ /** Whether the wrapper emitted its exit/error terminal signal before the bounded wait elapsed. */
+ exited: boolean;
+ /** Operating-system process id when Node assigned one before cancellation. */
+ pid?: number;
+ /** Initial signal requested by the server cancellation call. */
+ signal: NodeJS.Signals;
+}
+
+interface LhHeteroExecTask {
+ cancellation?: Promise<LhHeteroExecCancellationResult>;
+ exit: Promise<void>;
+ process: ChildProcess;
+}
+
/**
* External Agent Controller β€” manages external agent CLI processes via Electron IPC.
*
@@ -445,6 +461,8 @@ export default class HeterogeneousAgentCtr {
}
private sessions = new Map<string, AgentSession>();
+ /** Device-gateway CLI wrappers keyed by their server operation id. */
+ private lhHeteroExecTasks = new Map<string, LhHeteroExecTask>();
/**
* Per-operation AskUserQuestion bridge state. Keyed by `operationId` so the
* `submitIntervention` IPC can route an answer to the right pending MCP
@@ -2671,11 +2689,65 @@ export default class HeterogeneousAgentCtr {
}
/**
- * Cancel an ongoing session: SIGINT the CC tree, escalate to SIGKILL after
- * 2s if the CLI hasn't exited (some tool calls swallow SIGINT). The
- * `exit` handler on the spawned proc broadcasts completion and clears
- * `session.process`, so the escalation is a no-op when the graceful path
- * already landed.
+ * Waits for a spawned CLI process to release its OS process handle.
+ *
+ * Use when:
+ * - A cancellation caller must not start another writer until this child exits.
+ * - A graceful signal needs a bounded wait before escalation.
+ *
+ * Expects:
+ * - `proc` is a child owned by the current heterogeneous-agent session.
+ * - `timeoutMs` bounds only this wait and does not signal the process itself.
+ *
+ * Returns:
+ * - `true` after an observed exit, otherwise `false` after the timeout.
+ */
+ private waitForProcessExit(proc: ChildProcess, timeoutMs: number): Promise<boolean> {
+ if (proc.exitCode !== null && proc.exitCode !== undefined) return Promise.resolve(true);
+ if (proc.signalCode !== null && proc.signalCode !== undefined) return Promise.resolve(true);
+
+ return new Promise((resolve) => {
+ let settled = false;
+ const finish = (exited: boolean) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ proc.off('exit', onExit);
+ resolve(exited);
+ };
+ const onExit = () => finish(true);
+ const timer = setTimeout(() => finish(false), timeoutMs);
+
+ proc.once('exit', onExit);
+ });
+ }
+
+ /**
+ * Cancels an ongoing heterogeneous-agent session and waits for its native
+ * writer to stop before returning.
+ *
+ * Call stack:
+ *
+ * QueueTray.handleSendNow
+ * -> cancelOperation
+ * -> renderer onOperationCancel hook
+ * -> {@link HeterogeneousAgentCtr.cancelSession}
+ * -> {@link HeterogeneousAgentCtr.killProcessTree}
+ * -> {@link HeterogeneousAgentCtr.waitForProcessExit}
+ *
+ * Use when:
+ * - The user stops an active local heterogeneous-agent run.
+ * - β€œSend now” must safely resume the same native Codex thread.
+ *
+ * Expects:
+ * - `params.sessionId` identifies a session owned by this controller.
+ *
+ * Returns:
+ * - Only after the transport accepted interruption and, for CLI processes,
+ * the process exit was observed.
+ *
+ * Throws:
+ * - When a CLI process remains active after the bounded SIGKILL escalation.
*/
async cancelSession(params: CancelSessionParams): Promise<void> {
const session = this.sessions.get(params.sessionId);
@@ -2715,14 +2787,18 @@ export default class HeterogeneousAgentCtr {
return;
}
const proc = session.process;
+ const gracefulExit = this.waitForProcessExit(proc, 2000);
this.killProcessTree(proc, 'SIGINT');
- setTimeout(() => {
- if (session.process === proc && !proc.killed) {
- logger.warn('Session did not exit after SIGINT, escalating to SIGKILL:', params.sessionId);
- this.killProcessTree(proc, 'SIGKILL');
- }
- }, 2000);
+ if (await gracefulExit) return;
+ if (session.process !== proc) return;
+
+ logger.warn('Session did not exit after SIGINT, escalating to SIGKILL:', params.sessionId);
+ const forcedExit = this.waitForProcessExit(proc, 2000);
+ this.killProcessTree(proc, 'SIGKILL');
+ if (!(await forcedExit)) {
+ throw new Error(`Session ${params.sessionId} did not exit after SIGKILL`);
+ }
}
/**
@@ -3006,8 +3082,27 @@ export default class HeterogeneousAgentCtr {
stdio: ['pipe', 'inherit', 'inherit'],
});
+ // Keep the wrapper reachable by the gateway cancellation tool. The wrapper
+ // owns the inner agent handle and forwards SIGINT/SIGTERM into the native
+ // CLI process group, so signalling this process is the only reliable way
+ // to release a Codex thread writer before a replacement turn starts.
+ const exit = new Promise<void>((resolve) => {
+ child.once('exit', () => resolve());
+ child.once('error', () => resolve());
+ });
+ this.lhHeteroExecTasks.set(operationId, { exit, process: child });
+
child.on('exit', (code, signal) => {
logger.info('spawnLhHeteroExec: exited β€” op=%s code=%s signal=%s', operationId, code, signal);
+ if (this.lhHeteroExecTasks.get(operationId)?.process === child) {
+ this.lhHeteroExecTasks.delete(operationId);
+ }
+ });
+
+ child.on('error', () => {
+ if (this.lhHeteroExecTasks.get(operationId)?.process === child) {
+ this.lhHeteroExecTasks.delete(operationId);
+ }
});
return new Promise((resolve) => {
@@ -3049,4 +3144,65 @@ export default class HeterogeneousAgentCtr {
});
});
}
+
+ /**
+ * Cancels a device-gateway `lh hetero exec` wrapper and waits for its native
+ * writer to exit.
+ *
+ * Use when:
+ * - A server operation is interrupted from another client.
+ * - A replacement turn must not resume the same native thread concurrently.
+ *
+ * Expects:
+ * - `operationId` is the id supplied to {@link spawnLhHeteroExec}.
+ *
+ * Returns:
+ * - Process details when a live wrapper was found; otherwise `undefined`.
+ */
+ async cancelLhHeteroExec(params: {
+ operationId: string;
+ signal?: NodeJS.Signals;
+ }): Promise<LhHeteroExecCancellationResult | undefined> {
+ const { operationId, signal = 'SIGINT' } = params;
+ const task = this.lhHeteroExecTasks.get(operationId);
+ if (!task) return;
+ if (task.cancellation) return task.cancellation;
+
+ task.cancellation = (async () => {
+ const waitForExit = async (timeoutMs: number): Promise<boolean> => {
+ // Bound cancellation so an unresponsive wrapper cannot hold the gateway
+ // request forever. The timeout only gates waiting; the second signal below
+ // escalates the inner agent through the wrapper's repeated-SIGINT handler.
+ let timer: NodeJS.Timeout | undefined;
+ const timedOut = new Promise<false>((resolve) => {
+ timer = setTimeout(() => resolve(false), timeoutMs);
+ });
+ const exited = await Promise.race([task.exit.then(() => true as const), timedOut]);
+ if (timer) clearTimeout(timer);
+ return exited;
+ };
+
+ task.process.kill(signal);
+ let exited = await waitForExit(2000);
+
+ if (!exited) {
+ // `lh hetero exec` treats a repeated SIGINT as an explicit SIGKILL of the
+ // inner native process group. Give that path a short drain window so its
+ // heteroFinish callback can settle before the replacement starts.
+ task.process.kill(signal === 'SIGINT' ? 'SIGINT' : 'SIGKILL');
+ exited = await waitForExit(2000);
+ }
+
+ if (!exited) {
+ // Last resort: terminate the wrapper itself. This is intentionally after
+ // the cooperative path because a direct SIGKILL cannot run its finish hook.
+ task.process.kill('SIGKILL');
+ exited = await waitForExit(1000);
+ }
+
+ return { exited, pid: task.process.pid, signal };
+ })();
+
+ return task.cancellation;
+ }
}
diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
index 8e58b8f84c9..76f183e6d68 100644
--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
@@ -247,6 +247,7 @@ const mockShellCommandCtr = {
} as unknown as ShellCommandCtr;
const mockHeterogeneousAgentCtr = {
+ cancelLhHeteroExec: vi.fn().mockResolvedValue(undefined),
sendPrompt: vi.fn().mockResolvedValue(undefined),
spawnLhHeteroExec: vi.fn().mockResolvedValue({ status: 'accepted' }),
startSession: vi.fn().mockResolvedValue({ sessionId: 'mock-session-id' }),
@@ -851,6 +852,7 @@ describe('GatewayConnectionCtr', () => {
}
beforeEach(() => {
+ vi.mocked(mockHeterogeneousAgentCtr.cancelLhHeteroExec).mockClear();
vi.mocked(mockHeterogeneousAgentCtr.spawnLhHeteroExec).mockClear();
});
@@ -1315,6 +1317,30 @@ describe('GatewayConnectionCtr', () => {
killSpy.mockRestore();
});
+ /**
+ * @example Cancelling `op-codex` reaches the registered `lh hetero exec` wrapper.
+ */
+ it('cancels a device local hetero wrapper before checking platform tasks', async () => {
+ vi.mocked(mockHeterogeneousAgentCtr.cancelLhHeteroExec).mockResolvedValueOnce({
+ exited: true,
+ pid: 7777,
+ signal: 'SIGINT',
+ });
+ const client = await connectAndOpen();
+
+ client.simulateToolCallRequest(
+ 'cancelHeteroTask',
+ { signal: 'SIGINT', taskId: 'op-codex' },
+ 'req-cancel-codex',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(mockHeterogeneousAgentCtr.cancelLhHeteroExec).toHaveBeenCalledWith({
+ operationId: 'op-codex',
+ signal: 'SIGINT',
+ });
+ });
+
it('does not escalate cancellation after the process group is gone', async () => {
const alive = new Set([5556]);
const killSpy = vi.spyOn(process, 'kill').mockImplementation((pid, signal?) => {
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index e21497c0319..81212d214b9 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -622,6 +622,116 @@ describe('HeterogeneousAgentCtr', () => {
await rm(appStoragePath, { force: true, recursive: true });
});
+ describe('cancelSession', () => {
+ /**
+ * @example A replacement local Codex turn starts only after the interrupted CLI exits.
+ */
+ it('does not resolve CLI cancellation until the native process exits', async () => {
+ // ROOT CAUSE:
+ //
+ // cancelSession previously sent SIGINT and returned immediately. β€œSend now”
+ // could then start a second `codex exec resume` while the first process still
+ // owned the thread writer.
+ //
+ // Before: signal the child and schedule a detached escalation timer.
+ // After: signal, await exit, and synchronously escalate after a bounded wait.
+ const { proc } = createFakeProc();
+ proc.__start = vi.fn();
+ proc.exitCode = null;
+ proc.signalCode = null;
+ nextFakeProc = proc;
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ });
+ const prompt = ctr.sendPrompt({
+ operationId: 'op-cancel-wait',
+ prompt: 'sleep 60',
+ sessionId,
+ });
+ await vi.waitFor(() => expect(spawnCalls).toHaveLength(1));
+
+ let cancellationSettled = false;
+ const cancellation = ctr.cancelSession({ sessionId }).then(() => {
+ cancellationSettled = true;
+ });
+ await Promise.resolve();
+
+ expect(cancellationSettled).toBe(false);
+
+ proc.stdout.end();
+ proc.stderr.end();
+ proc.signalCode = 'SIGINT';
+ proc.emit('exit', null, 'SIGINT');
+
+ await cancellation;
+ await prompt;
+ });
+
+ /**
+ * @example A wedged native process ignores both graceful and forced termination.
+ */
+ it('rejects cancellation when process exit is not observed after SIGKILL', async () => {
+ // ROOT CAUSE:
+ //
+ // cancelSession awaited the post-SIGKILL timeout but discarded its false
+ // result. Callers therefore started replacement turns even though the old
+ // process could still own the native Codex thread writer.
+ //
+ // Before: await forcedExit; return undefined.
+ // After: throw when forcedExit resolves false.
+ const processKill = vi.spyOn(process, 'kill').mockReturnValue(true);
+
+ try {
+ const { proc } = createFakeProc();
+ proc.__start = vi.fn();
+ proc.exitCode = null;
+ proc.pid = 4242;
+ proc.signalCode = null;
+ nextFakeProc = proc;
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as unknown as ConstructorParameters<typeof HeterogeneousAgentCtr>[0]);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ });
+ const spawnCount = spawnCalls.length;
+ const prompt = ctr.sendPrompt({
+ operationId: 'op-cancel-timeout',
+ prompt: 'ignore termination',
+ sessionId,
+ });
+ await vi.waitFor(() => expect(spawnCalls).toHaveLength(spawnCount + 1));
+
+ vi.useFakeTimers();
+ const cancellation = expect(ctr.cancelSession({ sessionId })).rejects.toThrow(
+ `Session ${sessionId} did not exit after SIGKILL`,
+ );
+ await vi.advanceTimersByTimeAsync(4000);
+ await cancellation;
+
+ expect(processKill).toHaveBeenNthCalledWith(1, -4242, 'SIGINT');
+ expect(processKill).toHaveBeenNthCalledWith(2, -4242, 'SIGKILL');
+
+ vi.useRealTimers();
+ proc.stdout.end();
+ proc.stderr.end();
+ proc.signalCode = 'SIGKILL';
+ proc.emit('exit', null, 'SIGKILL');
+ await prompt;
+ } finally {
+ processKill.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+ });
+
describe('image cache (delegates to shared `normalizeImage`)', () => {
// Image fetch + cache moved to `@lobechat/heterogeneous-agents/spawn`'s
// `normalizeImage`. The desktop controller passes its own cacheDir so the
@@ -3660,6 +3770,8 @@ describe('HeterogeneousAgentCtr', () => {
const stdin = new EventEmitter() as any;
stdin.end = vi.fn();
stdin.write = vi.fn(() => true);
+ proc.kill = vi.fn(() => true);
+ proc.pid = 4321;
proc.stdin = stdin;
return proc;
};
@@ -3845,6 +3957,50 @@ describe('HeterogeneousAgentCtr', () => {
expect(() => proc.stdin.emit('error', new Error('write EPIPE'))).not.toThrow();
});
+
+ /**
+ * @example A replacement waits until operation A's wrapper exits before operation B starts.
+ */
+ it('waits for the gateway CLI wrapper to exit when cancelling its operation', async () => {
+ // ROOT CAUSE:
+ //
+ // Device-dispatched Codex wrappers were not registered by operation id, so
+ // server cancellation returned while the native thread still had an active
+ // writer. A replacement resume then failed with `already has an active writer`.
+ //
+ // Before: spawnLhHeteroExec acknowledged the child and discarded its handle.
+ // After: cancelLhHeteroExec signals that handle and resolves only after exit.
+ const proc = createGatewayCliProc();
+ nextFakeProc = proc;
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+
+ const ack = ctr.spawnLhHeteroExec(params);
+ proc.emit('spawn');
+ await ack;
+
+ let cancellationSettled = false;
+ const cancellation = ctr
+ .cancelLhHeteroExec({ operationId: params.operationId })
+ .then((result) => {
+ cancellationSettled = true;
+ return result;
+ });
+ await Promise.resolve();
+
+ expect(proc.kill).toHaveBeenCalledWith('SIGINT');
+ expect(cancellationSettled).toBe(false);
+
+ proc.emit('exit', 130, 'SIGINT');
+
+ await expect(cancellation).resolves.toEqual({
+ exited: true,
+ pid: 4321,
+ signal: 'SIGINT',
+ });
+ });
});
/**
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
index 993c470854f..854f6bd836f 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
@@ -271,6 +271,77 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
expect(mockSpawnHeteroSandbox).not.toHaveBeenCalled();
});
+ /**
+ * @example Operation B cannot reserve the topic until operation A's interrupt resolves.
+ */
+ it('waits for the replaced operation to stop before reserving the replacement', async () => {
+ // ROOT CAUSE:
+ //
+ // The old marker was atomically replaced without waiting for the device
+ // process behind it. That let operation B resume while operation A still
+ // owned the native Codex thread writer.
+ //
+ // Before: tryReserveTaskCallback ran immediately for the replacement.
+ // After: interruptTask settles the old physical run before reservation.
+ let releaseInterrupt: (() => void) | undefined;
+ const interruptSpy = vi.spyOn(service, 'interruptTask').mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ releaseInterrupt = () => resolve({ operationId: 'op-old', success: true });
+ }),
+ );
+
+ const replacement = service.execAgent({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ prompt: 'replacement turn',
+ replacesOperationId: 'op-old',
+ } as any);
+ await vi.waitFor(() => expect(interruptSpy).toHaveBeenCalledOnce());
+
+ expect(topicMock.tryReserveTaskCallback).not.toHaveBeenCalled();
+
+ releaseInterrupt?.();
+ await replacement;
+
+ expect(topicMock.tryReserveTaskCallback).toHaveBeenCalledWith('topic-1', expect.any(String), {
+ allowRunningOperationId: undefined,
+ allowSameReservationReentry: true,
+ ignoreRunningOperation: undefined,
+ replacesOperationId: 'op-old',
+ });
+ });
+
+ /**
+ * @example Operation B is rejected when operation A's device process remains alive.
+ */
+ it('does not reserve a replacement when device cancellation is unconfirmed', async () => {
+ // ROOT CAUSE:
+ //
+ // Device Gateway reports transport success separately from the cancellation
+ // payload. Ignoring `state.exited` allowed a replacement to resume while the
+ // previous native process could still own the Codex thread writer.
+ //
+ // Before: every resolved interrupt allowed topic reservation.
+ // After: an explicitly unconfirmed device cancellation rejects replacement.
+ vi.spyOn(service, 'interruptTask').mockResolvedValue({
+ deviceCancellationConfirmed: false,
+ operationId: 'op-old',
+ success: true,
+ });
+
+ await expect(
+ service.execAgent({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ prompt: 'replacement turn',
+ replacesOperationId: 'op-old',
+ } as any),
+ ).rejects.toThrow('Replaced heterogeneous agent process did not confirm termination');
+
+ expect(topicMock.tryReserveTaskCallback).not.toHaveBeenCalled();
+ });
+
it('should attach fileIds to the user message (SPA gateway device/sandbox mode)', async () => {
// regression: the hetero early exit used to create the user message
// without `files`, so images attached in device mode were never linked
@@ -705,6 +776,42 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
});
});
+ /**
+ * @example A topic whose native resume token is missing still receives its prior turns.
+ */
+ it('injects recent conversation history when a device run must start fresh', async () => {
+ mockMessageQuery.mockResolvedValue([
+ { content: 'Create the GPU pod', id: 'old-user', role: 'user' },
+ { content: 'The pod is electron-gpu-shell', id: 'old-assistant', role: 'assistant' },
+ { content: 'Delete it', id: 'msg-1', role: 'user' },
+ ]);
+ heteroAgentConfig.agencyConfig = {
+ boundDeviceId: 'device-1',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'codex' },
+ } as any;
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Delete it',
+ });
+
+ expect(mockDispatchAgentRun).toHaveBeenCalledWith(
+ expect.objectContaining({
+ resumeFallbackSystemContext: undefined,
+ resumeSessionId: undefined,
+ systemContext: 'device recovery context',
+ }),
+ );
+ expect(mockBuildRemoteDeviceHeteroContext).toHaveBeenCalledWith({
+ agentSystemContext: undefined,
+ conversationHistory: [
+ { content: 'Create the GPU pod', role: 'user' },
+ { content: 'The pod is electron-gpu-shell', role: 'assistant' },
+ ],
+ });
+ });
+
it('dispatches OpenCode to a bound device with its model args', async () => {
heteroAgentConfig.model = 'opencode';
heteroAgentConfig.provider = 'opencode';
@@ -1389,10 +1496,83 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
workspaceId: undefined,
},
expect.objectContaining({ apiName: 'cancelHeteroTask' }),
- 5_000,
+ 10_000,
);
});
+ /**
+ * @example Stopping a device Codex run sends `cancelHeteroTask` to that device.
+ */
+ it('cancels a device local hetero run before releasing its topic', async () => {
+ mockExecuteToolCall.mockResolvedValueOnce({ success: true, state: { exited: true } });
+ topicMock.findById.mockResolvedValue({
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'assistant-codex',
+ deviceId: 'author-desktop',
+ deviceUserId: 'author-user',
+ heteroType: 'codex',
+ operationId: 'operation-codex',
+ },
+ },
+ });
+
+ const result = await service.interruptTask({
+ operationId: 'operation-codex',
+ topicId: 'topic-1',
+ });
+
+ expect(mockExecuteToolCall).toHaveBeenCalledWith(
+ {
+ deviceId: 'author-desktop',
+ userId: 'author-user',
+ workspaceId: undefined,
+ },
+ expect.objectContaining({
+ apiName: 'cancelHeteroTask',
+ arguments: JSON.stringify({ signal: 'SIGINT', taskId: 'operation-codex' }),
+ }),
+ 10_000,
+ );
+ expect(result.deviceCancellationConfirmed).toBe(true);
+ });
+
+ /**
+ * @example A device response with `exited: false` remains an unsafe cancellation result.
+ */
+ it('reports an unconfirmed device local hetero cancellation', async () => {
+ // ROOT CAUSE:
+ //
+ // A successful Gateway envelope only proves that the device handled the
+ // tool call. The nested cancellation state is authoritative for whether
+ // the native writer actually exited.
+ //
+ // Before: `{ success: true, state: { exited: false } }` was ignored.
+ // After: interruptTask surfaces `deviceCancellationConfirmed: false`.
+ mockExecuteToolCall.mockResolvedValueOnce({ success: true, state: { exited: false } });
+ topicMock.findById.mockResolvedValue({
+ metadata: {
+ runningOperation: {
+ deviceId: 'author-desktop',
+ deviceUserId: 'author-user',
+ heteroType: 'codex',
+ operationId: 'operation-codex',
+ },
+ },
+ });
+
+ const result = await service.interruptTask({
+ operationId: 'operation-codex',
+ topicId: 'topic-1',
+ });
+
+ expect(result).toMatchObject({
+ deviceCancellationConfirmed: false,
+ operationId: 'operation-codex',
+ success: true,
+ });
+ });
+
it('cancels a remote child operation without touching the supervisor device', async () => {
topicMock.findById.mockResolvedValue({
metadata: {
@@ -1425,7 +1605,7 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
apiName: 'cancelHeteroTask',
arguments: JSON.stringify({ signal: 'SIGINT', taskId: 'operation-child' }),
}),
- 5_000,
+ 10_000,
);
});
@@ -1451,7 +1631,7 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
expect(mockExecuteToolCall).toHaveBeenCalledWith(
expect.objectContaining({ deviceId: 'member-desktop', userId }),
expect.objectContaining({ apiName: 'cancelHeteroTask' }),
- 5_000,
+ 10_000,
);
});
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index dc77886f729..6262dee6af8 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -96,6 +96,7 @@ import {
ThreadType,
} from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
+import { isRecord } from '@lobechat/utils/object';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
import type { ModelAbilities } from 'model-bank';
@@ -1420,6 +1421,19 @@ export class AiAgentService {
return withCreatedThread(await this.execAgentWithApprovalRollback(params));
}
+ // A replacement is allowed to take over the topic marker, but the device
+ // process that owned the old marker may still hold a native Codex/CC writer.
+ // Settle that physical run before reserving and dispatching the replacement;
+ // otherwise two `lh hetero exec` wrappers can resume the same thread.
+ if (params.replacesOperationId && !isInterventionThreadStart) {
+ const interruption = await this.interruptTask({
+ operationId: params.replacesOperationId,
+ topicId,
+ });
+ if (interruption.deviceCancellationConfirmed === false) {
+ throw new Error('Replaced heterogeneous agent process did not confirm termination');
+ }
+ }
const reserved = await acquireTopicStartReservation({
allowSameReservationReentry: !params.approvalResolutionRequestId,
replacesOperationId: isInterventionThreadStart ? undefined : params.replacesOperationId,
@@ -2855,7 +2869,7 @@ export class AiAgentService {
// a serialized duplicate. Amp threads are server-backed, so they rely on
// native continuation exclusively and never need this local-file fallback.
let conversationHistory: ConversationHistoryEntry[] | undefined;
- if (resumeSessionId && heteroType !== 'amp') {
+ if (heteroType !== 'amp') {
try {
const recentMsgs = await this.messageModel.query({ topicId, pageSize: 200 });
const turns = recentMsgs
@@ -2883,17 +2897,19 @@ export class AiAgentService {
// retry; successful same-session runs never consume the duplicate history.
const systemContext = buildCloudHeteroContext({
agentSystemContext: agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,
+ conversationHistory: resumeSessionId ? undefined : conversationHistory,
githubToken,
repos: topicRepos,
});
- const resumeFallbackSystemContext = conversationHistory
- ? buildCloudHeteroContext({
- agentSystemContext: agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,
- conversationHistory,
- githubToken,
- repos: topicRepos,
- })
- : undefined;
+ const resumeFallbackSystemContext =
+ resumeSessionId && conversationHistory
+ ? buildCloudHeteroContext({
+ agentSystemContext: agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,
+ conversationHistory,
+ githubToken,
+ repos: topicRepos,
+ })
+ : undefined;
// Feed the resolved images (signed URLs) to the dispatched CLI for vision β€”
// mirrors the local-mode path, where the client feeds the persisted
@@ -3361,13 +3377,16 @@ export class AiAgentService {
// the agent). The spawned CLI already receives deviceCwd as its actual cwd.
const deviceSystemContext = buildRemoteDeviceHeteroContext({
agentSystemContext: agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,
+ conversationHistory: resumeSessionId ? undefined : conversationHistory,
});
- const deviceResumeFallbackSystemContext = conversationHistory
- ? buildRemoteDeviceHeteroContext({
- agentSystemContext: agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,
- conversationHistory,
- })
- : undefined;
+ const deviceResumeFallbackSystemContext =
+ resumeSessionId && conversationHistory
+ ? buildRemoteDeviceHeteroContext({
+ agentSystemContext:
+ agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,
+ conversationHistory,
+ })
+ : undefined;
const result = await deviceGateway.dispatchAgentRun({
...heteroParams,
@@ -6402,16 +6421,35 @@ export class AiAgentService {
}
/**
- * Interrupt a running task
+ * Interrupts a running task and coordinates any device-hosted process shutdown.
+ *
+ * Call stack:
*
- * This method interrupts a SubAgent task by threadId or operationId.
- * It updates both operation status and Thread status to cancelled state.
+ * execAgent (replacement path)
+ * -> {@link AiAgentService.interruptTask}
+ * -> deviceGateway.executeToolCall(cancelHeteroTask)
+ * -> HeterogeneousAgentCtr.cancelLhHeteroExec
+ *
+ * Use when:
+ * - A user stops an agent runtime by thread or operation id.
+ * - A replacement run must wait for a device-hosted native writer to exit.
+ *
+ * Expects:
+ * - At least one of `threadId` or `operationId` resolves to an owned operation.
+ *
+ * Returns:
+ * - Runtime cancellation status and, for local device agents, whether process exit was confirmed.
*/
async interruptTask(params: {
operationId?: string;
threadId?: string;
topicId?: string;
- }): Promise<{ operationId?: string; success: boolean; threadId?: string }> {
+ }): Promise<{
+ deviceCancellationConfirmed?: boolean;
+ operationId?: string;
+ success: boolean;
+ threadId?: string;
+ }> {
const { threadId, operationId, topicId } = params;
log('interruptTask: threadId=%s, operationId=%s', threadId, operationId);
@@ -6419,6 +6457,7 @@ export class AiAgentService {
// 1. Get operationId and thread
let resolvedOperationId = operationId;
let thread;
+ let deviceCancellationConfirmed: boolean | undefined;
if (threadId) {
thread = await this.threadModel.findById(threadId);
@@ -6441,7 +6480,7 @@ export class AiAgentService {
resolvedTopicId = operation?.topicId ?? undefined;
}
- // 2. Cancel remote hetero process (openclaw / hermes) if applicable.
+ // 2. Cancel a device-hosted hetero process if applicable.
// Check topic.metadata.runningOperation for device + heteroType info seeded by execAgent.
// This runs regardless of whether interruptOperation succeeds β€” the remote process
// is independent of the local operation registry.
@@ -6471,11 +6510,12 @@ export class AiAgentService {
if (
targetOperation?.deviceId &&
targetOperation.heteroType &&
- isRemoteHeterogeneousType(targetOperation.heteroType)
+ (isRemoteHeterogeneousType(targetOperation.heteroType) ||
+ isLocalHeterogeneousType(targetOperation.heteroType))
) {
const taskId = targetOperation.operationId ?? resolvedOperationId;
log(
- 'interruptTask: cancelling remote hetero process heteroType=%s deviceId=%s taskId=%s',
+ 'interruptTask: cancelling device hetero process heteroType=%s deviceId=%s taskId=%s',
targetOperation.heteroType,
targetOperation.deviceId,
taskId,
@@ -6483,21 +6523,38 @@ export class AiAgentService {
const cancelWorkspaceId =
targetOperation.deviceWorkspaceId ??
(await this.resolveDeviceWorkspaceId(targetOperation.deviceId));
- await deviceGateway
- .executeToolCall(
- {
- deviceId: targetOperation.deviceId,
- userId: targetOperation.deviceUserId ?? this.userId,
- workspaceId: cancelWorkspaceId,
- },
- {
- apiName: 'cancelHeteroTask',
- arguments: JSON.stringify({ signal: 'SIGINT', taskId }),
- identifier: 'cancelHeteroTask',
- },
- 5_000,
- )
- .catch((err) => log('interruptTask: cancelHeteroTask dispatch failed: %O', err));
+ const cancelResult = await deviceGateway.executeToolCall(
+ {
+ deviceId: targetOperation.deviceId,
+ userId: targetOperation.deviceUserId ?? this.userId,
+ workspaceId: cancelWorkspaceId,
+ },
+ {
+ apiName: 'cancelHeteroTask',
+ arguments: JSON.stringify({ signal: 'SIGINT', taskId }),
+ identifier: 'cancelHeteroTask',
+ },
+ // The device first gives the wrapper/native CLI 2s to stop
+ // cooperatively, then escalates and drains its terminal callback.
+ 10_000,
+ );
+
+ if (isLocalHeterogeneousType(targetOperation.heteroType)) {
+ deviceCancellationConfirmed =
+ cancelResult.success &&
+ isRecord(cancelResult.state) &&
+ cancelResult.state.exited === true;
+ }
+
+ if (!cancelResult.success || deviceCancellationConfirmed === false) {
+ log(
+ 'interruptTask: device cancellation unconfirmed taskId=%s success=%s state=%O error=%s',
+ taskId,
+ cancelResult.success,
+ cancelResult.state,
+ cancelResult.error,
+ );
+ }
}
}
@@ -6514,6 +6571,7 @@ export class AiAgentService {
const alreadyCancelled = thread?.status === ThreadStatus.Cancel;
return {
+ deviceCancellationConfirmed,
operationId: resolvedOperationId,
success: alreadyCancelled,
threadId: thread?.id,
@@ -6532,6 +6590,7 @@ export class AiAgentService {
}
return {
+ deviceCancellationConfirmed,
operationId: resolvedOperationId,
success: true,
threadId: thread?.id,
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index caf96a48c59..7d8d02d2435 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -409,21 +409,26 @@ export class HeterogeneousPersistenceHandler {
}
/**
- * Flush trailing accumulators, persist the CLI's native session id (when
- * present) for next-turn resume, and drop the per-operation state.
+ * Flush trailing accumulators and drop the per-operation state.
*
* Resume id source: CC's `--resume <sessionId>` token comes from the
- * adapter's cached `system:init.session_id`. The CLI surfaces it here as a
- * `heteroFinish` argument; we write it to `topic.metadata.heteroSessionId`
- * (the same field the desktop renderer uses), so the next CLI spawn for
- * this topic can include `--resume <id>`.
+ * adapter's cached `system:init.session_id`. The heterogeneous-agent service
+ * settles topic-level resume ownership after this flush.
+ *
+ * Use when:
+ * - A heterogeneous operation reaches a terminal producer callback.
+ *
+ * Expects:
+ * - The operation state was created by ingest or can be bootstrapped from the topic marker.
+ *
+ * Returns:
+ * - A promise that resolves after final message state is flushed and released.
*/
async finish(params: {
assistantMessageId?: string;
error?: { body?: Record<string, unknown>; message: string; type: string };
operationId: string;
result: 'success' | 'error' | 'cancelled';
- sessionId?: string;
/**
* Needed to bootstrap state for a failed run that never ingested: a
* process-level failure (spawn ENOENT, auth printed straight to stderr)
@@ -463,20 +468,6 @@ export class HeterogeneousPersistenceHandler {
try {
await this.flushFinalState(state, params.error, params.result);
- if (params.sessionId) {
- await this.persistSessionId(state.topicId, params.sessionId);
- } else if (params.result === 'error') {
- // No new session id was produced and the run failed. The most common
- // cause in cloud sandboxes is `--resume <staleId>` failing because the
- // container was recycled and session files are gone. Clear any persisted
- // `heteroSessionId` so the next turn starts a fresh CC session instead
- // of looping on the same stale id.
- //
- // When CC ran (system.init was emitted) but produced an error result,
- // `params.sessionId` is set β€” so this branch is NOT reached and the
- // valid session id is kept for resume on the next turn.
- await this.clearSessionId(state.topicId);
- }
} finally {
operationStates.delete(params.operationId);
}
@@ -496,21 +487,6 @@ export class HeterogeneousPersistenceHandler {
}
}
- /**
- * Remove a stale `heteroSessionId` from topic metadata. Called when a run
- * fails without producing a new session id (e.g. `--resume` rejected because
- * the sandbox was recycled). Prevents the next turn from inheriting a session
- * id that will never succeed.
- */
- private async clearSessionId(topicId: string): Promise<void> {
- try {
- await this.deps.topicModel.updateMetadata(topicId, { heteroSessionId: undefined });
- log('cleared stale sessionId topic=%s', topicId);
- } catch (err) {
- log('clearSessionId failed topic=%s err=%O', topicId, err);
- }
- }
-
// ─── State management ────────────────────────────────────────────────────
private async loadOrCreateState(
@@ -1064,8 +1040,8 @@ export class HeterogeneousPersistenceHandler {
// produced a valid session id but got killed before finishing would
// otherwise leave `topic.metadata.heteroSessionId` empty, forcing the
// next turn to spawn a fresh CC session and drop all `--resume` history.
- // Writing it here makes resume survive abandon. finish() still overwrites
- // with its own sessionId (or clears a stale one on a resume failure).
+ // Writing it here makes resume survive abandon. The terminal service
+ // path may still overwrite it after verifying topic ownership.
await this.persistSessionId(state.topicId, sid);
}
}
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
index 5a422119ee0..325c9f7897b 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts
@@ -90,6 +90,7 @@ const createService = (
operationId,
status: 'settled',
})),
+ updateMetadata: vi.fn(async () => undefined),
};
const service = new HeterogeneousAgentService({} as any, 'user-test', {
agentOperationModel: agentOperationModel as any,
@@ -514,14 +515,30 @@ describe('HeterogeneousAgentService', () => {
});
});
- it('ignores a delayed finish when a newer operation owns the topic', async () => {
+ /**
+ * @example Operation A finishes after operation B owns the topic; A still becomes terminal.
+ */
+ it('settles a delayed finish without touching the newer topic operation', async () => {
+ // ROOT CAUSE:
+ //
+ // A delayed operation used to return on topic-owner conflict without
+ // settling its durable row. Persisting its session id before that conflict
+ // check could also overwrite the replacement operation's resume binding.
+ //
+ // Before: the old row remained running and its session binding could win.
+ // After: its message state flushes without a binding update, then its own
+ // row and terminal stream settle independently of the new topic owner.
const { manager, published } = createFakeStreamManager();
const persistenceHandler = createFakePersistenceHandler();
+ const settleRunningSpy = vi
+ .spyOn(AgentOperationModel.prototype, 'settleRunning')
+ .mockResolvedValue(true);
const topicModel = {
settleRunningOperation: vi.fn(async () => ({
activeOperationId: 'op-new',
status: 'conflict' as const,
})),
+ updateMetadata: vi.fn(async () => undefined),
} as any;
const completeOperationSpy = vi
.spyOn(CompletionLifecycle.prototype, 'completeOperation')
@@ -541,7 +558,13 @@ describe('HeterogeneousAgentService', () => {
});
expect(topicModel.settleRunningOperation).toHaveBeenCalledWith('topic-1', 'op-old');
- expect(published).toHaveLength(0);
+ expect(topicModel.updateMetadata).not.toHaveBeenCalled();
+ expect(settleRunningSpy).toHaveBeenCalledWith('op-old', 'done');
+ expect(published).toHaveLength(1);
+ expect(published[0].event).toMatchObject({
+ data: { operationId: 'op-old', reason: 'success' },
+ type: 'agent_runtime_end',
+ });
expect(completeOperationSpy).not.toHaveBeenCalled();
completeOperationSpy.mockRestore();
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts
index f60ce96c9b2..99995ac594e 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts
@@ -70,6 +70,7 @@ describe('HeterogeneousAgentService β€” phase 2c session id persistence + resume
findById,
settleRunningStatus: vi.fn(async () => undefined),
takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
+ updateMetadata,
} as any,
});
@@ -130,6 +131,7 @@ describe('HeterogeneousAgentService β€” phase 2c session id persistence + resume
findById,
settleRunningStatus: vi.fn(async () => undefined),
takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
+ updateMetadata,
} as any,
});
@@ -187,6 +189,7 @@ describe('HeterogeneousAgentService β€” phase 2c session id persistence + resume
findById,
settleRunningStatus: vi.fn(async () => undefined),
takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
+ updateMetadata,
} as any,
});
@@ -196,6 +199,7 @@ describe('HeterogeneousAgentService β€” phase 2c session id persistence + resume
agentType: 'claude-code',
operationId: 'op-stale',
result: 'error',
+ resumeSessionInvalidated: true,
// no sessionId β€” CC never initialized (resume failed)
topicId: 'topic-stale',
});
@@ -204,6 +208,72 @@ describe('HeterogeneousAgentService β€” phase 2c session id persistence + resume
expect(updateMetadata).toHaveBeenCalledWith('topic-stale', { heteroSessionId: undefined });
});
+ /**
+ * @example Codex `already has an active writer` preserves the requested session token.
+ */
+ it('preserves heteroSessionId for a transient pre-init resume failure', async () => {
+ // ROOT CAUSE:
+ //
+ // If a concurrent Codex writer rejected thread/resume, no new session id
+ // was emitted. The old implementation treated every such error as a dead
+ // session and cleared the valid token, forcing the next turn to start empty.
+ //
+ // Before: error + no sessionId always wrote heteroSessionId=undefined.
+ // After: only an explicit resumeSessionInvalidated signal may clear it.
+ const updateMetadata = vi.fn(async () => undefined);
+ const findById = vi.fn(async () => ({
+ id: 'topic-busy',
+ metadata: {
+ heteroSessionId: 'codex-thread-valid',
+ runningOperation: { assistantMessageId: 'asst-busy', operationId: 'op-busy' },
+ },
+ }));
+ const handler = new HeterogeneousPersistenceHandler({
+ messageModel: {
+ findById: vi.fn(async () => null),
+ getLatestSpineMessageId: vi.fn(async () => null),
+ listMessagePluginsByTopic: vi.fn(async () => []),
+ update: vi.fn(async () => ({ success: true })),
+ } as any,
+ threadModel: {} as any,
+ topicModel: { findById, updateMetadata } as any,
+ });
+ await handler.ingest({
+ events: [
+ {
+ data: { chunkType: 'text', content: '' },
+ operationId: 'op-busy',
+ stepIndex: 0,
+ timestamp: 1,
+ type: 'stream_chunk',
+ },
+ ],
+ operationId: 'op-busy',
+ topicId: 'topic-busy',
+ });
+ const service = new HeterogeneousAgentService({} as any, 'user-1', {
+ persistenceHandler: handler,
+ streamEventManager: createSilentStreamManager(),
+ topicModel: {
+ findById,
+ settleRunningOperation: vi.fn(async () => ({ status: 'settled' as const })),
+ updateMetadata,
+ } as any,
+ });
+
+ await service.heteroFinish({
+ agentType: 'codex',
+ error: { message: 'already has an active writer', type: 'AgentRuntimeError' },
+ operationId: 'op-busy',
+ result: 'error',
+ topicId: 'topic-busy',
+ });
+
+ expect(updateMetadata).not.toHaveBeenCalledWith('topic-busy', {
+ heteroSessionId: undefined,
+ });
+ });
+
it('persists sessionId even when result=error (so the next run can still resume context)', async () => {
const updateMetadata = vi.fn(async () => undefined);
const findById = vi.fn(async () => ({
@@ -248,6 +318,7 @@ describe('HeterogeneousAgentService β€” phase 2c session id persistence + resume
findById,
settleRunningStatus: vi.fn(async () => undefined),
takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
+ updateMetadata,
} as any,
});
@@ -267,7 +338,7 @@ describe('HeterogeneousAgentService β€” phase 2c session id persistence + resume
it('topic.metadata.runningOperation is preserved (updateMetadata merges, does not replace)', async () => {
// This contract is enforced by `TopicModel.updateMetadata` itself
- // (verified in packages/database tests). We just assert the handler
+ // (verified in packages/database tests). We just assert the service
// calls it with a partial β€” not the full metadata object.
const updateMetadata = vi.fn(async () => undefined);
const findById = vi.fn(async () => ({
@@ -313,6 +384,7 @@ describe('HeterogeneousAgentService β€” phase 2c session id persistence + resume
findById,
settleRunningStatus: vi.fn(async () => undefined),
takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
+ updateMetadata,
} as any,
});
@@ -382,6 +454,7 @@ describe('HeterogeneousAgentService β€” phase 2c session id persistence + resume
findById,
settleRunningStatus: vi.fn(async () => undefined),
takeRunningOperation: vi.fn(async () => ({ isRoot: true, operation: {} })),
+ updateMetadata,
} as any,
});
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index a96e70c0382..614cd2d138a 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -57,6 +57,8 @@ export interface HeterogeneousFinishParams {
error?: { body?: Record<string, unknown>; message: string; type: string };
operationId: string;
result: HeterogeneousFinishResult;
+ /** True only when the producer proved the requested native session unusable. */
+ resumeSessionInvalidated?: boolean;
/**
* Native CLI session id (e.g. CC's per-cwd session). Used in phase 2c to
* persist on `topic.metadata` so a subsequent `lh hetero exec` run can
@@ -252,6 +254,7 @@ export class HeterogeneousAgentService {
assistantMessageId: seedAssistantMessageId,
operationId,
result,
+ resumeSessionInvalidated,
sessionId,
topicId,
} = params;
@@ -278,20 +281,15 @@ export class HeterogeneousAgentService {
);
}
- // Drain any pending state in the persistence handler β€” flushes trailing
- // accumulated content / reasoning that the in-stream `agent_runtime_end`
- // already wrote (no-op when state is clean), persists the CLI's native
- // session id for next-turn resume, and frees the per-operation memory.
- // `topicId` lets finish() bootstrap state for a run that failed before
- // producing any stream event (spawn ENOENT / auth-on-stderr): the terminal
- // error must be written HERE, before the `agent_runtime_end` publish below
- // triggers the client's message refetch.
+ // Flush operation-scoped message state before clearing the topic marker.
+ // Zero-event failures bootstrap their assistant message from that marker,
+ // so settlement must happen afterwards. Topic-level session binding is
+ // deferred until ownership has been checked below.
await this.persistenceHandler.finish({
assistantMessageId: seedAssistantMessageId,
error,
operationId,
result,
- sessionId,
topicId,
});
@@ -299,6 +297,7 @@ export class HeterogeneousAgentService {
let assistantMessageId = seedAssistantMessageId;
let isolationThreadId: string | undefined;
let orchestrationRole: 'member' | 'supervisor' | undefined;
+ let staleActiveOperationId: string | undefined;
// `cancelled` is only an intermediate process signal. Keep the marker for
// the following success/error terminal callback, which owns completion.
@@ -306,26 +305,69 @@ export class HeterogeneousAgentService {
try {
const settled = await this.topicModel.settleRunningOperation(topicId, operationId);
if (settled.status === 'conflict') {
- log(
- 'heteroFinish: ignore stale finish topic=%s op=%s; current operation is %s',
- topicId,
- operationId,
- settled.activeOperationId,
- );
- return;
- }
-
- assistantMessageId = settled.assistantMessageId ?? assistantMessageId;
- if (settled.status === 'settled') {
- serializedHooks = settled.hooks as SerializedHook[] | undefined;
- isolationThreadId = settled.threadId;
- orchestrationRole = settled.orchestrationRole;
+ staleActiveOperationId = settled.activeOperationId;
+ } else {
+ assistantMessageId = settled.assistantMessageId ?? assistantMessageId;
+ if (settled.status === 'settled') {
+ serializedHooks = settled.hooks as SerializedHook[] | undefined;
+ isolationThreadId = settled.threadId;
+ orchestrationRole = settled.orchestrationRole;
+ }
}
} catch (err) {
log('heteroFinish: failed to settle runningOperation (non-fatal): %O', err);
}
}
+ if (staleActiveOperationId) {
+ log(
+ 'heteroFinish: settle stale finish topic=%s op=%s; current operation is %s',
+ topicId,
+ operationId,
+ staleActiveOperationId,
+ );
+
+ // The topic marker belongs to the replacement and must remain intact,
+ // but this operation still owns its durable row and stream. Settle those
+ // independent resources instead of leaving the old row `running`.
+ try {
+ await this.agentOperationModel.settleRunning(
+ operationId,
+ result === 'success' ? 'done' : 'error',
+ );
+ } catch (err) {
+ log('heteroFinish: failed to settle stale operation row (non-fatal): %O', err);
+ }
+ await this.streamEventManager.publishStreamEvent(operationId, {
+ data: {
+ agentType,
+ error,
+ operationId,
+ reason: result,
+ sessionId,
+ },
+ stepIndex: 0,
+ type: 'agent_runtime_end',
+ });
+ return;
+ }
+
+ const resumeBindingUpdate = sessionId
+ ? { heteroSessionId: sessionId }
+ : result === 'error' && resumeSessionInvalidated
+ ? { heteroSessionId: undefined }
+ : undefined;
+ if (resumeBindingUpdate) {
+ try {
+ // Only the producer can distinguish a missing native session from a
+ // transient pre-init error such as Codex's "already has an active writer".
+ // Clearing every error without a new id would fork the next turn empty.
+ await this.topicModel.updateMetadata(topicId, resumeBindingUpdate);
+ } catch (err) {
+ log('heteroFinish: update resume session binding failed (non-fatal): %O', err);
+ }
+ }
+
// Emit a terminal `agent_runtime_end` so renderer subscribers shut down even
// if the CLI stream missed it. A stale callback that belongs to neither the
// root operation nor one of its children returns above.
diff --git a/src/features/Conversation/ChatInput/QueueTray.tsx b/src/features/Conversation/ChatInput/QueueTray.tsx
index 46a73f8352f..009c0b37706 100644
--- a/src/features/Conversation/ChatInput/QueueTray.tsx
+++ b/src/features/Conversation/ChatInput/QueueTray.tsx
@@ -8,6 +8,7 @@ import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import FileIcon from '@/components/FileIcon';
+import { useSingleton } from '@/hooks/useSingleton';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
import {
@@ -20,6 +21,7 @@ import { useFileStore } from '@/store/file';
import { useConversationResourceAccess } from '../hooks/useConversationResourceAccess';
import { useConversationStore } from '../store';
+import { createQueueSendNowGate } from './utils';
const PREVIEW_SIZE = 28;
@@ -164,6 +166,7 @@ const QueueTray = memo(() => {
const removeQueuedMessage = useChatStore((s) => s.removeQueuedMessage);
const dispatchChatUploadFileList = useFileStore((s) => s.dispatchChatUploadFileList);
const editor = useConversationStore((s) => s.editor);
+ const sendNowGate = useSingleton(createQueueSendNowGate);
// Edit: restore both the text content AND the attached files back to the
// input area, so the user can tweak the message and re-send. Without the
@@ -188,38 +191,44 @@ const QueueTray = memo(() => {
// will pick them up after it finishes. Reads chatStore inline so we don't
// re-subscribe the whole tray to the operations map.
const handleSendNow = useCallback(
- (msg: QueuedMessage) => {
- const chat = useChatStore.getState();
- // Cancel EVERY running blocker the item could be queued behind, not just the
- // first: matching one op would miss an interim blocker or the second of the
- // two concurrent `regenerate` ops a delAndRegenerate/delAndResendThread
- // retry runs (outer wrapper + inner regenerateUserMessage). Leaving any
- // blocker running would make the sendMessage below re-enqueue the item, so
- // "Send now" becomes a no-op. The selector shares the queue-blocking
- // predicate with the enqueue check.
- const runningOpIds = operationSelectors.getRunningQueueBlockingOperationIds(context)(chat);
- for (const id of runningOpIds) chat.cancelOperation(id, 'send_now');
- removeQueuedMessage(contextKey, msg.id);
+ async (msg: QueuedMessage) => {
+ await sendNowGate
+ .run(async () => {
+ const chat = useChatStore.getState();
+ // Cancel EVERY running blocker the item could be queued behind, not just the
+ // first: matching one op would miss an interim blocker or the second of the
+ // two concurrent `regenerate` ops a delAndRegenerate/delAndResendThread
+ // retry runs (outer wrapper + inner regenerateUserMessage). Leaving any
+ // blocker running would make the sendMessage below re-enqueue the item, so
+ // "Send now" becomes a no-op. The selector shares the queue-blocking
+ // predicate with the enqueue check.
+ const runningOpIds =
+ operationSelectors.getRunningQueueBlockingOperationIds(context)(chat);
+ const cancellationConfirmed = await Promise.all(
+ runningOpIds.map((id) => chat.cancelOperation(id, 'send_now')),
+ );
+ if (cancellationConfirmed.some((confirmed) => !confirmed)) {
+ throw new Error('Running agent cancellation was not confirmed');
+ }
+ removeQueuedMessage(contextKey, msg.id);
- // Reconstruct UploadFileItem-shaped objects so the optimistic temp message
- // can rebuild imageList/videoList from the snapshotted preview metadata.
- const filesArray = msg.filesPreview?.length
- ? reconstructUploadFilesFromQueue(msg.filesPreview)
- : msg.files?.length
- ? (msg.files.map((id) => ({ id })) as any)
- : undefined;
- chat
- .sendMessage({
- context,
- editorData: msg.editorData,
- files: filesArray,
- message: msg.content,
+ // Reconstruct UploadFileItem-shaped objects so the optimistic temp message
+ // can rebuild imageList/videoList from the snapshotted preview metadata.
+ const filesArray = msg.filesPreview?.length
+ ? reconstructUploadFilesFromQueue(msg.filesPreview)
+ : msg.files?.length
+ ? (msg.files.map((id) => ({ id })) as any)
+ : undefined;
+ await chat.sendMessage({
+ context,
+ editorData: msg.editorData,
+ files: filesArray,
+ message: msg.content,
+ });
})
- .catch((e: unknown) => {
- console.error('[QueueTray] sendNow failed:', e);
- });
+ .catch((error) => console.error('[QueueTray] sendNow failed:', error));
},
- [context, contextKey, removeQueuedMessage],
+ [context, contextKey, removeQueuedMessage, sendNowGate],
);
if (queuedMessages.length === 0) return null;
diff --git a/src/features/Conversation/ChatInput/utils.test.ts b/src/features/Conversation/ChatInput/utils.test.ts
index fc388015c34..a47e62165d4 100644
--- a/src/features/Conversation/ChatInput/utils.test.ts
+++ b/src/features/Conversation/ChatInput/utils.test.ts
@@ -1,7 +1,8 @@
import type { UIChatMessage } from '@lobechat/types';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import {
+ createQueueSendNowGate,
getContextWindowMessages,
getConversationChatInputUiState,
toChatInputMessages,
@@ -14,6 +15,42 @@ const tokenMessages = [
{ content: 'latest user', id: 'msg-4', role: 'user' },
] as UIChatMessage[];
+describe('createQueueSendNowGate', () => {
+ /**
+ * @example Two different queued rows are clicked before the first writer exits.
+ */
+ it('rejects an overlapping row while the first send-now task is settling', async () => {
+ // ROOT CAUSE:
+ //
+ // QueueTray previously keyed its in-flight guard by message id. Clicking a
+ // second row after the first cancellation marked the blocker as cancelled
+ // could therefore dispatch another turn while the native writer still exited.
+ //
+ // Before: each queued message owned an independent in-flight flag.
+ // After: the conversation tray owns one gate across all queued messages.
+ const gate = createQueueSendNowGate();
+ let releaseFirst!: () => void;
+ const firstTask = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ releaseFirst = resolve;
+ }),
+ );
+ const secondTask = vi.fn(async () => {});
+
+ const first = gate.run(firstTask);
+ const second = gate.run(secondTask);
+
+ await expect(second).resolves.toBe(false);
+ expect(secondTask).not.toHaveBeenCalled();
+
+ releaseFirst();
+ await expect(first).resolves.toBe(true);
+ await expect(gate.run(secondTask)).resolves.toBe(true);
+ expect(secondTask).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('toChatInputMessages', () => {
it('preserves user, assistant, and tool messages with their real roles', () => {
expect(toChatInputMessages(tokenMessages).map((message) => message.role)).toEqual([
diff --git a/src/features/Conversation/ChatInput/utils.ts b/src/features/Conversation/ChatInput/utils.ts
index 04b3677efbc..3c0faf84265 100644
--- a/src/features/Conversation/ChatInput/utils.ts
+++ b/src/features/Conversation/ChatInput/utils.ts
@@ -10,6 +10,48 @@ interface ChatInputMessage {
role: SupportedChatInputRole;
}
+/** Coordinates mutually exclusive β€œSend now” attempts within one conversation tray. */
+export interface QueueSendNowGate {
+ /**
+ * Runs one send-now task when the gate is idle.
+ *
+ * @returns `true` when the task ran, or `false` when another task already owns the gate.
+ */
+ run: (task: () => Promise<void>) => Promise<boolean>;
+}
+
+/**
+ * Creates a conversation-scoped gate for queued β€œSend now” actions.
+ *
+ * Use when:
+ * - Multiple queued rows can request replacement of the same running agent turn.
+ * - A second click must remain queued while the first cancellation is settling.
+ *
+ * Expects:
+ * - The caller keeps one gate instance for the lifetime of a conversation tray.
+ * - Each task owns cancellation and dispatch from start through completion.
+ *
+ * Returns:
+ * - A gate that executes at most one task at a time and rejects overlapping attempts.
+ */
+export const createQueueSendNowGate = (): QueueSendNowGate => {
+ let active = false;
+
+ return {
+ run: async (task) => {
+ if (active) return false;
+ active = true;
+
+ try {
+ await task();
+ return true;
+ } finally {
+ active = false;
+ }
+ },
+ };
+};
+
const isSupportedChatInputMessage = (
message: UIChatMessage,
): message is UIChatMessage & { role: SupportedChatInputRole } =>
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index 95b85c6546c..1e54c890178 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -1106,7 +1106,18 @@ describe('GatewayActionImpl', () => {
expect(completeOperation).toHaveBeenCalledWith('parent-send-msg-op');
});
- it('registers a cancel handler that calls aiAgentService.interruptTask with the server operationId', async () => {
+ /**
+ * @example Send now receives the server's physical device cancellation result.
+ */
+ it('registers a cancel handler that propagates unconfirmed device shutdown', async () => {
+ // ROOT CAUSE:
+ //
+ // The gateway hook awaited interruptTask but discarded its result. A local
+ // Codex process could report `deviceCancellationConfirmed: false` while the
+ // hook resolved, allowing QueueTray to remove the message and send again.
+ //
+ // Before: interruptTask(...).catch(log) always resolved the cancel hook.
+ // After: an explicit false confirmation rejects the cancel hook.
const onOperationCancel = vi.fn();
const startOperation = vi.fn(() => ({ operationId: 'gw-op-local' }));
@@ -1171,6 +1182,15 @@ describe('GatewayActionImpl', () => {
operationId: 'server-op-xyz',
topicId: 'topic-1',
});
+
+ interruptTaskSpy.mockResolvedValueOnce({
+ deviceCancellationConfirmed: false,
+ operationId: 'server-op-xyz',
+ success: true,
+ });
+ await expect(handler()).rejects.toThrow(
+ 'Gateway operation server-op-xyz cancellation unconfirmed',
+ );
});
// Regression: after an error run the gateway session completes
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 042c0df0674..2b38d0ac37e 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -73,11 +73,13 @@ vi.mock('@/services/thread', () => ({
const mockStartSession = vi.fn();
const mockSendPrompt = vi.fn();
const mockStopSession = vi.fn();
+const mockCancelSession = vi.fn();
const mockGetSessionInfo = vi.fn();
const mockGetClaudeCodeIdentity = vi.fn(async (..._args: any[]) => null);
vi.mock('@/services/electron/heterogeneousAgent', () => ({
heterogeneousAgentService: {
+ cancelSession: (...args: unknown[]) => mockCancelSession(...args),
getClaudeCodeIdentity: (...args: any[]) => mockGetClaudeCodeIdentity(...args),
getSessionInfo: (...args: any[]) => mockGetSessionInfo(...args),
sendPrompt: (...args: any[]) => mockSendPrompt(...args),
@@ -530,6 +532,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
});
mockSendPrompt.mockResolvedValue(undefined);
mockStopSession.mockResolvedValue(undefined);
+ mockCancelSession.mockResolvedValue(undefined);
// Mirror the desktop main: `getSessionInfo` returns whatever the producer
// pipeline's adapter has extracted from the JSONL stream so far. Tests
// that never emit an init / thread.started event get `agentSessionId:
@@ -659,6 +662,95 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
return { get, store };
}
+ describe('cancellation coordination', () => {
+ /**
+ * @example β€œSend now” awaits the renderer cancellation hook before dispatching a replacement.
+ */
+ it('returns the desktop session cancellation promise from the operation cancel hook', async () => {
+ // ROOT CAUSE:
+ //
+ // The operation hook started cancelSession but returned undefined. QueueTray
+ // therefore believed cancellation had settled and resumed the same native
+ // Codex thread while the previous writer was still shutting down.
+ //
+ // Before: () => { cancelSession(...).catch(...) }
+ // After: async () => await cancelSession(...)
+ let cancelHandler: (() => Promise<void>) | undefined;
+ let resolveCancellation!: () => void;
+ let resolvePrompt!: () => void;
+ mockCancelSession.mockReturnValue(
+ new Promise<void>((resolve) => {
+ resolveCancellation = resolve;
+ }),
+ );
+ mockSendPrompt.mockReturnValue(
+ new Promise<void>((resolve) => {
+ resolvePrompt = resolve;
+ }),
+ );
+ const store = createMockStore({
+ onOperationCancel: vi.fn(
+ (_operationId: string, handler: () => Promise<void>) => (cancelHandler = handler),
+ ),
+ });
+ const get = vi.fn(() => store);
+ const executor = executeHeterogeneousAgent(get, defaultParams);
+
+ await vi.waitFor(() => expect(cancelHandler).toBeDefined());
+ let cancellationSettled = false;
+ const cancellation = cancelHandler!().then(() => {
+ cancellationSettled = true;
+ });
+ await Promise.resolve();
+
+ expect(mockCancelSession).toHaveBeenCalledWith('ipc-sess-1');
+ expect(cancellationSettled).toBe(false);
+
+ resolveCancellation();
+ await cancellation;
+ ipc.emitComplete('ipc-sess-1');
+ resolvePrompt();
+ await executor;
+ });
+
+ /**
+ * @example Desktop cannot confirm that the native process exited after interruption.
+ */
+ it('rejects the operation cancel hook when desktop cancellation fails', async () => {
+ // ROOT CAUSE:
+ //
+ // The renderer logged cancelSession failures but resolved its operation
+ // hook. The operation layer then treated a still-live native writer as a
+ // successful cancellation.
+ //
+ // Before: catch(error) logged and returned undefined.
+ // After: catch(error) logs and rethrows to the operation confirmation layer.
+ let cancelHandler: (() => Promise<void>) | undefined;
+ let resolvePrompt!: () => void;
+ const cancellationError = new Error('process did not exit after SIGKILL');
+ mockCancelSession.mockRejectedValue(cancellationError);
+ mockSendPrompt.mockReturnValue(
+ new Promise<void>((resolve) => {
+ resolvePrompt = resolve;
+ }),
+ );
+ const store = createMockStore({
+ onOperationCancel: vi.fn(
+ (_operationId: string, handler: () => Promise<void>) => (cancelHandler = handler),
+ ),
+ });
+ const get = vi.fn(() => store);
+ const executor = executeHeterogeneousAgent(get, defaultParams);
+
+ await vi.waitFor(() => expect(cancelHandler).toBeDefined());
+ await expect(cancelHandler!()).rejects.toBe(cancellationError);
+
+ ipc.emitComplete('ipc-sess-1');
+ resolvePrompt();
+ await executor;
+ });
+ });
+
describe('Claude Code Desktop-local API binding', () => {
let previousLab: ReturnType<typeof useUserStore.getState>['preference']['lab'];
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 6577f89feaa..8ece649e7b7 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -55,6 +55,26 @@ import { createGatewayEventHandler, isCompletedRuntimeEnd } from './gatewayEvent
import { createGatewayEventRouter } from './gatewayEventRouter';
import { createGatewayMemberStreamHandler } from './gatewayMemberStreamHandler';
+/**
+ * Interrupts a gateway operation and rejects when its physical shutdown is unconfirmed.
+ *
+ * Device confirmation is authoritative for local heterogeneous agents because
+ * their server runtime may already be absent while the native process still
+ * needs to release its writer. Other runtimes fall back to the service result.
+ */
+const interruptGatewayTaskOrThrow = async (
+ params: Parameters<typeof aiAgentService.interruptTask>[0],
+): Promise<void> => {
+ const result = await aiAgentService.interruptTask(params);
+ const cancellationConfirmed = result.deviceCancellationConfirmed ?? result.success;
+
+ if (!cancellationConfirmed) {
+ throw new Error(
+ `Gateway operation ${params.operationId ?? 'unknown'} cancellation unconfirmed`,
+ );
+ }
+};
+
/**
* When the agent runs against the local machine, resolve this desktop's
* own gateway deviceId so it can be passed as the run's routing `deviceId` and
@@ -719,9 +739,10 @@ export class GatewayActionImpl {
hasInterruptedAfterPersistence = true;
// Cancel arrived after execAgentTask resolved β€” server task exists. Interrupt generation,
// but keep reconciling the persisted message before returning to the caller.
- aiAgentService
- .interruptTask({ operationId: result.operationId, topicId: result.topicId })
- .catch((err) => console.error('[Gateway] interruptTask after cancel failed:', err));
+ interruptGatewayTaskOrThrow({
+ operationId: result.operationId,
+ topicId: result.topicId,
+ }).catch((err) => console.error('[Gateway] interruptTask after cancel failed:', err));
}
return true;
@@ -902,12 +923,13 @@ export class GatewayActionImpl {
// When the local operation is cancelled (e.g. user clicks stop), forward
// the interrupt directly to the server via the existing tRPC endpoint.
// Closure captures `result.operationId` (the server-side id) so we don't
- // depend on any metadata lookup. Fire-and-forget β€” errors are logged but
- // never block the local cancel flow.
+ // depend on any metadata lookup. The returned promise preserves an
+ // unconfirmed device shutdown so Send now can keep its queued message.
this.#get().onOperationCancel(gatewayOpId, async () => {
- await aiAgentService
- .interruptTask({ operationId: result.operationId, topicId: result.topicId })
- .catch((err) => console.error('[Gateway] interruptTask failed:', err));
+ await interruptGatewayTaskOrThrow({
+ operationId: result.operationId,
+ topicId: result.topicId,
+ });
});
const eventHandler = createGatewayEventHandler(this.#get, {
@@ -1124,9 +1146,7 @@ export class GatewayActionImpl {
// Forward local-op cancellation to the server-side agent loop via tRPC.
// See note in executeGatewayAgent for details.
this.#get().onOperationCancel(gatewayOpId, async () => {
- await aiAgentService
- .interruptTask({ operationId })
- .catch((err) => console.error('[Gateway] interruptTask failed:', err));
+ await interruptGatewayTaskOrThrow({ operationId });
});
const eventHandler = createGatewayEventHandler(this.#get, {
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 27d10741a75..bc443ffd927 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -1991,8 +1991,15 @@ export const executeHeterogeneousAgent = async (
// framework calls this; we SIGINT the CC process via the main-process IPC
// so the CLI exits instead of running to completion off-screen.
const sidForCancel = ipcRunSessionId;
- get().onOperationCancel?.(operationId, () => {
- heterogeneousAgentService.cancelSession(sidForCancel).catch(() => {});
+ get().onOperationCancel?.(operationId, async () => {
+ try {
+ await heterogeneousAgentService.cancelSession(sidForCancel);
+ } catch (error) {
+ // Let the operation layer report an unconfirmed cancellation so a
+ // replacement turn cannot start while the native writer may still live.
+ console.error('[HeterogeneousAgent] IPC session cancellation failed:', error);
+ throw error;
+ }
});
// ─── Debug tracing (dev only) ───
diff --git a/src/store/chat/slices/operation/__tests__/actions.test.ts b/src/store/chat/slices/operation/__tests__/actions.test.ts
index c6aa9cae6f8..8e5fc92bd7b 100644
--- a/src/store/chat/slices/operation/__tests__/actions.test.ts
+++ b/src/store/chat/slices/operation/__tests__/actions.test.ts
@@ -974,6 +974,72 @@ describe('Operation Actions', () => {
});
describe('cancelOperation with cancel handler', () => {
+ /**
+ * @example Send-now can await cancellation before dispatching its replacement turn.
+ */
+ it('resolves only after the registered cancel handler completes', async () => {
+ const { result } = renderHook(() => useChatStore());
+ let releaseCancellation: (() => void) | undefined;
+ const handler = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ releaseCancellation = resolve;
+ }),
+ );
+ let operationId: string;
+
+ act(() => {
+ operationId = result.current.startOperation({
+ context: { agentId: 'session1' },
+ type: 'execServerAgentRuntime',
+ }).operationId;
+ result.current.onOperationCancel(operationId, handler);
+ });
+
+ let settled = false;
+ const cancellation = result.current.cancelOperation(operationId!, 'send_now').then(() => {
+ settled = true;
+ });
+ await Promise.resolve();
+
+ expect(result.current.operations[operationId!].status).toBe('cancelled');
+ expect(settled).toBe(false);
+
+ releaseCancellation?.();
+ await cancellation;
+
+ expect(settled).toBe(true);
+ });
+
+ /**
+ * @example A native process remains active after the cancellation request fails.
+ */
+ it('reports an unconfirmed cancellation when the transport handler rejects', async () => {
+ // ROOT CAUSE:
+ //
+ // Cancellation handler errors were logged and converted into a successful
+ // void result. QueueTray could not distinguish β€œwriter exited” from β€œthe
+ // shutdown attempt failed” before dispatching a replacement turn.
+ //
+ // Before: handler rejection resolved cancelOperation(undefined).
+ // After: handler rejection resolves false and restores the running blocker.
+ const { result } = renderHook(() => useChatStore());
+ const handlerError = new Error('native process still active');
+ let operationId: string;
+
+ act(() => {
+ operationId = result.current.startOperation({
+ context: { agentId: 'session1' },
+ type: 'execHeterogeneousAgent',
+ }).operationId;
+ result.current.onOperationCancel(operationId, () => Promise.reject(handlerError));
+ });
+
+ await expect(result.current.cancelOperation(operationId!, 'send_now')).resolves.toBe(false);
+ expect(result.current.operations[operationId!].status).toBe('running');
+ expect(result.current.operations[operationId!].metadata.cancelReason).toBeUndefined();
+ });
+
it('should call cancel handler when operation is cancelled', async () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.ts
index 71f8e03b61a..a8ca9e80b92 100644
--- a/src/store/chat/slices/operation/actions.ts
+++ b/src/store/chat/slices/operation/actions.ts
@@ -386,17 +386,34 @@ export class OperationActionsImpl {
);
};
- cancelOperation = (operationId: string, reason: string = 'User cancelled'): void => {
+ /**
+ * Cancels an operation and reports whether its transport shutdown was confirmed.
+ *
+ * Use when:
+ * - A caller needs to stop an operation and its child operations.
+ * - A replacement task must not start after a failed transport cancellation.
+ *
+ * Expects:
+ * - `operationId` may already be absent or terminal; those states are safe no-ops.
+ * - Registered cancel handlers reject when their underlying transport remains active.
+ *
+ * Returns:
+ * - `true` when every cancellation handler settled successfully, otherwise `false`.
+ */
+ cancelOperation = async (
+ operationId: string,
+ reason: string = 'User cancelled',
+ ): Promise<boolean> => {
const operation = this.#get().operations[operationId];
if (!operation) {
log('[cancelOperation] operation not found: %s', operationId);
- return;
+ return true;
}
// Skip if already cancelled or completed
if (operation.status === 'cancelled' || operation.status === 'completed') {
log('[cancelOperation] operation %s already %s, skipping', operationId, operation.status);
- return;
+ return true;
}
log(
@@ -421,7 +438,10 @@ export class OperationActionsImpl {
this.#get().updateOperationMetadata(operationId, { isAborting: true });
}
- // 3. Call cancel handler if registered
+ // 3. Call cancel handler if registered. The local state transition below
+ // remains synchronous, while callers such as Send now can await the returned
+ // promise before starting a replacement native writer.
+ let cancelHandler = Promise.resolve(true);
if (operation.onCancelHandler) {
log('[cancelOperation] calling cancel handler for %s (type=%s)', operationId, operation.type);
@@ -432,15 +452,21 @@ export class OperationActionsImpl {
metadata: operation.metadata,
};
- // Execute handler asynchronously (don't block cancellation flow)
- // Use try-catch to handle synchronous errors, then wrap in Promise for async errors
+ // Start the handler without delaying the synchronous local state transition.
+ // The returned cancellation promise still waits for this work so replacement
+ // operations can coordinate with the underlying transport shutdown.
try {
- Promise.resolve(operation.onCancelHandler(cancelContext)).catch((err) => {
- log('[cancelOperation] cancel handler error for %s: %O', operationId, err);
- });
+ cancelHandler = Promise.resolve(operation.onCancelHandler(cancelContext)).then(
+ () => true,
+ (err) => {
+ log('[cancelOperation] cancel handler error for %s: %O', operationId, err);
+ return false;
+ },
+ );
} catch (err) {
// Handle synchronous errors from handler
log('[cancelOperation] cancel handler synchronous error for %s: %O', operationId, err);
+ cancelHandler = Promise.resolve(false);
}
}
@@ -460,13 +486,37 @@ export class OperationActionsImpl {
n(`cancelOperation/${operationId}`),
);
- // 4. Cancel all child operations recursively
+ // 5. Cancel all child operations recursively
+ let childCancellations: Promise<boolean>[] = [];
if (operation.childOperationIds && operation.childOperationIds.length > 0) {
log('[cancelOperation] cancelling %d child operations', operation.childOperationIds.length);
- operation.childOperationIds.forEach((childId) => {
- this.#get().cancelOperation(childId, 'Parent operation cancelled');
- });
+ childCancellations = operation.childOperationIds.map((childId) =>
+ this.#get().cancelOperation(childId, 'Parent operation cancelled'),
+ );
}
+
+ const confirmations = await Promise.all([cancelHandler, ...childCancellations]);
+ const cancellationConfirmed = confirmations.every(Boolean);
+ if (cancellationConfirmed) return true;
+
+ // The native transport may still own resources even though the optimistic
+ // UI transition above marked the operation cancelled. Restore the blocker
+ // so another send cannot mistake an unconfirmed shutdown for an idle chat.
+ this.#set(
+ produce((state: ChatStore) => {
+ const op = state.operations[operationId];
+ if (!op || op.status !== 'cancelled' || op.metadata.cancelReason !== reason) return;
+
+ op.status = 'running';
+ delete op.metadata.cancelReason;
+ delete op.metadata.duration;
+ delete op.metadata.endTime;
+ }),
+ false,
+ n(`cancelOperationFailed/${operationId}`),
+ );
+
+ return false;
};
failOperation = (