🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(heterogeneous-agent): support Devin CLI as a heterogeneous agent (#18554)
Coooolfanaacb88fba705
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.tsindex 3fb657b3763..26f6df67471 100644--- a/apps/cli/src/commands/hetero.test.ts+++ b/apps/cli/src/commands/hetero.test.ts@@ -5,6 +5,7 @@ import { PassThrough } from 'node:stream';import type { LocalHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';import { HETEROGENEOUS_AGENT_CONFIGS } from '@lobechat/heterogeneous-agents';+import { HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV } from '@lobechat/heterogeneous-agents/protocol';import type * as HeteroSpawn from '@lobechat/heterogeneous-agents/spawn';import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -125,6 +126,7 @@ describe('hetero exec command', () => {exitSpy.mockRestore();stdoutSpy.mockRestore();vi.restoreAllMocks();+ vi.unstubAllEnvs();});/** Build a fresh program with the hetero command registered. */@@ -219,6 +221,52 @@ describe('hetero exec command', () => {expect(call.operationId).toMatch(/^[0-9a-f-]{36}$/i);});+ it('keeps the agent in the detached wrapper process group when requested by dispatch', async () => {+ vi.stubEnv(HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV, '1');+ mockSpawnAgent.mockReturnValue(createFakeHandle());++ await runCmd(['hetero', 'exec', '--type', 'codex', '--prompt', 'do thing']);++ expect(mockSpawnAgent).toHaveBeenCalledWith(expect.objectContaining({ detached: false }));+ });++ it('does not duplicate Unix group signals inside an inherited wrapper group', async () => {+ vi.stubEnv(HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV, '1');+ let sigintHandler: (() => void) | undefined;+ vi.spyOn(process, 'on').mockImplementation(((event: string, listener: () => void) => {+ if (event === 'SIGINT') sigintHandler = listener;+ return process;+ }) as typeof process.on);++ let resolveExit:+ ((result: { code: number | null; signal: NodeJS.Signals | null }) => void) | undefined;+ const stderr = new PassThrough();+ setImmediate(() => stderr.end());+ const kill = vi.fn();+ mockSpawnAgent.mockResolvedValue({+ events: {+ [Symbol.asyncIterator]: () => ({+ next: async () => ({ done: true, value: undefined }),+ }),+ },+ exit: new Promise((resolve) => {+ resolveExit = resolve;+ }),+ kill,+ pid: 12_345,+ stderr,+ });++ const command = runCmd(['hetero', 'exec', '--type', 'codex', '--prompt', 'hi']);+ for (let i = 0; i < 20 && !sigintHandler; i += 1) await Promise.resolve();++ sigintHandler?.();+ expect(kill).not.toHaveBeenCalled();++ resolveExit?.({ code: null, signal: 'SIGINT' });+ await command;+ });+it('runs Qoder with its default command and forwards model and effort', async () => {mockSpawnAgent.mockReturnValue(createFakeHandle());@@ -273,6 +321,35 @@ describe('hetero exec command', () => {);});+ it('runs Devin through ACP with its selected model and native arguments', async () => {+ mockSpawnAgent.mockReturnValue(createFakeHandle());++ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'devin',+ '--prompt',+ 'do thing',+ '--model',+ 'claude-sonnet-4-6-thinking',+ '--agent-arg=--agent-type',+ '--agent-arg=coding',+ ]);++ expect(mockResolveHeteroSpawnCommand).toHaveBeenCalledWith('devin', undefined);+ expect(mockSpawnAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ agentType: 'devin',+ command: 'devin',+ extraArgs: ['--agent-type', 'coding', '--model', 'claude-sonnet-4-6-thinking'],+ initialModel: 'claude-sonnet-4-6-thinking',+ permissionMode: 'bypass',+ prompt: 'do thing',+ }),+ );+ });+it('runs TRAE Enterprise with ACP model selection and only native provider arguments', async () => {mockResolveHeteroSpawnCommand.mockResolvedValue({ command: 'traecli' });mockSpawnAgent.mockReturnValue(createFakeHandle());@@ -616,6 +693,33 @@ describe('hetero exec command', () => {);});+ it('passes an intervention bridge to server-ingest Devin runs', async () => {+ mockSpawnAgent.mockReturnValue(createFakeHandle());++ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'devin',+ '--prompt',+ 'do thing',+ '--topic',+ 'topic-1',+ '--operation-id',+ 'op-devin-server',+ '--render',+ 'none',+ ]);++ expect(mockSpawnAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ agentType: 'devin',+ askUserBridge: expect.objectContaining({ pending: expect.any(Function) }),+ permissionMode: 'bypass',+ }),+ );+ });+it('runs OpenCode with model, resume, and native args while ignoring effort and speed', async () => {mockSpawnAgent.mockReturnValue(createFakeHandle());diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.tsindex 7c86d3cca1d..fd5cadc61f9 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -12,6 +12,7 @@ import {} from '@lobechat/heterogeneous-agents';import { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';import { LobeBuiltinMcpServer } from '@lobechat/heterogeneous-agents/builtinMcp';+import { HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV } from '@lobechat/heterogeneous-agents/protocol';import { resolveHeteroSpawnCommand } from '@lobechat/heterogeneous-agents/resolveCliCommand';import type {AgentContentBlock,@@ -157,6 +158,7 @@ const buildExtraArgs = (...(options.effort ? ['--effort', options.effort] : []),]: options.type === 'cursor' ||+ options.type === 'devin' ||options.type === 'kimi-code' ||options.type === 'opencode' ||options.type === 'pi'@@ -504,6 +506,7 @@ const exec = async (options: ExecOptions): Promise<void> => {(agentType === 'claude-code' ||agentType === 'cursor' ||agentType === 'droid' ||+ agentType === 'devin' ||agentType === 'qoder') &&serverIngester) {@@ -512,6 +515,11 @@ const exec = async (options: ExecOptions): Promise<void> => {identifier: agentType === 'cursor' ? 'claude-code' : agentType,provider: agentType,});+ } else if (agentType === 'devin') {+ askBridge = new AskUserBridge(operationId, {+ identifier: 'devin',+ provider: 'devin',+ });} else {askServer = new LobeBuiltinMcpServer();await askServer.start();@@ -725,10 +733,17 @@ const exec = async (options: ExecOptions): Promise<void> => {return { code: 1, signal: null as NodeJS.Signals | null };});- // Ctrl-C → SIGINT to the child's process group.- // Repeated Ctrl-C escalates to SIGKILL.+ // Direct CLI runs own a detached child group and forward terminal signals.+ // Device-dispatched wrappers share their outer detached group, so the+ // gateway cancellation owner signals that group directly instead.+ const inheritsWrapperProcessGroup =+ process.platform !== 'win32' && process.env[HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV] === '1';let interrupted = false;const onSigint = () => {+ if (inheritsWrapperProcessGroup) {+ interrupted = true;+ return;+ }if (interrupted) {handle.kill('SIGKILL');return;@@ -738,7 +753,7 @@ const exec = async (options: ExecOptions): Promise<void> => {};const onSigterm = () => {interrupted = true;- handle.kill('SIGTERM');+ if (!inheritsWrapperProcessGroup) handle.kill('SIGTERM');};process.on('SIGINT', onSigint);process.on('SIGTERM', onSigterm);@@ -870,6 +885,10 @@ const exec = async (options: ExecOptions): Promise<void> => {// ENOENT on a stale global install. Custom commands are used verbatim.const resolvedCommand = await resolveHeteroSpawnCommand(agentType, options.command);const commandEnv = resolvedCommand.pathEnv ? { PATH: resolvedCommand.pathEnv } : undefined;+ // Devin ACP's `--permission-mode` is a global flag; default to bypass so+ // headless connected-device runs do not block on permission prompts. The mode+ // response must not overwrite the model selected by `initialModel`.+ const permissionMode = options.type === 'devin' ? 'bypass' : undefined;const first = await runOneAgent({@@ -877,14 +896,19 @@ const exec = async (options: ExecOptions): Promise<void> => {askUserBridge: askBridge,command: resolvedCommand.command,cwd: options.cwd || process.cwd(),+ detached: process.env[HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV] !== '1',env: commandEnv,extraArgs,+ permissionMode,// Device and sandbox executions are observed through the same gateway// stream as native server agents. Ask Claude Code for content-block// deltas so the current conversation receives text while the process is// running instead of seeing only the terminal assistant snapshot.includePartialMessages: options.type === 'claude-code',- initialModel: options.type === 'droid' || options.type === 'trae' ? options.model : undefined,+ initialModel:+ options.type === 'droid' || options.type === 'devin' || options.type === 'trae'+ ? options.model+ : undefined,operationId,prompt: resolved.prompt,resumeSessionId: options.resume,@@ -916,12 +940,16 @@ const exec = async (options: ExecOptions): Promise<void> => {askUserBridge: askBridge,command: resolvedCommand.command,cwd: options.cwd || process.cwd(),+ detached: process.env[HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV] !== '1',env: commandEnv,extraArgs,includePartialMessages: options.type === 'claude-code',initialModel:- options.type === 'droid' || options.type === 'trae' ? options.model : undefined,+ options.type === 'droid' || options.type === 'devin' || options.type === 'trae'+ ? options.model+ : undefined,operationId,+ permissionMode,prompt: resolved.resumeFallbackPrompt ?? resolved.prompt,uploadImage,// No resumeSessionId — start freshdiff --git a/apps/cli/src/daemon/taskRegistry.ts b/apps/cli/src/daemon/taskRegistry.tsindex 60103e1cd47..3bfdc87044a 100644--- a/apps/cli/src/daemon/taskRegistry.ts+++ b/apps/cli/src/daemon/taskRegistry.ts@@ -6,7 +6,12 @@ import { CLI_CONFIG_DIR_NAME } from '../constants/identity';export interface TaskEntry {agentId?: string;- agentType: 'hermes' | 'openclaw';+ /**+ * Heterogeneous agent type. Covers remote platform agents (`hermes`,+ * `openclaw`) and local CLI agents (`devin`, `claude-code`, `codex`, …)+ * dispatched through `lh connect` device gateway.+ */+ agentType: string;operationId: string;parentOperationId?: string;pid: number;diff --git a/apps/cli/src/device/agentRun.test.ts b/apps/cli/src/device/agentRun.test.tsindex e1e71877286..49e85cc14e1 100644--- a/apps/cli/src/device/agentRun.test.ts+++ b/apps/cli/src/device/agentRun.test.ts@@ -2,13 +2,24 @@ import { EventEmitter } from 'node:events';import { statSync } from 'node:fs';import os from 'node:os';+import { HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV } from '@lobechat/heterogeneous-agents/protocol';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { spawnHeteroAgentRun } from './agentRun';const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() }));+const { saveTaskMock, getTaskMock, removeTaskMock } = vi.hoisted(() => ({+ getTaskMock: vi.fn(),+ removeTaskMock: vi.fn(),+ saveTaskMock: vi.fn(),+}));vi.mock('node:child_process', () => ({ spawn: spawnMock }));+vi.mock('../daemon/taskRegistry', () => ({+ getTask: getTaskMock,+ removeTask: removeTaskMock,+ saveTask: saveTaskMock,+}));// `resolveHeteroSpawnCwd` stats the candidate directories; treat every path as// an existing directory unless a test says otherwise.vi.mock('node:fs', async (importOriginal) => {@@ -43,6 +54,9 @@ const baseParams = {describe('spawnHeteroAgentRun', () => {beforeEach(() => {vi.mocked(statSync).mockReturnValue(asDirectory);+ saveTaskMock.mockReset();+ getTaskMock.mockReset();+ removeTaskMock.mockReset();});afterEach(() => {@@ -86,11 +100,14 @@ describe('spawnHeteroAgentRun', () => {]);expect(opts).toMatchObject({cwd: '/work/dir',+ detached: true,env: expect.objectContaining({+ [HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV]: '1',LOBEHUB_ASSISTANT_MESSAGE_ID: 'asst',LOBEHUB_JWT: 'jwt-token',LOBEHUB_SERVER: 'https://app.lobehub.com',}),+ windowsHide: true,});expect(opts.env).not.toHaveProperty('LOBEHUB_WORKSPACE_ID');@@ -262,4 +279,76 @@ describe('spawnHeteroAgentRun', () => {]),);});++ // ─── Cancel regression: process registration ───+ // The connect daemon must register the spawned CLI child into the task+ // registry so `cancelHeteroTask` dispatched from the server can resolve it+ // by operationId and signal the whole process group.++ it('registers the spawned child PID into the task registry on spawn', async () => {+ const child = makeFakeChild();+ Object.defineProperty(child, 'pid', { value: 12345 });+ spawnMock.mockReturnValue(child);++ const ackPromise = spawnHeteroAgentRun({+ ...baseParams,+ agentType: 'devin',+ operationId: 'op-cancel-reg',+ topicId: 'tpc-cancel-reg',+ workspaceId: 'ws-reg',+ });+ child.emit('spawn');+ await ackPromise;++ expect(saveTaskMock).toHaveBeenCalledWith(+ expect.objectContaining({+ agentType: 'devin',+ operationId: 'op-cancel-reg',+ pid: 12345,+ taskId: 'op-cancel-reg',+ topicId: 'tpc-cancel-reg',+ workspaceId: 'ws-reg',+ }),+ );+ });++ it('removes the task registry entry on child exit when the PID still matches', async () => {+ const child = makeFakeChild();+ Object.defineProperty(child, 'pid', { value: 9988 });+ spawnMock.mockReturnValue(child);+ // The exit handler checks getTask to guard against stale exits clearing a+ // newer entry — simulate the registry still owning this PID.+ getTaskMock.mockReturnValue({ pid: 9988 });++ const ackPromise = spawnHeteroAgentRun({+ ...baseParams,+ operationId: 'op-exit-cleanup',+ });+ child.emit('spawn');+ await ackPromise;++ child.emit('exit', 0, null);++ expect(getTaskMock).toHaveBeenCalledWith('op-exit-cleanup');+ expect(removeTaskMock).toHaveBeenCalledWith('op-exit-cleanup');+ });++ it('does not remove the registry entry on exit when a newer PID replaced it', async () => {+ const child = makeFakeChild();+ Object.defineProperty(child, 'pid', { value: 7777 });+ spawnMock.mockReturnValue(child);+ // A newer run reused the same operationId with a different PID.+ getTaskMock.mockReturnValue({ pid: 8888 });++ const ackPromise = spawnHeteroAgentRun({+ ...baseParams,+ operationId: 'op-stale-exit',+ });+ child.emit('spawn');+ await ackPromise;++ child.emit('exit', 0, null);++ expect(removeTaskMock).not.toHaveBeenCalled();+ });});diff --git a/apps/cli/src/device/agentRun.ts b/apps/cli/src/device/agentRun.tsindex 9a0a689a34b..f8acb597c33 100644--- a/apps/cli/src/device/agentRun.ts+++ b/apps/cli/src/device/agentRun.ts@@ -2,10 +2,12 @@ import { spawn } from 'node:child_process';import {buildHeteroExecStdinPayload,+ HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV,type HeteroExecImageRef,} from '@lobechat/heterogeneous-agents/protocol';import { resolveHeteroSpawnCwd } from '@lobechat/heterogeneous-agents/workingDirectory';+import { getTask, removeTask, saveTask } from '../daemon/taskRegistry';import { registerAgentRun } from './agentRunRegistry';export interface SpawnHeteroAgentRunParams {@@ -134,11 +136,14 @@ export function spawnHeteroAgentRun(resolve(result);};+ let pid: number | undefined;const child = spawn(process.execPath, [...process.execArgv, ...cliArgs], {cwd: spawnCwd,+ detached: true,env: {...childEnv,...(assistantMessageId ? { LOBEHUB_ASSISTANT_MESSAGE_ID: assistantMessageId } : {}),+ [HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV]: '1',LOBEHUB_JWT: jwt,LOBEHUB_OPERATION_ID: operationId,LOBEHUB_SERVER: serverUrl,@@ -146,10 +151,29 @@ export function spawnHeteroAgentRun(...(workspaceId ? { LOBEHUB_WORKSPACE_ID: workspaceId } : {}),},stdio: ['pipe', 'inherit', 'inherit'],+ windowsHide: true,});child.once('spawn', () => {registerAgentRun(operationId, child);+ // Register the child into the task registry so `cancelHeteroTask`+ // dispatched from the server can resolve it by operationId and signal+ // the whole process group. `detached: true` places the CLI in its own+ // group; the inherited-group env contract keeps its agent descendants+ // in that same group without affecting the connect daemon.+ pid = child.pid;+ if (pid !== undefined) {+ saveTask({+ agentType,+ operationId,+ pid,+ startedAt: new Date().toISOString(),+ taskId: operationId,+ topicId,+ workspaceId,+ });+ }+// Only safe to write stdin once the process actually started.try {child.stdin?.write(stdinPayload);@@ -168,6 +192,12 @@ export function spawnHeteroAgentRun(});child.on('exit', (code, signal) => {+ // Only remove the registry entry if the exiting PID still owns this+ // task — a newer run that reused the same operationId must not be+ // cleared by a stale exit event.+ if (pid !== undefined && getTask(operationId)?.pid === pid) {+ removeTask(operationId);+ }logger?.info?.(`hetero exec exited (op=${operationId}) code=${code} signal=${signal}`);});});diff --git a/apps/cli/src/device/agentRunCancellation.test.ts b/apps/cli/src/device/agentRunCancellation.test.tsindex dfbe57aa8dc..d9d022db63d 100644--- a/apps/cli/src/device/agentRunCancellation.test.ts+++ b/apps/cli/src/device/agentRunCancellation.test.ts@@ -7,16 +7,30 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import { executeToolCall } from '../tools';import { spawnHeteroAgentRun } from './agentRun';-const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() }));+const { getTaskMock, removeTaskMock, saveTaskMock, spawnMock } = vi.hoisted(() => ({+ getTaskMock: vi.fn(),+ removeTaskMock: vi.fn(),+ saveTaskMock: vi.fn(),+ spawnMock: vi.fn(),+}));vi.mock('node:child_process', async (original) => ({...(await original<typeof ChildProcessModule>()),spawn: spawnMock,}));+vi.mock('../daemon/taskRegistry', () => ({+ getTask: getTaskMock,+ removeTask: removeTaskMock,+ saveTask: saveTaskMock,+}));const children: EventEmitter[] = [];afterEach(() => {for (const child of children.splice(0)) child.emit('close', 0, null);vi.useRealTimers();+ vi.restoreAllMocks();+ getTaskMock.mockReset();+ removeTaskMock.mockReset();+ saveTaskMock.mockReset();spawnMock.mockReset();});@@ -42,6 +56,39 @@ async function dispatch(operationId: string) {}describe('gateway-dispatched CLI agent cancellation', () => {+ it('prioritizes persisted process-group cancellation for a live dispatched wrapper', async () => {+ const child = await dispatch('cancel-live-group');+ getTaskMock.mockReturnValue({+ agentType: 'kimi-code',+ operationId: 'cancel-live-group',+ pid: 12345,+ startedAt: new Date().toISOString(),+ taskId: 'cancel-live-group',+ topicId: 'fixture-topic',+ });+ let groupAlive = true;+ const killSpy = vi.spyOn(process, 'kill').mockImplementation((pid, signal) => {+ if (pid !== -12345) return true;+ if (signal === 'SIGINT') {+ groupAlive = false;+ return true;+ }+ if (signal === 0 && !groupAlive) {+ throw Object.assign(new Error('process group exited'), { code: 'ESRCH' });+ }+ return true;+ });++ await expect(+ executeToolCall('cancelHeteroTask', JSON.stringify({ taskId: 'cancel-live-group' })),+ ).resolves.toMatchObject({+ success: true,+ state: { exited: true, pid: 12345 },+ });+ expect(killSpy).toHaveBeenCalledWith(-12345, 'SIGINT');+ expect(child.kill).not.toHaveBeenCalled();+ });+it('waits for the dispatched wrapper to close and returns structured exit confirmation', async () => {const child = await dispatch('cancel-live');let settled = false;diff --git a/apps/cli/src/tools/__tests__/heteroTask.test.ts b/apps/cli/src/tools/__tests__/heteroTask.test.tsindex 5b55d61a259..5d6f12cf94a 100644--- a/apps/cli/src/tools/__tests__/heteroTask.test.ts+++ b/apps/cli/src/tools/__tests__/heteroTask.test.ts@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTrpcClient } from '../../api/client';import { removeTask, saveTask } from '../../daemon/taskRegistry';-import { runHeteroTask } from '../heteroTask';+import { cancelHeteroTask, runHeteroTask } from '../heteroTask';// ─── Mocks ───@@ -691,3 +691,188 @@ describe('runHeteroTask (hermes)', () => {expect(fsState.content).toBeUndefined();});});++// ─── cancelHeteroTask: process-group kill regression ───+// When a local CLI agent (devin/claude-code/codex/…) is dispatched through+// `lh connect`, the spawned child runs in its own process group. The cancel+// handler must signal the whole group (negative PID) so the CLI wrapper, the+// ACP client, and any agent subprocesses all receive the signal — not just+// the top-level node wrapper.++describe('cancelHeteroTask (process-group kill)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ for (const key of Object.keys(taskStore)) delete taskStore[key];+ resetTrpcClientMock();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('signals the whole process group via negative PID on Unix', async () => {+ let groupAlive = true;+ const killSpy = vi.spyOn(process, 'kill').mockImplementation((_pid, signal) => {+ if (signal === 'SIGINT') groupAlive = false;+ if (signal === 0 && !groupAlive) {+ throw Object.assign(new Error('No such process'), { code: 'ESRCH' });+ }+ return true;+ });+ // Simulate a registered local CLI agent task.+ taskStore['op-cli-cancel'] = {+ agentType: 'devin',+ operationId: 'op-cli-cancel',+ pid: 4242,+ startedAt: new Date().toISOString(),+ taskId: 'op-cli-cancel',+ topicId: 'tpc-cli',+ };++ const result = await cancelHeteroTask({ signal: 'SIGINT', taskId: 'op-cli-cancel' });++ expect(killSpy).toHaveBeenCalledWith(-4242, 'SIGINT');+ expect(result).toEqual({+ exited: true,+ pid: 4242,+ signal: 'SIGINT',+ taskId: 'op-cli-cancel',+ });+ killSpy.mockRestore();+ });++ it('kills the persisted process tree with taskkill on Windows', async () => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('win32');+ let exitHandler: ((code: number) => void) | undefined;+ spawnMock.mockReturnValue({+ once: vi.fn((event: string, handler: (code: number) => void) => {+ if (event === 'exit') exitHandler = handler;+ }),+ });+ taskStore['op-windows-cancel'] = {+ agentType: 'codex',+ operationId: 'op-windows-cancel',+ pid: 4242,+ startedAt: new Date().toISOString(),+ taskId: 'op-windows-cancel',+ topicId: 'tpc-cli',+ };++ const cancellation = cancelHeteroTask({ signal: 'SIGINT', taskId: 'op-windows-cancel' });+ await vi.waitFor(() => expect(exitHandler).toBeDefined());+ exitHandler?.(0);++ await expect(cancellation).resolves.toEqual({+ exited: true,+ pid: 4242,+ signal: 'SIGINT',+ taskId: 'op-windows-cancel',+ });+ expect(spawnMock).toHaveBeenCalledWith('taskkill', ['/pid', '4242', '/T', '/F'], {+ stdio: 'ignore',+ windowsHide: true,+ });+ });++ it('still escalates after the wrapper exits and removes its registry entry', async () => {+ vi.useFakeTimers();+ let groupAlive = true;+ const killSpy = vi.spyOn(process, 'kill').mockImplementation((_pid, signal) => {+ if (signal === 'SIGKILL') groupAlive = false;+ if (signal === 0 && !groupAlive) {+ throw Object.assign(new Error('No such process'), { code: 'ESRCH' });+ }+ return true;+ });+ taskStore['op-cli-orphan'] = {+ agentType: 'devin',+ operationId: 'op-cli-orphan',+ pid: 4343,+ startedAt: new Date().toISOString(),+ taskId: 'op-cli-orphan',+ topicId: 'tpc-cli',+ };++ try {+ const cancellation = cancelHeteroTask({ signal: 'SIGINT', taskId: 'op-cli-orphan' });+ await Promise.resolve();+ removeTask('op-cli-orphan');+ await vi.advanceTimersByTimeAsync(2_000);+ const result = await cancellation;++ expect(killSpy).toHaveBeenCalledWith(-4343, 'SIGINT');+ expect(killSpy).toHaveBeenCalledWith(-4343, 'SIGKILL');+ expect(result).toEqual({+ exited: true,+ pid: 4343,+ signal: 'SIGINT',+ taskId: 'op-cli-orphan',+ });+ } finally {+ vi.useRealTimers();+ }+ });++ it('reports an unconfirmed cancellation when the group survives SIGKILL', async () => {+ vi.useFakeTimers();+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);+ taskStore['op-cli-stuck'] = {+ agentType: 'codex',+ operationId: 'op-cli-stuck',+ pid: 4444,+ startedAt: new Date().toISOString(),+ taskId: 'op-cli-stuck',+ topicId: 'tpc-cli',+ };++ try {+ const cancellation = cancelHeteroTask({ signal: 'SIGINT', taskId: 'op-cli-stuck' });+ await vi.advanceTimersByTimeAsync(5_100);++ await expect(cancellation).resolves.toEqual({+ exited: false,+ pid: 4444,+ signal: 'SIGINT',+ taskId: 'op-cli-stuck',+ });+ expect(killSpy).toHaveBeenCalledWith(-4444, 'SIGKILL');+ } finally {+ vi.useRealTimers();+ }+ });++ it('returns No task found when the task is not registered', async () => {+ const result = await cancelHeteroTask({ signal: 'SIGINT', taskId: 'op-missing' });++ expect(result).toEqual({+ message: 'No task found with taskId: op-missing',+ success: false,+ });+ });++ it('cleans up the registry and notifies when the process already exited', async () => {+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => {+ throw Object.assign(new Error('No such process'), { code: 'ESRCH' });+ });+ taskStore['op-gone'] = {+ agentType: 'claude-code',+ operationId: 'op-gone',+ pid: 5555,+ startedAt: new Date().toISOString(),+ taskId: 'op-gone',+ topicId: 'tpc-gone',+ };++ const result = await cancelHeteroTask({ signal: 'SIGINT', taskId: 'op-gone' });++ expect(removeTask).toHaveBeenCalledWith('op-gone');+ expect(notifyMutateMock).toHaveBeenCalledWith(expect.objectContaining({ topicId: 'tpc-gone' }));+ expect(result).toEqual({+ exited: true,+ pid: 5555,+ signal: 'SIGINT',+ taskId: 'op-gone',+ });+ killSpy.mockRestore();+ });+});diff --git a/apps/cli/src/tools/heteroTask.ts b/apps/cli/src/tools/heteroTask.tsindex bbe5f0d63cb..28946dc4364 100644--- a/apps/cli/src/tools/heteroTask.ts+++ b/apps/cli/src/tools/heteroTask.ts@@ -4,7 +4,12 @@ import os from 'node:os';import path from 'node:path';import type { RemoteHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';+import type {+ HeterogeneousAgentCancellationResult,+ HeterogeneousAgentCancellationSignal,+} from '@lobechat/heterogeneous-agents/protocol';import { resolveRemotePlatformRuntime } from '@lobechat/heterogeneous-agents/scanHost';+import { sleep } from '@lobechat/utils/sleep';import { getTrpcClient } from '../api/client';import { CLI_PRODUCT_NAME, resolveCliDirName } from '../constants/identity';@@ -81,10 +86,23 @@ export interface RunHeteroTaskParams {}export interface CancelHeteroTaskParams {- signal?: 'SIGINT' | 'SIGKILL' | 'SIGTERM';+ signal?: HeterogeneousAgentCancellationSignal;taskId: string;}+export interface CancelHeteroTaskResult extends HeterogeneousAgentCancellationResult {+ taskId: string;+}++export interface CancelHeteroTaskNotFoundResult {+ message: string;+ success: false;+}++const CANCEL_GRACE_MS = 2000;+const CANCEL_FORCE_MS = 3000;+const PROCESS_GROUP_POLL_MS = 50;+async function sendAutoNotify(topicId: string,taskId: string,@@ -415,24 +433,67 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<stringthrow new Error(`Unsupported agentType: ${agentType as string}`);}-export async function cancelHeteroTask(params: CancelHeteroTaskParams): Promise<string> {+function isUnixProcessGroupAlive(pid: number): boolean {+ try {+ process.kill(-pid, 0);+ return true;+ } catch (error) {+ return (error as NodeJS.ErrnoException).code !== 'ESRCH';+ }+}++async function waitForUnixProcessGroupExit(pid: number, timeoutMs: number): Promise<boolean> {+ const deadline = Date.now() + timeoutMs;+ while (isUnixProcessGroupAlive(pid)) {+ if (Date.now() >= deadline) return false;+ await sleep(PROCESS_GROUP_POLL_MS);+ }++ return true;+}++async function killWindowsProcessTree(pid: number): Promise<boolean> {+ return new Promise((resolve) => {+ const killer = spawn('taskkill', ['/pid', String(pid), '/T', '/F'], {+ stdio: 'ignore',+ windowsHide: true,+ });+ killer.once('error', () => resolve(false));+ killer.once('exit', (code) => resolve(code === 0));+ });+}++export async function cancelHeteroTask(+ params: CancelHeteroTaskParams,+): Promise<CancelHeteroTaskNotFoundResult | CancelHeteroTaskResult> {const { signal = 'SIGINT', taskId } = params;- const local = await cancelAgentRun(taskId, signal);- if (local) return JSON.stringify({ ...local, taskId, success: local.exited });const entry = getTask(taskId);if (!entry) {- return JSON.stringify({ message: `No task found with taskId: ${taskId}`, success: false });+ const local = await cancelAgentRun(taskId, signal);+ if (local) return { ...local, signal, taskId };+ return { message: `No task found with taskId: ${taskId}`, success: false };+ }++ // Kill the whole process group so the CLI wrapper, its inherited-group agent,+ // and tool subprocesses all receive the signal. `detached: true` at wrapper+ // spawn time made this negative-PID signal safe for the connect daemon. On+ // Windows there is no process-group signal, so use `taskkill /T /F`.+ if (process.platform === 'win32') {+ const exited = await killWindowsProcessTree(entry.pid);+ return { exited, pid: entry.pid, signal, taskId };}- // Both openclaw and hermes: kill by PID and let the child's close handler send the notify.try {- process.kill(entry.pid, signal);+ process.kill(-entry.pid, signal);} catch (err) {- // Process already exited — exit handler won't fire; clean up manually.+ const processGone = (err as NodeJS.ErrnoException).code === 'ESRCH';log.warn(`Failed to send ${signal} to pid ${entry.pid}: ${err instanceof Error ? err.message : String(err)}`,);+ if (!processGone) return { exited: false, pid: entry.pid, signal, taskId };++ // Process already exited — exit handler won't fire; clean up manually.removeTask(taskId);await sendAutoNotify(entry.topicId,@@ -442,7 +503,21 @@ export async function cancelHeteroTask(params: CancelHeteroTaskParams): Promise<entry.operationId,entry.workspaceId,);+ return { exited: true, pid: entry.pid, signal, taskId };+ }++ let exited = await waitForUnixProcessGroupExit(+ entry.pid,+ signal === 'SIGKILL' ? CANCEL_FORCE_MS : CANCEL_GRACE_MS,+ );+ if (!exited && signal !== 'SIGKILL') {+ try {+ process.kill(-entry.pid, 'SIGKILL');+ } catch {+ // The complete process group exited between the bounded wait and escalation.+ }+ exited = await waitForUnixProcessGroupExit(entry.pid, CANCEL_FORCE_MS);}- return JSON.stringify({ pid: entry.pid, signal, taskId });+ return { exited, pid: entry.pid, signal, taskId };}diff --git a/apps/cli/src/tools/index.test.ts b/apps/cli/src/tools/index.test.tsindex 31b1d289b1f..d6e2645240e 100644--- a/apps/cli/src/tools/index.test.ts+++ b/apps/cli/src/tools/index.test.ts@@ -125,6 +125,25 @@ describe('executeToolCall', () => {expect(result.error).toContain('Unknown tool API');});+ it('should expose cancellation confirmation as structured state', async () => {+ const result = await executeToolCall(+ 'cancelHeteroTask',+ JSON.stringify({ taskId: 'missing-operation' }),+ );++ expect(result).toEqual({+ content: JSON.stringify({+ message: 'No task found with taskId: missing-operation',+ success: false,+ }),+ state: {+ message: 'No task found with taskId: missing-operation',+ success: false,+ },+ success: false,+ });+ });+it('should carry structured state on file reads', async () => {const filePath = path.join(tmpDir, 'str.txt');await writeFile(filePath, 'content');diff --git a/apps/cli/src/tools/index.ts b/apps/cli/src/tools/index.tsindex d1ee7b9fcb3..52510c4618b 100644--- a/apps/cli/src/tools/index.ts+++ b/apps/cli/src/tools/index.ts@@ -71,8 +71,15 @@ export async function executeToolCall(const content = typeof result === 'string' ? result : JSON.stringify(result);if (apiName === 'cancelHeteroTask') {- const state = JSON.parse(content) as { success?: boolean };- return { content, state, success: state.success !== false };+ const state = (typeof result === 'string' ? JSON.parse(content) : result) as {+ exited?: boolean;+ success?: boolean;+ };+ return {+ content,+ state,+ success: state.success !== false && state.exited !== false,+ };}return { content, success: true };diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex 507ad1e78f5..b8729e18f89 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -1,4 +1,4 @@-import { execFileSync, spawn } from 'node:child_process';+import { type ChildProcess, execFileSync, spawn } from 'node:child_process';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';@@ -6,6 +6,7 @@ import path from 'node:path';import type { DeviceControlDeps } from '@lobechat/device-control';import type { AgentRunRequestMessage, GatewayMcpParams } from '@lobechat/device-gateway-client';import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';+import type { HeterogeneousAgentCancellationSignal } from '@lobechat/heterogeneous-agents/protocol';import type { RemotePlatformCommandRuntime } from '@lobechat/heterogeneous-agents/scanHost';import {resolveRemotePlatformCommand,@@ -127,7 +128,7 @@ const safeJsonParse = (input: string): unknown => {export default class GatewayConnectionCtr extends ControllerModule {static override readonly groupName = 'gatewayConnection';- /** In-memory registry for running platform agent tasks (openclaw / hermes). */+ /** In-memory registry for running hetero agent tasks (openclaw / hermes / local-cli dispatch). */private readonly platformTasks = new Map<string, PlatformTaskEntry>();private readonly platformTaskKillTimers = new Map<number, NodeJS.Timeout>();@@ -327,6 +328,30 @@ export default class GatewayConnectionCtr extends ControllerModule {systemContext: request.systemContext,topicId: request.topicId,workspaceId: request.ingestWorkspaceId ?? request.workspaceId,+ // Register the spawned CLI process so `cancelHeteroTask` (sent by the+ // server's `interruptTask` when the user clicks Stop) can find and kill+ // it by operationId. The entry is cleaned up on child exit below.+ onChildSpawned: (child: ChildProcess) => {+ const pid = child.pid;+ if (pid === undefined) return;+ const taskId = request.operationId;+ this.platformTasks.set(taskId, {+ agentType: request.agentType,+ operationId: request.operationId,+ pid,+ topicId: request.topicId,+ workspaceId: request.ingestWorkspaceId ?? request.workspaceId,+ });+ child.once('exit', () => {+ // Only clear if this exit belongs to the current entry — a+ // superseding run for the same operationId may have already+ // replaced it.+ const current = this.platformTasks.get(taskId);+ if (current?.pid === pid) {+ this.platformTasks.delete(taskId);+ }+ });+ },});} catch (err) {const reason = err instanceof Error ? err.message : String(err);@@ -1107,7 +1132,7 @@ export default class GatewayConnectionCtr extends ControllerModule {const { signal = 'SIGINT', taskId } = args;const localExec = await this.heterogeneousAgentCtr.cancelLhHeteroExec({operationId: taskId,- signal: signal as NodeJS.Signals,+ signal: signal as HeterogeneousAgentCancellationSignal,});if (localExec) {return JSON.stringify({ ...localExec, taskId });diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 6e24bcbc596..16828d0984f 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -27,16 +27,22 @@ import {resolveHeterogeneousAgentCommand,resolveHeterogeneousProviderBinding,} from '@lobechat/heterogeneous-agents';+import type { AskUserBridgeOptions } from '@lobechat/heterogeneous-agents/askUser';import { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';import type {LobeBuiltinMcpServer,McpToolResult,} from '@lobechat/heterogeneous-agents/builtinMcp';import { listHeterogeneousAgentModels } from '@lobechat/heterogeneous-agents/models';-import type { HeteroExecImageRef } from '@lobechat/heterogeneous-agents/protocol';+import type {+ HeteroExecImageRef,+ HeterogeneousAgentCancellationResult,+ HeterogeneousAgentCancellationSignal,+} from '@lobechat/heterogeneous-agents/protocol';import {buildHeteroExecStdinPayload,buildHeterogeneousPrompt,+ HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV,} from '@lobechat/heterogeneous-agents/protocol';import {CLAUDE_CODE_QUOTA_FRESH_MS,@@ -56,6 +62,8 @@ import {buildCodexAppServerThreadParams,buildCursorAcpArgs,buildCursorAcpPrompt,+ buildDevinAcpArgs,+ buildDevinAcpPrompt,buildDroidAcpArgs,buildDroidAcpPrompt,buildGrokAcpArgs,@@ -67,12 +75,14 @@ import {CodexThreadSession,createFileStoreImageUploader,CursorAcpSession,+ DevinAcpSession,DroidAcpSession,ensureClaudeCodeResumeTranscript,getCodexAppServerUnsupportedArgs,GrokAcpSession,isCodexAppServerCompatibilityError,isCursorAcpSessionNotFoundError,+ isDevinAcpSessionNotFoundError,isDroidAcpSessionNotFoundError,readCodexSessionModel,resolveCliSpawnPlan,@@ -91,6 +101,7 @@ import type {HeteroSessionImportMessage,ListHeterogeneousAgentModelsParams,} from '@lobechat/types';+import { sleep } from '@lobechat/utils/sleep';import { app as electronApp, BrowserWindow } from 'electron';import { isPlainObject } from 'es-toolkit';import semver from 'semver';@@ -363,6 +374,7 @@ interface AgentSession {command: string;cursorAcpSession?: CursorAcpSession;cwd?: string;+ devinAcpSession?: DevinAcpSession;droidAcpSession?: DroidAcpSession;env?: Record<string, string>;grokAcpSession?: GrokAcpSession;@@ -410,15 +422,7 @@ 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;-}+export type LhHeteroExecCancellationResult = HeterogeneousAgentCancellationResult;interface LhHeteroExecTask {cancellation?: Promise<LhHeteroExecCancellationResult>;@@ -426,6 +430,10 @@ interface LhHeteroExecTask {process: ChildProcess;}+interface InteractiveAcpSession {+ run: () => Promise<void>;+}+/*** External Agent Controller — manages external agent CLI processes via Electron IPC.*@@ -700,6 +708,33 @@ export default class HeterogeneousAgentCtr {};}+ private getDevinResumeError(+ error: unknown,+ session: AgentSession,+ ): HeterogeneousAgentSessionError | undefined {+ if (+ session.agentType !== 'devin' ||+ !session.resumeSessionId ||+ !isDevinAcpSessionNotFoundError(error)+ ) {+ return;+ }++ return {+ agentType: 'devin',+ code: HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,+ command: session.command,+ details: {+ code: error.rpcError.code,+ data: error.rpcError.data,+ },+ message: 'The saved Devin session could not be found, so a new conversation will start.',+ resumeSessionId: session.resumeSessionId,+ stderr: error.message,+ workingDirectory: session.cwd,+ };+ }+private getCliAuthRequiredError(error: unknown,session: AgentSession,@@ -727,7 +762,8 @@ export default class HeterogeneousAgentCtr {this.getCodexResumeError(error, session) ??this.getDroidResumeError(error, session) ??this.getGrokResumeError(error, session) ??- this.getCursorResumeError(error, session);+ this.getCursorResumeError(error, session) ??+ this.getDevinResumeError(error, session);if (resumeError) return resumeError;const authRequiredError = this.getCliAuthRequiredError(error, session);@@ -1126,7 +1162,7 @@ export default class HeterogeneousAgentCtr {private setupAcpInterventionForOp(operationId: string,sessionId: string,- provider: 'cursor' | 'droid',+ provider: NonNullable<AskUserBridgeOptions['provider']>,): {bridge: AskUserBridge;cleanup: () => Promise<void>;@@ -1562,6 +1598,10 @@ export default class HeterogeneousAgentCtr {return this.sendPromptWithDroidAcp(params, session);}+ if (session.agentType === 'devin') {+ return this.sendPromptWithDevinAcp(params, session);+ }+if (session.agentType === 'trae') {return this.sendPromptWithTraeAcp(params, session);}@@ -2198,18 +2238,97 @@ export default class HeterogeneousAgentCtr {});session.cursorAcpSession = cursorAcpSession;+ await this.runInteractiveAcpSession({+ acpSession: cursorAcpSession,+ activeSessionKey: 'cursorAcpSession',+ cleanup: intervention.cleanup,+ isResumeError: isCursorAcpSessionNotFoundError,+ session,+ stderrChunks,+ traceSession,+ transport: 'cursor-acp',+ });+ }++ private async sendPromptWithDroidAcp(+ params: SendPromptParams,+ session: AgentSession,+ ): Promise<void> {+ const cwd = this.resolveSessionWorkingDirectory(session);+ const spawnEnv = this.buildSessionSpawnEnv(session);+ const commandPath = session.resolvedCommandPath ?? this.resolveSessionCommand(session);+ const promptInput = buildHeterogeneousPrompt({+ imageList: params.imageList,+ prompt: params.prompt,+ systemContext: params.systemContext,+ });+ const prompt = await buildDroidAcpPrompt(promptInput, { cacheDir: this.fileCacheDir });+ const tracePayload = `${JSON.stringify(prompt)}\n`;+ const traceSession = await this.createCliTraceSession({+ cliArgs: buildDroidAcpArgs(session.args),+ cwd,+ imageList: params.imageList ?? [],+ session,+ stdinPayload: tracePayload,+ });+ void this.writeCliTraceFile(traceSession, 'stdin.txt', tracePayload);++ if (session.cancelledByUs) {+ await this.completeCancelledSessionBeforeLaunch(session);+ return;+ }++ const stderrChunks: string[] = [];+ const intervention = this.setupAcpInterventionForOp(+ params.operationId,+ session.sessionId,+ 'droid',+ );+ const droidAcpSession = new DroidAcpSession({+ args: session.args,+ askUserBridge: intervention.bridge,+ clientVersion: electronApp.getVersion(),+ commandPath,+ cwd,+ env: spawnEnv,+ initialModel: session.model,+ onEvents: async (events) => {+ for (const event of events) {+ this.broadcast('heteroAgentEvent', { event, sessionId: session.sessionId });+ }+ },+ onModel: (model) => {+ session.model = model;+ session.modelSource = 'droid-acp';+ },+ onRawMessage: (line) => this.appendCliTraceFile(traceSession, 'stdout.jsonl', line),+ onRuntimeStatus: (status) => this.broadcast('heteroAgentRuntimeStatus', status),+ onSessionId: (agentSessionId) => {+ session.agentSessionId = agentSessionId;+ },+ onStderr: (data) => {+ stderrChunks.push(data);+ return this.appendCliTraceFile(traceSession, 'stderr.log', data);+ },+ operationId: params.operationId,+ prompt,+ resumeSessionId: session.agentSessionId,+ sessionId: session.sessionId,+ });+ session.droidAcpSession = droidAcpSession;+try {- await cursorAcpSession.run();+ await droidAcpSession.run();void this.writeCliTraceJson(traceSession, 'exit.json', {finishedAt: new Date().toISOString(),- transport: 'cursor-acp',+ transport: 'droid-acp',});await this.flushCliTrace(traceSession);this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });} catch (error) {void this.writeCliTraceJson(traceSession, 'process-error.json', {message: this.getErrorMessage(error),- transport: 'cursor-acp',+ transport: 'droid-acp',});await this.flushCliTrace(traceSession);if (session.cancelledByUs) {@@ -2217,7 +2336,7 @@ export default class HeterogeneousAgentCtr {return;}const stderr = stderrChunks.join('').trim();- const errorForClassification = isCursorAcpSessionNotFoundError(error)+ const errorForClassification = isDroidAcpSessionNotFoundError(error)? error: stderr? new Error([this.getErrorMessage(error), stderr].filter(Boolean).join('\n'), {@@ -2234,11 +2353,11 @@ export default class HeterogeneousAgentCtr {});} finally {await intervention.cleanup();- if (session.cursorAcpSession === cursorAcpSession) session.cursorAcpSession = undefined;+ if (session.droidAcpSession === droidAcpSession) session.droidAcpSession = undefined;}}- private async sendPromptWithDroidAcp(+ private async sendPromptWithDevinAcp(params: SendPromptParams,session: AgentSession,): Promise<void> {@@ -2250,10 +2369,10 @@ export default class HeterogeneousAgentCtr {prompt: params.prompt,systemContext: params.systemContext,});- const prompt = await buildDroidAcpPrompt(promptInput, { cacheDir: this.fileCacheDir });+ const prompt = await buildDevinAcpPrompt(promptInput, { cacheDir: this.fileCacheDir });const tracePayload = `${JSON.stringify(prompt)}\n`;const traceSession = await this.createCliTraceSession({- cliArgs: buildDroidAcpArgs(session.args),+ cliArgs: buildDevinAcpArgs(session.args),cwd,imageList: params.imageList ?? [],session,@@ -2270,9 +2389,9 @@ export default class HeterogeneousAgentCtr {const intervention = this.setupAcpInterventionForOp(params.operationId,session.sessionId,- 'droid',+ 'devin',);- const droidAcpSession = new DroidAcpSession({+ const devinAcpSession = new DevinAcpSession({args: session.args,askUserBridge: intervention.bridge,clientVersion: electronApp.getVersion(),@@ -2287,7 +2406,7 @@ export default class HeterogeneousAgentCtr {},onModel: (model) => {session.model = model;- session.modelSource = 'droid-acp';+ session.modelSource = 'devin-acp';},onRawMessage: (line) => this.appendCliTraceFile(traceSession, 'stdout.jsonl', line),onRuntimeStatus: (status) => this.broadcast('heteroAgentRuntimeStatus', status),@@ -2303,20 +2422,51 @@ export default class HeterogeneousAgentCtr {resumeSessionId: session.agentSessionId,sessionId: session.sessionId,});- session.droidAcpSession = droidAcpSession;+ session.devinAcpSession = devinAcpSession;++ await this.runInteractiveAcpSession({+ acpSession: devinAcpSession,+ activeSessionKey: 'devinAcpSession',+ cleanup: intervention.cleanup,+ isResumeError: isDevinAcpSessionNotFoundError,+ session,+ stderrChunks,+ traceSession,+ transport: 'devin-acp',+ });+ }+ private async runInteractiveAcpSession({+ acpSession,+ activeSessionKey,+ cleanup,+ isResumeError,+ session,+ stderrChunks,+ traceSession,+ transport,+ }: {+ acpSession: InteractiveAcpSession;+ activeSessionKey: 'cursorAcpSession' | 'devinAcpSession' | 'traeAcpSession';+ cleanup?: () => Promise<void>;+ isResumeError?: (error: unknown) => boolean;+ session: AgentSession;+ stderrChunks: string[];+ traceSession: CliTraceSession | undefined;+ transport: 'cursor-acp' | 'devin-acp' | 'trae-acp';+ }): Promise<void> {try {- await droidAcpSession.run();+ await acpSession.run();void this.writeCliTraceJson(traceSession, 'exit.json', {finishedAt: new Date().toISOString(),- transport: 'droid-acp',+ transport,});await this.flushCliTrace(traceSession);this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });} catch (error) {void this.writeCliTraceJson(traceSession, 'process-error.json', {message: this.getErrorMessage(error),- transport: 'droid-acp',+ transport,});await this.flushCliTrace(traceSession);if (session.cancelledByUs) {@@ -2324,7 +2474,7 @@ export default class HeterogeneousAgentCtr {return;}const stderr = stderrChunks.join('').trim();- const errorForClassification = isDroidAcpSessionNotFoundError(error)+ const errorForClassification = isResumeError?.(error)? error: stderr? new Error([this.getErrorMessage(error), stderr].filter(Boolean).join('\n'), {@@ -2340,8 +2490,14 @@ export default class HeterogeneousAgentCtr {cause: error,});} finally {- await intervention.cleanup();- if (session.droidAcpSession === droidAcpSession) session.droidAcpSession = undefined;+ await cleanup?.();+ if (activeSessionKey === 'cursorAcpSession' && session.cursorAcpSession === acpSession) {+ session.cursorAcpSession = undefined;+ } else if (activeSessionKey === 'devinAcpSession' && session.devinAcpSession === acpSession) {+ session.devinAcpSession = undefined;+ } else if (activeSessionKey === 'traeAcpSession' && session.traeAcpSession === acpSession) {+ session.traeAcpSession = undefined;+ }}}@@ -2407,42 +2563,17 @@ export default class HeterogeneousAgentCtr {});session.traeAcpSession = traeAcpSession;- try {- await traeAcpSession.run();- void this.writeCliTraceJson(traceSession, 'exit.json', {- finishedAt: new Date().toISOString(),- transport: 'trae-acp',- });- await this.flushCliTrace(traceSession);- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });- } catch (error) {- void this.writeCliTraceJson(traceSession, 'process-error.json', {- message: this.getErrorMessage(error),- transport: 'trae-acp',- });- await this.flushCliTrace(traceSession);- if (session.cancelledByUs) {- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });- return;- }- const stderr = stderrChunks.join('').trim();- const errorForClassification = stderr- ? new Error([this.getErrorMessage(error), stderr].filter(Boolean).join('\n'), {- cause: error,- })- : error;- const sessionError = this.getSessionErrorPayload(errorForClassification, session);- this.broadcast('heteroAgentSessionError', {- error: sessionError,- sessionId: session.sessionId,- });- throw new Error(typeof sessionError === 'string' ? sessionError : sessionError.message, {- cause: error,- });- } finally {- await session.hostedProviderBinding?.cleanup();- if (session.traeAcpSession === traeAcpSession) session.traeAcpSession = undefined;- }+ await this.runInteractiveAcpSession({+ acpSession: traeAcpSession,+ activeSessionKey: 'traeAcpSession',+ cleanup: async () => {+ await session.hostedProviderBinding?.cleanup();+ },+ session,+ stderrChunks,+ traceSession,+ transport: 'trae-acp',+ });}private async verifyCodexSessionModel({@@ -2863,6 +2994,39 @@ export default class HeterogeneousAgentCtr {}}+ private isProcessGroupAlive(pid: number): boolean {+ try {+ process.kill(-pid, 0);+ return true;+ } catch (error) {+ return (error as NodeJS.ErrnoException).code !== 'ESRCH';+ }+ }++ private async waitForProcessTreeExit(+ task: LhHeteroExecTask,+ timeoutMs: number,+ ): Promise<boolean> {+ if (process.platform === 'win32') {+ 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;+ }+ if (!task.process.pid) return true;++ const deadline = Date.now() + timeoutMs;+ while (this.isProcessGroupAlive(task.process.pid)) {+ if (Date.now() >= deadline) return false;+ await sleep(50);+ }++ return true;+ }+/*** Waits for a spawned CLI process to release its OS process handle.*@@ -2929,6 +3093,10 @@ export default class HeterogeneousAgentCtr {if (!session) return;session.cancelledByUs = true;+ if (session.devinAcpSession) {+ session.devinAcpSession.interrupt();+ return;+ }if (session.grokAcpSession) {session.grokAcpSession.interrupt();return;@@ -2987,6 +3155,11 @@ export default class HeterogeneousAgentCtr {const session = this.sessions.get(params.sessionId);if (!session) return;+ if (session.devinAcpSession) {+ session.cancelledByUs = true;+ session.devinAcpSession.close();+ }+if (session.grokAcpSession) {session.cancelledByUs = true;session.grokAcpSession.close();@@ -3092,6 +3265,10 @@ export default class HeterogeneousAgentCtr {this.unlinkPendingInterventionConfigsSync();for (const [, session] of this.sessions) {session.hostedProviderBinding?.cleanupSync();+ if (session.devinAcpSession) {+ session.cancelledByUs = true;+ session.devinAcpSession.close();+ }if (session.grokAcpSession) {session.cancelledByUs = true;session.grokAcpSession.close();@@ -3177,6 +3354,12 @@ export default class HeterogeneousAgentCtr {topicId: string;/** Topic/run workspace — forwarded as `LOBEHUB_WORKSPACE_ID` for ingest. */workspaceId?: string;+ /**+ * Called once the child process has spawned (pid available). The caller+ * (gateway dispatcher) uses this to register the process so a later+ * `cancelHeteroTask` can kill it by operationId.+ */+ onChildSpawned?: (child: ChildProcess) => void;}): Promise<{ reason?: string; status: 'accepted' | 'rejected' }> {const {agentType,@@ -3186,6 +3369,7 @@ export default class HeterogeneousAgentCtr {imageList,jwt,operationId,+ onChildSpawned,prompt,resumeFallbackSystemContext,resumeSessionId,@@ -3250,6 +3434,7 @@ export default class HeterogeneousAgentCtr {...process.env,...buildProxyEnv(this.app.storeManager.get('networkProxy')),ELECTRON_RUN_AS_NODE: '1',+ [HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV]: '1',LOBEHUB_JWT: jwt,...(assistantMessageId ? { LOBEHUB_ASSISTANT_MESSAGE_ID: assistantMessageId } : {}),LOBEHUB_SERVER: serverUrl,@@ -3264,16 +3449,22 @@ export default class HeterogeneousAgentCtr {// Execute the CLI shipped with this desktop build. A bare `lh` would prefer// an older global install earlier on PATH, letting model discovery report a// capability that the actual execution runtime does not support.+ // `detached: true` puts the CLI in its own process group so+ // `killPlatformProcessTree(-pid, signal)` reaches the CLI and its children;+ // the inherited-group env contract prevents the inner agent from detaching+ // into a second, unreachable group.const child = spawn(process.execPath, [cliScript, ...args], {cwd: spawnCwd,+ detached: true,env,stdio: ['pipe', 'inherit', 'inherit'],+ windowsHide: true,});- // 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.+ // Keep the wrapper reachable by the gateway cancellation tool. Its pid is+ // also the inherited process-group id shared by the native agent and tool+ // descendants, so the gateway can confirm the complete writer tree exited+ // before a replacement turn starts.const exit = new Promise<void>((resolve) => {child.once('exit', () => resolve());child.once('error', () => resolve());@@ -3311,6 +3502,12 @@ export default class HeterogeneousAgentCtr {});child.once('spawn', () => {+ // Register the child with the gateway's platform task registry so a+ // later `cancelHeteroTask` (triggered by the user clicking Stop in the+ // web UI) can find and kill this process by operationId. Without this+ // the CLI keeps running after the user cancels — the server only marks+ // its own operation state as interrupted, never signalling the device.+ onChildSpawned?.(child);try {child.stdin.write(stdinPayload);child.stdin.end();@@ -3349,7 +3546,7 @@ export default class HeterogeneousAgentCtr {*/async cancelLhHeteroExec(params: {operationId: string;- signal?: NodeJS.Signals;+ signal?: HeterogeneousAgentCancellationSignal;}): Promise<LhHeteroExecCancellationResult | undefined> {const { operationId, signal = 'SIGINT' } = params;const task = this.lhHeteroExecTasks.get(operationId);@@ -3357,35 +3554,14 @@ export default class HeterogeneousAgentCtr {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);- }+ this.killProcessTree(task.process, signal);+ let exited = await this.waitForProcessTreeExit(task, 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);+ // The wrapper and native agent inherit one detached group. Escalate that+ // complete group instead of relying on a second wrapper-only SIGINT.+ this.killProcessTree(task.process, 'SIGKILL');+ exited = await this.waitForProcessTreeExit(task, 3000);}return { exited, pid: task.process.pid, signal };diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.tsindex 5454a9c6ee0..ebf523df06b 100644--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts@@ -1,5 +1,6 @@import type * as ChildProcessModule from 'node:child_process';import type * as CryptoModule from 'node:crypto';+import { EventEmitter } from 'node:events';import { deriveDeviceId, deriveScopedFallbackId } from '@lobechat/device-identity';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -1191,6 +1192,102 @@ describe('GatewayConnectionCtr', () => {status: 'rejected',});});++ // Regression: spawnLhHeteroExec must register its child process into+ // platformTasks so cancelHeteroTask (sent by the server's interruptTask+ // when the user clicks Stop) can find and kill it by operationId.+ // Without this the CLI keeps running after the user cancels.+ describe('agent run process registration', () => {+ it('registers the spawned child in platformTasks via onChildSpawned', async () => {+ let capturedOnChildSpawned: ((child: any) => void) | undefined;+ vi.mocked(mockHeterogeneousAgentCtr.spawnLhHeteroExec).mockImplementationOnce(+ (params: any) => {+ capturedOnChildSpawned = params.onChildSpawned;+ return Promise.resolve({ status: 'accepted' });+ },+ );++ const client = await connectAndOpen();+ client.simulateAgentRunRequest('devin', 'op-register');+ await vi.advanceTimersByTimeAsync(0);++ // Simulate the child process spawning — onChildSpawned is called by+ // HeterogeneousAgentImpl once the real child emits 'spawn'.+ const mockChild = new EventEmitter() as any;+ mockChild.pid = 12345;+ capturedOnChildSpawned?.(mockChild);++ // The process should now be registered under its operationId.+ const cancelResult = await ctr['cancelHeteroTask']({+ signal: 'SIGINT',+ taskId: 'op-register',+ });++ const parsed = JSON.parse(cancelResult);+ expect(parsed.pid).toBe(12345);+ expect(parsed.signal).toBe('SIGINT');+ expect(parsed.taskId).toBe('op-register');+ });++ it('cleans up platformTasks when the child exits', async () => {+ let capturedOnChildSpawned: ((child: any) => void) | undefined;+ vi.mocked(mockHeterogeneousAgentCtr.spawnLhHeteroExec).mockImplementationOnce(+ (params: any) => {+ capturedOnChildSpawned = params.onChildSpawned;+ return Promise.resolve({ status: 'accepted' });+ },+ );++ const client = await connectAndOpen();+ client.simulateAgentRunRequest('claude-code', 'op-cleanup');+ await vi.advanceTimersByTimeAsync(0);++ const mockChild = new EventEmitter() as any;+ mockChild.pid = 67890;+ capturedOnChildSpawned?.(mockChild);++ // Simulate the child exiting normally.+ mockChild.emit('exit', 0, null);++ // After exit, cancelHeteroTask should report no task found.+ 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');+ });++ it('keeps the process-group escalation after the wrapper exits', async () => {+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);+ let capturedOnChildSpawned: ((child: any) => void) | undefined;+ vi.mocked(mockHeterogeneousAgentCtr.spawnLhHeteroExec).mockImplementationOnce(+ (params: any) => {+ capturedOnChildSpawned = params.onChildSpawned;+ return Promise.resolve({ status: 'accepted' });+ },+ );++ const client = await connectAndOpen();+ client.simulateAgentRunRequest('devin', 'op-orphan');+ await vi.advanceTimersByTimeAsync(0);++ const mockChild = new EventEmitter() as any;+ mockChild.pid = 67900;+ capturedOnChildSpawned?.(mockChild);+ await ctr['cancelHeteroTask']({ signal: 'SIGINT', taskId: 'op-orphan' });++ // The wrapper honors SIGINT, while process.kill(-pid, 0) still reports+ // that a detached descendant remains in the process group.+ mockChild.emit('exit', null, 'SIGINT');+ await vi.advanceTimersByTimeAsync(2_000);++ expect(killSpy).toHaveBeenCalledWith(-67900, 'SIGINT');+ expect(killSpy).toHaveBeenCalledWith(-67900, 'SIGKILL');+ killSpy.mockRestore();+ });+ });});// ─── runHeteroTask ───diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex a9629a734c9..fae02f7f52f 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -7,6 +7,7 @@ import { PassThrough } from 'node:stream';import type { CodexQuotaSnapshot } from '@lobechat/electron-client-ipc';import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';+import { HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV } from '@lobechat/heterogeneous-agents/protocol';import { AcpRpcResponseError } from '@lobechat/heterogeneous-agents/spawn';// `electron` is mocked below; this binding is the mock object so tests can// flip `isPackaged` to exercise the packaged-build tracing gate.@@ -146,6 +147,10 @@ const {droidAcpSessionConstructMock,droidAcpSessionInterruptMock,droidAcpSessionRunMock,+ devinAcpSessionCloseMock,+ devinAcpSessionConstructMock,+ devinAcpSessionInterruptMock,+ devinAcpSessionRunMock,grokAcpSessionCloseMock,grokAcpSessionConstructMock,grokAcpSessionInterruptMock,@@ -176,6 +181,10 @@ const {droidAcpSessionConstructMock: vi.fn(),droidAcpSessionInterruptMock: vi.fn(),droidAcpSessionRunMock: vi.fn(),+ devinAcpSessionCloseMock: vi.fn(),+ devinAcpSessionConstructMock: vi.fn(),+ devinAcpSessionInterruptMock: vi.fn(),+ devinAcpSessionRunMock: vi.fn(),grokAcpSessionCloseMock: vi.fn(),grokAcpSessionConstructMock: vi.fn(),grokAcpSessionInterruptMock: vi.fn(),@@ -387,6 +396,54 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {}}+ class MockDevinAcpSession {+ constructor(private readonly options: any) {+ devinAcpSessionConstructMock(options);+ }++ close() {+ devinAcpSessionCloseMock();+ }++ interrupt() {+ devinAcpSessionInterruptMock();+ }++ async run() {+ if (devinAcpSessionRunMock.getMockImplementation()) {+ return devinAcpSessionRunMock(this.options);+ }+ const now = Date.now();+ this.options.onRuntimeStatus({+ activeTasks: [],+ lastEventAt: now,+ operationId: this.options.operationId,+ sessionId: this.options.sessionId,+ state: 'running',+ transport: 'devin-acp',+ });+ this.options.onSessionId('devin-session-1');+ this.options.onModel?.('claude-sonnet-4-6-thinking');+ await this.options.onEvents([+ {+ data: { stopReason: 'end_turn' },+ operationId: this.options.operationId,+ stepIndex: 0,+ timestamp: now,+ type: 'agent_runtime_end',+ },+ ]);+ this.options.onRuntimeStatus({+ activeTasks: [],+ lastEventAt: now,+ operationId: this.options.operationId,+ sessionId: this.options.sessionId,+ state: 'closed',+ transport: 'devin-acp',+ });+ }+ }+class MockTraeAcpSession {constructor(private readonly options: any) {traeAcpSessionConstructMock(options);@@ -480,6 +537,7 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {CodexThreadSession: MockCodexThreadSession,CursorAcpSession: MockCursorAcpSession,DroidAcpSession: MockDroidAcpSession,+ DevinAcpSession: MockDevinAcpSession,isCodexAppServerCompatibilityError: (error: Error) =>error.name === 'CodexAppServerConnectionError',GrokAcpSession: MockGrokAcpSession,@@ -597,6 +655,10 @@ describe('HeterogeneousAgentCtr', () => {cursorAcpSessionConstructMock.mockReset();cursorAcpSessionInterruptMock.mockReset();cursorAcpSessionRunMock.mockReset();+ devinAcpSessionCloseMock.mockReset();+ devinAcpSessionConstructMock.mockReset();+ devinAcpSessionInterruptMock.mockReset();+ devinAcpSessionRunMock.mockReset();grokAcpSessionCloseMock.mockReset();grokAcpSessionConstructMock.mockReset();grokAcpSessionInterruptMock.mockReset();@@ -1608,6 +1670,195 @@ describe('HeterogeneousAgentCtr', () => {});});+ describe('sendPrompt (devin ACP)', () => {+ beforeEach(() => {+ spawnCalls.length = 0;+ execFileMock.mockReset();+ });++ it('routes Devin through ACP and persists its native session and model', async () => {+ const send = vi.fn();+ mockGetAllWindows.mockReturnValue([+ {+ isDestroyed: () => false,+ webContents: { send },+ },+ ]);+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);+ const { sessionId } = await ctr.startSession({+ agentType: 'devin',+ args: ['--model', 'claude-sonnet-4-6-thinking'],+ command: 'devin',+ initialModel: 'claude-sonnet-4-6-thinking',+ resumeSessionId: 'devin-session-old',+ });++ await ctr.sendPrompt({+ operationId: 'op-devin',+ prompt: 'private user request',+ sessionId,+ systemContext: 'private selected workspace context',+ });++ expect(spawnCalls).toHaveLength(0);+ expect(devinAcpSessionConstructMock).toHaveBeenCalledWith(+ expect.objectContaining({+ args: ['--model', 'claude-sonnet-4-6-thinking'],+ askUserBridge: expect.any(Object),+ clientVersion: '1.0.0-test',+ commandPath: 'devin',+ cwd: FAKE_DESKTOP_PATH,+ initialModel: 'claude-sonnet-4-6-thinking',+ operationId: 'op-devin',+ prompt: [+ { text: 'private selected workspace context', type: 'text' },+ { text: 'private user request', type: 'text' },+ ],+ resumeSessionId: 'devin-session-old',+ sessionId,+ }),+ );+ await expect(ctr.getSessionInfo({ sessionId })).resolves.toEqual({+ agentSessionId: 'devin-session-1',+ });+ expect(send).toHaveBeenCalledWith(+ 'heteroAgentRuntimeStatus',+ expect.objectContaining({ state: 'running', transport: 'devin-acp' }),+ );+ expect(send).toHaveBeenCalledWith('heteroAgentSessionComplete', { sessionId });+ });++ it('forwards Devin permission choices through the intervention bridge', async () => {+ const send = vi.fn();+ mockGetAllWindows.mockReturnValue([+ {+ isDestroyed: () => false,+ webContents: { send },+ },+ ]);+ let receivedAnswer: unknown;+ devinAcpSessionRunMock.mockImplementation(async (options) => {+ receivedAnswer = await options.askUserBridge.pending({+ arguments: {+ questions: [+ {+ header: 'Permission required',+ multiSelect: false,+ options: [{ label: 'Allow' }, { label: 'Reject' }],+ question: 'Run tests?',+ },+ ],+ },+ toolCallId: 'devin-permission-1',+ });+ });+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);+ const { sessionId } = await ctr.startSession({ agentType: 'devin', command: 'devin' });+ const run = ctr.sendPrompt({ operationId: 'op-devin-question', prompt: 'work', sessionId });++ await vi.waitFor(() =>+ expect(send).toHaveBeenCalledWith(+ 'heteroAgentEvent',+ expect.objectContaining({+ event: expect.objectContaining({+ data: expect.objectContaining({+ identifier: 'devin',+ provider: 'devin',+ toolCallId: 'devin-permission-1',+ }),+ type: 'agent_intervention_request',+ }),+ sessionId,+ }),+ ),+ );+ await ctr.submitIntervention({+ operationId: 'op-devin-question',+ result: { 'Run tests?': 'Allow' },+ toolCallId: 'devin-permission-1',+ });+ await run;++ expect(receivedAnswer).toEqual({ result: { 'Run tests?': 'Allow' } });+ });++ it('classifies a missing resumed Devin ACP session', async () => {+ const send = vi.fn();+ mockGetAllWindows.mockReturnValue([+ {+ isDestroyed: () => false,+ webContents: { send },+ },+ ]);+ const missingSessionError = new AcpRpcResponseError('session/load', {+ code: -32_016,+ data: {+ 'cognition.ai/errorKind': 'session_not_found',+ 'cognition.ai/retryable': false,+ },+ message: 'Session not found',+ });+ devinAcpSessionRunMock.mockRejectedValue(missingSessionError);+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);+ const { sessionId } = await ctr.startSession({+ agentType: 'devin',+ command: 'devin',+ cwd: '/Users/fake/projects/repo',+ resumeSessionId: 'missing-devin-session',+ });++ await expect(+ ctr.sendPrompt({ operationId: 'op-devin-resume', prompt: 'continue', sessionId }),+ ).rejects.toThrow(+ 'The saved Devin session could not be found, so a new conversation will start.',+ );+ expect(send).toHaveBeenCalledWith('heteroAgentSessionError', {+ error: expect.objectContaining({+ agentType: 'devin',+ code: HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,+ command: 'devin',+ resumeSessionId: 'missing-devin-session',+ }),+ sessionId,+ });+ });++ it.each([+ ['cancelSession', devinAcpSessionInterruptMock],+ ['stopSession', devinAcpSessionCloseMock],+ ] as const)('%s delegates to the active Devin ACP session', async (action, expectedMock) => {+ let resolveRun: (() => void) | undefined;+ devinAcpSessionRunMock.mockImplementation(+ () =>+ new Promise<void>((resolve) => {+ resolveRun = resolve;+ }),+ );+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);+ const { sessionId } = await ctr.startSession({ agentType: 'devin', command: 'devin' });+ const run = ctr.sendPrompt({ operationId: 'op-devin', prompt: 'work', sessionId });+ await vi.waitFor(() => expect(devinAcpSessionConstructMock).toHaveBeenCalledOnce());++ await ctr[action]({ sessionId });++ expect(expectedMock).toHaveBeenCalledOnce();+ resolveRun?.();+ await run;+ });+ });+describe('sendPrompt (grok-build ACP)', () => {beforeEach(() => {spawnCalls.length = 0;@@ -3895,6 +4146,14 @@ describe('HeterogeneousAgentCtr', () => {runMock: cursorAcpSessionRunMock,useCodexAppServer: false,},+ {+ agentType: 'devin',+ command: 'devin',+ constructMock: devinAcpSessionConstructMock,+ label: 'Devin ACP',+ runMock: devinAcpSessionRunMock,+ useCodexAppServer: false,+ },{agentType: 'trae',command: 'traecli',@@ -4002,9 +4261,11 @@ describe('HeterogeneousAgentCtr', () => {'op-gateway',]);expect(spawnCall.options.cwd).toBe(process.cwd());+ expect(spawnCall.options.windowsHide).toBe(true);expect(spawnCall.options.env).toEqual(expect.objectContaining({ELECTRON_RUN_AS_NODE: '1',+ [HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV]: '1',LOBEHUB_ASSISTANT_MESSAGE_ID: 'asst-gateway',LOBEHUB_JWT: 'device-jwt',LOBEHUB_SERVER: 'https://server.example.com',@@ -4156,9 +4417,9 @@ describe('HeterogeneousAgentCtr', () => {});/**- * @example A replacement waits until operation A's wrapper exits before operation B starts.+ * @example A replacement waits until operation A's process group exits before operation B starts.*/- it('waits for the gateway CLI wrapper to exit when cancelling its operation', async () => {+ it('waits for the complete gateway CLI process group before confirming cancellation', async () => {// ROOT CAUSE://// Device-dispatched Codex wrappers were not registered by operation id, so@@ -4166,7 +4427,17 @@ describe('HeterogeneousAgentCtr', () => {// 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.+ // After: cancelLhHeteroExec signals the wrapper-owned process group and+ // resolves only after the complete group disappears.+ vi.useFakeTimers();+ let groupAlive = true;+ const killSpy = vi.spyOn(process, 'kill').mockImplementation((_pid, signal) => {+ if (signal === 'SIGKILL') groupAlive = false;+ if (signal === 0 && !groupAlive) {+ throw Object.assign(new Error('No such process'), { code: 'ESRCH' });+ }+ return true;+ });const proc = createGatewayCliProc();nextFakeProc = proc;const ctr = new HeterogeneousAgentCtr({@@ -4174,29 +4445,39 @@ describe('HeterogeneousAgentCtr', () => {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;+ try {+ 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(killSpy).toHaveBeenCalledWith(-4321, 'SIGINT');+ expect(cancellationSettled).toBe(false);++ // The wrapper can exit while a native agent or tool descendant remains.+ proc.emit('exit', 130, 'SIGINT');+ await vi.advanceTimersByTimeAsync(1950);+ expect(cancellationSettled).toBe(false);++ await vi.advanceTimersByTimeAsync(100);+ expect(killSpy).toHaveBeenCalledWith(-4321, 'SIGKILL');+ await expect(cancellation).resolves.toEqual({+ exited: true,+ pid: 4321,+ signal: 'SIGINT',});- 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',- });+ } finally {+ killSpy.mockRestore();+ vi.useRealTimers();+ }});});diff --git a/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts b/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.tsindex a48b840bbe4..b407b61cc24 100644--- a/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts+++ b/apps/desktop/src/main/modules/binaries/__tests__/cliAgentBinaries.test.ts@@ -343,6 +343,18 @@ describe('cliAgentBinaries', () => {});});+ it('detects Devin through the shared version probe', async () => {+ callExecFile('/Users/test/.local/bin/devin\n');+ callExecFile('devin 3000.4.25 (7e8e528a)');++ const { devinBinary } = await import('../cliAgentBinaries');+ await expect(devinBinary.detect()).resolves.toMatchObject({+ available: true,+ path: '/Users/test/.local/bin/devin',+ version: '3000.4.25',+ });+ });+it('detects the official TRAE CLI by its ACP capability', async () => {callExecFile('/Users/test/.local/bin/traecli\n');callExecFile('trae-cli version 0.120.52');diff --git a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.tsindex 2473ac287b3..83153b4e856 100644--- a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts+++ b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts@@ -104,6 +104,13 @@ export const droidBinary: BinarySpec = {priority: 3,};+export const devinBinary: BinarySpec = {+ description: 'Devin - Cognition agentic coding CLI',+ detect: () => detectHeterogeneousCliCommand('devin', 'devin'),+ name: 'devin',+ priority: 3,+};+/** xAI Grok Build CLI @see https://docs.x.ai/build/overview */export const grokBuildBinary: BinarySpec = {description: 'Grok Build - xAI agentic coding CLI',@@ -216,6 +223,7 @@ export const heterogeneousCliAgentBinaries = {'codex': codexBinary,'cursor': cursorBinary,'droid': droidBinary,+ 'devin': devinBinary,'grok-build': grokBuildBinary,'kimi-code': kimiCliBinary,'opencode': opencodeBinary,diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/devin.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/devin.test.tsnew file mode 100644index 00000000000..2ebc369da7d--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/devin.test.ts@@ -0,0 +1,11 @@+import { describe, expect, it } from 'vitest';++import { getHeterogeneousAgentDriver } from '../index';+import { devinDriver } from './devin';++describe('devinDriver', () => {+ it('is registered and routes prompts through the native ACP session', async () => {+ expect(getHeterogeneousAgentDriver('devin')).toBe(devinDriver);+ await expect(devinDriver.buildSpawnPlan({} as never)).rejects.toThrow('native ACP session');+ });+});diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/devin.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/devin.tsnew file mode 100644index 00000000000..0a1fdea2ecb--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/devin.ts@@ -0,0 +1,7 @@+import type { HeterogeneousAgentDriver } from '../types';++export const devinDriver: HeterogeneousAgentDriver = {+ async buildSpawnPlan() {+ throw new Error('Devin prompts must run through the native ACP session');+ },+};diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts b/apps/desktop/src/main/modules/heterogeneousAgent/index.tsindex e1bf4ca285a..0ef65d04a25 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/index.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/index.ts@@ -6,6 +6,7 @@ import { codeBuddyDriver } from './drivers/codeBuddy';import { codexDriver } from './drivers/codex';import { cursorDriver } from './drivers/cursor';import { droidDriver } from './drivers/droid';+import { devinDriver } from './drivers/devin';import { grokBuildDriver } from './drivers/grokBuild';import { kimiCodeDriver } from './drivers/kimiCode';import { opencodeDriver } from './drivers/opencode';@@ -21,6 +22,7 @@ const heterogeneousAgentDrivers = {'codex': codexDriver,'cursor': cursorDriver,'droid': droidDriver,+ 'devin': devinDriver,'grok-build': grokBuildDriver,'kimi-code': kimiCodeDriver,'opencode': opencodeDriver,diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.interruptTask.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.interruptTask.test.tsindex ebf0888a97d..bb8c48bbfd7 100644--- a/apps/server/src/routers/lambda/__tests__/aiAgent.interruptTask.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.interruptTask.test.ts@@ -29,6 +29,19 @@ vi.mock('@/server/services/aiChat', () => ({AiChatService: vi.fn().mockImplementation(() => ({})),}));+// Mock deviceGateway so we can assert cancelHeteroTask dispatches without a+// live device connection. Use vi.hoisted so the mock fn is available to the+// hoisted vi.mock factory.+const { mockExecuteToolCall } = vi.hoisted(() => ({+ mockExecuteToolCall: vi.fn(),+}));+vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: {+ executeToolCall: mockExecuteToolCall,+ },+ getScopedOnlineDevices: vi.fn(() => []),+}));+describe('aiAgentRouter.interruptTask', () => {let serverDB: LobeChatDatabase;let userId: string;@@ -43,6 +56,8 @@ describe('aiAgentRouter.interruptTask', () => {userId = await createTestUser(serverDB);mockInterruptOperation.mockReset();mockInterruptOperation.mockResolvedValue(true);+ mockExecuteToolCall.mockReset();+ mockExecuteToolCall.mockResolvedValue({ content: '{}', success: true });// Create test agentconst [agent] = await serverDB@@ -295,4 +310,95 @@ describe('aiAgentRouter.interruptTask', () => {expect(result.success).toBe(true);});});++ // Regression: previously only remote-task hetero types (openclaw / hermes)+ // triggered a `cancelHeteroTask` dispatch to the device. Local-cli types+ // (claude-code / codex / devin / trae / qoder) that also run on a remote+ // device via `dispatchAgentRun` were silently skipped — the UI showed+ // cancelled but the CLI process kept running. Now any hetero type with a+ // deviceId in the topic's runningOperation triggers the cancel dispatch.+ describe('device hetero cancel dispatch', () => {+ it.each(['devin', 'claude-code', 'codex', 'trae', 'qoder', 'openclaw', 'hermes'] as const)(+ 'dispatches cancelHeteroTask for %s running on a device',+ async (heteroType) => {+ // Seed topic.metadata.runningOperation with a device + heteroType so+ // interruptTask can resolve the target without a separate device lookup.+ await serverDB+ .update(topics)+ .set({+ metadata: {+ runningOperation: {+ assistantMessageId: 'asst-cancel-test',+ deviceId: 'device-1',+ deviceWorkspaceId: 'ws-device',+ heteroType,+ operationId: 'op-device-cancel',+ },+ },+ })+ .where(eq(topics.id, testTopicId));++ // Also point the thread's operationId at the same op so the router+ // resolves it without needing a separate operation row.+ await serverDB+ .update(threads)+ .set({ metadata: { operationId: 'op-device-cancel' } })+ .where(eq(threads.id, testThreadId));++ const caller = aiAgentRouter.createCaller(createTestContext());++ await caller.interruptTask({+ operationId: 'op-device-cancel',+ topicId: testTopicId,+ });++ expect(mockExecuteToolCall).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: 'device-1' }),+ expect.objectContaining({+ apiName: 'cancelHeteroTask',+ identifier: 'cancelHeteroTask',+ }),+ 10_000,+ );++ // The signal should be SIGINT (graceful) and taskId should match the+ // operationId so the device can look up the process.+ const [, toolCall] = mockExecuteToolCall.mock.calls[0];+ const args = JSON.parse(toolCall.arguments);+ expect(args.signal).toBe('SIGINT');+ expect(args.taskId).toBe('op-device-cancel');+ },+ );++ it('does not dispatch cancelHeteroTask when the operation has no deviceId', async () => {+ // runningOperation with heteroType but no deviceId — e.g. a cloud-sandbox+ // run that has no remote process to kill.+ await serverDB+ .update(topics)+ .set({+ metadata: {+ runningOperation: {+ assistantMessageId: 'asst-no-device',+ heteroType: 'devin',+ operationId: 'op-no-device',+ },+ },+ })+ .where(eq(topics.id, testTopicId));++ await serverDB+ .update(threads)+ .set({ metadata: { operationId: 'op-no-device' } })+ .where(eq(threads.id, testThreadId));++ const caller = aiAgentRouter.createCaller(createTestContext());++ await caller.interruptTask({+ operationId: 'op-no-device',+ topicId: testTopicId,+ });++ expect(mockExecuteToolCall).not.toHaveBeenCalled();+ });+ });});diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.tsindex e5603778e1f..a6715ff7ab4 100644--- a/apps/server/src/routers/lambda/device.ts+++ b/apps/server/src/routers/lambda/device.ts@@ -312,6 +312,7 @@ export const deviceRouter = router({'codebuddy','cursor','droid',+ 'devin','grok-build','opencode','pi',diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.tsindex ed301737bea..56a277df472 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts@@ -135,6 +135,7 @@ const topicMock = {appendRunningOperationChild: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-1', metadata: undefined }),findById: vi.fn().mockResolvedValue(undefined),+ patchRunningOperation: vi.fn().mockResolvedValue(true),settleRunningOperation: vi.fn().mockResolvedValue({ status: 'settled' }),releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),tryReserveTaskCallback: vi.fn().mockResolvedValue(true),@@ -235,6 +236,7 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>topicMock.appendRunningOperationChild.mockResolvedValue(true);topicMock.create.mockResolvedValue({ id: 'topic-1', metadata: undefined });topicMock.findById.mockResolvedValue(undefined);+ topicMock.patchRunningOperation.mockResolvedValue(true);topicMock.releaseTaskCallbackReservation.mockResolvedValue(undefined);topicMock.tryReserveTaskCallback.mockResolvedValue(true);topicMock.updateMetadata.mockResolvedValue(undefined);@@ -1839,6 +1841,29 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>expect(findRunningOpSeed()).toBeUndefined();});+ it('patches device info onto an isolation child without replacing the parent marker', async () => {+ heteroAgentConfig.agencyConfig = {+ boundDeviceId: 'device-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'claude-code' },+ } as any;++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { isolationThread: true, topicId: 'topic-1' },+ parentOperationId: 'parent-operation',+ prompt: 'run this callAgent child on the device',+ } as any);++ const childOperation = topicMock.appendRunningOperationChild.mock.calls.at(-1)?.[2];+ expect(topicMock.patchRunningOperation).toHaveBeenCalledWith(+ 'topic-1',+ childOperation.operationId,+ expect.objectContaining({ deviceId: 'device-1', heteroType: 'claude-code' }),+ );+ expect(findRunningOpSeed()).toBeUndefined();+ });+it('falls back to claiming the topic marker when the parent is not the current root (e.g. nested isolation chain)', async () => {topicMock.appendRunningOperationChild.mockResolvedValueOnce(false);diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.tsindex 6e91dc4982d..9dca4f82375 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts@@ -950,6 +950,26 @@ export const dispatchHeteroAgent = async (userMessageId: userMessageId ?? parentMessageId ?? '',};}++ // Local CLI hetero agents dispatch to a device just like remote platform+ // agents, so persist the device route after the dispatch is accepted.+ // interruptTask uses these fields to find and stop the native process.+ try {+ const patched = await deps.topicModel.patchRunningOperation(topicId, operationId, {+ deviceId: dispatchDeviceId,+ deviceWorkspaceId: dispatchWorkspaceId,+ heteroType,+ });+ log(+ 'execAgent: patch runningOperation device info=%s deviceId=%s heteroType=%s op=%s',+ patched,+ dispatchDeviceId,+ heteroType,+ operationId,+ );+ } catch (err) {+ log('execAgent: failed to patch runningOperation with device info: %O', err);+ }} else {if (!supportsCloudHeterogeneousSandbox(heteroType)) {const message = `${getHeterogeneousAgentTitle(heteroType)} requires a local or connected device; cloud sandbox execution is not supported.`;diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex 6628f5560f5..54d6c3db999 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -513,7 +513,16 @@ export class DeviceGateway {deviceId: string;env?: Record<string, string>;timeout?: number;- type: 'codebuddy' | 'cursor' | 'droid' | 'grok-build' | 'opencode' | 'pi' | 'qoder' | 'trae';+ type:+ | 'codebuddy'+ | 'cursor'+ | 'devin'+ | 'droid'+ | 'grok-build'+ | 'opencode'+ | 'pi'+ | 'qoder'+ | 'trae';userId: string;workspaceId?: string;}): Promise<HeterogeneousAgentModelCatalog> {diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.tsindex f059beb7d2b..cc95afa564f 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts@@ -301,6 +301,7 @@ const INTERVENTION_KINDS = new Set<AgentInterventionInteractionKind>([const INTERVENTION_PROVIDERS = new Set<AgentInterventionProvider>(['claude-code','cursor',+ 'devin','droid','qoder',]);diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.tsindex cae76f1cb7a..524520884ed 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.eventBranches.test.ts@@ -1224,9 +1224,9 @@ describe('HeterogeneousPersistenceHandler — event branch coverage', () => {],}),deadline: 1_900_000_000_000,- identifier: 'claude-code',+ identifier: 'devin',interactionKind: 'permission',- provider: 'cursor',+ provider: 'devin',toolCallId: 'permission-1',});@@ -1263,7 +1263,7 @@ describe('HeterogeneousPersistenceHandler — event branch coverage', () => {type: 'permission',},interactionKind: 'permission',- provider: 'cursor',+ provider: 'devin',sourceRef: {operationId: 'op-test',toolCallId: 'permission-1',diff --git a/apps/server/src/services/verify/__tests__/modelConfig.test.ts b/apps/server/src/services/verify/__tests__/modelConfig.test.tsindex 0e9ca9b8cd4..c04e3ce6811 100644--- a/apps/server/src/services/verify/__tests__/modelConfig.test.ts+++ b/apps/server/src/services/verify/__tests__/modelConfig.test.ts@@ -1,4 +1,8 @@import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import {+ LOCAL_HETEROGENEOUS_AGENT_TYPES,+ REMOTE_HETEROGENEOUS_AGENT_CONFIGS,+} from '@lobechat/types';import { beforeEach, describe, expect, it, vi } from 'vitest';import {@@ -29,10 +33,14 @@ describe('resolveVerifyModelConfig', () => {});it('recognizes heterogeneous providers that cannot run Verify LLM calls', () => {- expect(isHeterogeneousVerifyProvider('claude-code')).toBe(true);- expect(isHeterogeneousVerifyProvider('codex')).toBe(true);- expect(isHeterogeneousVerifyProvider('cursor')).toBe(true);- expect(isHeterogeneousVerifyProvider('droid')).toBe(true);+ const heterogeneousProviders = [+ ...LOCAL_HETEROGENEOUS_AGENT_TYPES,+ ...REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type),+ ];++ for (const provider of heterogeneousProviders) {+ expect(isHeterogeneousVerifyProvider(provider)).toBe(true);+ }expect(isHeterogeneousVerifyProvider('openai')).toBe(false);expect(isHeterogeneousVerifyProvider(null)).toBe(false);});@@ -60,25 +68,28 @@ describe('resolveVerifyModelConfig', () => {expect(getBuiltinAgentMock).not.toHaveBeenCalled();});- it('falls back to the builtin verify agent model for a heterogeneous parent', async () => {- getAgentModelConfigMock- // 1st call: no pinned verifier (undefined → not called), so the mock- // queue starts at the builtin slug lookup.- .mockResolvedValueOnce({- model: 'deepseek-v4-pro',- provider: 'lobehub',- });-- await expect(- resolveVerifyModelConfig(db, 'u', {- parentModel: 'claude-opus-4-8',- parentProvider: 'claude-code',- }),- ).resolves.toEqual({ model: 'deepseek-v4-pro', provider: 'lobehub' });-- expect(getBuiltinAgentMock).toHaveBeenCalledWith(BUILTIN_AGENT_SLUGS.verifyAgent);- expect(getAgentModelConfigMock).toHaveBeenCalledWith(BUILTIN_AGENT_SLUGS.verifyAgent);- });+ it.each(['claude-code', 'devin'])(+ 'filters a %s parent and falls back to the builtin verifier model',+ async (parentProvider) => {+ getAgentModelConfigMock+ // 1st call: no pinned verifier (undefined → not called), so the mock+ // queue starts at the builtin slug lookup.+ .mockResolvedValueOnce({+ model: 'deepseek-v4-pro',+ provider: 'lobehub',+ });++ await expect(+ resolveVerifyModelConfig(db, 'u', {+ parentModel: 'claude-opus-4-8',+ parentProvider,+ }),+ ).resolves.toEqual({ model: 'deepseek-v4-pro', provider: 'lobehub' });++ expect(getBuiltinAgentMock).toHaveBeenCalledWith(BUILTIN_AGENT_SLUGS.verifyAgent);+ expect(getAgentModelConfigMock).toHaveBeenCalledWith(BUILTIN_AGENT_SLUGS.verifyAgent);+ },+ );/*** Regression: the resolver used to inherit the parent run's model, so thediff --git a/apps/server/src/services/verify/modelConfig.ts b/apps/server/src/services/verify/modelConfig.tsindex c033ade7be6..80c930f01a6 100644--- a/apps/server/src/services/verify/modelConfig.ts+++ b/apps/server/src/services/verify/modelConfig.ts@@ -5,6 +5,10 @@ import {DEFAULT_VERIFY_MODEL,DEFAULT_VERIFY_PROVIDER,} from '@lobechat/business-const';+import {+ LOCAL_HETEROGENEOUS_AGENT_TYPES,+ REMOTE_HETEROGENEOUS_AGENT_CONFIGS,+} from '@lobechat/types';import { AgentModel } from '@/database/models/agent';import type { LobeChatDatabase } from '@/database/type';@@ -20,15 +24,9 @@ interface ResolveVerifyModelConfigParams {verifierAgentId?: string | null;}-const HETEROGENEOUS_PROVIDER_IDS = new Set([- 'amp',- 'claude-code',- 'codex',- 'cursor',- 'droid',- 'hermes',- 'opencode',- 'openclaw',+const HETEROGENEOUS_PROVIDER_IDS = new Set<string>([+ ...LOCAL_HETEROGENEOUS_AGENT_TYPES,+ ...REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type),]);export const isHeterogeneousVerifyProvider = (provider?: string | null): boolean =>diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 6b86a862f2c..aefe97e93df 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -231,6 +231,7 @@"connectAgent.providerDesc.codebuddy": "Tencent coding agent CLI","connectAgent.providerDesc.codex": "OpenAI coding agent CLI","connectAgent.providerDesc.cursor": "Cursor coding agent CLI",+ "connectAgent.providerDesc.devin": "Cognition coding agent CLI","connectAgent.providerDesc.droid": "Factory coding agent CLI","connectAgent.providerDesc.grok-build": "xAI coding agent CLI","connectAgent.providerDesc.hermes": "Personal agent platform",@@ -328,6 +329,15 @@"desktopNotification.aiReplyCompleted.title": "Reply completed","desktopNotification.humanApprovalRequired.body": "An Agent needs your approval to continue","desktopNotification.humanApprovalRequired.title": "Approval required",+ "devinInstallGuide.actions.openDocs": "Open Install Guide",+ "devinInstallGuide.actions.openSystemTools": "Open System Tools",+ "devinInstallGuide.afterInstall": "After installing, run `devin auth login`, then retry your message or click Re-detect in System Tools.",+ "devinInstallGuide.desc": "Devin needs the Devin CLI to run locally. Install it and make sure the `devin` command is available in your PATH.",+ "devinInstallGuide.installWithBrew": "Windows PowerShell",+ "devinInstallGuide.installWithNpm": "macOS / Linux / WSL",+ "devinInstallGuide.menuNotification.title": "Devin CLI not found",+ "devinInstallGuide.reason": "LobeHub could not start Devin: {{message}}",+ "devinInstallGuide.title": "Install Devin CLI","dm.placeholder": "Your private messages with {{agentTitle}} will appear here.","dm.tooltip": "Send a private message","dm.visibleTo": "Visible to {{target}} only",@@ -1257,6 +1267,7 @@"newCodeBuddyAgent": "Add CodeBuddy","newCodexAgent": "Add Codex","newCursorAgent": "Add Cursor",+ "newDevinAgent": "Add Devin","newDroidAgent": "Add Factory Droid","newGrokBuildAgent": "Add Grok Build","newGroupChat": "Create Group",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex fbae83b4edd..b343bf88935 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -231,6 +231,7 @@"connectAgent.providerDesc.codebuddy": "腾讯编码助理 CLI","connectAgent.providerDesc.codex": "OpenAI 编码助理 CLI","connectAgent.providerDesc.cursor": "Cursor 编码助理 CLI",+ "connectAgent.providerDesc.devin": "Cognition 编码助理 CLI","connectAgent.providerDesc.droid": "Factory 编码助理 CLI","connectAgent.providerDesc.grok-build": "xAI 编码助理 CLI","connectAgent.providerDesc.hermes": "个人助理平台",@@ -328,6 +329,15 @@"desktopNotification.aiReplyCompleted.title": "AI 回复完成","desktopNotification.humanApprovalRequired.body": "Agent 需要你的批准后才能继续","desktopNotification.humanApprovalRequired.title": "需要你的批准",+ "devinInstallGuide.actions.openDocs": "打开安装指南",+ "devinInstallGuide.actions.openSystemTools": "打开系统工具",+ "devinInstallGuide.afterInstall": "安装完成后,请运行 `devin auth login` 登录,然后重试刚才的消息,或在系统工具中点击“重新检测”。",+ "devinInstallGuide.desc": "Devin 需要在本地运行 Devin CLI。请安装它,并确保 `devin` 命令在您的 PATH 中可用。",+ "devinInstallGuide.installWithBrew": "Windows PowerShell",+ "devinInstallGuide.installWithNpm": "macOS / Linux / WSL",+ "devinInstallGuide.menuNotification.title": "未找到 Devin CLI",+ "devinInstallGuide.reason": "LobeHub 无法启动 Devin:{{message}}",+ "devinInstallGuide.title": "安装 Devin CLI","dm.placeholder": "你与 {{agentTitle}} 的私信会显示在这里。","dm.tooltip": "发送私信","dm.visibleTo": "仅 {{target}} 可见",@@ -1257,6 +1267,7 @@"newCodeBuddyAgent": "添加 CodeBuddy","newCodexAgent": "添加 Codex","newCursorAgent": "添加 Cursor",+ "newDevinAgent": "添加 Devin","newDroidAgent": "添加 Factory Droid","newGrokBuildAgent": "添加 Grok Build","newGroupChat": "创建群组",diff --git a/packages/agent-gateway-client/src/intervention.test.ts b/packages/agent-gateway-client/src/intervention.test.tsindex aca57900b8d..93b425e5bc7 100644--- a/packages/agent-gateway-client/src/intervention.test.ts+++ b/packages/agent-gateway-client/src/intervention.test.ts@@ -210,4 +210,12 @@ describe('sanitizeAgentInterventionRequestForReview', () => {sanitizeAgentInterventionRequestForReview(request({ interactionKind: undefined })),).toBeUndefined();});++ it('accepts Devin as a durable intervention provider', () => {+ const sanitized = sanitizeAgentInterventionRequestForReview(+ request({ identifier: 'devin', provider: 'devin' }),+ );++ expect(sanitized).toMatchObject({ identifier: 'devin', provider: 'devin' });+ });});diff --git a/packages/agent-gateway-client/src/intervention.ts b/packages/agent-gateway-client/src/intervention.tsindex b6f71f14259..82be478f01e 100644--- a/packages/agent-gateway-client/src/intervention.ts+++ b/packages/agent-gateway-client/src/intervention.ts@@ -11,7 +11,13 @@ const INTERACTION_KINDS = new Set<AgentInterventionInteractionKind>(['plan','question',]);-const PROVIDERS = new Set<AgentInterventionProvider>(['claude-code', 'cursor', 'droid', 'qoder']);+const PROVIDERS = new Set<AgentInterventionProvider>([+ 'claude-code',+ 'cursor',+ 'devin',+ 'droid',+ 'qoder',+]);const asRecord = (value: unknown): Record<string, unknown> | undefined =>value !== null && typeof value === 'object' && !Array.isArray(value)diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.tsindex 5ea63efa853..ded4a9f2ca4 100644--- a/packages/agent-gateway-client/src/types.ts+++ b/packages/agent-gateway-client/src/types.ts@@ -197,7 +197,7 @@ export interface OperationHeartbeatData extends StepCompleteData {export type AgentInterventionInteractionKind = 'permission' | 'plan' | 'question';/** Producer that owns the blocked interaction. */-export type AgentInterventionProvider = 'claude-code' | 'cursor' | 'droid' | 'qoder';+export type AgentInterventionProvider = 'claude-code' | 'cursor' | 'devin' | 'droid' | 'qoder';/** Whitelisted option surface that may be persisted for cold-start review. */export interface AgentInterventionRenderOption {diff --git a/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts b/packages/agent-manager-runtime/src/heteroAgentDescriptor.tsindex 88759973858..c43023acdc6 100644--- a/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts+++ b/packages/agent-manager-runtime/src/heteroAgentDescriptor.ts@@ -83,6 +83,13 @@ const HETERO_PROFILES: Record<HeteroType, HeteroTypeProfile> = {displayName: 'Factory Droid',kind: 'cli',},+ 'devin': {+ capabilities: CODING_CAPABILITIES,+ description:+ 'Devin — Cognition’s autonomous local coding agent with filesystem and shell access that completes software-engineering tasks through its own tools and models.',+ displayName: 'Devin',+ kind: 'cli',+ },'grok-build': {capabilities: CODING_CAPABILITIES,description:diff --git a/packages/builtin-tools/src/register.ts b/packages/builtin-tools/src/register.tsindex 0db2543a161..24d7692edc5 100644--- a/packages/builtin-tools/src/register.ts+++ b/packages/builtin-tools/src/register.ts@@ -187,6 +187,7 @@ import { registerBuiltinStreamings } from './streamings';import { TwitterIdentifier, TwitterInspectors } from './twitter';const DROID_IDENTIFIER = 'droid';+const DEVIN_IDENTIFIER = 'devin';const QODER_IDENTIFIER = 'qoder';const OPENCODE_IDENTIFIER = 'opencode';const PI_IDENTIFIER = 'pi';@@ -228,6 +229,9 @@ export const registerBuiltinToolSurfaces = (): void => {[DROID_IDENTIFIER]: {[ClaudeCodeApiName.AskUserQuestion]: ClaudeCodeRenders[ClaudeCodeApiName.AskUserQuestion],},+ [DEVIN_IDENTIFIER]: {+ [ClaudeCodeApiName.AskUserQuestion]: ClaudeCodeRenders[ClaudeCodeApiName.AskUserQuestion],+ },[QODER_IDENTIFIER]: ClaudeCodeRenders as Record<string, BuiltinRender>,[CloudSandboxManifest.identifier]: CloudSandboxRenders as Record<string, BuiltinRender>,[GroupAgentBuilderManifest.identifier]: GroupAgentBuilderRenders as Record<@@ -282,6 +286,9 @@ export const registerBuiltinToolSurfaces = (): void => {[DROID_IDENTIFIER]: {[ClaudeCodeApiName.AskUserQuestion]: ClaudeCodeInspectors[ClaudeCodeApiName.AskUserQuestion],},+ [DEVIN_IDENTIFIER]: {+ [ClaudeCodeApiName.AskUserQuestion]: ClaudeCodeInspectors[ClaudeCodeApiName.AskUserQuestion],+ },[QODER_IDENTIFIER]: ClaudeCodeInspectors as Record<string, BuiltinInspector>,[CloudSandboxManifest.identifier]: CloudSandboxInspectors as Record<string, BuiltinInspector>,[GroupAgentBuilderManifest.identifier]: GroupAgentBuilderInspectors as Record<@@ -366,6 +373,10 @@ export const registerBuiltinToolSurfaces = (): void => {[ClaudeCodeApiName.AskUserQuestion]:ClaudeCodeInterventions[ClaudeCodeApiName.AskUserQuestion],},+ [DEVIN_IDENTIFIER]: {+ [ClaudeCodeApiName.AskUserQuestion]:+ ClaudeCodeInterventions[ClaudeCodeApiName.AskUserQuestion],+ },[QODER_IDENTIFIER]: ClaudeCodeInterventions as Record<string, BuiltinIntervention>,[CloudSandboxManifest.identifier]: CloudSandboxInterventions as Record<string,diff --git a/packages/database/src/models/__tests__/topics/topic.update.test.ts b/packages/database/src/models/__tests__/topics/topic.update.test.tsindex 94374cd6f00..0bec6692e03 100644--- a/packages/database/src/models/__tests__/topics/topic.update.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.update.test.ts@@ -331,6 +331,87 @@ describe('TopicModel - Update', () => {);});+ it('patches a child running operation without replacing its parent or siblings', async () => {+ const topicId = 'task-callback-patch-child-operation';+ await serverDB.insert(topics).values({+ id: topicId,+ metadata: {+ runningOperation: {+ assistantMessageId: 'assistant-parent',+ childOperations: [+ {+ assistantMessageId: 'assistant-child-1',+ hooks: [{ id: 'child-hook', type: 'onComplete', webhook: { url: '/child-hook' } }],+ operationId: 'child-operation-1',+ },+ { assistantMessageId: 'assistant-child-2', operationId: 'child-operation-2' },+ ],+ hooks: [{ id: 'parent-hook', type: 'onComplete', webhook: { url: '/parent-hook' } }],+ operationId: 'parent-operation',+ },+ },+ title: 'Test',+ userId,+ });++ await expect(+ topicModel.patchRunningOperation(topicId, 'child-operation-1', {+ deviceId: 'device-1',+ heteroType: 'devin',+ }),+ ).resolves.toBe(true);++ const topic = await topicModel.findById(topicId);+ expect(topic?.metadata?.runningOperation).toMatchObject({+ hooks: [{ id: 'parent-hook', type: 'onComplete', webhook: { url: '/parent-hook' } }],+ operationId: 'parent-operation',+ });+ expect(topic?.metadata?.runningOperation?.childOperations).toEqual([+ expect.objectContaining({+ deviceId: 'device-1',+ heteroType: 'devin',+ hooks: [{ id: 'child-hook', type: 'onComplete', webhook: { url: '/child-hook' } }],+ operationId: 'child-operation-1',+ }),+ { assistantMessageId: 'assistant-child-2', operationId: 'child-operation-2' },+ ]);+ });++ it('patches a root running operation without changing its children', async () => {+ const topicId = 'task-callback-patch-root-operation';+ await serverDB.insert(topics).values({+ id: topicId,+ metadata: {+ runningOperation: {+ assistantMessageId: 'assistant-parent',+ childOperations: [+ { assistantMessageId: 'assistant-child', operationId: 'child-operation' },+ ],+ operationId: 'parent-operation',+ },+ },+ title: 'Test',+ userId,+ });++ await expect(+ topicModel.patchRunningOperation(topicId, 'parent-operation', {+ deviceId: 'device-1',+ heteroType: 'devin',+ }),+ ).resolves.toBe(true);++ const topic = await topicModel.findById(topicId);+ expect(topic?.metadata?.runningOperation).toMatchObject({+ deviceId: 'device-1',+ heteroType: 'devin',+ operationId: 'parent-operation',+ });+ expect(topic?.metadata?.runningOperation?.childOperations).toEqual([+ { assistantMessageId: 'assistant-child', operationId: 'child-operation' },+ ]);+ });+it('atomically takes a child running operation once', async () => {const topicId = 'task-callback-take-child-operation';await serverDB.insert(topics).values({diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 2f0df3c68b0..f7fb4f8ff3f 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -59,6 +59,8 @@ import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';import { recomputeTopicUsage } from './topicUsage';type OnboardingSessionMetadataPatch = Partial<NonNullable<ChatTopicMetadata['onboardingSession']>>;+type RunningOperation = NonNullable<ChatTopicMetadata['runningOperation']>;+type RunningOperationPatch = Omit<Partial<RunningOperation>, 'childOperations' | 'operationId'>;type TopicMetadataPatch = Omit<Partial<ChatTopicMetadata>, 'onboardingSession'> & {onboardingSession?: OnboardingSessionMetadataPatch;};@@ -1980,7 +1982,7 @@ export class TopicModel {appendRunningOperationChild = async (id: string,parentOperationId: string,- child: NonNullable<ChatTopicMetadata['runningOperation']>,+ child: RunningOperation,): Promise<boolean> =>this.db.transaction(async (tx) => {const [existing] = await tx@@ -2011,6 +2013,43 @@ export class TopicModel {return true;});+ patchRunningOperation = async (+ id: string,+ operationId: string,+ patch: RunningOperationPatch,+ ): Promise<boolean> =>+ this.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(and(eq(topics.id, id), this.ownership()))+ .for('update');+ const runningOperation = existing?.metadata?.runningOperation;+ if (!existing || !runningOperation) return false;++ let nextRunningOperation: RunningOperation;+ if (runningOperation.operationId === operationId) {+ nextRunningOperation = { ...runningOperation, ...patch };+ } else {+ let matched = false;+ const childOperations = runningOperation.childOperations?.map((child) => {+ if (child.operationId !== operationId) return child;+ matched = true;+ return { ...child, ...patch };+ });+ if (!matched) return false;+ nextRunningOperation = { ...runningOperation, childOperations };+ }++ await tx+ .update(topics)+ .set({+ metadata: { ...existing.metadata, runningOperation: nextRunningOperation },+ })+ .where(and(eq(topics.id, id), this.ownership()));+ return true;+ });+removeRunningOperationChild = async (id: string, operationId: string): Promise<boolean> =>this.db.transaction(async (tx) => {const [existing] = await txdiff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.tsindex 6ecf66cc483..8b1bec28891 100644--- a/packages/device-control/src/types.ts+++ b/packages/device-control/src/types.ts@@ -267,7 +267,16 @@ export interface ListHeterogeneousAgentModelsParams {command?: string;cwd?: string;env?: Record<string, string>;- type: 'codebuddy' | 'cursor' | 'droid' | 'grok-build' | 'opencode' | 'pi' | 'qoder' | 'trae';+ type:+ | 'codebuddy'+ | 'cursor'+ | 'devin'+ | 'droid'+ | 'grok-build'+ | 'opencode'+ | 'pi'+ | 'qoder'+ | 'trae';}export interface HeterogeneousAgentModelCatalogItem {diff --git a/packages/heterogeneous-agents/src/adapters/devinAcp.test.ts b/packages/heterogeneous-agents/src/adapters/devinAcp.test.tsnew file mode 100644index 00000000000..c2d22a46b90--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/devinAcp.test.ts@@ -0,0 +1,115 @@+import { describe, expect, it } from 'vitest';++import type { HeterogeneousAgentEvent } from '../types';+import { DevinAcpAdapter } from './devinAcp';++const dataFor = (events: HeterogeneousAgentEvent[], type: HeterogeneousAgentEvent['type']) =>+ events.filter((event) => event.type === type).map((event) => event.data);++describe('DevinAcpAdapter', () => {+ it('emits step_complete with turn_metadata from session/prompt result usage', () => {+ const adapter = new DevinAcpAdapter();++ const events = [+ ...adapter.adapt({ model: 'glm-5-2', sessionId: 'humane-truck', type: 'devin_session' }),+ ...adapter.adapt({+ content: { text: 'done', type: 'text' },+ sessionUpdate: 'agent_message_chunk',+ }),+ ...adapter.adapt({+ stopReason: 'end_turn',+ type: 'devin_prompt_completed',+ usage: {+ cachedReadTokens: 12466,+ inputTokens: 12897,+ outputTokens: 630,+ totalTokens: 13527,+ },+ }),+ ];++ expect(dataFor(events, 'step_complete')).toEqual([+ {+ model: 'glm-5-2',+ phase: 'turn_metadata',+ provider: 'devin',+ usage: {+ inputCachedTokens: 12466,+ inputCacheMissTokens: 431,+ inputWriteCacheTokens: undefined,+ outputReasoningTokens: undefined,+ outputTextTokens: 630,+ totalInputTokens: 12897,+ totalOutputTokens: 630,+ totalTokens: 13527,+ },+ },+ ]);+ });++ it('extracts token usage from usage_update _meta cognition.ai fields', () => {+ const adapter = new DevinAcpAdapter();+ adapter.adapt({ model: 'glm-5-2', sessionId: 'humane-truck', type: 'devin_session' });+ adapter.adapt({+ sessionUpdate: 'usage_update',+ size: 200000,+ used: 12368,+ _meta: {+ 'cognition.ai/cachedReadTokens': 50,+ 'cognition.ai/inputTokens': 12292,+ 'cognition.ai/outputTokens': 76,+ },+ });++ const events = [+ ...adapter.adapt({+ content: { text: 'ok', type: 'text' },+ sessionUpdate: 'agent_message_chunk',+ }),+ ...adapter.adapt({ stopReason: 'end_turn', type: 'devin_prompt_completed' }),+ ];++ expect(dataFor(events, 'step_complete')).toEqual([+ {+ model: 'glm-5-2',+ phase: 'turn_metadata',+ provider: 'devin',+ usage: {+ inputCachedTokens: 50,+ inputCacheMissTokens: 12242,+ inputWriteCacheTokens: undefined,+ outputReasoningTokens: undefined,+ outputTextTokens: 76,+ totalInputTokens: 12292,+ totalOutputTokens: 76,+ totalTokens: 12368,+ },+ },+ ]);+ });++ it('falls back to ACP prompt result usage when usage_update has no _meta', () => {+ const adapter = new DevinAcpAdapter();+ adapter.adapt({ sessionUpdate: 'usage_update', size: 200000, used: 999 });++ const events = adapter.adapt({+ stopReason: 'end_turn',+ type: 'devin_prompt_completed',+ usage: { inputTokens: 100, outputTokens: 20, totalTokens: 120 },+ });++ expect(dataFor(events, 'step_complete')).toEqual([+ {+ phase: 'turn_metadata',+ provider: 'devin',+ usage: {+ inputCacheMissTokens: 100,+ outputTextTokens: 20,+ totalInputTokens: 100,+ totalOutputTokens: 20,+ totalTokens: 120,+ },+ },+ ]);+ });+});diff --git a/packages/heterogeneous-agents/src/adapters/devinAcp.ts b/packages/heterogeneous-agents/src/adapters/devinAcp.tsnew file mode 100644index 00000000000..a6c4dc1bb36--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/devinAcp.ts@@ -0,0 +1,45 @@+import { isRecord } from '@lobechat/utils/object';++import type { UsageData } from '../types';+import { TraeAcpAdapter, type TraeAcpPayload } from './traeAcp';++const toFiniteNumber = (value: unknown): number | undefined => {+ if (typeof value === 'number' && Number.isFinite(value)) return value;+};++/** Maps Devin's ACP `session/update` and `session/prompt` usage into the shared event contract. */+export class DevinAcpAdapter extends TraeAcpAdapter {+ constructor() {+ super({ eventPrefix: 'devin', provider: 'devin' });+ }++ protected override extractUsageFromUsageUpdate(raw: TraeAcpPayload): UsageData | undefined {+ const meta = isRecord(raw._meta) ? raw._meta : undefined;+ if (!meta) return;++ const input = toFiniteNumber(meta['cognition.ai/inputTokens']);+ const output = toFiniteNumber(meta['cognition.ai/outputTokens']);+ if (input === undefined || output === undefined) return;++ const cachedRead = toFiniteNumber(meta['cognition.ai/cachedReadTokens']) ?? 0;+ const cachedWrite = toFiniteNumber(meta['cognition.ai/cachedWriteTokens']) ?? 0;+ const thought =+ toFiniteNumber(meta['cognition.ai/thoughtTokens']) ??+ toFiniteNumber(meta['cognition.ai/reasoningTokens']) ??+ 0;++ const inputCacheMiss = Math.max(0, input - cachedRead);+ const outputText = Math.max(0, output - thought);++ return {+ inputCachedTokens: cachedRead || undefined,+ inputCacheMissTokens: inputCacheMiss,+ inputWriteCacheTokens: cachedWrite || undefined,+ outputReasoningTokens: thought || undefined,+ outputTextTokens: outputText,+ totalInputTokens: input + cachedWrite,+ totalOutputTokens: output,+ totalTokens: input + output + cachedWrite,+ };+ }+}diff --git a/packages/heterogeneous-agents/src/adapters/index.ts b/packages/heterogeneous-agents/src/adapters/index.tsindex 692243632e1..7d7911fe776 100644--- a/packages/heterogeneous-agents/src/adapters/index.ts+++ b/packages/heterogeneous-agents/src/adapters/index.ts@@ -6,6 +6,7 @@ export { CodexAppServerAdapter } from './codexAppServer';export { CursorAdapter } from './cursor';export { CursorAcpAdapter } from './cursorAcp';export { DroidAcpAdapter } from './droidAcp';+export { DevinAcpAdapter } from './devinAcp';export { GrokBuildAdapter } from './grokBuild';export { KimiCodeAdapter } from './kimiCode';export { OpenCodeAdapter } from './opencode';diff --git a/packages/heterogeneous-agents/src/adapters/traeAcp.ts b/packages/heterogeneous-agents/src/adapters/traeAcp.tsindex 64e01a948a3..c0cac4b9285 100644--- a/packages/heterogeneous-agents/src/adapters/traeAcp.ts+++ b/packages/heterogeneous-agents/src/adapters/traeAcp.ts@@ -1,10 +1,14 @@+import { isRecord } from '@lobechat/utils/object';+import type {AgentEventAdapter,HeterogeneousAgentEvent,+ StepCompleteData,StreamChunkData,ToolCallPayload,ToolResultData,ToolStateChunkData,+ UsageData,} from '../types';import { AcpStreamLifecycle } from './acpCommon';@@ -21,9 +25,10 @@ export interface AcpSessionAdapterOptions {provider?: string;}-interface TraeAcpPayload {+export interface TraeAcpPayload {[key: string]: unknown;content?: unknown;+ cost?: unknown;input?: unknown;kind?: unknown;message?: unknown;@@ -35,11 +40,14 @@ interface TraeAcpPayload {rawOutput?: unknown;sessionId?: unknown;sessionUpdate?: unknown;+ size?: unknown;status?: unknown;stopReason?: unknown;title?: unknown;toolCallId?: unknown;type?: unknown;+ usage?: unknown;+ used?: unknown;}interface TraeAcpToolContent {@@ -57,6 +65,15 @@ interface TraeAcpToolResultState {rawOutput?: unknown;}+const toFiniteNumber = (value: unknown): number | undefined => {+ if (typeof value === 'number' && Number.isFinite(value)) return value;+ if (typeof value === 'string') {+ const parsed = Number(value);+ if (Number.isFinite(parsed)) return parsed;+ }+ return;+};+const stringify = (value: unknown): string => {if (typeof value === 'string') return value;if (value === undefined) return '';@@ -99,10 +116,12 @@ export class TraeAcpAdapter implements AgentEventAdapter {private readonly eventPrefix: string;private readonly provider: string;private completedTools = new Set<string>();+ protected lastCostUsd?: number;+ protected lastUsage?: UsageData;private model?: string;private pendingTools = new Set<string>();private snapshotSeq = new Map<string, number>();- private readonly stream = new AcpStreamLifecycle((stepIndex) => ({+ protected readonly stream = new AcpStreamLifecycle((stepIndex) => ({...(this.model ? { model: this.model } : {}),...(stepIndex > 0 ? { newStep: true } : {}),provider: this.provider,@@ -128,12 +147,23 @@ export class TraeAcpAdapter implements AgentEventAdapter {if (typeof raw.model === 'string') this.model = raw.model;return [];}- if (raw.type === `${this.eventPrefix}_prompt_completed`) return this.complete(raw.stopReason);+ if (raw.type === `${this.eventPrefix}_prompt_completed`) {+ const usage = this.toUsageData(raw.usage) ?? this.lastUsage;+ const costUsd = this.toCostUsd(raw.cost) ?? this.lastCostUsd;+ return this.complete(raw.stopReason, usage, costUsd);+ }if (raw.type === `${this.eventPrefix}_error`) {return this.fail(stringify(raw.message) || `${this.provider} ACP failed`);}switch (raw.sessionUpdate) {+ case 'usage_update': {+ const usage = this.extractUsageFromUsageUpdate(raw);+ if (usage) this.lastUsage = usage;+ const costUsd = this.toCostUsd(raw.cost);+ if (costUsd !== undefined) this.lastCostUsd = costUsd;+ return [];+ }case 'agent_message_chunk': {const text = (raw.content as { text?: unknown } | null)?.text;return typeof text === 'string' && text@@ -172,7 +202,7 @@ export class TraeAcpAdapter implements AgentEventAdapter {flush(): HeterogeneousAgentEvent[] {if (this.terminal) return [];- return this.complete('end_turn');+ return this.complete('end_turn', this.lastUsage, this.lastCostUsd);}private updateTool(raw: TraeAcpPayload): HeterogeneousAgentEvent[] {@@ -268,17 +298,101 @@ export class TraeAcpAdapter implements AgentEventAdapter {return events;}- private complete(stopReason: unknown): HeterogeneousAgentEvent[] {+ protected complete(+ stopReason: unknown,+ usage?: UsageData,+ costUsd?: number,+ ): HeterogeneousAgentEvent[] {if (this.terminal) return [];this.terminal = true;const runtimeEndData =stopReason === 'cancelled' ? { reason: 'interrupted', stopReason } : { stopReason };- return [++ const result: HeterogeneousAgentEvent[] = [...this.closePending(),...this.stream.closeStream({ stopReason }),this.stream.event('visible_output_end', {}),- this.stream.event('agent_runtime_end', runtimeEndData),];++ if (usage) {+ if (costUsd !== undefined) usage.cost = costUsd;+ const stepCompleteData: StepCompleteData = {+ model: this.model,+ phase: 'turn_metadata',+ provider: this.provider,+ usage,+ };+ result.push(this.stream.event('step_complete', stepCompleteData));+ }++ result.push(this.stream.event('agent_runtime_end', runtimeEndData));+ return result;+ }++ /**+ * Convert an ACP experimental `Usage` shape into the shared `UsageData`.+ * Returns `undefined` when required fields are missing or invalid.+ */+ protected toUsageData(usage: unknown): UsageData | undefined {+ if (!isRecord(usage)) return;++ const total = toFiniteNumber(usage.totalTokens) ?? toFiniteNumber(usage.total_tokens);+ const input = toFiniteNumber(usage.inputTokens) ?? toFiniteNumber(usage.input_tokens);+ const output = toFiniteNumber(usage.outputTokens) ?? toFiniteNumber(usage.output_tokens);+ if (typeof input !== 'number' || typeof output !== 'number' || input < 0 || output < 0) return;++ const cachedRead =+ toFiniteNumber(usage.cachedReadTokens) ??+ toFiniteNumber(usage.cached_read_tokens) ??+ toFiniteNumber(usage.cacheReadTokens) ??+ toFiniteNumber(usage.cache_read_tokens) ??+ 0;+ const cachedWrite =+ toFiniteNumber(usage.cachedWriteTokens) ??+ toFiniteNumber(usage.cached_write_tokens) ??+ toFiniteNumber(usage.cacheWriteTokens) ??+ toFiniteNumber(usage.cache_write_tokens) ??+ 0;+ const thought =+ toFiniteNumber(usage.thoughtTokens) ??+ toFiniteNumber(usage.thought_tokens) ??+ toFiniteNumber(usage.reasoningTokens) ??+ toFiniteNumber(usage.reasoning_tokens) ??+ 0;++ const inputCacheMiss = Math.max(0, input - cachedRead);+ const outputText = Math.max(0, output - thought);+ const totalTokens = total ?? input + output + cachedWrite;++ return {+ inputCachedTokens: cachedRead || undefined,+ inputCacheMissTokens: inputCacheMiss,+ inputWriteCacheTokens: cachedWrite || undefined,+ outputReasoningTokens: thought || undefined,+ outputTextTokens: outputText,+ totalInputTokens: input + cachedWrite,+ totalOutputTokens: output,+ totalTokens,+ };+ }++ /**+ * Extract token usage from a `usage_update` notification.+ * The ACP spec only requires `used`/`size`/`cost`; per-turn token breakdown+ * lives in `_meta` as vendor extensions. Subclasses may override this to+ * parse provider-specific `_meta` keys (e.g. `cognition.ai/*Tokens`).+ */+ protected extractUsageFromUsageUpdate(_raw: TraeAcpPayload): UsageData | undefined {+ return;+ }++ /** Extract a USD cost amount from an ACP `cost` object. */+ private toCostUsd(cost: unknown): number | undefined {+ if (!isRecord(cost)) return;+ if (cost.currency !== 'USD') return;+ const amount = toFiniteNumber(cost.amount);+ if (amount === undefined || amount <= 0) return;+ return amount;}private fail(message: string): HeterogeneousAgentEvent[] {diff --git a/packages/heterogeneous-agents/src/client/index.ts b/packages/heterogeneous-agents/src/client/index.tsindex b91477edb39..ef2520a60de 100644--- a/packages/heterogeneous-agents/src/client/index.ts+++ b/packages/heterogeneous-agents/src/client/index.ts@@ -5,6 +5,7 @@ import {CodeBuddy,Codex,Cursor,+ Devin,getLobeIconCDN,Grok,Kimi,@@ -35,6 +36,7 @@ const heterogeneousAgentIcons = {'codex': Codex,'cursor': Cursor,'droid': DroidIcon,+ 'devin': Devin,'grok-build': Grok,'kimi-code': Kimi,'opencode': OpenCode,diff --git a/packages/heterogeneous-agents/src/config.test.ts b/packages/heterogeneous-agents/src/config.test.tsindex 3feb0eea304..a34e7ee4eb0 100644--- a/packages/heterogeneous-agents/src/config.test.ts+++ b/packages/heterogeneous-agents/src/config.test.ts@@ -20,6 +20,7 @@ describe('heterogeneous agent config', () => {'codex','cursor','droid',+ 'devin','grok-build','kimi-code','opencode',@@ -72,6 +73,15 @@ describe('heterogeneous agent config', () => {title: 'Amp',type: 'amp',});+ expect(getHeterogeneousAgentConfig('devin')).toMatchObject({+ auth: { signInCommand: 'devin auth login' },+ defaultCommand: 'devin',+ install: {+ commands: expect.arrayContaining(['irm https://static.devin.ai/cli/setup.ps1 | iex']),+ },+ title: 'Devin',+ type: 'devin',+ });expect(getHeterogeneousAgentConfig('grok-build')).toMatchObject({auth: { signInCommand: 'grok login' },defaultCommand: 'grok',@@ -135,6 +145,13 @@ describe('heterogeneous agent config', () => {command: 'kimi',message: 'Kimi Code could not authenticate. Run `kimi`, use `/login`, then retry.',});+ expect(isHeterogeneousAgentAuthRequired('devin', 'Run devin auth login to continue')).toBe(+ true,+ );+ expect(buildHeterogeneousAgentAuthRequiredError({ agentType: 'devin' })).toMatchObject({+ command: 'devin',+ message: 'Devin could not authenticate. Run `devin auth login`, then retry.',+ });expect(isHeterogeneousAgentAuthRequired('cursor', 'Authentication required')).toBe(true);expect(buildHeterogeneousAgentAuthRequiredError({ agentType: 'cursor' })).toMatchObject({command: 'agent',@@ -167,6 +184,7 @@ describe('heterogeneous agent config', () => {'codex': 'Codex','cursor': 'Cursor','droid': 'Factory Droid',+ 'devin': 'Devin','grok-build': 'Grok Build','hermes': 'Hermes','kimi-code': 'Kimi Code',@@ -191,6 +209,7 @@ describe('heterogeneous agent config', () => {expect(isRemoteHeterogeneousType('amp')).toBe(false);expect(isRemoteHeterogeneousType('codebuddy')).toBe(false);expect(isRemoteHeterogeneousType('droid')).toBe(false);+ expect(isRemoteHeterogeneousType('devin')).toBe(false);expect(isRemoteHeterogeneousType('opencode')).toBe(false);expect(isRemoteHeterogeneousType('pi')).toBe(false);expect(isRemoteHeterogeneousType('qoder')).toBe(false);diff --git a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.test.ts b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.test.tsindex 33031fd44e4..6f09c159d08 100644--- a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.test.ts+++ b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.test.ts@@ -279,6 +279,63 @@ describe('heterogeneous agent model discovery', () => {);});+ it('parses and discovers Devin model variants from JSON', async () => {+ const stdout = JSON.stringify({+ families: [+ {+ family_label: 'Claude Sonnet 4.6',+ variants: [+ { label: 'Claude Sonnet 4.6', model_uid: 'claude-sonnet-4-6' },+ { label: 'Claude Sonnet 4.6 Thinking', model_uid: 'claude-sonnet-4-6-thinking' },+ ],+ },+ {+ family_label: 'Duplicate',+ variants: [{ label: 'Duplicate', model_uid: 'claude-sonnet-4-6' }, {}],+ },+ ],+ });+ resolveExecFile(stdout);+ const { listHeterogeneousAgentModels, parseDevinModelCatalog } = await importModule();++ expect(parseDevinModelCatalog(stdout)).toEqual([+ {+ id: 'claude-sonnet-4-6',+ label: 'Claude Sonnet 4.6',+ modelId: 'claude-sonnet-4-6',+ providerId: 'devin',+ },+ {+ id: 'claude-sonnet-4-6-thinking',+ label: 'Claude Sonnet 4.6 Thinking',+ modelId: 'claude-sonnet-4-6-thinking',+ providerId: 'devin',+ },+ ]);+ expect(parseDevinModelCatalog('not json')).toEqual([]);++ await expect(+ listHeterogeneousAgentModels({+ command: '/custom/devin',+ cwd: '/repo',+ env: { DEVIN_MODEL: 'sonnet' },+ type: 'devin',+ }),+ ).resolves.toMatchObject({+ models: [+ { id: 'claude-sonnet-4-6', providerId: 'devin' },+ { id: 'claude-sonnet-4-6-thinking', providerId: 'devin' },+ ],+ status: 'success',+ });+ expect(execFileMock).toHaveBeenLastCalledWith(+ '/custom/devin',+ ['models', 'list', '--format', 'json'],+ expect.objectContaining({ cwd: '/repo', env: { DEVIN_MODEL: 'sonnet' } }),+ expect.any(Function),+ );+ });+it('parses and discovers Grok Build models', async () => {const stdout = ['You are not authenticated.',diff --git a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.tsindex eea1b523b01..cfae000fe04 100644--- a/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts+++ b/packages/heterogeneous-agents/src/models/listHeterogeneousAgentModels.ts@@ -8,6 +8,7 @@ import type {HeterogeneousAgentModelCatalogErrorCode,ListHeterogeneousAgentModelsParams,} from '@lobechat/types';+import { isRecord } from '@lobechat/utils/object';import { getHeterogeneousTypeLabel } from '../labels';import { resolveCliSpawnPlan } from '../spawn/cliSpawn';@@ -82,6 +83,39 @@ export const parseCursorModelCatalog = (stdout: string): HeterogeneousAgentModelreturn models;};+export const parseDevinModelCatalog = (stdout: string): HeterogeneousAgentModel[] => {+ let result: unknown;+ try {+ result = JSON.parse(stdout);+ } catch {+ return [];+ }+ if (!isRecord(result) || !Array.isArray(result.families)) return [];++ const seen = new Set<string>();+ const models: HeterogeneousAgentModel[] = [];+ for (const family of result.families) {+ if (!isRecord(family) || !Array.isArray(family.variants)) continue;+ for (const variant of family.variants) {+ if (!isRecord(variant) || typeof variant.model_uid !== 'string' || !variant.model_uid)+ continue;+ if (seen.has(variant.model_uid)) continue;++ seen.add(variant.model_uid);+ models.push({+ id: variant.model_uid,+ ...(typeof variant.label === 'string' && variant.label+ ? { label: variant.label }+ : undefined),+ modelId: variant.model_uid,+ providerId: 'devin',+ });+ }+ }++ return models;+};+/** Parse the model rows emitted by `grok models`. */export const parseGrokBuildModelCatalog = (stdout: string): HeterogeneousAgentModel[] => {const seen = new Set<string>();@@ -264,9 +298,11 @@ export const listHeterogeneousAgentModels = async (const args =params.type === 'codebuddy'? ['--help']- : params.type === 'grok-build' || params.type === 'opencode'- ? ['models']- : ['--list-models'];+ : params.type === 'devin'+ ? ['models', 'list', '--format', 'json']+ : params.type === 'grok-build' || params.type === 'opencode'+ ? ['models']+ : ['--list-models'];const spawnPlan = await resolveCliSpawnPlan(resolved.command, args);const { stderr, stdout } = await execFilePromise(spawnPlan.command, spawnPlan.args, {cwd: params.cwd,@@ -299,13 +335,15 @@ export const listHeterogeneousAgentModels = async (models:params.type === 'cursor'? parseCursorModelCatalog(String(stdout))- : params.type === 'grok-build'- ? parseGrokBuildModelCatalog(String(stdout))- : params.type === 'pi'- ? parsePiModelCatalog(String(stdout))- : params.type === 'qoder'- ? parseQoderModelCatalog(String(stdout))- : parseOpenCodeModelCatalog(String(stdout)),+ : params.type === 'devin'+ ? parseDevinModelCatalog(String(stdout))+ : params.type === 'grok-build'+ ? parseGrokBuildModelCatalog(String(stdout))+ : params.type === 'pi'+ ? parsePiModelCatalog(String(stdout))+ : params.type === 'qoder'+ ? parseQoderModelCatalog(String(stdout))+ : parseOpenCodeModelCatalog(String(stdout)),status: 'success',updatedAt,};diff --git a/packages/heterogeneous-agents/src/protocol/cancellation.ts b/packages/heterogeneous-agents/src/protocol/cancellation.tsnew file mode 100644index 00000000000..8e228374721--- /dev/null+++ b/packages/heterogeneous-agents/src/protocol/cancellation.ts@@ -0,0 +1,11 @@+export type HeterogeneousAgentCancellationSignal = 'SIGINT' | 'SIGKILL' | 'SIGTERM';++/** Device-gateway confirmation that a heterogeneous-agent process tree stopped. */+export interface HeterogeneousAgentCancellationResult {+ /** Whether the complete wrapper-owned process tree exited before the bounded wait elapsed. */+ exited: boolean;+ /** Operating-system process id assigned to the wrapper process. */+ pid?: number;+ /** Initial signal requested by the server cancellation call. */+ signal: HeterogeneousAgentCancellationSignal;+}diff --git a/packages/heterogeneous-agents/src/protocol/index.ts b/packages/heterogeneous-agents/src/protocol/index.tsindex 1f8e6ea387b..f44bb5411d8 100644--- a/packages/heterogeneous-agents/src/protocol/index.ts+++ b/packages/heterogeneous-agents/src/protocol/index.ts@@ -7,7 +7,12 @@* Executor-side helpers that materialize this contract (`normalizeImage`,* `buildAgentInput`, `spawnAgent`, …) live under `./spawn` instead.*/+export type {+ HeterogeneousAgentCancellationResult,+ HeterogeneousAgentCancellationSignal,+} from './cancellation';export { buildHeteroExecStdinPayload, type HeteroExecImageRef } from './execStdinPayload';+export const HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV = 'LOBEHUB_HETERO_EXEC_INHERIT_PROCESS_GROUP';export {buildHeterogeneousPrompt,type HeterogeneousPromptContextProvider,diff --git a/packages/heterogeneous-agents/src/registry.test.ts b/packages/heterogeneous-agents/src/registry.test.tsindex 59faa68dd50..6a9668c8d74 100644--- a/packages/heterogeneous-agents/src/registry.test.ts+++ b/packages/heterogeneous-agents/src/registry.test.ts@@ -8,6 +8,7 @@ import {CursorAcpAdapter,CursorAdapter,DroidAcpAdapter,+ DevinAcpAdapter,GrokBuildAdapter,KimiCodeAdapter,OpenCodeAdapter,@@ -56,6 +57,10 @@ describe('registry', () => {expect(createAdapter('droid-acp')).toBeInstanceOf(DroidAcpAdapter);});+ it('creates a DevinAcpAdapter for "devin"', () => {+ expect(createAdapter('devin')).toBeInstanceOf(DevinAcpAdapter);+ });+it('creates a GrokBuildAdapter for "grok-build"', () => {expect(createAdapter('grok-build')).toBeInstanceOf(GrokBuildAdapter);});diff --git a/packages/heterogeneous-agents/src/registry.ts b/packages/heterogeneous-agents/src/registry.tsindex 984507fca30..cb981ae890d 100644--- a/packages/heterogeneous-agents/src/registry.ts+++ b/packages/heterogeneous-agents/src/registry.ts@@ -14,6 +14,7 @@ import {CursorAcpAdapter,CursorAdapter,DroidAcpAdapter,+ DevinAcpAdapter,GrokBuildAdapter,KimiCodeAdapter,OpenCodeAdapter,@@ -47,6 +48,9 @@ const localAgentRegistry = {'droid': {createAdapter: () => new DroidAcpAdapter(),},+ 'devin': {+ createAdapter: () => new DevinAcpAdapter(),+ },'grok-build': {createAdapter: () => new GrokBuildAdapter(),},diff --git a/packages/heterogeneous-agents/src/spawn/acpAgentSession.ts b/packages/heterogeneous-agents/src/spawn/acpAgentSession.tsindex 1bdf897eb44..05b4593d695 100644--- a/packages/heterogeneous-agents/src/spawn/acpAgentSession.ts+++ b/packages/heterogeneous-agents/src/spawn/acpAgentSession.ts@@ -50,6 +50,8 @@ export interface AcpAgentSessionOptions {clientVersion: string;commandPath: string;cwd: string;+ /** Create a dedicated Unix process group. Disable beneath a detached wrapper. */+ detached?: boolean;env: NodeJS.ProcessEnv;onEvents: (events: AgentStreamEvent[]) => Promise<void> | void;onRawMessage: (line: string) => Promise<void> | void;@@ -115,6 +117,7 @@ export abstract class AcpAgentSession<args: config.args,commandPath: options.commandPath,cwd: options.cwd,+ detached: options.detached,env: options.env,onMessage: (message) => this.handleAgentMessage(message),onRawMessage: options.onRawMessage,diff --git a/packages/heterogeneous-agents/src/spawn/acpStdioClient.test.ts b/packages/heterogeneous-agents/src/spawn/acpStdioClient.test.tsindex 2eb94ac8ce1..edc0630d1a8 100644--- a/packages/heterogeneous-agents/src/spawn/acpStdioClient.test.ts+++ b/packages/heterogeneous-agents/src/spawn/acpStdioClient.test.ts@@ -210,6 +210,33 @@ describe('AcpStdioClient', () => {expect(onMessage).toHaveBeenCalledWith({ method: 'first' });});+ it('inherits an outer wrapper process group and signals the child directly', async () => {+ const { child } = createProcess();+ spawnMock.mockReturnValue(child);+ const processKill = vi.spyOn(process, 'kill').mockImplementation(() => true);+ const client = new AcpStdioClient({+ args: ['agent', 'stdio'],+ commandPath: 'agent',+ cwd: '/workspace',+ detached: false,+ env: { ...process.env },+ onMessage: vi.fn(),+ onRawMessage: vi.fn(),+ onStderr: vi.fn(),+ });+ await client.start();++ expect(spawnMock).toHaveBeenCalledWith(+ 'agent',+ ['agent', 'stdio'],+ expect.objectContaining({ detached: false }),+ );+ client.close('SIGKILL');++ expect(child.kill).toHaveBeenCalledWith('SIGKILL');+ expect(processKill).not.toHaveBeenCalled();+ });+it('terminates the child process tree with taskkill on Windows', async () => {Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' });const { child } = createProcess();diff --git a/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts b/packages/heterogeneous-agents/src/spawn/acpStdioClient.tsindex 1840a6f2690..164d7f5405e 100644--- a/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts+++ b/packages/heterogeneous-agents/src/spawn/acpStdioClient.ts@@ -32,6 +32,8 @@ export interface AcpStdioClientOptions {args: string[];commandPath: string;cwd: string;+ /** Create a dedicated Unix process group. Disable beneath a detached wrapper. */+ detached?: boolean;env: NodeJS.ProcessEnv;onMessage: (message: AcpRpcMessage) => Promise<void> | void;onRawMessage: (line: string) => Promise<void> | void;@@ -100,9 +102,10 @@ export class AcpStdioClient {const spawnPlan = await resolveCliSpawnPlan(this.options.commandPath, this.options.args);if (this.closed) throw new Error('ACP stdio client is closed');+ const detached = process.platform !== 'win32' && (this.options.detached ?? true);const child = spawn(spawnPlan.command, spawnPlan.args, {cwd: this.options.cwd,- detached: process.platform !== 'win32',+ detached,env: this.options.env,stdio: ['pipe', 'pipe', 'pipe'],});@@ -314,15 +317,21 @@ export class AcpStdioClient {return;}- try {- process.kill(-child.pid, signal);- } catch {+ const detached = this.options.detached ?? true;+ if (detached) {try {- child.kill(signal);+ process.kill(-child.pid, signal);+ return;} catch {- // already gone+ // Fall through to a direct signal when the process group is gone.}}++ try {+ child.kill(signal);+ } catch {+ // already gone+ }}private toError(error: unknown): Error {diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.tsindex 6229d1fdfcc..2e3cc397169 100644--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts@@ -124,6 +124,7 @@ export interface HeterogeneousAgentRuntimeStatus {| 'codex-app-server'| 'cursor-acp'| 'droid-acp'+ | 'devin-acp'| 'trae-acp';}diff --git a/packages/heterogeneous-agents/src/spawn/devinAcpSession.test.ts b/packages/heterogeneous-agents/src/spawn/devinAcpSession.test.tsnew file mode 100644index 00000000000..acbf2294f89--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/devinAcpSession.test.ts@@ -0,0 +1,618 @@+import type { ChildProcess } from 'node:child_process';+import { EventEmitter } from 'node:events';+import { PassThrough } from 'node:stream';++import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { AskUserBridge } from '../askUser/AskUserBridge';+import { AcpRpcResponseError } from './acpStdioClient';+import {+ buildDevinAcpArgs,+ buildDevinAcpPrompt,+ DevinAcpSession,+ type DevinAcpSessionOptions,+ isDevinAcpSessionNotFoundError,+} from './devinAcpSession';++const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() }));++vi.mock('node:child_process', async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>();+ return { ...actual, spawn: spawnMock };+});++interface RpcMessage {+ error?: { code: number; data?: unknown; message: string };+ id?: number | string;+ method?: string;+ params?: Record<string, unknown>;+ result?: unknown;+}++const createAcpProcess = ({+ initializeResult,+ loadError,+ permissionRequest = false,+}: {+ initializeResult?: Record<string, unknown>;+ loadError?: { code: number; data?: unknown; message: string };+ permissionRequest?: boolean;+} = {}) => {+ const child = new EventEmitter() as ChildProcess;+ const stdout = new PassThrough();+ const stderr = new PassThrough();+ const requests: RpcMessage[] = [];+ let promptRequest: RpcMessage | undefined;+ let currentMode = 'accept-edits';+ let currentModel = 'claude-sonnet-4-6-thinking';+ const send = (message: Record<string, unknown>) =>+ stdout.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`);++ Object.assign(child, {+ kill: vi.fn(() => true),+ killed: false,+ pid: 987_654,+ stderr,+ stdin: {+ once: vi.fn(),+ write: vi.fn((chunk: string) => {+ const message = JSON.parse(chunk.trim()) as RpcMessage;+ requests.push(message);+ queueMicrotask(() => {+ switch (message.method) {+ case 'initialize': {+ send({+ id: message.id,+ result:+ initializeResult ??+ ({+ agentCapabilities: {+ loadSession: true,+ promptCapabilities: { image: true },+ },+ authMethods: [{ id: 'devin-browser', name: 'Log in with browser' }],+ protocolVersion: 1,+ } satisfies Record<string, unknown>),+ });+ return;+ }+ case 'authenticate': {+ send({ id: message.id, result: {} });+ return;+ }+ case 'session/new': {+ send({+ id: message.id,+ result: {+ configOptions: [+ {+ category: 'model',+ currentValue: currentModel,+ id: 'model',+ name: 'Model',+ options: [+ { name: 'Claude Sonnet 4.6 Thinking', value: 'claude-sonnet-4-6-thinking' },+ { name: 'GLM 5.2', value: 'glm-5-2' },+ { name: 'SWE 1.7 Medium', value: 'swe-1-7-medium' },+ ],+ },+ ],+ sessionId: 'devin-session-1',+ },+ });+ return;+ }+ case 'session/load': {+ send(+ loadError ? { error: loadError, id: message.id } : { id: message.id, result: {} },+ );+ return;+ }+ case 'session/set_config_option': {+ const params = message.params as { configId?: string; value?: string } | undefined;+ if (params?.configId === 'mode' && params.value) currentMode = params.value;+ if (params?.configId === 'model' && params.value) currentModel = params.value;+ send({+ id: message.id,+ result: {+ configOptions: [+ {+ category: 'mode',+ currentValue: currentMode,+ id: 'mode',+ name: 'Session Mode',+ },+ {+ category: 'model',+ currentValue: currentModel,+ id: 'model',+ name: 'Model',+ },+ ],+ },+ });+ return;+ }+ case 'session/prompt': {+ promptRequest = message;+ send({+ method: 'session/update',+ params: {+ sessionId: 'devin-session-1',+ update: {+ _meta: { 'cognition.ai/inferenceToolName': 'exec' },+ kind: 'execute',+ rawInput: { command: 'pwd' },+ sessionUpdate: 'tool_call',+ title: 'Ran command',+ toolCallId: 'tool-1',+ },+ },+ });+ send({+ method: 'session/update',+ params: {+ sessionId: 'devin-session-1',+ update: {+ content: [{ content: { text: '/workspace', type: 'text' }, type: 'content' }],+ sessionUpdate: 'tool_call_update',+ status: 'completed',+ toolCallId: 'tool-1',+ },+ },+ });+ send({+ method: 'session/update',+ params: {+ sessionId: 'devin-session-1',+ update: {+ content: { text: 'Done', type: 'text' },+ sessionUpdate: 'agent_message_chunk',+ },+ },+ });+ if (permissionRequest) {+ send({+ id: 'permission-1',+ method: 'session/request_permission',+ params: {+ options: [+ { kind: 'allow_once', name: 'Allow', optionId: 'allow_once' },+ {+ kind: 'allow_always',+ name: 'Allow for this session',+ optionId: 'allow_session',+ },+ { kind: 'reject_once', name: 'Reject', optionId: 'reject_once' },+ ],+ sessionId: 'devin-session-1',+ toolCall: {+ _meta: { 'cognition.ai/editableCommand': 'printf test' },+ toolCallId: 'tool-1',+ },+ },+ });+ } else {+ send({ id: message.id, result: { stopReason: 'end_turn' } });+ }+ return;+ }+ }++ if (message.id === 'permission-1' && message.result && promptRequest) {+ send({ id: promptRequest.id, result: { stopReason: 'end_turn' } });+ }+ });+ return true;+ }),+ },+ stdout,+ });++ return { child, requests };+};++const createSessionOptions = (+ overrides: Partial<DevinAcpSessionOptions> = {},+): DevinAcpSessionOptions => ({+ args: ['--model', 'sonnet'],+ clientVersion: '1.2.3',+ commandPath: 'devin',+ cwd: '/workspace',+ env: process.env,+ onEvents: vi.fn(),+ onModel: vi.fn(),+ onRawMessage: vi.fn(),+ onRuntimeStatus: vi.fn(),+ onSessionId: vi.fn(),+ onStderr: vi.fn(),+ operationId: 'operation-1',+ prompt: [{ text: 'hello', type: 'text' }],+ sessionId: 'session-1',+ ...overrides,+});++afterEach(() => {+ vi.restoreAllMocks();+ spawnMock.mockReset();+});++describe('Devin ACP helpers', () => {+ it('places the ACP subcommand before provider arguments', () => {+ expect(buildDevinAcpArgs(['--model', 'sonnet'])).toEqual(['acp', '--model', 'sonnet']);+ });++ it('does not inject a default permission mode', () => {+ expect(buildDevinAcpArgs(['--model', 'sonnet'])).toEqual(['acp', '--model', 'sonnet']);+ });++ it('moves a permission mode already in extra args before the acp subcommand', () => {+ expect(buildDevinAcpArgs(['--permission-mode', 'dangerous', '--model', 'sonnet'])).toEqual([+ '--permission-mode',+ 'dangerous',+ 'acp',+ '--model',+ 'sonnet',+ ]);+ });++ it('supports --permission-mode=<value> in extra args', () => {+ expect(buildDevinAcpArgs(['--permission-mode=normal', '--model', 'sonnet'])).toEqual([+ '--permission-mode',+ 'normal',+ 'acp',+ '--model',+ 'sonnet',+ ]);+ });++ it('builds text and image prompt blocks', async () => {+ await expect(+ buildDevinAcpPrompt([+ { text: 'inspect this', type: 'text' },+ {+ source: { data: 'aGVsbG8=', mediaType: 'image/png', type: 'base64' },+ type: 'image',+ },+ ]),+ ).resolves.toEqual([+ { text: 'inspect this', type: 'text' },+ { data: 'aGVsbG8=', mimeType: 'image/png', type: 'image' },+ ]);+ });++ it('recognizes Devin session-not-found RPC errors', () => {+ expect(+ isDevinAcpSessionNotFoundError(+ new AcpRpcResponseError('session/load', {+ code: -32_016,+ data: { 'cognition.ai/errorKind': 'session_not_found' },+ message: 'Session not found',+ }),+ ),+ ).toBe(true);+ expect(+ isDevinAcpSessionNotFoundError(+ new AcpRpcResponseError('session/prompt', {+ code: -32_016,+ message: 'Session not found',+ }),+ ),+ ).toBe(false);+ });+});++describe('DevinAcpSession', () => {+ it('uses cached credentials without starting browser authentication', async () => {+ const fake = createAcpProcess();+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const options = createSessionOptions();+ const events: AgentStreamEvent[] = [];+ options.onEvents = (batch) => {+ events.push(...batch);+ };++ await new DevinAcpSession(options).run();++ expect(spawnMock).toHaveBeenCalledWith(+ 'devin',+ ['acp', '--model', 'sonnet'],+ expect.objectContaining({ cwd: '/workspace', stdio: ['pipe', 'pipe', 'pipe'] }),+ );+ expect(fake.requests.map(({ method }) => method).filter(Boolean)).toEqual([+ 'initialize',+ 'session/new',+ 'session/prompt',+ ]);+ expect(options.onSessionId).toHaveBeenCalledWith('devin-session-1');+ expect(options.onModel).toHaveBeenCalledWith('claude-sonnet-4-6-thinking');+ expect(events).toContainEqual(+ expect.objectContaining({+ data: expect.objectContaining({+ toolCalling: expect.objectContaining({ apiName: 'exec', id: 'tool-1' }),+ }),+ type: 'tool_start',+ }),+ );+ expect(events).toContainEqual(+ expect.objectContaining({+ data: { chunkType: 'text', content: 'Done' },+ type: 'stream_chunk',+ }),+ );+ expect(events).toContainEqual(expect.objectContaining({ type: 'agent_runtime_end' }));+ expect(options.onRuntimeStatus).toHaveBeenLastCalledWith(+ expect.objectContaining({ state: 'closed', transport: 'devin-acp' }),+ );+ });++ it('loads a saved session and preserves the structured not-found error', async () => {+ const success = createAcpProcess();+ spawnMock.mockReturnValueOnce(success.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const options = createSessionOptions({ resumeSessionId: 'saved-session' });++ await new DevinAcpSession(options).run();++ expect(success.requests.find(({ method }) => method === 'session/load')?.params).toEqual({+ cwd: '/workspace',+ mcpServers: [],+ sessionId: 'saved-session',+ });+ expect(options.onSessionId).toHaveBeenCalledWith('saved-session');++ const missing = createAcpProcess({+ loadError: {+ code: -32_016,+ data: { 'cognition.ai/errorKind': 'session_not_found' },+ message: 'Session not found',+ },+ });+ spawnMock.mockReturnValueOnce(missing.child);++ await expect(+ new DevinAcpSession(createSessionOptions({ resumeSessionId: 'missing-session' })).run(),+ ).rejects.toSatisfy(isDevinAcpSessionNotFoundError);+ expect(missing.requests.some(({ method }) => method === 'session/prompt')).toBe(false);+ });++ it('requires an explicit user choice before granting permission', async () => {+ const fake = createAcpProcess({ permissionRequest: true });+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const bridge = new AskUserBridge('operation-1');+ const run = new DevinAcpSession(createSessionOptions({ askUserBridge: bridge })).run();+ const intervention = await bridge.events()[Symbol.asyncIterator]().next();++ expect(intervention.value).toMatchObject({+ data: {+ apiName: 'askUserQuestion',+ interactionKind: 'permission',+ toolCallId: 'devin-permission-permission-1-tool-1',+ },+ type: 'agent_intervention_request',+ });+ expect(JSON.parse(intervention.value!.data.arguments)).toEqual({+ questions: [+ {+ header: 'Permission required',+ multiSelect: false,+ options: [+ { id: 'allow_once', label: 'Allow' },+ { id: 'allow_session', label: 'Allow for this session' },+ { id: 'reject_once', label: 'Reject' },+ ],+ question: 'printf test',+ },+ ],+ });+ bridge.resolve(intervention.value!.data.toolCallId, {+ result: { 'printf test': 'allow_session' },+ });+ await run;++ expect(fake.requests.find(({ id }) => id === 'permission-1')?.result).toEqual({+ outcome: { optionId: 'allow_session', outcome: 'selected' },+ });+ });++ it('does not resolve permission choices by their display label', async () => {+ const fake = createAcpProcess({ permissionRequest: true });+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const bridge = new AskUserBridge('operation-1');+ const run = new DevinAcpSession(createSessionOptions({ askUserBridge: bridge })).run();+ const intervention = await bridge.events()[Symbol.asyncIterator]().next();++ bridge.resolve(intervention.value!.data.toolCallId, {+ result: { 'printf test': 'Allow for this session' },+ });+ await run;++ expect(fake.requests.find(({ id }) => id === 'permission-1')?.result).toEqual({+ outcome: { outcome: 'cancelled' },+ });+ });++ it('cancels permission requests when no intervention bridge is available', async () => {+ const fake = createAcpProcess({ permissionRequest: true });+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);++ await new DevinAcpSession(createSessionOptions()).run();++ expect(fake.requests.find(({ id }) => id === 'permission-1')?.result).toEqual({+ outcome: { outcome: 'cancelled' },+ });+ });++ it('sets the ACP session mode when a permission mode is configured', async () => {+ const fake = createAcpProcess();+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const options = createSessionOptions({ permissionMode: 'bypass' });++ await new DevinAcpSession(options).run();++ expect(spawnMock).toHaveBeenCalledWith(+ 'devin',+ ['acp', '--model', 'sonnet'],+ expect.objectContaining({ cwd: '/workspace', stdio: ['pipe', 'pipe', 'pipe'] }),+ );+ expect(fake.requests.map(({ method }) => method).filter(Boolean)).toEqual([+ 'initialize',+ 'session/new',+ 'session/set_config_option',+ 'session/prompt',+ ]);+ expect(+ fake.requests.find(({ method }) => method === 'session/set_config_option')?.params,+ ).toEqual({+ configId: 'mode',+ sessionId: 'devin-session-1',+ value: 'bypass',+ });+ expect(options.onSessionId).toHaveBeenCalledWith('devin-session-1');+ });++ it('lets a user-supplied --permission-mode in args override the default', async () => {+ const fake = createAcpProcess();+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const options = createSessionOptions({+ args: ['--permission-mode', 'dangerous', '--model', 'sonnet'],+ permissionMode: 'bypass',+ });++ await new DevinAcpSession(options).run();++ expect(spawnMock).toHaveBeenCalledWith(+ 'devin',+ ['--permission-mode', 'dangerous', 'acp', '--model', 'sonnet'],+ expect.objectContaining({ cwd: '/workspace', stdio: ['pipe', 'pipe', 'pipe'] }),+ );+ expect(+ fake.requests.find(({ method }) => method === 'session/set_config_option')?.params,+ ).toEqual({+ configId: 'mode',+ sessionId: 'devin-session-1',+ value: 'dangerous',+ });+ });++ it('sets the ACP session mode on a resumed session', async () => {+ const fake = createAcpProcess();+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const options = createSessionOptions({+ permissionMode: 'bypass',+ resumeSessionId: 'saved-session',+ });++ await new DevinAcpSession(options).run();++ expect(fake.requests.map(({ method }) => method).filter(Boolean)).toEqual([+ 'initialize',+ 'session/load',+ 'session/set_config_option',+ 'session/prompt',+ ]);+ expect(+ fake.requests.find(({ method }) => method === 'session/set_config_option')?.params,+ ).toEqual({+ configId: 'mode',+ sessionId: 'saved-session',+ value: 'bypass',+ });+ });++ it('applies initialModel through session/set_config_option when it differs from the default', async () => {+ const fake = createAcpProcess();+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const options = createSessionOptions({ initialModel: 'glm-5-2' });++ await new DevinAcpSession(options).run();++ expect(fake.requests.map(({ method }) => method).filter(Boolean)).toEqual([+ 'initialize',+ 'session/new',+ 'session/set_config_option',+ 'session/prompt',+ ]);+ expect(+ fake.requests.find(({ method }) => method === 'session/set_config_option')?.params,+ ).toEqual({+ configId: 'model',+ sessionId: 'devin-session-1',+ value: 'glm-5-2',+ });+ expect(options.onModel).toHaveBeenCalledWith('glm-5-2');+ });++ it('matches a human-readable model label to the ACP model value', async () => {+ const fake = createAcpProcess();+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const options = createSessionOptions({ initialModel: 'glm 5.2' });++ await new DevinAcpSession(options).run();++ expect(+ fake.requests.find(({ method }) => method === 'session/set_config_option')?.params,+ ).toEqual({+ configId: 'model',+ sessionId: 'devin-session-1',+ value: 'glm-5-2',+ });+ expect(options.onModel).toHaveBeenCalledWith('glm-5-2');+ });++ it('does not call session/set_config_option for model when initialModel matches the default', async () => {+ const fake = createAcpProcess();+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const options = createSessionOptions({ initialModel: 'claude-sonnet-4-6-thinking' });++ await new DevinAcpSession(options).run();++ expect(fake.requests.map(({ method }) => method).filter(Boolean)).toEqual([+ 'initialize',+ 'session/new',+ 'session/prompt',+ ]);+ });++ it('sets both permission mode and model when both are configured', async () => {+ const fake = createAcpProcess();+ spawnMock.mockReturnValue(fake.child);+ vi.spyOn(process, 'kill').mockImplementation(() => true);+ const options = createSessionOptions({ initialModel: 'glm-5-2', permissionMode: 'bypass' });++ await new DevinAcpSession(options).run();++ expect(fake.requests.map(({ method }) => method).filter(Boolean)).toEqual([+ 'initialize',+ 'session/new',+ 'session/set_config_option',+ 'session/set_config_option',+ 'session/prompt',+ ]);+ const setConfigRequests = fake.requests.filter(+ ({ method }) => method === 'session/set_config_option',+ );+ expect(setConfigRequests[0]?.params).toEqual({+ configId: 'model',+ sessionId: 'devin-session-1',+ value: 'glm-5-2',+ });+ expect(setConfigRequests[1]?.params).toEqual({+ configId: 'mode',+ sessionId: 'devin-session-1',+ value: 'bypass',+ });+ expect(options.onModel).toHaveBeenCalledWith('glm-5-2');+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/devinAcpSession.ts b/packages/heterogeneous-agents/src/spawn/devinAcpSession.tsnew file mode 100644index 00000000000..79062ecc235--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/devinAcpSession.ts@@ -0,0 +1,398 @@+import { isRecord } from '@lobechat/utils/object';++import type { AskUserBridge, InterventionAnswer } from '../askUser/AskUserBridge';+import type { AgentPromptInput } from '../protocol';+import type { AcpAgentSessionOptions } from './acpAgentSession';+import { ACP_PROTOCOL_VERSION, AcpAgentSession } from './acpAgentSession';+import type { AcpRpcMessage } from './acpStdioClient';+import { AcpRpcResponseError, AcpServerRequestError } from './acpStdioClient';+import type { BuildAgentInputOptions } from './input';+import type {+ TraeAcpImagePromptBlock,+ TraeAcpPromptBlock,+ TraeAcpTextPromptBlock,+} from './traeAcpSession';+import { buildTraeAcpPrompt, parseTraeAcpModelCatalog } from './traeAcpSession';++const TRANSPORT = 'devin-acp' as const;++export type DevinAcpTextPromptBlock = TraeAcpTextPromptBlock;+export type DevinAcpImagePromptBlock = TraeAcpImagePromptBlock;+export type DevinAcpPromptBlock = TraeAcpPromptBlock;++interface DevinAcpInitializeResult {+ agentCapabilities?: {+ loadSession?: boolean;+ promptCapabilities?: { image?: boolean };+ };+ protocolVersion?: number | string;+}++interface DevinAcpSessionResult {+ configOptions?: unknown;+ sessionId?: string;+}++interface DevinAcpSetConfigOptionResult {+ configOptions?: unknown;+}++interface DevinAcpPromptResult {+ stopReason?: string;+ /** ACP experimental `Usage` from `session/prompt` result. */+ usage?: unknown;+}++interface DevinAcpPermissionOption {+ name: string;+ optionId: string;+}++interface DevinAcpPermissionRequest {+ options: DevinAcpPermissionOption[];+ toolCall: {+ title: string;+ toolCallId: string;+ };+}++interface CanonicalAskQuestionArgs {+ questions: Array<{+ header: string;+ multiSelect: false;+ options: Array<{ id: string; label: string }>;+ question: string;+ }>;+}++export interface DevinAcpSessionOptions extends AcpAgentSessionOptions {+ askUserBridge?: AskUserBridge;+ initialModel?: string;+ onModel?: (model: string) => void;+ /** Devin ACP permission mode, applied via `session/set_config_option`. */+ permissionMode?: string;+ prompt: DevinAcpPromptBlock[];+}++export const buildDevinAcpArgs = (extraArgs: string[] = []): string[] => {+ const args = [...extraArgs];+ let resolvedMode: string | undefined;++ // A user-supplied --permission-mode in extraArgs wins and must be moved+ // before the `acp` subcommand, since it is a `devin` global option.+ for (let i = 0; i < args.length; i += 1) {+ const arg = args[i];+ if (arg === '--permission-mode') {+ resolvedMode = args[i + 1];+ args.splice(i, 2);+ break;+ }+ if (arg.startsWith('--permission-mode=')) {+ resolvedMode = arg.slice('--permission-mode='.length);+ args.splice(i, 1);+ break;+ }+ }++ if (!resolvedMode) return ['acp', ...args];+ return ['--permission-mode', resolvedMode, 'acp', ...args];+};++export const buildDevinAcpPrompt = (+ prompt: AgentPromptInput,+ options: BuildAgentInputOptions = {},+): Promise<DevinAcpPromptBlock[]> => buildTraeAcpPrompt(prompt, options);++export const isDevinAcpSessionNotFoundError = (error: unknown): error is AcpRpcResponseError => {+ if (!(error instanceof AcpRpcResponseError) || error.method !== 'session/load') return false;++ const data = isRecord(error.rpcError.data) ? error.rpcError.data : undefined;+ return (+ error.rpcError.code === -32_016 &&+ (data?.['cognition.ai/errorKind'] === 'session_not_found' ||+ error.rpcError.message === 'Session not found')+ );+};++export class DevinAcpSession extends AcpAgentSession<+ DevinAcpInitializeResult,+ DevinAcpSessionOptions+> {+ private acceptUpdates = false;+ private readonly resolvedPermissionMode?: string;++ constructor(options: DevinAcpSessionOptions) {+ const devinArgs = buildDevinAcpArgs(options.args);+ super(options, {+ args: devinArgs,+ pipeline: { agentType: 'devin', cwd: options.cwd },+ processLabel: 'Devin ACP',+ transport: TRANSPORT,+ });+ this.resolvedPermissionMode =+ devinArgs[0] === '--permission-mode' ? devinArgs[1] : (options.permissionMode ?? undefined);+ }++ get sessionId(): string | undefined {+ return this.acpSessionId;+ }++ protected buildInitializeParams(): unknown {+ return {+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },+ clientInfo: {+ name: 'lobehub',+ title: 'LobeHub',+ version: this.options.clientVersion,+ },+ protocolVersion: ACP_PROTOCOL_VERSION,+ };+ }++ protected validateInitialized(initialized: DevinAcpInitializeResult): void {+ if (+ initialized.protocolVersion !== ACP_PROTOCOL_VERSION &&+ initialized.protocolVersion !== String(ACP_PROTOCOL_VERSION)+ ) {+ throw new Error(+ `Devin ACP returned unsupported protocol version: ${String(initialized.protocolVersion)}`,+ );+ }+ }++ protected async establishSession(initialized: DevinAcpInitializeResult): Promise<string> {+ if (+ this.options.prompt.some((block) => block.type === 'image') &&+ initialized.agentCapabilities?.promptCapabilities?.image !== true+ ) {+ throw new Error('Devin ACP agent does not support image prompt blocks');+ }+ if (this.options.resumeSessionId && initialized.agentCapabilities?.loadSession !== true) {+ throw new Error('Devin ACP agent does not support loading sessions');+ }++ const sessionResult = await this.client.request<DevinAcpSessionResult>(+ this.options.resumeSessionId ? 'session/load' : 'session/new',+ {+ cwd: this.options.cwd,+ mcpServers: [],+ ...(this.options.resumeSessionId ? { sessionId: this.options.resumeSessionId } : {}),+ },+ );+ const sessionId = sessionResult.sessionId ?? this.options.resumeSessionId;+ if (!sessionId) throw new Error('Devin ACP returned no session id');++ const model = await this.applyInitialModel(sessionId, sessionResult);+ if (this.resolvedPermissionMode) {+ await this.client.request<DevinAcpSetConfigOptionResult>('session/set_config_option', {+ configId: 'mode',+ sessionId,+ value: this.resolvedPermissionMode,+ });+ // Permission mode should not clobber the model selected above. The model+ // resolved from the model set_config_option is authoritative.+ }+ if (model) {+ this.pipeline.configureSession({ model });+ this.options.onModel?.(model);+ }+ this.options.onSessionId(sessionId);+ await this.pushToPipeline({ model, sessionId, type: 'devin_session' });+ return sessionId;+ }++ protected onBeforePrompt(): void {+ this.acceptUpdates = true;+ }++ protected buildPromptParams(sessionId: string): unknown {+ return { prompt: this.options.prompt, sessionId };+ }++ protected override async settlePrompt(result: unknown): Promise<void> {+ await this.client.drain();+ const promptResult = isRecord(result) ? result : undefined;+ await this.pushToPipeline({+ stopReason: (promptResult as DevinAcpPromptResult | undefined)?.stopReason,+ type: 'devin_prompt_completed',+ usage: (promptResult as DevinAcpPromptResult | undefined)?.usage,+ });+ }++ protected async onRunFailure(error: Error): Promise<void> {+ await this.pushToPipeline({ message: error.message, type: 'devin_error' });+ await this.emitEvents(await this.pipeline.flush());+ }++ protected async handleAgentMessage(message: AcpRpcMessage): Promise<void> {+ if (!this.acceptUpdates || message.method !== 'session/update') return;+ const params = isRecord(message.params) ? message.params : undefined;+ if (!isRecord(params?.update)) return;++ const update = this.normalizeSessionUpdate(params.update);+ if (update.sessionUpdate === 'config_option_update') {+ const model = this.resolveCurrentModel(update.configOptions);+ if (model) {+ this.pipeline.configureSession({ model });+ this.options.onModel?.(model);+ }+ }+ await this.pushToPipeline(update);+ }++ protected async handleServerRequest(message: AcpRpcMessage): Promise<unknown> {+ if (message.method !== 'session/request_permission') {+ throw new AcpServerRequestError(-32_601, `Unsupported ACP client request: ${message.method}`);+ }++ const request = this.parsePermissionRequest(message.params);+ const selected = await this.selectPermissionOption(message, request);+ return {+ outcome: selected+ ? { optionId: selected.optionId, outcome: 'selected' }+ : { outcome: 'cancelled' },+ };+ }++ private normalizeSessionUpdate(update: Record<string, unknown>): Record<string, unknown> {+ if (typeof update.name === 'string') return update;+ const meta = isRecord(update._meta) ? update._meta : undefined;+ const inferenceToolName = meta?.['cognition.ai/inferenceToolName'];+ return typeof inferenceToolName === 'string' && inferenceToolName+ ? { ...update, name: inferenceToolName }+ : update;+ }++ private resolveCurrentModel(configOptions: unknown): string | undefined {+ return parseTraeAcpModelCatalog({ configOptions })?.currentModelId;+ }++ private async applyInitialModel(+ sessionId: string,+ sessionResult: DevinAcpSessionResult,+ ): Promise<string | undefined> {+ const requestedModel = this.options.initialModel?.trim();+ if (!requestedModel || requestedModel === 'default') {+ return this.resolveCurrentModel(sessionResult.configOptions);+ }++ const currentModel = this.resolveCurrentModel(sessionResult.configOptions);+ if (+ currentModel &&+ this.normalizeModelId(currentModel) === this.normalizeModelId(requestedModel)+ ) {+ return currentModel;+ }++ const catalog = parseTraeAcpModelCatalog({ configOptions: sessionResult.configOptions });+ if (!catalog) {+ return this.setModelOption(sessionId, requestedModel);+ }++ const selected = catalog.models.find((model) =>+ [model.id, model.label].some(+ (candidate) =>+ typeof candidate === 'string' &&+ this.normalizeModelId(candidate) === this.normalizeModelId(requestedModel),+ ),+ );++ if (!selected) {+ throw new Error(`Devin ACP model is unavailable: ${requestedModel}`);+ }++ return this.setModelOption(sessionId, selected.id);+ }++ private async setModelOption(sessionId: string, value: string): Promise<string | undefined> {+ const setResult = await this.client.request<DevinAcpSetConfigOptionResult>(+ 'session/set_config_option',+ { configId: 'model', sessionId, value },+ );+ return this.resolveCurrentModel(setResult.configOptions) ?? value;+ }++ private normalizeModelId(value: string): string {+ return value.toLowerCase().replaceAll(/[^a-z0-9]/g, '');+ }++ private parsePermissionRequest(value: unknown): DevinAcpPermissionRequest {+ if (!isRecord(value) || !Array.isArray(value.options) || !isRecord(value.toolCall)) {+ throw new AcpServerRequestError(-32_602, 'Invalid session/request_permission request');+ }++ const options = value.options.flatMap((option) =>+ isRecord(option) && typeof option.name === 'string' && typeof option.optionId === 'string'+ ? [{ name: option.name, optionId: option.optionId }]+ : [],+ );+ if (+ options.length !== value.options.length ||+ options.length === 0 ||+ typeof value.toolCall.toolCallId !== 'string'+ ) {+ throw new AcpServerRequestError(-32_602, 'Invalid session/request_permission options');+ }++ const meta = isRecord(value.toolCall._meta) ? value.toolCall._meta : undefined;+ const editableCommand = meta?.['cognition.ai/editableCommand'];+ const title =+ typeof value.toolCall.title === 'string' && value.toolCall.title+ ? value.toolCall.title+ : typeof editableCommand === 'string' && editableCommand+ ? editableCommand+ : 'Allow Devin to continue?';+ return {+ options,+ toolCall: { title, toolCallId: value.toolCall.toolCallId },+ };+ }++ private async selectPermissionOption(+ message: AcpRpcMessage,+ request: DevinAcpPermissionRequest,+ ): Promise<DevinAcpPermissionOption | undefined> {+ if (!this.options.askUserBridge) return;++ const toolCallId = `devin-permission-${String(message.id)}-${request.toolCall.toolCallId}`;+ const arguments_ = {+ questions: [+ {+ header: 'Permission required',+ multiSelect: false,+ options: request.options.map(({ name, optionId }) => ({ id: optionId, label: name })),+ question: request.toolCall.title,+ },+ ],+ } satisfies CanonicalAskQuestionArgs;+ await this.pushToPipeline({+ identifier: 'claude-code',+ rawInput: arguments_,+ sessionUpdate: 'tool_call',+ title: 'askUserQuestion',+ toolCallId,+ });+ const answer = await this.options.askUserBridge.pending({+ arguments: arguments_,+ interactionKind: 'permission',+ toolCallId,+ });+ await this.pushToPipeline({+ rawOutput: answer,+ sessionUpdate: 'tool_call_update',+ status: 'completed',+ toolCallId,+ });++ const selections = this.getAnswerSelections(answer, request.toolCall.title);+ return request.options.find(({ optionId }) => selections.includes(optionId));+ }++ private getAnswerSelections(answer: InterventionAnswer, question: string): string[] {+ if (answer.cancelled || !isRecord(answer.result)) return [];+ const selection = answer.result[question];+ return (Array.isArray(selection) ? selection : [selection]).flatMap((value) =>+ typeof value === 'string' ? [value] : [],+ );+ }+}diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.tsindex 2b3b47156a0..fc49bd90b30 100644--- a/packages/heterogeneous-agents/src/spawn/index.ts+++ b/packages/heterogeneous-agents/src/spawn/index.ts@@ -97,6 +97,16 @@ export {type ListDroidAcpModelsOptions,parseDroidAcpModelCatalog,} from './droidAcpSession';+export {+ buildDevinAcpArgs,+ buildDevinAcpPrompt,+ type DevinAcpImagePromptBlock,+ type DevinAcpPromptBlock,+ DevinAcpSession,+ type DevinAcpSessionOptions,+ type DevinAcpTextPromptBlock,+ isDevinAcpSessionNotFoundError,+} from './devinAcpSession';export {createFileStoreImageUploader,type FileStoreCreateFileInput,diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.tsindex 6a43301483d..3c21cc81f82 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts@@ -246,6 +246,20 @@ describe('resolveCliCommand', () => {});});+ it('resolves and validates Devin using its version banner', async () => {+ callExecFile('/Users/x/.local/bin/devin\n');+ callExecFile('devin 3000.4.25 (7e8e528a)');++ const { detectHeterogeneousCliCommand } = await importModule();+ const status = await detectHeterogeneousCliCommand('devin', 'devin');++ expect(status).toMatchObject({+ available: true,+ path: '/Users/x/.local/bin/devin',+ version: '3000.4.25',+ });+ });+it("falls back to Cursor's unambiguous alias when another CLI owns `agent`", async () => {const originalPath = process.env.PATH;const originalShell = process.env.SHELL;diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.tsindex 6244e39e301..ab319bd9333 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts@@ -689,6 +689,9 @@ const HETEROGENEOUS_CLI_AGENT_OPTIONS = {validateHelpKeywords: ['--output-format', 'ACP modes'],validatePattern: /^v?\d+\.\d+\.\d+(?:[-+][\dA-Za-z.-]+)?$/,},+ 'devin': {+ validateKeywords: ['devin'],+ },'grok-build': {validateHelpArgs: ['agent', '--help'],validateHelpKeywords: ['agent', 'stdio'],@@ -823,6 +826,10 @@ const getWellKnownCommandPaths = (agentType: HeterogeneousCliAgentType): string[path.join(homedir(), 'Library', 'pnpm', 'droid'),];}+ case 'devin': {+ if (platform() !== 'darwin' && platform() !== 'linux') return [];+ return [path.join(homedir(), '.local', 'bin', 'devin')];+ }case 'grok-build': {if (platform() === 'win32') {return [path.join(homedir(), '.grok', 'bin', 'grok.exe')];diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.tsindex 8548b36abf4..b20cd13a3c5 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts@@ -178,11 +178,17 @@ const createGrokAcpProc = ({const createFakeAcpProc = ({promptAutoComplete = true,-}: { promptAutoComplete?: boolean } = {}) => {+ responseText = 'TRAE response',+ sessionId = 'trae-session-1',+}: { promptAutoComplete?: boolean; responseText?: string; sessionId?: string } = {}) => {const proc = new EventEmitter() as any;const stdout = new PassThrough();const stderr = new PassThrough();- const requests: Array<{ id?: number; method?: string }> = [];+ const requests: Array<{+ id?: number;+ method?: string;+ params?: Record<string, unknown>;+ }> = [];const send = (message: Record<string, unknown>) =>stdout.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`);proc.stdout = stdout;@@ -193,7 +199,11 @@ const createFakeAcpProc = ({proc.stdin = {once: vi.fn(),write: vi.fn((chunk: string) => {- const message = JSON.parse(chunk.trim()) as { id?: number; method?: string };+ const message = JSON.parse(chunk.trim()) as {+ id?: number;+ method?: string;+ params?: Record<string, unknown>;+ };requests.push(message);queueMicrotask(() => {switch (message.method) {@@ -217,11 +227,14 @@ const createFakeAcpProc = ({currentValue: 'seed-2.0-code',id: 'model',name: 'Model',- options: [{ name: 'GPT 5.4', value: 'gpt-5.4' }],+ options: [+ { name: 'GPT 5.4', value: 'gpt-5.4' },+ { name: 'Sonnet', value: 'sonnet' },+ ],type: 'select',},],- sessionId: 'trae-session-1',+ sessionId,},});return;@@ -235,9 +248,9 @@ const createFakeAcpProc = ({send({method: 'session/update',params: {- sessionId: 'trae-session-1',+ sessionId,update: {- content: { text: 'TRAE response', type: 'text' },+ content: { text: responseText, type: 'text' },sessionUpdate: 'agent_message_chunk',},},@@ -383,6 +396,32 @@ describe('spawnAgent', () => {for (const event of events) expect(event.operationId).toBe('op-1');});+ it('inherits an outer wrapper process group instead of detaching again', async () => {+ const fake = createFakeProc({ stdoutChunks: [ccInit] });+ nextFakeProc = fake.proc;+ const processKill = vi.spyOn(process, 'kill').mockImplementation(() => true);++ const { spawnAgent } = await import('./spawnAgent');+ const handle = await spawnAgent({+ agentType: 'claude-code',+ detached: false,+ operationId: 'op-inherited-group',+ prompt: 'do a thing',+ });++ expect(spawnCalls[0].options.detached).toBe(false);+ handle.kill('SIGKILL');+ expect(fake.proc.kill).toHaveBeenCalledWith('SIGKILL');+ expect(processKill).not.toHaveBeenCalled();++ fake.start();+ for await (const _event of handle.events) {+ // Drain the adapted stream so the fake process can settle cleanly.+ }+ await handle.exit;+ processKill.mockRestore();+ });+it('runs Grok Build through ACP and exposes its native session to CLI callers', async () => {const fake = createGrokAcpProc();nextFakeProc = fake.proc;@@ -564,6 +603,94 @@ describe('spawnAgent', () => {killSpy.mockRestore();});+ it('runs Devin through ACP behind the standard handle contract', async () => {+ const fake = createFakeAcpProc({+ responseText: 'Devin response',+ sessionId: 'devin-session-1',+ });+ nextFakeProc = fake.proc;+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);++ try {+ const { spawnAgent } = await import('./spawnAgent');+ const handle = await spawnAgent({+ agentType: 'devin',+ extraArgs: ['--model', 'sonnet'],+ initialModel: 'sonnet',+ operationId: 'op-devin',+ prompt: 'do a thing',+ });+ const events = [];+ for await (const event of handle.events) events.push(event);++ await expect(handle.exit).resolves.toEqual({ code: 0, signal: null });+ expect(spawnCalls[0]).toMatchObject({+ args: ['acp', '--model', 'sonnet'],+ command: 'devin',+ });+ expect(fake.requests.map(({ method }) => method).filter(Boolean)).toEqual([+ 'initialize',+ 'session/new',+ 'session/set_config_option',+ 'session/prompt',+ ]);+ expect(+ fake.requests.find(({ method }) => method === 'session/set_config_option')?.params,+ ).toEqual({+ configId: 'model',+ sessionId: 'devin-session-1',+ value: 'sonnet',+ });+ expect(handle.sessionId).toBe('devin-session-1');+ expect(events).toContainEqual(expect.objectContaining({ type: 'agent_runtime_end' }));+ } finally {+ killSpy.mockRestore();+ }+ });++ it('applies a permission mode through ACP session/set_config_option', async () => {+ const fake = createFakeAcpProc({+ responseText: 'Devin response',+ sessionId: 'devin-session-1',+ });+ nextFakeProc = fake.proc;+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);++ try {+ const { spawnAgent } = await import('./spawnAgent');+ const handle = await spawnAgent({+ agentType: 'devin',+ extraArgs: ['--model', 'sonnet'],+ initialModel: 'sonnet',+ operationId: 'op-devin',+ permissionMode: 'bypass',+ prompt: 'do a thing',+ });+ const events = [];+ for await (const event of handle.events) events.push(event);++ await expect(handle.exit).resolves.toEqual({ code: 0, signal: null });+ expect(spawnCalls[0]).toMatchObject({+ args: ['acp', '--model', 'sonnet'],+ command: 'devin',+ });+ const setConfigRequests = fake.requests.filter(+ ({ method }) => method === 'session/set_config_option',+ );+ expect(setConfigRequests).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ params: { configId: 'mode', sessionId: 'devin-session-1', value: 'bypass' },+ }),+ ]),+ );+ expect(handle.sessionId).toBe('devin-session-1');+ expect(events).toContainEqual(expect.objectContaining({ type: 'agent_runtime_end' }));+ } finally {+ killSpy.mockRestore();+ }+ });+it('runs TRAE through ACP behind the standard handle contract', async () => {const fake = createFakeAcpProc();nextFakeProc = fake.proc;diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex 4396dec68bb..fdb7c4f39b0 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -12,6 +12,7 @@ import { isPathLikeCommand, resolveCliSpawnPlan } from './cliSpawn';import { readCodexSessionModel, resolveCodexInitialModel } from './codexModel';import { buildCursorAcpPrompt, CursorAcpSession } from './cursorAcpSession';import { buildDroidAcpPrompt, DroidAcpSession } from './droidAcpSession';+import { buildDevinAcpPrompt, DevinAcpSession } from './devinAcpSession';import { buildGrokAcpPrompt, GrokAcpSession } from './grokAcpSession';import type { AgentPromptInput, BuildAgentInputOptions } from './input';import { buildAgentInput } from './input';@@ -31,6 +32,8 @@ export interface SpawnAgentOptions {command?: string;/** Working directory for the spawned child. Defaults to `process.cwd()`. */cwd?: string;+ /** Create a dedicated Unix process group. Disable beneath a detached wrapper. */+ detached?: boolean;/** Extra environment variables merged on top of `process.env`. */env?: Record<string, string>;/** Extra CLI arguments appended after the agent's preset flags. */@@ -66,6 +69,8 @@ export interface SpawnAgentOptions {* events still carry the conventional shape.*/operationId: string;+ /** (Devin ACP only) Global `--permission-mode` value, placed before `acp`. */+ permissionMode?: string;/*** User prompt. A plain string is sugar for a single text block; the array* form supports mixed text + image content blocks (URL / path / base64).@@ -101,9 +106,9 @@ export interface SpawnAgentHandle {*/exit: Promise<{ code: number | null; signal: NodeJS.Signals | null }>;/**- * Send a signal to the child. On Unix, the child is spawned with- * `detached: true` so the whole process group can be signaled via- * `process.kill(-pid, signal)`; this helper does that automatically.+ * Send a signal to the child. A dedicated Unix process group is signaled as+ * a tree; inherited-group children receive a direct signal because their+ * outer wrapper owns group-level cancellation.*/kill: (signal?: NodeJS.Signals) => void;/** Spawned child PID, undefined if spawn failed pre-PID. */@@ -354,7 +359,7 @@ const buildSpawnArgs = (params: BuildSpawnArgsParams): string[] => {}};-const killProcessTree = (proc: ChildProcess, signal: NodeJS.Signals): void => {+const killProcessTree = (proc: ChildProcess, signal: NodeJS.Signals, detached: boolean): void => {if (!proc.pid || proc.killed) return;// On Windows the spawn `detached` flag has different semantics; fall back@@ -370,15 +375,20 @@ const killProcessTree = (proc: ChildProcess, signal: NodeJS.Signals): void => {return;}- try {- process.kill(-proc.pid, signal);- } catch {+ if (detached) {try {- proc.kill(signal);+ process.kill(-proc.pid, signal);+ return;} catch {- // already gone+ // Fall through to a direct signal when the process group is gone.}}++ try {+ proc.kill(signal);+ } catch {+ // already gone+ }};/** Guarded raw-stdout tee: diagnostic sink failures must not affect the ACP run. */@@ -483,6 +493,35 @@ const createAcpSpawnBridge = () => {return { attach, events, onEvents, onStderr, stderr };};+interface AcpSpawnSession {+ close: (signal?: NodeJS.Signals) => void;+ interrupt: () => void;+ pid?: number;+ run: () => Promise<void>;+ sessionId?: string;+}++const createAcpSpawnHandle = (+ bridge: ReturnType<typeof createAcpSpawnBridge>,+ session: AcpSpawnSession,+ getSessionId: () => string | undefined = () => session.sessionId,+): SpawnAgentHandle => {+ const { exit, kill } = bridge.attach(session);++ return {+ events: bridge.events,+ exit,+ kill,+ get pid() {+ return session.pid;+ },+ get sessionId() {+ return getSessionId();+ },+ stderr: bridge.stderr,+ };+};+const spawnGrokAcpAgent = async (options: SpawnAgentOptions,command: string,@@ -495,6 +534,7 @@ const spawnGrokAcpAgent = async (clientVersion: 'lobehub-cli',commandPath: command,cwd,+ detached: options.detached,env: { ...process.env, ...options.env },onEvents: bridge.onEvents,onRawMessage: teeAcpRawStdout(options.onRawStdout),@@ -506,20 +546,7 @@ const spawnGrokAcpAgent = async (resumeSessionId: options.resumeSessionId,sessionId: options.operationId,});- const { exit, kill } = bridge.attach(session);-- return {- events: bridge.events,- exit,- kill,- get pid() {- return session.pid;- },- get sessionId() {- return session.sessionId;- },- stderr: bridge.stderr,- };+ return createAcpSpawnHandle(bridge, session);};const spawnCursorAcpAgent = async (@@ -535,6 +562,7 @@ const spawnCursorAcpAgent = async (clientVersion: 'lobehub-cli',commandPath: command,cwd,+ detached: options.detached,env: { ...process.env, ...options.env },onEvents: bridge.onEvents,onRawMessage: teeAcpRawStdout(options.onRawStdout),@@ -546,20 +574,7 @@ const spawnCursorAcpAgent = async (resumeSessionId: options.resumeSessionId,sessionId: options.operationId,});- const { exit, kill } = bridge.attach(session);-- return {- events: bridge.events,- exit,- kill,- get pid() {- return session.pid;- },- get sessionId() {- return session.sessionId;- },- stderr: bridge.stderr,- };+ return createAcpSpawnHandle(bridge, session);};const spawnDroidAcpAgent = async (@@ -603,6 +618,36 @@ const spawnDroidAcpAgent = async (};};+const spawnDevinAcpAgent = async (+ options: SpawnAgentOptions,+ command: string,+ cwd: string,+): Promise<SpawnAgentHandle> => {+ const prompt = await buildDevinAcpPrompt(options.prompt, options.inputOptions);+ const bridge = createAcpSpawnBridge();+ const session = new DevinAcpSession({+ args: options.extraArgs ?? [],+ askUserBridge: options.askUserBridge,+ clientVersion: 'lobehub-cli',+ commandPath: command,+ cwd,+ detached: options.detached,+ env: { ...process.env, ...options.env },+ initialModel: options.initialModel,+ onEvents: bridge.onEvents,+ permissionMode: options.permissionMode,+ onRawMessage: teeAcpRawStdout(options.onRawStdout),+ onRuntimeStatus: () => {},+ onSessionId: () => {},+ onStderr: bridge.onStderr,+ operationId: options.operationId,+ prompt,+ resumeSessionId: options.resumeSessionId,+ sessionId: options.operationId,+ });+ return createAcpSpawnHandle(bridge, session);+};+/*** Spawn an external agent CLI (Amp, Claude Code, CodeBuddy, Codex, Cursor,* Factory Droid, Kimi Code, OpenCode, Pi, Qoder, or TRAE) and yield its stream as unified@@ -624,6 +669,9 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentconst command = resolveHeterogeneousAgentCommand(options.agentType, options.command);const cwd = options.cwd || process.cwd();assertSpawnableWorkingDirectory(cwd);+ if (options.agentType === 'devin') {+ return spawnDevinAcpAgent(options, command, cwd);+ }if (options.agentType === 'grok-build') {return spawnGrokAcpAgent(options, command, cwd);}@@ -658,9 +706,10 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentconst initialCumulativeUsage = resumedCodexSession?.cumulativeUsage;const cliSpawnPlan = await resolveCliSpawnPlan(command, args);+ const detached = process.platform !== 'win32' && (options.detached ?? true);const proc = spawn(cliSpawnPlan.command, cliSpawnPlan.args, {cwd,- detached: process.platform !== 'win32',+ detached,env: childEnv,stdio: ['pipe', 'pipe', 'pipe'],});@@ -808,7 +857,7 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentexit,kill: (signal: NodeJS.Signals = 'SIGINT') => {killedByUs = true;- killProcessTree(proc, signal);+ killProcessTree(proc, signal, detached);},pid: proc.pid,get sessionId() {@@ -841,6 +890,7 @@ export const spawnTraeAcpAgent = async (options: SpawnAgentOptions): Promise<SpaclientVersion: '1.0.0',commandPath: commandStatus.path,cwd,+ detached: options.detached,env: {...childEnv,...(commandStatus.resolvedPathEnv ? { PATH: commandStatus.resolvedPathEnv } : {}),@@ -856,18 +906,5 @@ export const spawnTraeAcpAgent = async (options: SpawnAgentOptions): Promise<SparesumeSessionId: options.resumeSessionId,sessionId: options.operationId,});- const { exit, kill } = bridge.attach(session);-- return {- events: bridge.events,- exit,- kill,- get pid() {- return session.pid;- },- get sessionId() {- return session.nativeSessionId;- },- stderr: bridge.stderr,- };+ return createAcpSpawnHandle(bridge, session, () => session.nativeSessionId);};diff --git a/packages/heterogeneous-agents/src/spawn/traeAcpSession.ts b/packages/heterogeneous-agents/src/spawn/traeAcpSession.tsindex dfc356c5348..36265a2f4ff 100644--- a/packages/heterogeneous-agents/src/spawn/traeAcpSession.ts+++ b/packages/heterogeneous-agents/src/spawn/traeAcpSession.ts@@ -184,7 +184,9 @@ export const parseTraeAcpModelCatalog = (const configOptions = Array.isArray(result?.configOptions)? result.configOptions.map((value) => value as TraeAcpConfigOption | null): [];- const selectableOptions = configOptions.filter((option) => option?.type === 'select');+ const selectableOptions = configOptions.filter(+ (option) => option?.type === undefined || option.type === 'select',+ );const modelConfig =selectableOptions.find((option) => option?.category === 'model') ??selectableOptions.find((option) => option?.id === 'model') ??diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.tsindex eaa74f31aec..df765bbbb27 100644--- a/packages/heterogeneous-agents/src/types.ts+++ b/packages/heterogeneous-agents/src/types.ts@@ -300,6 +300,8 @@ export interface ToolCallPayload {* this shape. Provider-specific shape knowledge does not leak past the adapter.*/export interface UsageData {+ /** Estimated session or turn cost in USD, if the CLI reports it. */+ cost?: number;/** Input tokens served from the prompt cache (cache reads). */inputCachedTokens?: number;/** Input tokens that missed the prompt cache (fresh prompt bytes). */diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex ad44205aaa9..acf3e06fccb 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1006,6 +1006,17 @@ export default {'droidInstallGuide.menuNotification.title': 'Factory Droid CLI not found','droidInstallGuide.reason': 'LobeHub could not start Factory Droid: {{message}}','droidInstallGuide.title': 'Install Factory Droid CLI',+ 'devinInstallGuide.actions.openDocs': 'Open Install Guide',+ 'devinInstallGuide.actions.openSystemTools': 'Open System Tools',+ 'devinInstallGuide.afterInstall':+ 'After installing, run `devin auth login`, then retry your message or click Re-detect in System Tools.',+ 'devinInstallGuide.desc':+ 'Devin needs the Devin CLI to run locally. Install it and make sure the `devin` command is available in your PATH.',+ 'devinInstallGuide.installWithBrew': 'Windows PowerShell',+ 'devinInstallGuide.installWithNpm': 'macOS / Linux / WSL',+ 'devinInstallGuide.menuNotification.title': 'Devin CLI not found',+ 'devinInstallGuide.reason': 'LobeHub could not start Devin: {{message}}',+ 'devinInstallGuide.title': 'Install Devin CLI','grokBuildInstallGuide.actions.openDocs': 'Open Install Guide','grokBuildInstallGuide.actions.openSystemTools': 'Open System Tools','grokBuildInstallGuide.afterInstall':@@ -1085,6 +1096,7 @@ export default {'newCodexAgent': 'Add Codex','newCursorAgent': 'Add Cursor','newDroidAgent': 'Add Factory Droid',+ 'newDevinAgent': 'Add Devin','newGrokBuildAgent': 'Add Grok Build','newKimiCodeAgent': 'Add Kimi Code','newOpenCodeAgent': 'Add OpenCode',@@ -1176,6 +1188,7 @@ export default {'connectAgent.providerDesc.codex': 'OpenAI coding agent CLI','connectAgent.providerDesc.cursor': 'Cursor coding agent CLI','connectAgent.providerDesc.droid': 'Factory coding agent CLI',+ 'connectAgent.providerDesc.devin': 'Cognition coding agent CLI','connectAgent.providerDesc.grok-build': 'xAI coding agent CLI','connectAgent.providerDesc.amp': 'Sourcegraph coding agent CLI','connectAgent.providerDesc.kimi-code': 'Moonshot AI coding agent CLI',diff --git a/packages/types/src/agent/agencyConfig.test.ts b/packages/types/src/agent/agencyConfig.test.tsindex be8af52881e..807ec820b15 100644--- a/packages/types/src/agent/agencyConfig.test.ts+++ b/packages/types/src/agent/agencyConfig.test.ts@@ -308,6 +308,34 @@ describe('buildHeteroSpawnArgs', () => {).toEqual(['--model', 'gpt-5']);});+ it('forwards Devin native arguments and model through direct ACP and device execution', () => {+ const provider: HeterogeneousProviderConfig = {+ args: ['--agent-type', 'coding'],+ model: 'claude-sonnet-4-6-thinking',+ type: 'devin',+ };++ expect(buildHeteroSpawnArgs(provider)).toEqual([+ '--agent-type',+ 'coding',+ '--model',+ 'claude-sonnet-4-6-thinking',+ ]);+ expect(buildHeteroExecArgs(provider)).toEqual([+ '--agent-arg=--agent-type',+ '--agent-arg=coding',+ '--model',+ 'claude-sonnet-4-6-thinking',+ ]);+ expect(+ buildHeteroSpawnArgs({+ args: ['--model', 'native-model'],+ model: 'selector-model',+ type: 'devin',+ }),+ ).toEqual(['--model', 'native-model']);+ });+it('forwards Grok Build model and effort through direct ACP and device execution', () => {const provider: HeterogeneousProviderConfig = {args: ['--no-subagents'],diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.tsindex d23fb215f5a..60403a671bc 100644--- a/packages/types/src/agent/agencyConfig.ts+++ b/packages/types/src/agent/agencyConfig.ts@@ -56,7 +56,16 @@ export interface ListHeterogeneousAgentModelsParams {command?: string;cwd?: string;env?: Record<string, string>;- type: 'codebuddy' | 'cursor' | 'droid' | 'grok-build' | 'opencode' | 'pi' | 'qoder' | 'trae';+ type:+ | 'codebuddy'+ | 'cursor'+ | 'devin'+ | 'droid'+ | 'grok-build'+ | 'opencode'+ | 'pi'+ | 'qoder'+ | 'trae';}export interface HeterogeneousAgentModelCatalogSuccess {@@ -538,6 +547,7 @@ export const buildHeteroSpawnArgs = (provider.type !== 'codex' &&provider.type !== 'cursor' &&provider.type !== 'droid' &&+ provider.type !== 'devin' &&provider.type !== 'grok-build' &&provider.type !== 'kimi-code' &&provider.type !== 'opencode' &&@@ -610,7 +620,7 @@ export const buildHeteroSpawnArgs = (}}- if (provider.type === 'cursor' || provider.type === 'kimi-code') {+ if (provider.type === 'cursor' || provider.type === 'devin' || provider.type === 'kimi-code') {const model = provider.model?.trim();if (model &&@@ -674,6 +684,7 @@ export const buildHeteroExecArgs = (provider.type !== 'codex' &&provider.type !== 'cursor' &&provider.type !== 'droid' &&+ provider.type !== 'devin' &&provider.type !== 'grok-build' &&provider.type !== 'kimi-code' &&provider.type !== 'opencode' &&@@ -766,7 +777,7 @@ export const buildHeteroExecArgs = (}}- if (provider.type === 'cursor' || provider.type === 'kimi-code') {+ if (provider.type === 'cursor' || provider.type === 'devin' || provider.type === 'kimi-code') {const model = provider.model?.trim();if (model &&diff --git a/packages/types/src/agent/heteroSelectorCapabilities.test.ts b/packages/types/src/agent/heteroSelectorCapabilities.test.tsindex 6e73d88f797..5dffcf65831 100644--- a/packages/types/src/agent/heteroSelectorCapabilities.test.ts+++ b/packages/types/src/agent/heteroSelectorCapabilities.test.ts@@ -19,6 +19,7 @@ describe('selector availability', () => {expect(isHeteroSelectorAvailable('codex')).toBe(true);expect(isHeteroSelectorAvailable('cursor')).toBe(true);expect(isHeteroSelectorAvailable('droid')).toBe(true);+ expect(isHeteroSelectorAvailable('devin')).toBe(true);expect(isHeteroSelectorAvailable('grok-build')).toBe(true);expect(isHeteroSelectorAvailable('opencode')).toBe(true);expect(isHeteroSelectorAvailable('pi')).toBe(true);@@ -42,6 +43,7 @@ describe('selector availability', () => {expect(getHeteroSelectorCapability('codex')?.speed).toBeDefined();expect(getHeteroSelectorCapability('cursor')?.model?.source).toBe('catalog');expect(getHeteroSelectorCapability('droid')?.model?.source).toBe('catalog');+ expect(getHeteroSelectorCapability('devin')?.model?.source).toBe('catalog');expect(getHeteroSelectorCapability('grok-build')?.model?.source).toBe('catalog');expect(getHeteroSelectorCapability('grok-build')?.effort?.levels('grok-4.6')).toEqual(['low',@@ -157,6 +159,25 @@ describe('applyHeteroSelection', () => {]);});+ it('clears a hand-authored Devin model before applying a catalog selection', () => {+ const provider: HeterogeneousProviderConfig = {+ args: ['--agent-type', 'coding', '--model=old-model'],+ type: 'devin',+ };+ const patch = applyHeteroSelection(provider, { model: 'claude-sonnet-4-6-thinking' });++ expect(patch).toEqual({+ args: ['--agent-type', 'coding'],+ model: 'claude-sonnet-4-6-thinking',+ });+ expect(buildHeteroSpawnArgs({ ...provider, ...patch })).toEqual([+ '--agent-type',+ 'coding',+ '--model',+ 'claude-sonnet-4-6-thinking',+ ]);+ });+it('clears Grok Build model and effort flags before applying a selection', () => {const provider: HeterogeneousProviderConfig = {args: ['-m', 'old-model', '--reasoning-effort=low', '--no-subagents'],diff --git a/packages/types/src/agent/heteroSelectorCapabilities.ts b/packages/types/src/agent/heteroSelectorCapabilities.tsindex 6f2c1656d46..8da810a3546 100644--- a/packages/types/src/agent/heteroSelectorCapabilities.ts+++ b/packages/types/src/agent/heteroSelectorCapabilities.ts@@ -410,6 +410,13 @@ export const HETERO_SELECTOR_CAPABILITIES = {'droid': {model: { encodings: [], resolve: resolvePersistedModel, source: 'catalog' },},+ 'devin': {+ model: {+ encodings: [{ flags: ['--model'], kind: 'flag' }],+ resolve: resolvePersistedModel,+ source: 'catalog',+ },+ },'grok-build': {effort: {encodings: [{ flags: GROK_BUILD_REASONING_EFFORT_FLAGS, kind: 'flag' }],diff --git a/packages/types/src/agent/heterogeneousAgent.ts b/packages/types/src/agent/heterogeneousAgent.tsindex 89d41fa89f2..5ade849b1f6 100644--- a/packages/types/src/agent/heterogeneousAgent.ts+++ b/packages/types/src/agent/heterogeneousAgent.ts@@ -208,6 +208,35 @@ export const HETEROGENEOUS_AGENT_CONFIGS = [title: 'Factory Droid',type: 'droid',},+ {+ auth: {+ docsUrl: 'https://docs.devin.ai/cli/enterprise/devin-auth',+ errorMessage: 'Devin could not authenticate. Run `devin auth login`, then retry.',+ patterns: [+ ...COMMON_AUTH_REQUIRED_PATTERNS,+ 'authentication required',+ 'not logged in',+ 'devin auth login',+ ],+ signInCommand: 'devin auth login',+ },+ defaultCommand: 'devin',+ defaultTopicGroupMode: 'byProject',+ iconId: 'Devin',+ install: {+ commands: [+ 'curl -fsSL https://cli.devin.ai/install.sh | bash',+ 'irm https://static.devin.ai/cli/setup.ps1 | iex',+ ],+ docsUrl: 'https://docs.devin.ai/cli',+ },+ kind: 'local-cli',+ menuKey: 'newDevinAgent',+ menuLabelKey: 'newDevinAgent',+ resume: { supported: true },+ title: 'Devin',+ type: 'devin',+ },{auth: {docsUrl: 'https://docs.x.ai/build/overview',diff --git a/packages/types/src/agent/heterogeneousIntervention.ts b/packages/types/src/agent/heterogeneousIntervention.tsindex 1b7622e1c5c..ab5c0549abf 100644--- a/packages/types/src/agent/heterogeneousIntervention.ts+++ b/packages/types/src/agent/heterogeneousIntervention.ts@@ -6,6 +6,7 @@ export type HeterogeneousAgentInterventionKind =export const HETEROGENEOUS_AGENT_INTERVENTION_PROVIDERS = ['claude-code','cursor',+ 'devin','droid','qoder',] as const;diff --git a/packages/types/src/tool/intervention.test.ts b/packages/types/src/tool/intervention.test.tsnew file mode 100644index 00000000000..d25fc812114--- /dev/null+++ b/packages/types/src/tool/intervention.test.ts@@ -0,0 +1,16 @@+import { describe, expect, it } from 'vitest';++import { classifyToolInterventionPresentation } from './intervention';++describe('classifyToolInterventionPresentation', () => {+ it('renders Devin questions and provider-specific interactions as forms', () => {+ expect(classifyToolInterventionPresentation('devin', 'askUserQuestion')).toEqual({+ interactionKind: 'question',+ surface: 'form',+ });+ expect(classifyToolInterventionPresentation('devin', 'requestPermission')).toEqual({+ interactionKind: 'custom',+ surface: 'form',+ });+ });+});diff --git a/packages/types/src/tool/intervention.ts b/packages/types/src/tool/intervention.tsindex c98faff98e1..ceef9ab1cd3 100644--- a/packages/types/src/tool/intervention.ts+++ b/packages/types/src/tool/intervention.ts@@ -165,6 +165,7 @@ export type ToolInterventionPresentation = {const ASK_USER_QUESTION_IDENTIFIERS = new Set(['claude-code','cursor',+ 'devin','droid','lobe-agent','lobe-user-interaction',@@ -174,6 +175,7 @@ const ASK_USER_QUESTION_IDENTIFIERS = new Set([const HETEROGENEOUS_CUSTOM_INTERACTION_IDENTIFIERS = new Set(['claude-code','cursor',+ 'devin','droid','qoder',]);@@ -190,7 +192,7 @@ export const classifyToolInterventionPresentation = (return { interactionKind: 'custom', surface: 'form' };}- // Claude Code / Cursor ACP / Droid ACP / Qoder expose provider-specific intervention+ // Claude Code / Cursor ACP / Devin ACP / Droid ACP / Qoder expose provider-specific intervention// forms (permission, plan, bespoke prompts). They are intentionally kept// non-binary even when a newly added API name is not yet known to Web.if (HETEROGENEOUS_CUSTOM_INTERACTION_IDENTIFIERS.has(identifier)) {diff --git a/src/features/ConnectAgent/providers.ts b/src/features/ConnectAgent/providers.tsindex bb2fd37cab7..6cf0b59f8a0 100644--- a/src/features/ConnectAgent/providers.ts+++ b/src/features/ConnectAgent/providers.ts@@ -17,6 +17,7 @@ import {CodeBuddy,Codex,Cursor,+ Devin,Grok,HermesAgent,Kimi,@@ -43,6 +44,7 @@ export interface ConnectableProvider {| typeof Codex| typeof Cursor| typeof DroidIcon+ | typeof Devin| typeof Grok| typeof HermesAgent| typeof Kimi@@ -78,6 +80,7 @@ const CLI_BRANDS: Record<LocalHeterogeneousAgentType, ConnectableProvider['brand'codex': Codex,'cursor': Cursor,'droid': DroidIcon,+ 'devin': Devin,'grok-build': Grok,'kimi-code': Kimi,'opencode': OpenCode,diff --git a/src/features/Conversation/Error/heterogeneous.ts b/src/features/Conversation/Error/heterogeneous.tsindex b82bc2eddea..bafbd1660db 100644--- a/src/features/Conversation/Error/heterogeneous.ts+++ b/src/features/Conversation/Error/heterogeneous.ts@@ -34,6 +34,7 @@ export const isHeterogeneousAgentStatusGuideError = (agentType === 'codex' ||agentType === 'cursor' ||agentType === 'droid' ||+ agentType === 'devin' ||agentType === 'grok-build' ||agentType === 'kimi-code' ||agentType === 'opencode' ||diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsxindex 28853be7859..0de3a2fda2b 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx@@ -1,10 +1,16 @@/*** @vitest-environment happy-dom*/-import { render, screen } from '@testing-library/react';+import type { BuiltinInterventionProps } from '@lobechat/types';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';import { describe, expect, it, vi } from 'vitest';import FallbackIntervention from './Fallback';+import Intervention from './index';++const { submitHeteroIntervention } = vi.hoisted(() => ({+ submitHeteroIntervention: vi.fn(),+}));const metaMap: Record<string, { avatar?: string; title?: string }> = {'calculator': { title: 'Calculator' },@@ -28,6 +34,31 @@ vi.mock('react-i18next', () => ({}),}));+vi.mock('@lobechat/builtin-tools/interventions', () => ({+ getBuiltinIntervention: (identifier?: string, apiName?: string) => {+ if (identifier !== 'devin' || apiName !== 'askUserQuestion') return;++ return ({ onInteractionAction }: BuiltinInterventionProps) => (+ <button+ data-testid="devin-permission-option"+ type="button"+ onClick={() =>+ void onInteractionAction?.({+ payload: { 'Allow Devin to continue?': 'allow-once' },+ type: 'submit',+ })+ }+ >+ Allow once+ </button>+ );+ },+}));++vi.mock('../../../../../hooks/useConversationResourceAccess', () => ({+ useConversationResourceAccess: () => ({ canUseResource: true }),+}));+vi.mock('@/store/tool/selectors', () => ({toolSelectors: {getMetaById: (id: string) => () => metaMap[id],@@ -56,8 +87,21 @@ vi.mock('../../../../../store', () => ({getDbMessageById: () => () => undefined,},useConversationStore: (- selector: (state: { updatePluginArguments: ReturnType<typeof vi.fn> }) => unknown,- ) => selector({ updatePluginArguments: vi.fn() }),+ selector: (state: {+ cancelToolInteraction: ReturnType<typeof vi.fn>;+ skipToolInteraction: ReturnType<typeof vi.fn>;+ submitHeteroIntervention: typeof submitHeteroIntervention;+ submitToolInteraction: ReturnType<typeof vi.fn>;+ updatePluginArguments: ReturnType<typeof vi.fn>;+ }) => unknown,+ ) =>+ selector({+ cancelToolInteraction: vi.fn(),+ skipToolInteraction: vi.fn(),+ submitHeteroIntervention,+ submitToolInteraction: vi.fn(),+ updatePluginArguments: vi.fn(),+ }),}));vi.mock('../Arguments', () => ({@@ -126,3 +170,25 @@ describe('FallbackIntervention', () => {expect(screen.getByRole('img', { name: 'Web Search' })).toHaveAttribute('src', iconUrl);});});++describe('heterogeneous custom intervention', () => {+ it('routes a Devin permission option ID through submitHeteroIntervention', async () => {+ render(+ <Intervention+ apiName="askUserQuestion"+ id="message-devin-permission"+ identifier="devin"+ requestArgs='{"questions":[{"question":"Allow Devin to continue?","options":[{"id":"allow-once","label":"Allow once"}]}]}'+ toolCallId="devin-permission-1"+ />,+ );++ fireEvent.click(screen.getByTestId('devin-permission-option'));++ await waitFor(() => {+ expect(submitHeteroIntervention).toHaveBeenCalledWith('message-devin-permission', 'submit', {+ 'Allow Devin to continue?': 'allow-once',+ });+ });+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.tsindex 752188c453f..8cdd9812cfb 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.ts+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.ts@@ -105,9 +105,12 @@ describe('customInteractionHandlers', () => {});});- it.each(['droid', 'qoder'])('routes %s tools through the heterogeneous custom flow', (type) => {- expect(isCustomInteractionIdentifier(type, 'askUserQuestion')).toBe(true);- });+ it.each(['devin', 'droid', 'qoder'])(+ 'routes %s tools through the heterogeneous custom flow',+ (type) => {+ expect(isCustomInteractionIdentifier(type, 'askUserQuestion')).toBe(true);+ },+ );it('persists skipped marketplace picks from the original tool arguments', async () => {await recordCustomInteractionResolution(diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.tsindex 275c1be9596..6151c45650e 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts@@ -16,6 +16,7 @@ import { installMarketplaceAgents } from '@/services/installMarketplaceAgents';import { topicService } from '@/services/topic';const CURSOR_IDENTIFIER = 'cursor';+const DEVIN_IDENTIFIER = 'devin';const DROID_IDENTIFIER = 'droid';const QODER_IDENTIFIER = 'qoder';@@ -168,6 +169,7 @@ const findCustomInteractionSubmitHandler = (identifier: string, apiName?: stringconst HETERO_CUSTOM_INTERACTION_IDENTIFIERS = new Set<string>([ClaudeCodeIdentifier,CURSOR_IDENTIFIER,+ DEVIN_IDENTIFIER,DROID_IDENTIFIER,QODER_IDENTIFIER,]);diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsxindex 87c65c80071..51e3c0613a5 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/config.tsx@@ -7,6 +7,7 @@ import {CodeBuddy,Codex,Cursor,+ Devin,Grok,Kimi,OpenCode,@@ -46,6 +47,10 @@ const GUIDE_PRESENTATION_CONFIG = {icon: DroidIcon,translationPrefix: 'droidInstallGuide',},+ 'devin': {+ icon: Devin,+ translationPrefix: 'devinInstallGuide',+ },'grok-build': {icon: Grok,translationPrefix: 'grokBuildInstallGuide',diff --git a/src/features/Recommendations/actions/heteroAgent.ts b/src/features/Recommendations/actions/heteroAgent.tsindex 56da9434663..71b6935d3b3 100644--- a/src/features/Recommendations/actions/heteroAgent.ts+++ b/src/features/Recommendations/actions/heteroAgent.ts@@ -8,6 +8,7 @@ import {CodeBuddy,Codex,Cursor,+ Devin,Grok,Kimi,OpenCode,@@ -26,6 +27,7 @@ const avatarIcons = {'codex': Codex.Avatar,'cursor': Cursor.Avatar,'droid': DroidIcon.Avatar,+ 'devin': Devin.Avatar,'grok-build': Grok.Avatar,'kimi-code': Kimi.Avatar,'opencode': OpenCode.Avatar,diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.tsindex 28183fe9feb..464dec159a3 100644--- a/src/helpers/executionTarget.test.ts+++ b/src/helpers/executionTarget.test.ts@@ -62,6 +62,7 @@ describe('isHeterogeneousSandboxExecutionAvailable', () => {it('keeps local-only CLIs on local or connected devices', () => {expect(isHeterogeneousSandboxExecutionAvailable('droid')).toBe(false);+ expect(isHeterogeneousSandboxExecutionAvailable('devin')).toBe(false);expect(isHeterogeneousSandboxExecutionAvailable('qoder')).toBe(false);expect(isHeterogeneousSandboxExecutionAvailable('trae')).toBe(false);});diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.tsindex 3758d19fa14..d2ef4b3c1c8 100644--- a/src/helpers/executionTarget.ts+++ b/src/helpers/executionTarget.ts@@ -118,6 +118,7 @@ export const isHeterogeneousSandboxExecutionAvailable = (type: string | undefinetype !== 'codebuddy' &&type !== 'cursor' &&type !== 'droid' &&+ type !== 'devin' &&type !== 'kimi-code' &&type !== 'hermes' &&type !== 'opencode' &&diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsxindex 2ed5077f0e9..a8b2deb1d7b 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.tsx@@ -346,6 +346,7 @@ const HeterogeneousAgentStatusCard = memo<HeterogeneousAgentStatusCardProps>(provider.type === 'codex' ||provider.type === 'cursor' ||provider.type === 'droid' ||+ provider.type === 'devin' ||provider.type === 'kimi-code' ||provider.type === 'opencode' ||provider.type === 'pi' ||diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex b19e6484718..54e5248049c 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -2192,6 +2192,29 @@ describe('heterogeneousAgentExecutor DB persistence', () => {);});+ it('should pass the selected Devin model through ACP and native args', async () => {+ const store = createMockStore();+ const get = vi.fn(() => store);++ await executeHeterogeneousAgent(get, {+ ...defaultParams,+ heterogeneousProvider: {+ args: ['--agent-type', 'coding'],+ command: 'devin',+ model: 'claude-sonnet-4-6-thinking',+ type: 'devin' as const,+ },+ });++ expect(mockStartSession).toHaveBeenCalledWith(+ expect.objectContaining({+ agentType: 'devin',+ args: ['--agent-type', 'coding', '--model', 'claude-sonnet-4-6-thinking'],+ initialModel: 'claude-sonnet-4-6-thinking',+ }),+ );+ });+it('should execute a persisted legacy provider config without type', async () => {const store = createMockStore();const get = vi.fn(() => store);diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex fea2a25b47b..d4940a41e92 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -1937,7 +1937,7 @@ export const executeHeterogeneousAgent = async (cwd: workingDirectory,env: sessionEnv,initialModel:- (adapterType === 'droid' || adapterType === 'trae') &&+ (adapterType === 'devin' || adapterType === 'droid' || adapterType === 'trae') &&!providerBindingActive &&heterogeneousProvider.model &&heterogeneousProvider.model !== HETEROGENEOUS_AGENT_DEFAULT_SELECTIONdiff --git a/src/store/tool/builtinToolRegistry.test.ts b/src/store/tool/builtinToolRegistry.test.tsindex f065c990cac..f1d2c7c727c 100644--- a/src/store/tool/builtinToolRegistry.test.ts+++ b/src/store/tool/builtinToolRegistry.test.ts@@ -419,6 +419,11 @@ describe('builtin tool registry', () => {expect(getBuiltinRender('droid', UserInteractionApiName.askUserQuestion)).toBeDefined();expect(getBuiltinIntervention('droid', UserInteractionApiName.askUserQuestion)).toBeDefined();expect(getBuiltinRender('droid', 'Read')).toBeUndefined();+ expect(getBuiltinInspector('devin', UserInteractionApiName.askUserQuestion)).toBeDefined();+ expect(getBuiltinRender('devin', UserInteractionApiName.askUserQuestion)).toBeDefined();+ expect(getBuiltinIntervention('devin', UserInteractionApiName.askUserQuestion)).toBe(+ ClaudeCodeInterventions[UserInteractionApiName.askUserQuestion],+ );expect(getBuiltinIntervention('qoder', UserInteractionApiName.askUserQuestion)).toBeDefined();});diff --git a/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.ts b/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.tsindex 5b76df15f5d..54c58e64539 100644--- a/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.ts+++ b/src/store/tool/slices/builtin/executors/__tests__/heteroCli.test.ts@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import {claudeCodeExecutor,codexExecutor,+ devinExecutor,droidExecutor,grokBuildExecutor,kimiCodeExecutor,@@ -40,6 +41,7 @@ describe('heteroCli executors', () => {expect(claudeCodeExecutor.identifier).toBe('claude-code');expect(codexExecutor.identifier).toBe('codex');expect(droidExecutor.identifier).toBe('droid');+ expect(devinExecutor.identifier).toBe('devin');expect(grokBuildExecutor.identifier).toBe('grok-build');expect(kimiCodeExecutor.identifier).toBe('kimi-code');expect(openCodeExecutor.identifier).toBe('opencode');@@ -78,6 +80,22 @@ describe('heteroCli executors', () => {});});+ it('observes Devin exec calls for worktree side effects', async () => {+ await devinExecutor.onAfterCall!(+ call({+ apiName: 'exec',+ identifier: 'devin',+ params: { command: 'git worktree add /tmp/devin-wt' },+ }),+ );++ expect(detectMocks.recordGitCommandEffects).toHaveBeenCalledWith({+ command: 'git worktree add /tmp/devin-wt',+ resultContent: '',+ topicId: 't1',+ });+ });+it('observes Grok Build execute calls for worktree side effects', async () => {await grokBuildExecutor.onAfterCall!(call({diff --git a/src/store/tool/slices/builtin/executors/catalog.ts b/src/store/tool/slices/builtin/executors/catalog.tsindex 90ea04f300e..cdd6f0a4ae3 100644--- a/src/store/tool/slices/builtin/executors/catalog.ts+++ b/src/store/tool/slices/builtin/executors/catalog.ts@@ -21,6 +21,7 @@ import {codeBuddyExecutor,codexExecutor,cursorExecutor,+ devinExecutor,droidExecutor,grokBuildExecutor,kimiCodeExecutor,@@ -51,6 +52,7 @@ export const builtinToolExecutors = [codexExecutor,cursorExecutor,droidExecutor,+ devinExecutor,grokBuildExecutor,kimiCodeExecutor,openCodeExecutor,diff --git a/src/store/tool/slices/builtin/executors/heteroCli.ts b/src/store/tool/slices/builtin/executors/heteroCli.tsindex 941ab6d1e24..7c0eabfaa43 100644--- a/src/store/tool/slices/builtin/executors/heteroCli.ts+++ b/src/store/tool/slices/builtin/executors/heteroCli.ts@@ -110,6 +110,7 @@ export const cursorExecutor = new HeteroCliExecutor('cursor', new Set(['shellToo// Droid's ACP shell tool name is not a documented protocol guarantee. Keep this// hook inert rather than guessing and recording unrelated tool calls.export const droidExecutor = new HeteroCliExecutor('droid', new Set());+export const devinExecutor = new HeteroCliExecutor('devin', new Set(['exec']));export const grokBuildExecutor = new HeteroCliExecutor('grok-build', new Set(['execute']));export const kimiCodeExecutor = new HeteroCliExecutor('kimi-code', new Set(['Shell']));export const openCodeExecutor = new HeteroCliExecutor('opencode', new Set(['bash']));