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(desktop): confirm hetero cancellation when the app lost its task record (#19603)

Arvin Xu8fa80700de76
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index f29775d2258..7d175a61268 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -17,6 +17,7 @@ import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechat
import AuvService, { type AuvRunCommandParams } from '@/services/auvSrv';
import GatewayConnectionService from '@/services/gatewayConnectionSrv';
import ImessageBridgeService from '@/services/imessageBridgeSrv';
+import { findHeteroExecProcesses } from '@/utils/heteroExecProcess';
import { createLogger } from '@/utils/logger';
import { setDesktopUserAgentHeader } from '@/utils/user-agent';
@@ -28,6 +29,13 @@ import McpCtr from './McpCtr';
import RemoteServerConfigCtr from './RemoteServerConfigCtr';
import ShellCommandCtr from './ShellCommandCtr';
+/**
+ * How long an orphaned `hetero exec` group may take to exit after cancellation.
+ * Covers the 2s graceful window plus SIGKILL, and stays under the server's 10s
+ * `cancelHeteroTask` timeout.
+ */
+const ORPHAN_EXIT_TIMEOUT_MS = 5000;
+
const logger = createLogger('controllers:GatewayConnectionCtr');
const deviceProtocolHandler = createProtocolHandler('device');
@@ -1144,7 +1152,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
const entry = this.platformTasks.get(taskId);
if (!entry) {
- return JSON.stringify({ message: `No task found with taskId: ${taskId}`, success: false });
+ return JSON.stringify(await this.cancelUntrackedHeteroExec(taskId, signal as NodeJS.Signals));
}
// The close handler sends the terminal notify after the whole tree exits.
@@ -1153,6 +1161,68 @@ export default class GatewayConnectionCtr extends ControllerModule {
return JSON.stringify({ pid: entry.pid, signal, taskId });
}
+ /**
+ * Cancels an operation that neither in-memory registry knows about.
+ *
+ * Use when:
+ * - The desktop app restarted after dispatching `lh hetero exec`: the
+ * registries are empty, but the server keeps the task running until the
+ * device confirms `exited: true`.
+ *
+ * Expects:
+ * - `taskId` is the operation id passed as `--operation-id` to the wrapper.
+ *
+ * Returns:
+ * - `exited: true` only when the OS shows no wrapper for the operation, or
+ * after every orphaned wrapper group has exited.
+ * - `exited: false` when an orphan survives SIGKILL or the process table
+ * cannot be read, so a retry never races a live writer.
+ * - Windows keeps the previous unconfirmed answer; orphan lookup is Unix-only.
+ */
+ private async cancelUntrackedHeteroExec(
+ taskId: string,
+ signal: NodeJS.Signals,
+ ): Promise<Record<string, unknown>> {
+ if (process.platform === 'win32') {
+ return { message: `No task found with taskId: ${taskId}`, success: false };
+ }
+
+ let orphans: Awaited<ReturnType<typeof findHeteroExecProcesses>>;
+ try {
+ orphans = await findHeteroExecProcesses(taskId);
+ } catch (error) {
+ logger.warn('cancelHeteroTask: process lookup failed for %s: %O', taskId, error);
+ return {
+ exited: false,
+ message: `Could not inspect running processes for taskId: ${taskId}`,
+ reason: 'lookup_failed',
+ success: false,
+ taskId,
+ };
+ }
+
+ if (orphans.length === 0) {
+ return { exited: true, reason: 'not_found', success: true, taskId };
+ }
+
+ const pids = orphans.map((orphan) => orphan.pid);
+ logger.warn('cancelHeteroTask: terminating orphaned hetero exec for %s: %o', taskId, pids);
+
+ // The wrapper leads a detached group shared by its native agent child, so
+ // this reaches the whole writer tree and escalates to SIGKILL after 2s.
+ for (const pid of pids) this.killPlatformProcessTree(pid, signal);
+
+ const deadline = Date.now() + ORPHAN_EXIT_TIMEOUT_MS;
+ while (pids.some((pid) => this.isPlatformProcessGroupAlive(pid))) {
+ if (Date.now() >= deadline) {
+ return { exited: false, pids, reason: 'orphan_alive', signal, success: false, taskId };
+ }
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+
+ return { exited: true, pids, reason: 'orphan_terminated', signal, success: true, taskId };
+ }
+
/**
* Send a notify message to the server so the frontend receives agent output or
* a completion signal. Uses the tRPC agentNotify.notify endpoint directly —
diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
index ebf523df06b..d77bd783fc2 100644
--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
@@ -205,6 +205,12 @@ vi.mock('node:child_process', async (importOriginal) => {
return { ...actual, execFileSync: execFileSyncMock, spawn: spawnMock };
});
+const findHeteroExecProcessesMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@/utils/heteroExecProcess', () => ({
+ findHeteroExecProcesses: findHeteroExecProcessesMock,
+}));
+
vi.mock('@lobechat/heterogeneous-agents/scanHost', () => ({
resolveRemotePlatformCommand: resolveRemotePlatformCommandMock,
resolveRemotePlatformRuntime: resolveRemotePlatformRuntimeMock,
@@ -1248,15 +1254,17 @@ describe('GatewayConnectionCtr', () => {
// Simulate the child exiting normally.
mockChild.emit('exit', 0, null);
+ findHeteroExecProcessesMock.mockResolvedValueOnce([]);
- // After exit, cancelHeteroTask should report no task found.
+ // After exit, the registry no longer holds the task, so cancellation
+ // falls back to the OS process table and confirms nothing is running.
const cancelResult = await ctr['cancelHeteroTask']({
signal: 'SIGINT',
taskId: 'op-cleanup',
});
const parsed = JSON.parse(cancelResult);
- expect(parsed.success).toBe(false);
- expect(parsed.message).toContain('No task found');
+ expect(findHeteroExecProcessesMock).toHaveBeenCalledWith('op-cleanup');
+ expect(parsed).toMatchObject({ exited: true, reason: 'not_found', success: true });
});
it('keeps the process-group escalation after the wrapper exits', async () => {
@@ -1598,6 +1606,125 @@ describe('GatewayConnectionCtr', () => {
operationId: 'op-codex',
signal: 'SIGINT',
});
+ expect(findHeteroExecProcessesMock).not.toHaveBeenCalled();
+ expect(client.sendToolCallResponse).toHaveBeenCalledWith(
+ expect.objectContaining({
+ requestId: 'req-cancel-codex',
+ result: expect.objectContaining({
+ state: { exited: true, pid: 7777, signal: 'SIGINT', taskId: 'op-codex' },
+ success: true,
+ }),
+ }),
+ );
+ });
+
+ /**
+ * Regression: after a desktop restart both in-memory registries are empty.
+ * The server keeps the task stuck until the device confirms `exited: true`,
+ * so the device must ask the OS instead of answering "No task found".
+ */
+ describe('when neither registry knows the operation (app restarted)', () => {
+ it('confirms the exit when no hetero exec process is alive', async () => {
+ findHeteroExecProcessesMock.mockResolvedValueOnce([]);
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+
+ const parsed = JSON.parse(
+ await ctr['cancelHeteroTask']({ signal: 'SIGINT', taskId: 'op-restarted' }),
+ );
+
+ expect(findHeteroExecProcessesMock).toHaveBeenCalledWith('op-restarted');
+ expect(parsed).toEqual({
+ exited: true,
+ reason: 'not_found',
+ success: true,
+ taskId: 'op-restarted',
+ });
+ expect(killSpy).not.toHaveBeenCalled();
+ killSpy.mockRestore();
+ });
+
+ it('terminates an orphaned wrapper group and confirms only after it exits', async () => {
+ findHeteroExecProcessesMock.mockResolvedValueOnce([{ pid: 4242 }]);
+ const alive = new Set([4242]);
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation((pid, signal?) => {
+ const target = Math.abs(Number(pid));
+ if (signal === 0) {
+ if (!alive.has(target)) throw Object.assign(new Error('ESRCH'), { code: 'ESRCH' });
+ return true;
+ }
+ return true;
+ });
+
+ const pending = ctr['cancelHeteroTask']({ signal: 'SIGINT', taskId: 'op-orphaned' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(killSpy).toHaveBeenCalledWith(-4242, 'SIGINT');
+
+ // Still alive: the device must not confirm yet.
+ let settled = false;
+ void pending.then(() => {
+ settled = true;
+ });
+ await vi.advanceTimersByTimeAsync(500);
+ expect(settled).toBe(false);
+
+ alive.delete(4242);
+ await vi.advanceTimersByTimeAsync(100);
+ const parsed = JSON.parse(await pending);
+
+ expect(parsed).toEqual({
+ exited: true,
+ pids: [4242],
+ reason: 'orphan_terminated',
+ signal: 'SIGINT',
+ success: true,
+ taskId: 'op-orphaned',
+ });
+ expect(killSpy).not.toHaveBeenCalledWith(-4242, 'SIGKILL');
+ killSpy.mockRestore();
+ });
+
+ it('escalates and reports unconfirmed when the orphan will not die', async () => {
+ findHeteroExecProcessesMock.mockResolvedValueOnce([{ pid: 4343 }]);
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+
+ const pending = ctr['cancelHeteroTask']({ signal: 'SIGINT', taskId: 'op-stubborn' });
+ await vi.advanceTimersByTimeAsync(6000);
+ const parsed = JSON.parse(await pending);
+
+ expect(killSpy).toHaveBeenCalledWith(-4343, 'SIGINT');
+ expect(killSpy).toHaveBeenCalledWith(-4343, 'SIGKILL');
+ expect(parsed).toMatchObject({
+ exited: false,
+ pids: [4343],
+ reason: 'orphan_alive',
+ success: false,
+ taskId: 'op-stubborn',
+ });
+ killSpy.mockRestore();
+ });
+
+ it('does not claim an exit when the process table cannot be read', async () => {
+ findHeteroExecProcessesMock.mockRejectedValueOnce(new Error('spawn ps ENOENT'));
+
+ const parsed = JSON.parse(
+ await ctr['cancelHeteroTask']({ signal: 'SIGINT', taskId: 'op-no-ps' }),
+ );
+
+ expect(parsed).toMatchObject({ exited: false, reason: 'lookup_failed', success: false });
+ });
+
+ it('keeps the previous unconfirmed answer on Windows', async () => {
+ const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32');
+
+ const parsed = JSON.parse(
+ await ctr['cancelHeteroTask']({ signal: 'SIGINT', taskId: 'op-win' }),
+ );
+
+ expect(findHeteroExecProcessesMock).not.toHaveBeenCalled();
+ expect(parsed.success).toBe(false);
+ expect(parsed.exited).toBeUndefined();
+ platformSpy.mockRestore();
+ });
});
it('does not escalate cancellation after the process group is gone', async () => {
diff --git a/apps/desktop/src/main/utils/__tests__/heteroExecProcess.test.ts b/apps/desktop/src/main/utils/__tests__/heteroExecProcess.test.ts
new file mode 100644
index 00000000000..389d400fcf5
--- /dev/null
+++ b/apps/desktop/src/main/utils/__tests__/heteroExecProcess.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest';
+
+import { isHeteroExecCommandFor, parseHeteroExecProcesses } from '../heteroExecProcess';
+
+const OP = 'op_1789469228314_agt_wTVg1V72zhow_tpc_hLx07QnXKl3Y_Ft2WdCfP';
+
+describe('heteroExecProcess', () => {
+ it('matches the packaged desktop wrapper argv for the operation', () => {
+ expect(
+ isHeteroExecCommandFor(
+ `/Applications/LobeHub.app/Contents/MacOS/LobeHub /Applications/LobeHub.app/Contents/Resources/bin/lobe-cli.js hetero exec --type kimi-code --operation-id ${OP} --topic tpc_hLx07QnXKl3Y --render none --input-json - --cwd /tmp/work`,
+ OP,
+ ),
+ ).toBe(true);
+ expect(isHeteroExecCommandFor(`node lh.js hetero exec --operation-id=${OP}`, OP)).toBe(true);
+ });
+
+ it('ignores other operations, prefixes and non-exec commands', () => {
+ expect(isHeteroExecCommandFor(`lh hetero exec --operation-id ${OP}-2`, OP)).toBe(false);
+ expect(isHeteroExecCommandFor(`lh hetero exec --operation-id op_other`, OP)).toBe(false);
+ expect(isHeteroExecCommandFor(`lh topic view --operation-id ${OP}`, OP)).toBe(false);
+ expect(isHeteroExecCommandFor(`--operation-id ${OP} hetero exec`, OP)).toBe(false);
+ expect(isHeteroExecCommandFor('kimi-code', OP)).toBe(false);
+ expect(isHeteroExecCommandFor(`lh hetero exec --operation-id ${OP}`, '')).toBe(false);
+ });
+
+ it('parses ps output and skips the current process', () => {
+ const output = [
+ ` 85278 /Applications/LobeHub.app/Contents/MacOS/LobeHub lobe-cli.js hetero exec --type kimi-code --operation-id ${OP} --topic t`,
+ ' 85296 kimi-code ',
+ ` 100 node lh.js hetero exec --operation-id ${OP}`,
+ '',
+ ].join('\n');
+
+ expect(parseHeteroExecProcesses(output, OP, 100)).toEqual([{ pid: 85278 }]);
+ expect(parseHeteroExecProcesses(output, 'op_missing', 100)).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/utils/heteroExecProcess.ts b/apps/desktop/src/main/utils/heteroExecProcess.ts
new file mode 100644
index 00000000000..b978b188af3
--- /dev/null
+++ b/apps/desktop/src/main/utils/heteroExecProcess.ts
@@ -0,0 +1,89 @@
+import { execFile } from 'node:child_process';
+
+/** A live `lh hetero exec` wrapper process found in the OS process table. */
+export interface HeteroExecProcess {
+ pid: number;
+}
+
+/**
+ * Whether a process command line is an `lh hetero exec` wrapper for the given
+ * operation.
+ *
+ * The wrapper argv is the only OS-visible identity of a device run: the native
+ * agent child (e.g. `kimi-code`) carries no operation id, but it inherits the
+ * wrapper's detached process group, so signalling the wrapper's group reaches it.
+ */
+export const isHeteroExecCommandFor = (commandLine: string, operationId: string): boolean => {
+ if (!operationId) return false;
+
+ const tokens = commandLine.trim().split(/\s+/);
+ const execIndex = tokens.findIndex(
+ (token, index) => token === 'hetero' && tokens[index + 1] === 'exec',
+ );
+ if (execIndex < 0) return false;
+
+ for (let index = execIndex + 2; index < tokens.length; index++) {
+ if (tokens[index] === '--operation-id' && tokens[index + 1] === operationId) return true;
+ if (tokens[index] === `--operation-id=${operationId}`) return true;
+ }
+
+ return false;
+};
+
+/** Parses `ps -A -o pid=,args=` output into wrappers that belong to `operationId`. */
+export const parseHeteroExecProcesses = (
+ psOutput: string,
+ operationId: string,
+ selfPid: number = process.pid,
+): HeteroExecProcess[] => {
+ const processes: HeteroExecProcess[] = [];
+
+ for (const rawLine of psOutput.split('\n')) {
+ const line = rawLine.trimStart();
+ const separator = line.search(/\s/);
+ if (separator <= 0) continue;
+
+ const pidText = line.slice(0, separator);
+ if (!/^\d+$/.test(pidText)) continue;
+
+ const pid = Number(pidText);
+ if (!Number.isSafeInteger(pid) || pid <= 0 || pid === selfPid) continue;
+ if (!isHeteroExecCommandFor(line.slice(separator), operationId)) continue;
+
+ processes.push({ pid });
+ }
+
+ return processes;
+};
+
+/**
+ * Finds live `lh hetero exec` wrappers for an operation by asking the OS.
+ *
+ * Use when:
+ * - The in-memory registries have no record of the operation (for example after
+ * an app restart) and cancellation must know whether a writer is still alive.
+ *
+ * Expects:
+ * - A Unix host with `ps` (macOS, Linux). Callers must not use this on Windows.
+ *
+ * Returns:
+ * - The matching wrapper pids; an empty list when none is running.
+ * - Rejects when the process table cannot be read, so callers never mistake a
+ * failed lookup for a confirmed exit.
+ */
+export const findHeteroExecProcesses = (operationId: string): Promise<HeteroExecProcess[]> =>
+ new Promise((resolve, reject) => {
+ // `-ww` keeps long Electron + script paths from truncating the argv on macOS.
+ execFile(
+ 'ps',
+ ['-A', '-ww', '-o', 'pid=,args='],
+ { maxBuffer: 32 * 1024 * 1024, timeout: 3000, windowsHide: true },
+ (error, stdout) => {
+ if (error) {
+ reject(error);
+ return;
+ }
+ resolve(parseHeteroExecProcesses(String(stdout), operationId));
+ },
+ );
+ });