Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(hetero-agent): let OpenClaw/Hermes run on local desktop (#17961)

AmAzing-5c55c2d04814
diff --git a/apps/desktop/src/main/controllers/BinaryCtr.ts b/apps/desktop/src/main/controllers/BinaryCtr.ts
index 5a0b73a34fb..33c3543b50a 100644
--- a/apps/desktop/src/main/controllers/BinaryCtr.ts
+++ b/apps/desktop/src/main/controllers/BinaryCtr.ts
@@ -5,6 +5,8 @@ import type {
ClaudeAuthStatus,
DetectHeterogeneousAgentCommandParams,
} from '@lobechat/electron-client-ipc';
+import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
+import { resolveRemotePlatformCommand } from '@lobechat/heterogeneous-agents/scanHost';
import type { BinaryCategory, BinaryStatus } from '@/core/infrastructure/BinaryManager';
import { detectHeterogeneousCliCommand } from '@/modules/binaries';
@@ -43,6 +45,9 @@ export default class BinaryCtr extends ControllerModule {
params: DetectHeterogeneousAgentCommandParams,
): Promise<BinaryStatus> {
logger.debug('Detecting heterogeneous agent command:', params);
+ if (isRemoteHeterogeneousType(params.agentType)) {
+ return resolveRemotePlatformCommand(params.agentType);
+ }
return detectHeterogeneousCliCommand(params.agentType, params.command);
}
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index 96e61410fd3..4a1fa96369a 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -1,4 +1,4 @@
-import { execFileSync, execSync, spawn } from 'node:child_process';
+import { execFileSync, spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -21,7 +21,9 @@ import type {
RunCommandParams,
WriteLocalFileParams,
} from '@lobechat/electron-client-ipc';
+import { resolveRemotePlatformCommand } from '@lobechat/heterogeneous-agents/scanHost';
import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';
+import { execa } from 'execa';
import GatewayConnectionService from '@/services/gatewayConnectionSrv';
import ImessageBridgeService from '@/services/imessageBridgeSrv';
@@ -156,6 +158,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
/** In-memory registry for running platform agent tasks (openclaw / hermes). */
private readonly platformTasks = new Map<string, PlatformTaskEntry>();
+ private readonly platformTaskKillTimers = new Map<number, NodeJS.Timeout>();
/** Maps topicId β†’ hermes session_id for multi-turn conversation continuity. */
private readonly hermesSessionMap = new Map<string, string>();
@@ -666,33 +669,22 @@ export default class GatewayConnectionCtr extends ControllerModule {
}): Promise<{ available: boolean; reason?: string; version?: string }> {
const { platform } = args;
- const binaryMap: Record<string, string> = {
+ const platformMap: Record<string, 'hermes' | 'openclaw'> = {
hermes: 'hermes',
openclaw: 'openclaw',
};
- const binary = binaryMap[platform];
- if (!binary) {
+ const platformType = platformMap[platform];
+ if (!platformType) {
return { available: false, reason: `Unknown platform: ${platform}` };
}
- const whichCmd = process.platform === 'win32' ? `where ${binary}` : `which ${binary}`;
-
- try {
- execSync(whichCmd, { stdio: 'pipe' });
- } catch {
+ const status = await resolveRemotePlatformCommand(platformType);
+ if (!status.available) {
return { available: false, reason: `${platform} is not installed on this device` };
}
- try {
- const raw = execSync(`${binary} --version`, {
- encoding: 'utf8',
- stdio: 'pipe',
- }).trim();
- return { available: true, version: raw };
- } catch {
- return { available: true };
- }
+ return status.version ? { available: true, version: status.version } : { available: true };
}
private async getAgentProfile(args: { agentId?: string; platform: string }): Promise<{
@@ -864,6 +856,11 @@ export default class GatewayConnectionCtr extends ControllerModule {
};
if (agentType === 'openclaw') {
+ const commandStatus = await resolveRemotePlatformCommand('openclaw');
+ if (!commandStatus.available || !commandStatus.path) {
+ throw new Error('OpenClaw executable not found');
+ }
+ if (commandStatus.resolvedPathEnv) childEnv.PATH = commandStatus.resolvedPathEnv;
const lhPath = this.resolveLhPath();
const openclawAgent = process.env['OPENCLAW_AGENT_ID'] ?? 'main';
@@ -877,29 +874,36 @@ export default class GatewayConnectionCtr extends ControllerModule {
// lock will cause the new one to exit with code 1.
for (const [existingTaskId, entry] of this.platformTasks) {
if (entry.topicId === topicId && entry.agentType === 'openclaw') {
- try {
- process.kill(entry.pid, 'SIGTERM');
- } catch {
- // Already exited β€” nothing to do.
- }
+ this.killPlatformProcessTree(entry.pid, 'SIGTERM');
this.platformTasks.delete(existingTaskId);
}
}
- const child = spawn(
- 'openclaw',
- [
- 'agent',
- '--agent',
- openclawAgent,
- '--session-id',
- topicId,
- '--message',
- enrichedPrompt,
- '--local',
- ],
- { cwd: workDir, detached: true, env: childEnv, stdio: 'ignore' },
- );
+ const openclawArgs = [
+ 'agent',
+ '--agent',
+ openclawAgent,
+ '--session-id',
+ topicId,
+ '--message',
+ enrichedPrompt,
+ '--local',
+ ];
+ const child =
+ process.platform === 'win32'
+ ? execa(commandStatus.path, openclawArgs, {
+ cwd: workDir,
+ detached: true,
+ env: childEnv,
+ reject: false,
+ stdio: 'ignore',
+ })
+ : spawn(commandStatus.path, openclawArgs, {
+ cwd: workDir,
+ detached: true,
+ env: childEnv,
+ stdio: 'ignore',
+ });
const pid = child.pid;
if (pid === undefined) throw new Error('Failed to get PID for openclaw process');
@@ -915,6 +919,11 @@ export default class GatewayConnectionCtr extends ControllerModule {
});
child.on('close', (code, signal) => {
+ // Do not clear the process-group kill timer here: the group leader can
+ // exit while detached tool children keep running. Escalation only stops
+ // once the whole group is confirmed gone (see killPlatformProcessTree).
+ if (this.platformTasks.get(taskId)?.pid !== pid) return;
+
this.platformTasks.delete(taskId);
if (code !== 0 || signal !== null) {
const text = signal
@@ -952,14 +961,15 @@ export default class GatewayConnectionCtr extends ControllerModule {
}
if (agentType === 'hermes') {
+ const commandStatus = await resolveRemotePlatformCommand('hermes');
+ if (!commandStatus.available || !commandStatus.path) {
+ throw new Error('Hermes executable not found');
+ }
+ if (commandStatus.resolvedPathEnv) childEnv.PATH = commandStatus.resolvedPathEnv;
// Kill any existing hermes process for this topicId before spawning a new one.
for (const [existingTaskId, entry] of this.platformTasks) {
if (entry.topicId === topicId && entry.agentType === 'hermes') {
- try {
- process.kill(entry.pid, 'SIGTERM');
- } catch {
- // Already exited β€” nothing to do.
- }
+ this.killPlatformProcessTree(entry.pid, 'SIGTERM');
this.platformTasks.delete(existingTaskId);
}
}
@@ -972,12 +982,23 @@ export default class GatewayConnectionCtr extends ControllerModule {
}
// Hermes prints "session_id: <id>\n<response>" to stdout in --quiet mode.
- const child = spawn('hermes', hermesArgs, {
- cwd: workDir,
- detached: true,
- env: childEnv,
- stdio: ['ignore', 'pipe', 'ignore'],
- });
+ const child =
+ process.platform === 'win32'
+ ? execa(commandStatus.path, hermesArgs, {
+ cwd: workDir,
+ detached: true,
+ env: childEnv,
+ reject: false,
+ stderr: 'ignore',
+ stdin: 'ignore',
+ stdout: 'pipe',
+ })
+ : spawn(commandStatus.path, hermesArgs, {
+ cwd: workDir,
+ detached: true,
+ env: childEnv,
+ stdio: ['ignore', 'pipe', 'ignore'],
+ });
const pid = child.pid;
if (pid === undefined) throw new Error('Failed to get PID for hermes process');
@@ -998,6 +1019,9 @@ export default class GatewayConnectionCtr extends ControllerModule {
});
child.on('close', (code, signal) => {
+ // Keep any pending process-group escalation; see openclaw close handler.
+ if (this.platformTasks.get(taskId)?.pid !== pid) return;
+
this.platformTasks.delete(taskId);
if (code !== 0 || signal !== null) {
@@ -1065,6 +1089,68 @@ export default class GatewayConnectionCtr extends ControllerModule {
throw new Error(`Unsupported agentType: ${agentType}`);
}
+ /** Kill the complete detached platform-agent process tree. */
+ private killPlatformProcessTree(pid: number, signal: NodeJS.Signals): void {
+ if (process.platform === 'win32') {
+ try {
+ spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' });
+ } catch {
+ // The wrapper already exited.
+ }
+ return;
+ }
+
+ let signalled = false;
+ try {
+ process.kill(-pid, signal);
+ signalled = true;
+ } catch {
+ try {
+ process.kill(pid, signal);
+ signalled = true;
+ } catch {
+ // The process tree already exited.
+ }
+ }
+
+ if (signalled && signal !== 'SIGKILL') {
+ this.clearPlatformTaskKillTimer(pid);
+ const timer = setTimeout(() => {
+ this.platformTaskKillTimers.delete(pid);
+ // The group leader's `close` can fire while detached tool children are
+ // still alive; only stop escalating once the whole group is gone.
+ if (!this.isPlatformProcessGroupAlive(pid)) return;
+ logger.warn('Platform task did not exit after signal, escalating to SIGKILL:', pid);
+ this.killPlatformProcessTree(pid, 'SIGKILL');
+ }, 2000);
+ timer.unref();
+ this.platformTaskKillTimers.set(pid, timer);
+ }
+ }
+
+ /** Whether the detached platform process group (or its leader) is still alive. */
+ private isPlatformProcessGroupAlive(pid: number): boolean {
+ try {
+ process.kill(-pid, 0);
+ return true;
+ } catch {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+ }
+ }
+
+ private clearPlatformTaskKillTimer(pid: number): void {
+ const timer = this.platformTaskKillTimers.get(pid);
+ if (!timer) return;
+
+ clearTimeout(timer);
+ this.platformTaskKillTimers.delete(pid);
+ }
+
private async cancelHeteroTask(args: { signal?: string; taskId: string }): Promise<string> {
const { signal = 'SIGINT', taskId } = args;
const entry = this.platformTasks.get(taskId);
@@ -1073,19 +1159,8 @@ export default class GatewayConnectionCtr extends ControllerModule {
return JSON.stringify({ message: `No task found with taskId: ${taskId}`, success: false });
}
- // Both openclaw and hermes: kill by PID; the close handler sends the done signal.
- try {
- process.kill(entry.pid, signal);
- } catch {
- this.platformTasks.delete(taskId);
- await this.sendNotify({
- agentId: entry.agentId,
- content: 'Task already completed or cancelled',
- role: 'assistant',
- topicId: entry.topicId,
- workspaceId: entry.workspaceId,
- });
- }
+ // The close handler sends the terminal notify after the whole tree exits.
+ this.killPlatformProcessTree(entry.pid, signal as NodeJS.Signals);
return JSON.stringify({ pid: entry.pid, signal, taskId });
}
diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
index 35c199945c6..40618b104e8 100644
--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
@@ -1,4 +1,4 @@
-import type { execSync as ExecSyncType } from 'node:child_process';
+import type * as ChildProcessModule from 'node:child_process';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -183,15 +183,19 @@ vi.mock('node:crypto', () => ({
randomUUID: vi.fn(() => 'mock-device-uuid'),
}));
-const execSyncMock = vi.hoisted(() => vi.fn());
const execFileSyncMock = vi.hoisted(() => vi.fn());
const spawnMock = vi.hoisted(() => vi.fn());
+const resolveRemotePlatformCommandMock = vi.hoisted(() => vi.fn());
vi.mock('node:child_process', async (importOriginal) => {
- const actual = await importOriginal<{ execSync: typeof ExecSyncType }>();
- return { ...actual, execFileSync: execFileSyncMock, execSync: execSyncMock, spawn: spawnMock };
+ const actual = await importOriginal<typeof ChildProcessModule>();
+ return { ...actual, execFileSync: execFileSyncMock, spawn: spawnMock };
});
+vi.mock('@lobechat/heterogeneous-agents/scanHost', () => ({
+ resolveRemotePlatformCommand: resolveRemotePlatformCommandMock,
+}));
+
vi.mock('node:os', () => ({
default: { hostname: vi.fn(() => 'mock-hostname'), tmpdir: vi.fn(() => '/tmp') },
}));
@@ -1004,6 +1008,12 @@ describe('GatewayConnectionCtr', () => {
beforeEach(() => {
execFileSyncMock.mockReturnValue('/usr/local/bin/lh\n');
+ resolveRemotePlatformCommandMock.mockResolvedValue({
+ available: true,
+ path: '/resolved/bin/openclaw',
+ resolvedPathEnv: '/resolved/bin:/usr/bin',
+ version: '1.2.3',
+ });
spawnMock.mockReset();
});
@@ -1026,7 +1036,13 @@ describe('GatewayConnectionCtr', () => {
await vi.advanceTimersByTimeAsync(0);
expect(spawnMock).toHaveBeenCalledTimes(1);
- const [, spawnArgs] = spawnMock.mock.calls[0] as [string, string[]];
+ const [spawnCommand, spawnArgs, spawnOptions] = spawnMock.mock.calls[0] as [
+ string,
+ string[],
+ { env: NodeJS.ProcessEnv },
+ ];
+ expect(spawnCommand).toBe('/resolved/bin/openclaw');
+ expect(spawnOptions.env.PATH).toBe('/resolved/bin:/usr/bin');
const messageArg = spawnArgs[spawnArgs.indexOf('--message') + 1];
expect(messageArg).toContain('hello');
expect(messageArg).toContain('lh notify');
@@ -1034,6 +1050,7 @@ describe('GatewayConnectionCtr', () => {
it('kills an existing concurrent openclaw process for the same topicId before spawning', async () => {
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const notifySpy = vi.spyOn(ctr as any, 'sendNotify');
// First task
const child1 = makeMockChild(1111);
@@ -1068,12 +1085,150 @@ describe('GatewayConnectionCtr', () => {
);
await vi.advanceTimersByTimeAsync(0);
- expect(killSpy).toHaveBeenCalledWith(1111, 'SIGTERM');
+ expect(killSpy).toHaveBeenCalledWith(-1111, 'SIGTERM');
expect(spawnMock).toHaveBeenCalledTimes(2);
+ // The replaced child may close after the new operation has started. It must
+ // neither send a terminal notify for the new operation nor remove its task.
+ child1._emit('close', null, 'SIGTERM');
+ expect(notifySpy).not.toHaveBeenCalled();
+
+ client.simulateToolCallRequest(
+ 'cancelHeteroTask',
+ { signal: 'SIGINT', taskId: 'task-2' },
+ 'req-cancel-2',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+ expect(killSpy).toHaveBeenCalledWith(-2222, 'SIGINT');
+
+ killSpy.mockRestore();
+ });
+
+ it('kills the complete detached process group when cancelling a task', async () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const child = makeMockChild(5555);
+ spawnMock.mockReturnValue(child);
+ const client = await connectAndOpen();
+ client.simulateToolCallRequest(
+ 'runHeteroTask',
+ {
+ agentType: 'openclaw',
+ operationId: 'op-cancel',
+ prompt: 'work',
+ taskId: 'task-cancel',
+ topicId: 'topic-cancel',
+ },
+ 'req-run-cancel',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ client.simulateToolCallRequest(
+ 'cancelHeteroTask',
+ { signal: 'SIGINT', taskId: 'task-cancel' },
+ 'req-cancel',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(killSpy).toHaveBeenCalledWith(-5555, 'SIGINT');
+
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(killSpy).toHaveBeenCalledWith(-5555, 'SIGKILL');
+ killSpy.mockRestore();
+ });
+
+ it('does not escalate cancellation after the process group is gone', async () => {
+ const alive = new Set([5556]);
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation((pid, signal?) => {
+ const target = typeof pid === 'number' ? Math.abs(pid) : Number(pid);
+ if (signal === 0) {
+ if (!alive.has(target)) throw Object.assign(new Error('ESRCH'), { code: 'ESRCH' });
+ return true;
+ }
+ if (signal === 'SIGINT' || signal === 'SIGTERM') {
+ // Leader exits, but leave group membership to the close handler's cleanup
+ // simulation below so the escalation probe can see "gone".
+ }
+ if (signal === 'SIGKILL') {
+ alive.delete(target);
+ }
+ return true;
+ });
+ const child = makeMockChild(5556);
+ spawnMock.mockReturnValue(child);
+ const client = await connectAndOpen();
+ client.simulateToolCallRequest(
+ 'runHeteroTask',
+ {
+ agentType: 'openclaw',
+ operationId: 'op-cancel-exit',
+ prompt: 'work',
+ taskId: 'task-cancel-exit',
+ topicId: 'topic-cancel-exit',
+ },
+ 'req-run-cancel-exit',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ client.simulateToolCallRequest(
+ 'cancelHeteroTask',
+ { signal: 'SIGINT', taskId: 'task-cancel-exit' },
+ 'req-cancel-exit',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+ // Whole tree is gone with the leader β€” escalation must not fire SIGKILL.
+ alive.delete(5556);
+ child._emit('close', 0, null);
+ await vi.advanceTimersByTimeAsync(2000);
+
+ expect(killSpy).toHaveBeenCalledWith(-5556, 'SIGINT');
+ expect(killSpy).not.toHaveBeenCalledWith(-5556, 'SIGKILL');
+ killSpy.mockRestore();
+ });
+
+ it('still escalates when the group leader exits but detached children remain', async () => {
+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const child = makeMockChild(5557);
+ spawnMock.mockReturnValue(child);
+ const client = await connectAndOpen();
+ client.simulateToolCallRequest(
+ 'runHeteroTask',
+ {
+ agentType: 'openclaw',
+ operationId: 'op-cancel-orphan',
+ prompt: 'work',
+ taskId: 'task-cancel-orphan',
+ topicId: 'topic-cancel-orphan',
+ },
+ 'req-run-cancel-orphan',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+
+ client.simulateToolCallRequest(
+ 'cancelHeteroTask',
+ { signal: 'SIGINT', taskId: 'task-cancel-orphan' },
+ 'req-cancel-orphan',
+ );
+ await vi.advanceTimersByTimeAsync(0);
+ // Leader closed, but process.kill(-pid, 0) still succeeds β†’ orphans remain.
+ child._emit('close', null, 'SIGINT');
+ await vi.advanceTimersByTimeAsync(2000);
+
+ expect(killSpy).toHaveBeenCalledWith(-5557, 'SIGINT');
+ expect(killSpy).toHaveBeenCalledWith(-5557, 'SIGKILL');
killSpy.mockRestore();
});
+ it('uses taskkill to terminate the full Windows wrapper process tree', () => {
+ const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32');
+
+ (ctr as any).killPlatformProcessTree(6666, 'SIGINT');
+
+ expect(spawnMock).toHaveBeenCalledWith('taskkill', ['/pid', '6666', '/T', '/F'], {
+ stdio: 'ignore',
+ });
+ platformSpy.mockRestore();
+ });
+
it('does not kill processes for a different topicId', async () => {
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
@@ -1126,15 +1281,15 @@ describe('GatewayConnectionCtr', () => {
}
beforeEach(() => {
- execSyncMock.mockReset();
+ resolveRemotePlatformCommandMock.mockReset();
});
- it('returns available:true with version when binary is installed', async () => {
- execSyncMock.mockImplementation((cmd: string) => {
- if (cmd.startsWith('which ') || cmd.startsWith('where '))
- return '/usr/local/bin/openclaw\n';
- if (cmd.includes('--version')) return 'openclaw 1.2.3\n';
- return '';
+ it('uses the shared login-shell resolver for capability checks', async () => {
+ resolveRemotePlatformCommandMock.mockResolvedValue({
+ available: true,
+ path: '/login-shell/bin/openclaw',
+ resolvedPathEnv: '/login-shell/bin:/usr/bin',
+ version: '1.2.3',
});
const client = await connectAndOpen();
@@ -1148,18 +1303,18 @@ describe('GatewayConnectionCtr', () => {
expect(client.sendToolCallResponse).toHaveBeenCalledWith({
requestId: 'req-cap',
result: {
- content: JSON.stringify({ available: true, version: 'openclaw 1.2.3' }),
- state: { available: true, version: 'openclaw 1.2.3' },
+ content: JSON.stringify({ available: true, version: '1.2.3' }),
+ state: { available: true, version: '1.2.3' },
success: true,
},
});
+ expect(resolveRemotePlatformCommandMock).toHaveBeenCalledWith('openclaw');
});
- it('returns available:true without version when --version command fails', async () => {
- execSyncMock.mockImplementation((cmd: string) => {
- if (cmd.startsWith('which ') || cmd.startsWith('where '))
- return '/usr/local/bin/openclaw\n';
- throw new Error('version command failed');
+ it('returns available:true when the shared resolver has no version', async () => {
+ resolveRemotePlatformCommandMock.mockResolvedValue({
+ available: true,
+ path: '/login-shell/bin/openclaw',
});
const client = await connectAndOpen();
@@ -1181,8 +1336,8 @@ describe('GatewayConnectionCtr', () => {
});
it('returns available:false when binary is not installed', async () => {
- execSyncMock.mockImplementation(() => {
- throw new Error('command not found');
+ resolveRemotePlatformCommandMock.mockResolvedValue({
+ available: false,
});
const client = await connectAndOpen();
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 814d26fd01b..6a14df1a99a 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -242,6 +242,8 @@ const ExecAgentSchema = z
.optional(),
/** Explicit device ID to bind to the topic and activate for this run */
deviceId: z.string().optional(),
+ /** Current desktop device hint, honored only for an effective local target */
+ localDeviceId: z.string().optional(),
/** Optional existing message IDs to include in context */
existingMessageIds: z.array(z.string()).optional().default([]),
/** File IDs of already-uploaded attachments to attach to the new user message */
@@ -882,6 +884,7 @@ export const aiAgentRouter = router({
appContext,
autoStart = true,
deviceId,
+ localDeviceId,
existingMessageIds = [],
fileIds,
mentionedAgents,
@@ -931,6 +934,7 @@ export const aiAgentRouter = router({
// intentionally not part of the client-passable input schema.
clientIp: ctx.clientIp ?? undefined,
deviceId,
+ localDeviceId,
existingMessageIds,
fileIds,
mentionedAgents,
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index 8192111df89..3d9b8c4e6ab 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -143,11 +143,16 @@ export const deviceRouter = router({
z.object({
deviceId: z.string(),
platform: remotePlatformEnum,
+ scope: z.enum(['personal', 'workspace']).optional(),
}),
)
.query(async ({ ctx, input }) => {
const result = await deviceGateway.executeToolCall(
- { deviceId: input.deviceId, userId: ctx.userId, workspaceId: ctx.workspaceId },
+ {
+ deviceId: input.deviceId,
+ userId: ctx.userId,
+ workspaceId: input.scope === 'personal' ? undefined : ctx.workspaceId,
+ },
{
apiName: 'checkPlatformCapability',
arguments: JSON.stringify({ platform: input.platform }),
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
index 8657262b3d4..9bba1b0506f 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
@@ -7,6 +7,7 @@ const {
mockDeviceFindWorkspaceDeviceById,
mockBuildRemoteDeviceHeteroContext,
mockDispatchAgentRun,
+ mockExecuteToolCall,
mockGetHeterogeneousResumeSessionId,
mockMessageCreate,
mockResolveAttachmentsByFileIds,
@@ -19,6 +20,7 @@ const {
mockDeviceFindByDeviceId: vi.fn(),
mockDeviceFindWorkspaceDeviceById: vi.fn(),
mockDispatchAgentRun: vi.fn().mockResolvedValue({ success: true }),
+ mockExecuteToolCall: vi.fn().mockResolvedValue({ success: true }),
mockGetHeterogeneousResumeSessionId: vi.fn().mockResolvedValue(undefined),
mockIngestAttachment: vi.fn(),
mockMessageCreate: vi.fn(),
@@ -173,6 +175,7 @@ vi.mock('@/server/services/agentRuntime', () => ({
operationId: 'op-123',
success: true,
}),
+ interruptOperation: vi.fn().mockResolvedValue(true),
})),
}));
@@ -187,6 +190,7 @@ vi.mock('@/server/modules/Mecha', () => ({
vi.mock('@/server/services/deviceGateway', () => ({
deviceGateway: {
dispatchAgentRun: mockDispatchAgentRun,
+ executeToolCall: mockExecuteToolCall,
isConfigured: false,
queryDeviceList: vi.fn().mockResolvedValue([]),
resolveDeviceWorkspaceId: vi.fn().mockResolvedValue(undefined),
@@ -211,6 +215,7 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
mockResolveAttachmentsByFileIds.mockResolvedValue({ ...emptyResolvedAttachments });
mockSpawnHeteroSandbox.mockResolvedValue(undefined);
mockDispatchAgentRun.mockResolvedValue({ success: true });
+ mockExecuteToolCall.mockResolvedValue({ success: true });
mockGetHeterogeneousResumeSessionId.mockResolvedValue(undefined);
mockDeviceFindByDeviceId.mockResolvedValue({ defaultCwd: '/Users/alice/repo' });
mockDeviceFindWorkspaceDeviceById.mockResolvedValue(undefined);
@@ -218,6 +223,9 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
heteroAgentConfig.agencyConfig = { heterogeneousProvider: { type: 'claude-code' } } as any;
heteroAgentConfig.model = 'claude-code';
heteroAgentConfig.provider = 'anthropic';
+ delete (heteroAgentConfig as any).userId;
+ delete (heteroAgentConfig as any).visibility;
+ delete (heteroAgentConfig as any).workspaceId;
service = new AiAgentService(mockDb, userId);
});
@@ -733,5 +741,155 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
expect.objectContaining({ heteroType: 'claude-code' }),
);
});
+
+ it('keeps the conversation workspace separate from a personal platform device scope', async () => {
+ heteroAgentConfig.agencyConfig = {
+ executionTarget: 'local',
+ heterogeneousProvider: { type: 'openclaw' },
+ } as any;
+ (heteroAgentConfig as any).userId = userId;
+ (heteroAgentConfig as any).visibility = 'public';
+ (heteroAgentConfig as any).workspaceId = 'workspace-a';
+ service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-a' });
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ localDeviceId: 'personal-desktop',
+ prompt: 'do the task on this computer',
+ } as any);
+
+ expect(mockExecuteToolCall).toHaveBeenCalledWith(
+ {
+ deviceId: 'personal-desktop',
+ userId,
+ workspaceId: undefined,
+ },
+ expect.objectContaining({
+ apiName: 'runHeteroTask',
+ arguments: expect.any(String),
+ }),
+ 120_000,
+ );
+ const toolCall = mockExecuteToolCall.mock.calls.at(-1)?.[1];
+ expect(JSON.parse(toolCall.arguments)).toEqual(
+ expect.objectContaining({
+ agentType: 'openclaw',
+ workspaceId: 'workspace-a',
+ }),
+ );
+ const seed = findRunningOpSeed();
+ expect(seed.runningOperation).toEqual(
+ expect.objectContaining({
+ deviceId: 'personal-desktop',
+ deviceUserId: userId,
+ heteroType: 'openclaw',
+ }),
+ );
+ });
+
+ it("routes a legacy author binding through the author's personal principal", async () => {
+ heteroAgentConfig.agencyConfig = {
+ boundDeviceId: 'author-desktop',
+ heterogeneousProvider: { type: 'openclaw' },
+ } as any;
+ (heteroAgentConfig as any).userId = 'author-user';
+ (heteroAgentConfig as any).visibility = 'public';
+ (heteroAgentConfig as any).workspaceId = 'workspace-a';
+ service = new AiAgentService(mockDb, 'member-user', { workspaceId: 'workspace-a' });
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ localDeviceId: 'member-desktop',
+ prompt: 'run the legacy-bound task',
+ } as any);
+
+ expect(mockExecuteToolCall).toHaveBeenCalledWith(
+ {
+ deviceId: 'author-desktop',
+ userId: 'author-user',
+ workspaceId: undefined,
+ },
+ expect.objectContaining({ apiName: 'runHeteroTask' }),
+ 120_000,
+ );
+ const seed = findRunningOpSeed();
+ expect(seed.runningOperation).toEqual(
+ expect.objectContaining({
+ deviceId: 'author-desktop',
+ deviceUserId: 'author-user',
+ heteroType: 'openclaw',
+ }),
+ );
+ });
+
+ it('cancels a platform task through the principal persisted at dispatch', async () => {
+ topicMock.findById.mockResolvedValue({
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'assistant-1',
+ deviceId: 'author-desktop',
+ deviceUserId: 'author-user',
+ heteroType: 'openclaw',
+ operationId: 'operation-1',
+ },
+ },
+ });
+
+ await service.interruptTask({ operationId: 'operation-1', topicId: 'topic-1' });
+
+ expect(mockExecuteToolCall).toHaveBeenCalledWith(
+ {
+ deviceId: 'author-desktop',
+ userId: 'author-user',
+ workspaceId: undefined,
+ },
+ expect.objectContaining({ apiName: 'cancelHeteroTask' }),
+ 5_000,
+ );
+ });
+
+ it('recovers the topic from the operation when the cancellation caller omits it', async () => {
+ (service as any).agentOperationModel.findById = vi
+ .fn()
+ .mockResolvedValue({ topicId: 'topic-from-operation' });
+ topicMock.findById.mockResolvedValue({
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'assistant-1',
+ deviceId: 'member-desktop',
+ deviceUserId: userId,
+ heteroType: 'hermes',
+ operationId: 'operation-1',
+ },
+ },
+ });
+
+ await service.interruptTask({ operationId: 'operation-1' });
+
+ expect(topicMock.findById).toHaveBeenCalledWith('topic-from-operation');
+ expect(mockExecuteToolCall).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'member-desktop', userId }),
+ expect.objectContaining({ apiName: 'cancelHeteroTask' }),
+ 5_000,
+ );
+ });
+
+ it('does not cancel a newer operation currently running on the same topic', async () => {
+ topicMock.findById.mockResolvedValue({
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'assistant-2',
+ deviceId: 'member-desktop',
+ deviceUserId: userId,
+ heteroType: 'openclaw',
+ operationId: 'operation-2',
+ },
+ },
+ });
+
+ await service.interruptTask({ operationId: 'operation-1', topicId: 'topic-1' });
+
+ expect(mockExecuteToolCall).not.toHaveBeenCalled();
+ });
});
});
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 0e00b1dca1a..7c293217cef 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -110,6 +110,7 @@ import {
isDeviceLockedPlan,
resolveExecutionPlan,
resolveToolMode,
+ resolveWorkspaceScoped,
} from '@/helpers/executionTarget';
import { shouldEnableBuiltinSkill } from '@/helpers/skillFilters';
import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';
@@ -1196,6 +1197,7 @@ export class AiAgentService {
clientIp,
userAgent,
deviceId: requestedDeviceId,
+ localDeviceId,
botPlatformContext,
discordContext,
existingMessageIds = [],
@@ -2235,8 +2237,36 @@ export class AiAgentService {
userId: this.userId,
};
- const remoteDeviceId =
- effectiveRequestedDeviceId || agentConfig.agencyConfig?.boundDeviceId || undefined;
+ const platformPlan = isRemoteHetero
+ ? resolveExecutionPlan({
+ agencyConfig: agentConfig.agencyConfig,
+ canUseDevice,
+ clientExecutionAvailable: Boolean(localDeviceId),
+ isHetero: true,
+ localDeviceId,
+ requestedDeviceId: effectiveRequestedDeviceId,
+ sandboxExecutionAvailable: false,
+ trigger: requestTriggerMetadata?.trigger,
+ workspaceScoped: resolveWorkspaceScoped(
+ isPublicWorkspaceAgent && !canManageAgent,
+ memberDeviceOverride,
+ ),
+ })
+ : undefined;
+ const remoteDeviceId = platformPlan?.kind === 'device' ? platformPlan.deviceId : undefined;
+ const remoteDeviceWorkspaceId = remoteDeviceId
+ ? await this.resolveDeviceWorkspaceId(remoteDeviceId)
+ : undefined;
+ const usesCallersPersonalDevice =
+ platformPlan?.kind === 'device' &&
+ !remoteDeviceWorkspaceId &&
+ (effectiveRequestedDeviceId === remoteDeviceId ||
+ (platformPlan.target === 'local' &&
+ agentConfig.agencyConfig?.executionTargetSelectionPolicy !== 'fixed') ||
+ (!canManageAgent && memberDeviceOverride?.boundDeviceId === remoteDeviceId));
+ const remoteDeviceUserId = usesCallersPersonalDevice
+ ? this.userId
+ : (agentConfig.userId ?? this.userId);
// Register the run's lifecycle hooks so the hetero terminal path fires
// onComplete/onError through the same `hookDispatcher` the normal LLM
@@ -2258,7 +2288,12 @@ export class AiAgentService {
hooks: serializedHooks,
// Store deviceId + heteroType so interruptTask can cancel remote processes
...(isRemoteHetero && remoteDeviceId
- ? { deviceId: remoteDeviceId, heteroType }
+ ? {
+ deviceId: remoteDeviceId,
+ deviceUserId: remoteDeviceUserId,
+ deviceWorkspaceId: remoteDeviceWorkspaceId,
+ heteroType,
+ }
: undefined),
operationId,
scope: appContext?.scope ?? undefined,
@@ -2266,13 +2301,13 @@ export class AiAgentService {
},
});
- // Remote hetero agents (openclaw / hermes) dispatch to the device identified
- // by agencyConfig.boundDeviceId and communicate back via agentNotify.notify.
- // They always go through the gateway WS channel β€” open the stream now so the
- // frontend can subscribe before the first lh notify arrives.
+ // Notify-based platform agents (openclaw / hermes) communicate back via
+ // agentNotify.notify. A local run uses the requesting desktop's device ID;
+ // a remote run uses agencyConfig.boundDeviceId. Both use the gateway transport,
+ // so open the stream before the first notify arrives.
if (isRemoteHetero) {
- // Remote hetero agents are device-only β€” there is no sandbox to
+ // Platform task agents require either this desktop or a connected device β€” there is no sandbox to
// degrade to, so a denied sender (external bot user) is refused
// outright instead of reaching the owner's machine.
if (!canUseDevice) {
@@ -2304,12 +2339,12 @@ export class AiAgentService {
};
}
if (!remoteDeviceId) {
- log('execAgent: openclaw/hermes requires a bound device (boundDeviceId not set)');
+ log('execAgent: openclaw/hermes requires a local or connected device');
await this.finalizeHeteroDispatchError({
agentId: resolvedAgentId,
assistantMessageId: assistantMessageRecord.id,
- detail: 'No device bound to this agent. Configure boundDeviceId.',
- message: 'No bound device for remote hetero agent',
+ detail: 'No local or connected device is available for this agent.',
+ message: 'No execution device for platform agent',
operationId,
topicId,
});
@@ -2319,7 +2354,7 @@ export class AiAgentService {
autoStarted: false,
createdAt: new Date().toISOString(),
error: 'No bound device',
- message: 'Remote hetero agent requires boundDeviceId',
+ message: 'Platform agent requires a local or connected device',
operationId,
status: 'error',
success: false,
@@ -2344,9 +2379,12 @@ export class AiAgentService {
// lh connect only handles tool_call_request (not agent_run_request),
// so we use executeToolCall with the runHeteroTask tool instead of dispatchAgentRun.
- const remoteDeviceWorkspaceId = await this.resolveDeviceWorkspaceId(remoteDeviceId);
const result = await deviceGateway.executeToolCall(
- { deviceId: remoteDeviceId, userId: this.userId, workspaceId: remoteDeviceWorkspaceId },
+ {
+ deviceId: remoteDeviceId,
+ userId: remoteDeviceUserId,
+ workspaceId: remoteDeviceWorkspaceId,
+ },
{
apiName: 'runHeteroTask',
arguments: JSON.stringify({
@@ -2361,7 +2399,7 @@ export class AiAgentService {
// topic so agentNotify can resolve the workspace-owned topic.
// Without this the device's notify call falls back to personal
// mode and TopicModel.findById returns NOT_FOUND.
- workspaceId: remoteDeviceWorkspaceId,
+ workspaceId: this.workspaceId,
}),
identifier: 'runHeteroTask',
},
@@ -5394,18 +5432,35 @@ export class AiAgentService {
throw new Error('Operation ID not found');
}
+ // Not every cancellation entry point knows the topic (reconnect, task,
+ // bot/messenger stop). Recover it from the owner-scoped operation row so
+ // device cancellation is symmetric across every caller.
+ let resolvedTopicId = topicId;
+ if (!resolvedTopicId) {
+ const operation = await this.agentOperationModel.findById(resolvedOperationId);
+ resolvedTopicId = operation?.topicId ?? undefined;
+ }
+
// 2. Cancel remote hetero process (openclaw / hermes) if applicable.
// Check topic.metadata.runningOperation for device + heteroType info seeded by execAgent.
// This runs regardless of whether interruptOperation succeeds β€” the remote process
// is independent of the local operation registry.
- if (topicId) {
- const topic = await this.topicModel.findById(topicId);
+ if (resolvedTopicId) {
+ const topic = await this.topicModel.findById(resolvedTopicId);
const runningOp = (topic?.metadata as any)?.runningOperation as
- { deviceId?: string; heteroType?: string; operationId?: string } | undefined;
+ | {
+ deviceId?: string;
+ deviceUserId?: string;
+ deviceWorkspaceId?: string;
+ heteroType?: string;
+ operationId?: string;
+ }
+ | undefined;
if (
runningOp?.deviceId &&
runningOp.heteroType &&
+ runningOp.operationId === resolvedOperationId &&
isRemoteHeterogeneousType(runningOp.heteroType)
) {
const taskId = runningOp.operationId ?? resolvedOperationId;
@@ -5415,12 +5470,13 @@ export class AiAgentService {
runningOp.deviceId,
taskId,
);
- const cancelWorkspaceId = await this.resolveDeviceWorkspaceId(runningOp.deviceId);
+ const cancelWorkspaceId =
+ runningOp.deviceWorkspaceId ?? (await this.resolveDeviceWorkspaceId(runningOp.deviceId));
await deviceGateway
.executeToolCall(
{
deviceId: runningOp.deviceId,
- userId: this.userId,
+ userId: runningOp.deviceUserId ?? this.userId,
workspaceId: cancelWorkspaceId,
},
{
diff --git a/packages/electron-client-ipc/src/types/binary.ts b/packages/electron-client-ipc/src/types/binary.ts
index 5fc83edac74..e981e78ea63 100644
--- a/packages/electron-client-ipc/src/types/binary.ts
+++ b/packages/electron-client-ipc/src/types/binary.ts
@@ -25,8 +25,10 @@ export interface BinaryInfo {
export type HeterogeneousCliAgentType = 'amp' | 'claude-code' | 'codex' | 'opencode' | 'pi';
+export type DetectableHeterogeneousAgentType = HeterogeneousCliAgentType | 'hermes' | 'openclaw';
+
export interface DetectHeterogeneousAgentCommandParams {
- agentType: HeterogeneousCliAgentType;
+ agentType: DetectableHeterogeneousAgentType;
command: string;
}
diff --git a/packages/heterogeneous-agents/src/config.ts b/packages/heterogeneous-agents/src/config.ts
index 7b24342e0f8..dbf7d7da37f 100644
--- a/packages/heterogeneous-agents/src/config.ts
+++ b/packages/heterogeneous-agents/src/config.ts
@@ -3,8 +3,8 @@ export type HeterogeneousAgentMenuLabelKey =
/**
* Config for local CLI hetero agents (Amp, Claude Code, Codex, OpenCode, Pi) that run as
- * desktop subprocesses via Electron IPC. Remote device agents (openclaw,
- * hermes) have their own setup flow and are not listed here.
+ * desktop subprocesses via Electron IPC. Platform task agents (openclaw,
+ * hermes) use a separate notify-based runner and are not listed here.
*/
export interface HeterogeneousAgentConfig {
command: string;
@@ -62,9 +62,9 @@ export const getHeterogeneousAgentConfig = (type: string) =>
HETEROGENEOUS_AGENT_CONFIGS.find((config) => config.type === type);
/**
- * Config for remote platform hetero agents that communicate back via
- * agentNotify.notify. Unlike local CLI agents these are always bound to
- * a device via `lh connect` and do not run as desktop subprocesses.
+ * Config for platform task hetero agents that communicate back via
+ * agentNotify.notify. They can run on this desktop or a connected device,
+ * but use a different execution protocol from local CLI stream adapters.
* Add new remote platform types here to automatically propagate display
* names across the UI (model tag, loading indicator, agent list, etc.).
*/
@@ -81,7 +81,7 @@ export const REMOTE_HETEROGENEOUS_AGENT_CONFIGS = [
/** Union of all local CLI hetero types. */
export type LocalHeterogeneousAgentType = (typeof HETEROGENEOUS_AGENT_CONFIGS)[number]['type'];
-/** Union of all remote platform hetero types. */
+/** Union of all notify-based platform task hetero types. */
export type RemoteHeterogeneousAgentType =
(typeof REMOTE_HETEROGENEOUS_AGENT_CONFIGS)[number]['type'];
@@ -90,6 +90,6 @@ export type HeterogeneousAgentType = LocalHeterogeneousAgentType | RemoteHeterog
const REMOTE_HETERO_TYPES = new Set<string>(REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map((c) => c.type));
-/** Returns true when `type` identifies a remote platform agent (OpenClaw or Hermes). */
+/** Returns true when `type` identifies a notify-based platform agent. */
export const isRemoteHeterogeneousType = (type: string): type is RemoteHeterogeneousAgentType =>
REMOTE_HETERO_TYPES.has(type);
diff --git a/packages/heterogeneous-agents/src/scan/scanHost.test.ts b/packages/heterogeneous-agents/src/scan/scanHost.test.ts
new file mode 100644
index 00000000000..05e3cb88e86
--- /dev/null
+++ b/packages/heterogeneous-agents/src/scan/scanHost.test.ts
@@ -0,0 +1,52 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { probeRemotePlatform, resolveRemotePlatformCommand } from './scanHost';
+
+const { detectHeterogeneousCliCommandMock, detectValidatedCommandMock } = vi.hoisted(() => ({
+ detectHeterogeneousCliCommandMock: vi.fn(),
+ detectValidatedCommandMock: vi.fn(),
+}));
+
+vi.mock('../spawn/resolveCliCommand', () => ({
+ detectHeterogeneousCliCommand: detectHeterogeneousCliCommandMock,
+ detectValidatedCommand: detectValidatedCommandMock,
+}));
+
+describe('platform command scanning', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('uses the shared PATH and Windows-shim-aware command resolver', async () => {
+ detectValidatedCommandMock.mockResolvedValue({
+ available: true,
+ path: '/resolved/bin/openclaw',
+ resolvedPathEnv: '/resolved/bin:/usr/bin',
+ version: 'openclaw 1.2.3',
+ });
+
+ await expect(resolveRemotePlatformCommand('openclaw')).resolves.toEqual({
+ available: true,
+ path: '/resolved/bin/openclaw',
+ resolvedPathEnv: '/resolved/bin:/usr/bin',
+ version: '1.2.3',
+ });
+ expect(detectValidatedCommandMock).toHaveBeenCalledWith('openclaw', {
+ validateKeywords: ['openclaw'],
+ });
+ });
+
+ it('keeps host scan responses free of executable paths', async () => {
+ detectValidatedCommandMock.mockResolvedValue({
+ available: true,
+ path: '/private/bin/hermes',
+ resolvedPathEnv: '/private/bin:/usr/bin',
+ version: 'Hermes Agent v0.9.0 (build 1)',
+ });
+
+ await expect(probeRemotePlatform('hermes')).resolves.toEqual({
+ available: true,
+ version: '0.9.0',
+ });
+ });
+});
diff --git a/packages/heterogeneous-agents/src/scan/scanHost.ts b/packages/heterogeneous-agents/src/scan/scanHost.ts
index 521c1442319..0d6a291297a 100644
--- a/packages/heterogeneous-agents/src/scan/scanHost.ts
+++ b/packages/heterogeneous-agents/src/scan/scanHost.ts
@@ -1,12 +1,13 @@
-import { execFile } from 'node:child_process';
-import { promisify } from 'node:util';
-
import {
HETEROGENEOUS_AGENT_CONFIGS,
REMOTE_HETEROGENEOUS_AGENT_CONFIGS,
type RemoteHeterogeneousAgentType,
} from '../config';
-import { detectHeterogeneousCliCommand } from '../spawn/resolveCliCommand';
+import {
+ type CliCommandStatus,
+ detectHeterogeneousCliCommand,
+ detectValidatedCommand,
+} from '../spawn/resolveCliCommand';
import type { HeterogeneousAgentScanMap, HeterogeneousAgentScanStatus } from './types';
/**
@@ -17,10 +18,6 @@ import type { HeterogeneousAgentScanMap, HeterogeneousAgentScanStatus } from './
* (`@lobechat/heterogeneous-agents/scanHost`), never from a browser bundle.
*/
-const execFileP = promisify(execFile);
-
-const PROBE_TIMEOUT_MS = 5000;
-
// openclaw prints "openclaw x.y.z"; hermes prints "Hermes Agent vX.Y.Z (...)"
const parsePlatformVersion = (type: RemoteHeterogeneousAgentType, output: string) => {
if (type === 'hermes') {
@@ -30,21 +27,28 @@ const parsePlatformVersion = (type: RemoteHeterogeneousAgentType, output: string
return output.split(/\s+/).at(-1);
};
-const probeRemotePlatform = async (
+/**
+ * Resolve and validate a notify-based platform executable using the same
+ * login-shell PATH and Windows npm-shim handling as the CLI agent resolver.
+ * Spawn sites must use the returned absolute path and `resolvedPathEnv` too;
+ * otherwise a packaged Electron app can detect a command that it cannot run.
+ */
+export const resolveRemotePlatformCommand = async (
+ type: RemoteHeterogeneousAgentType,
+): Promise<CliCommandStatus> => {
+ const status = await detectValidatedCommand(type, { validateKeywords: [type] });
+ return status.version
+ ? { ...status, version: parsePlatformVersion(type, status.version) }
+ : status;
+};
+
+export const probeRemotePlatform = async (
type: RemoteHeterogeneousAgentType,
): Promise<HeterogeneousAgentScanStatus> => {
- try {
- const { stdout } = await execFileP(type, ['--version'], {
- timeout: PROBE_TIMEOUT_MS,
- windowsHide: true,
- });
- return { available: true, version: parsePlatformVersion(type, stdout.trim()) };
- } catch (error) {
- return {
- available: false,
- reason: error instanceof Error ? error.message : `${type} not found or failed to run`,
- };
- }
+ const status = await resolveRemotePlatformCommand(type);
+ return status.available
+ ? { available: true, version: status.version }
+ : { available: false, reason: `${type} not found or failed to run` };
};
export const scanHeterogeneousAgentsOnHost = async (): Promise<HeterogeneousAgentScanMap> => {
diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.ts
index f1ee4572d5a..d787421dc4f 100644
--- a/packages/types/src/agent/agencyConfig.ts
+++ b/packages/types/src/agent/agencyConfig.ts
@@ -141,9 +141,9 @@ const CODEX_FAST_SERVICE_TIER_VALUES = ['fast', 'priority'] as const;
* process on the desktop or a connected device; uses `command`, `args`, `env`,
* `systemContext`.
*
- * - **Remote platform** (`openclaw` | `hermes`): dispatched to a machine
- * connected via `lh connect`; device is identified by `LobeAgentAgencyConfig.boundDeviceId`.
- * `platformAgentId` selects the named agent on the remote platform (defaults to `'main'`).
+ * - **Platform task** (`openclaw` | `hermes`): runs on this desktop when
+ * `executionTarget` is `local`, or on a machine connected via `lh connect`
+ * when it is `device`. `platformAgentId` selects the named platform agent.
*/
export interface HeterogeneousProviderConfig {
/** Additional CLI arguments for the agent command (local CLI only). */
@@ -606,11 +606,11 @@ export const buildHeteroExecArgs = (
* automatically; with several online the model selects one via the
* remote-device tool. The ONLY mode that touches a device the user
* did not explicitly select. Opt-in: never a silent default.
- * - `local` : in-process spawn on the user's Electron desktop (desktop only)
+ * - `local` : run on the user's Electron desktop (desktop only)
* - `device` : dispatched to an `lh connect` device identified by `boundDeviceId`
* - `sandbox` : server-spawned cloud sandbox
*
- * Remote hetero agents (`openclaw` | `hermes`) are always `device`.
+ * Platform task agents (`openclaw` | `hermes`) support `local` and `device` targets.
*/
export type DeviceExecutionTarget = 'auto' | 'device' | 'local' | 'none' | 'sandbox';
@@ -640,14 +640,12 @@ export type AgentModelSelectionPolicy = 'fixed' | 'member';
export interface LobeAgentAgencyConfig {
/**
* Device ID of the machine connected via `lh connect`.
- * Required when `executionTarget === 'device'` (and always set for remote
- * hetero agents `openclaw` / `hermes`).
+ * Required when `executionTarget === 'device'`.
*/
boundDeviceId?: string;
/**
* Execution target for the hetero agent. When omitted, resolves to a
- * platform default: `'local'` on desktop, `'none'` on web (or `'device'` for
- * remote hetero providers).
+ * platform default: `'local'` on desktop and `'none'` on web.
*/
executionTarget?: DeviceExecutionTarget;
/**
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 1f23119d885..7728845eb23 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -189,6 +189,8 @@ export interface ExecAgentParams {
fileIds?: string[];
/** Additional system instructions appended after the agent's own system role */
instructions?: string;
+ /** Current desktop's device ID; used only when the effective target is `local`. */
+ localDeviceId?: string;
/** Override the agent's default model */
model?: string;
/**
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 644d33286b3..8d72d51896e 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -192,6 +192,14 @@ export interface ChatTopicMetadata {
*/
runningOperation?: {
assistantMessageId: string;
+ /** Device selected for a notify-based platform task. */
+ deviceId?: string;
+ /** Personal-device owner used to route dispatch and cancellation through the same principal. */
+ deviceUserId?: string;
+ /** Workspace principal used for a workspace-enrolled device. */
+ deviceWorkspaceId?: string;
+ /** Notify-based platform type used to select the cancellation protocol. */
+ heteroType?: string;
/**
* Serialized lifecycle hooks (onComplete / onError) registered for this run.
*
@@ -435,6 +443,10 @@ export const chatTopicMetadataUpdateSchema = z.object({
runningOperation: z
.object({
assistantMessageId: z.string(),
+ deviceId: z.string().optional(),
+ deviceUserId: z.string().optional(),
+ deviceWorkspaceId: z.string().optional(),
+ heteroType: z.string().optional(),
hooks: z.array(serializedAgentHookSchema).optional(),
operationId: z.string(),
scope: z.string().optional(),
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index 5b4083ad030..73450e03c63 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -1,10 +1,7 @@
'use client';
import { isDesktop } from '@lobechat/const';
-import {
- HETEROGENEOUS_TYPE_LABELS,
- isRemoteHeterogeneousType,
-} from '@lobechat/heterogeneous-agents';
+import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';
import type { DeviceExecutionTarget } from '@lobechat/types';
import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
@@ -342,8 +339,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
const heteroType = agencyConfig?.heterogeneousProvider?.type;
const boundDeviceId = agencyConfig?.boundDeviceId;
- // Local heterogeneous agents (remote types already early-return
- // below) bring their own toolchain and must execute somewhere, so `'none'`
+ // Heterogeneous agents bring their own toolchain and must execute somewhere, so `'none'`
// (plain chat, no execution environment) isn't a valid target for them: hide
// the option and never fall back to / honour a stale stored `'none'`.
const isHetero = !!heteroType;
@@ -435,8 +431,6 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
isWorkspacePreferenceLoading,
]);
- // Don't render for remote hetero agents β€” they use RemoteAgentConfigCard in profile.
- if (heteroType && isRemoteHeterogeneousType(heteroType)) return null;
if (!canShowExecutionTarget) return null;
const boundDevice =
diff --git a/src/features/ConnectAgent/index.tsx b/src/features/ConnectAgent/index.tsx
index aaaf4549190..bb62bd2dec0 100644
--- a/src/features/ConnectAgent/index.tsx
+++ b/src/features/ConnectAgent/index.tsx
@@ -33,9 +33,14 @@ import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { deviceService } from '@/services/device';
import { useAgentStore } from '@/store/agent';
+import { useElectronStore } from '@/store/electron';
import { useHomeStore } from '@/store/home';
-import { CONNECTABLE_PROVIDERS, type ConnectableProvider } from './providers';
+import {
+ buildPlatformAgencyConfig,
+ CONNECTABLE_PROVIDERS,
+ type ConnectableProvider,
+} from './providers';
import { type ScanTarget, useAgentScan } from './useAgentScan';
const styles = createStaticStyles(({ css }) => ({
@@ -354,6 +359,7 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(
const { close, setCanDismissByClickOutside } = useModalContext();
const navigate = useWorkspaceAwareNavigate();
const storeCreateAgent = useAgentStore((s) => s.createAgent);
+ const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
const refreshAgentList = useHomeStore((s) => s.refreshAgentList);
// Workspace agents must bind workspace devices: a workspace agent on a
@@ -400,24 +406,13 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(
const targetLabel =
target?.kind === 'device' ? deviceLabel(target.device) : t('connectAgent.create.localDevice');
- // Providers listed for the current target: local targets only run CLI
- // subprocess agents. Device targets expose every remotely scannable agent.
- const visibleProviders = useMemo(
- () =>
- CONNECTABLE_PROVIDERS.filter((provider) => {
- if (target?.kind === 'local' && provider.kind === 'platform') return false;
- return true;
- }),
- [target?.kind],
- );
-
const inventory = useMemo(() => {
if (scanState.status !== 'success' || !scanState.agents) return [];
const rank = (available?: boolean) => (available ? 0 : 1);
- return [...visibleProviders]
+ return [...CONNECTABLE_PROVIDERS]
.map((provider) => ({ provider, status: scanState.agents?.[provider.type] }))
.sort((a, b) => rank(a.status?.available) - rank(b.status?.available));
- }, [scanState, visibleProviders]);
+ }, [scanState]);
const detectedCount = inventory.filter((entry) => entry.status?.available).length;
@@ -457,18 +452,19 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(
// title / description / avatar without an extra wait.
if (
provider.kind === 'platform' &&
- target?.kind === 'device' &&
isRemoteHeterogeneousType(provider.type) &&
!profiles[provider.type]
) {
+ const deviceId = target?.kind === 'device' ? target.device.deviceId : currentDeviceId;
+ if (!deviceId) return;
const platform = provider.type;
void deviceService
- .getAgentProfile({ deviceId: target.device.deviceId, platform })
+ .getAgentProfile({ deviceId, platform })
.then((profile) => setProfiles((prev) => ({ ...prev, [platform]: profile })))
.catch(() => {});
}
},
- [profiles, target],
+ [currentDeviceId, profiles, target],
);
const goConfirm = useCallback(() => {
@@ -483,16 +479,18 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(
(provider: ConnectableProvider, overrides?: { description?: string; name?: string }) => {
const title = overrides?.name?.trim() || provider.title;
- if (target?.kind === 'device' && provider.kind === 'platform') {
+ if (provider.kind === 'platform' && isRemoteHeterogeneousType(provider.type)) {
const profile = isRemoteHeterogeneousType(provider.type)
? profiles[provider.type]
: undefined;
return {
config: {
- agencyConfig: {
- boundDeviceId: target.device.deviceId,
- heterogeneousProvider: { type: provider.type },
- },
+ agencyConfig: buildPlatformAgencyConfig(
+ provider.type,
+ target?.kind === 'device'
+ ? { deviceId: target.device.deviceId, kind: 'device' }
+ : { kind: 'local' },
+ ),
avatar: profile?.avatar || undefined,
description: (overrides?.description ?? profile?.description)?.trim() || undefined,
title: overrides?.name?.trim() || profile?.title || provider.title,
@@ -797,9 +795,11 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(
<Flexbox gap={6}>
<SectionLabel>{t('connectAgent.create.scanning')}</SectionLabel>
<div className={styles.groupList}>
- {[90, 70, 110, 80, 100, 75].slice(0, visibleProviders.length).map((width, i) => (
- <SkeletonRow key={i} width={width} />
- ))}
+ {[90, 70, 110, 80, 100, 75, 95]
+ .slice(0, CONNECTABLE_PROVIDERS.length)
+ .map((width, i) => (
+ <SkeletonRow key={i} width={width} />
+ ))}
</div>
</Flexbox>
)}
diff --git a/src/features/ConnectAgent/providers.ts b/src/features/ConnectAgent/providers.ts
index 7d37d3671ef..03382b2665c 100644
--- a/src/features/ConnectAgent/providers.ts
+++ b/src/features/ConnectAgent/providers.ts
@@ -9,8 +9,8 @@ import { Amp, ClaudeCode, Codex, HermesAgent, OpenClaw, OpenCode, Pi } from '@lo
/**
* One row in the connect wizard's agent inventory. `kind` mirrors the domain
- * split: `cli` agents spawn as processes (locally or on a bound device),
- * `platform` agents are always device-bound and reached over the gateway.
+ * split: `cli` agents use stream adapters, while `platform` agents use the
+ * notify-based task runner on this desktop or a bound device.
*/
export interface ConnectableProvider {
/** CDN avatar to stamp on created cli agents (platform agents use the device profile's). */
@@ -63,3 +63,13 @@ export const CONNECTABLE_PROVIDERS: ConnectableProvider[] = [
export const getConnectableProvider = (type: HeterogeneousAgentType) =>
CONNECTABLE_PROVIDERS.find((provider) => provider.type === type);
+
+export const buildPlatformAgencyConfig = (
+ type: RemoteHeterogeneousAgentType,
+ target: { deviceId: string; kind: 'device' } | { kind: 'local' },
+) => ({
+ ...(target.kind === 'device'
+ ? { boundDeviceId: target.deviceId, executionTarget: 'device' as const }
+ : undefined),
+ heterogeneousProvider: { type },
+});
diff --git a/src/features/ConnectAgent/useAgentScan.test.ts b/src/features/ConnectAgent/useAgentScan.test.ts
new file mode 100644
index 00000000000..411b6e6e2cf
--- /dev/null
+++ b/src/features/ConnectAgent/useAgentScan.test.ts
@@ -0,0 +1,54 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { buildPlatformAgencyConfig } from './providers';
+import { scanLocal } from './useAgentScan';
+
+const detectHeterogeneousAgentCommand = vi.hoisted(() => vi.fn());
+
+vi.mock('@/services/electron/binary', () => ({
+ binaryService: { detectHeterogeneousAgentCommand },
+}));
+
+describe('scanLocal', () => {
+ beforeEach(() => {
+ detectHeterogeneousAgentCommand.mockReset();
+ });
+
+ it('scans OpenClaw and Hermes alongside the local coding-agent CLIs', async () => {
+ detectHeterogeneousAgentCommand.mockImplementation(async ({ agentType }) => ({
+ available: true,
+ version: `${agentType}-version`,
+ }));
+
+ const agents = await scanLocal();
+
+ expect(agents.openclaw).toEqual({ available: true, version: 'openclaw-version' });
+ expect(agents.hermes).toEqual({ available: true, version: 'hermes-version' });
+ expect(detectHeterogeneousAgentCommand).toHaveBeenCalledWith({
+ agentType: 'openclaw',
+ command: 'openclaw',
+ });
+ expect(detectHeterogeneousAgentCommand).toHaveBeenCalledWith({
+ agentType: 'hermes',
+ command: 'hermes',
+ });
+ });
+});
+
+describe('buildPlatformAgencyConfig', () => {
+ it('uses the default local target without binding a device for this computer', () => {
+ expect(buildPlatformAgencyConfig('openclaw', { kind: 'local' })).toEqual({
+ heterogeneousProvider: { type: 'openclaw' },
+ });
+ });
+
+ it('binds a selected remote device explicitly', () => {
+ expect(
+ buildPlatformAgencyConfig('hermes', { deviceId: 'remote-device', kind: 'device' }),
+ ).toEqual({
+ boundDeviceId: 'remote-device',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'hermes' },
+ });
+ });
+});
diff --git a/src/features/ConnectAgent/useAgentScan.ts b/src/features/ConnectAgent/useAgentScan.ts
index 99fb7cd153b..8b7b3aa4fe0 100644
--- a/src/features/ConnectAgent/useAgentScan.ts
+++ b/src/features/ConnectAgent/useAgentScan.ts
@@ -1,11 +1,12 @@
import type { HeterogeneousAgentScanMap } from '@lobechat/heterogeneous-agents';
-import { HETEROGENEOUS_AGENT_CLIENT_CONFIGS } from '@lobechat/heterogeneous-agents/client';
import type { DeviceListItem } from '@lobechat/types';
import { useCallback, useRef, useState } from 'react';
import { deviceService } from '@/services/device';
import { binaryService } from '@/services/electron/binary';
+import { CONNECTABLE_PROVIDERS } from './providers';
+
/**
* Where the wizard scans for installed agents: the local desktop machine
* (agents run as desktop subprocesses) or a gateway-connected device.
@@ -21,22 +22,21 @@ export interface AgentScanState {
const IDLE: AgentScanState = { agents: null, status: 'idle' };
/**
- * Local scans probe the four CLI agents through the desktop binary detector
- * (which + login-shell PATH + well-known install paths). Platform agents
- * (openclaw / hermes) are device-bound by design, so a local target never
- * reports them β€” the inventory simply omits those rows.
+ * Local scans probe every connectable agent through the desktop binary detector.
+ * Although OpenClaw and Hermes use the gateway execution path, they are installed
+ * on and selected from this machine just like the coding-agent CLIs.
*/
-const scanLocal = async (): Promise<HeterogeneousAgentScanMap> => {
+export const scanLocal = async (): Promise<HeterogeneousAgentScanMap> => {
const entries = await Promise.all(
- HETEROGENEOUS_AGENT_CLIENT_CONFIGS.map(async (config) => {
+ CONNECTABLE_PROVIDERS.map(async (provider) => {
try {
const status = await binaryService.detectHeterogeneousAgentCommand({
- agentType: config.type,
- command: config.command,
+ agentType: provider.type,
+ command: provider.command ?? provider.type,
});
- return [config.type, { available: status.available, version: status.version }] as const;
+ return [provider.type, { available: status.available, version: status.version }] as const;
} catch {
- return [config.type, { available: false }] as const;
+ return [provider.type, { available: false }] as const;
}
}),
);
diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.ts
index 36a6c174adb..94fe06b94bb 100644
--- a/src/helpers/executionTarget.test.ts
+++ b/src/helpers/executionTarget.test.ts
@@ -6,6 +6,7 @@ import {
type ExecutionPlan,
executionTargetToRuntimeMode,
isDeviceLockedPlan,
+ isHeterogeneousSandboxExecutionAvailable,
resolveExecutionPlan,
resolveExecutionTarget,
resolveRuntimeMode,
@@ -25,6 +26,17 @@ const piCfg = (over: Partial<LobeAgentAgencyConfig> = {}): LobeAgentAgencyConfig
heterogeneousProvider: { command: 'pi', type: 'pi' },
...over,
});
+const openClawCfg = (over: Partial<LobeAgentAgencyConfig> = {}): LobeAgentAgencyConfig => ({
+ heterogeneousProvider: { type: 'openclaw' },
+ ...over,
+});
+
+describe('isHeterogeneousSandboxExecutionAvailable', () => {
+ it('keeps notify-based platform agents on local or connected devices', () => {
+ expect(isHeterogeneousSandboxExecutionAvailable('openclaw')).toBe(false);
+ expect(isHeterogeneousSandboxExecutionAvailable('hermes')).toBe(false);
+ });
+});
describe('resolveWorkspaceScoped', () => {
it('preserves shared-row coercion until a workspace member explicitly selects a target', () => {
@@ -37,6 +49,22 @@ describe('resolveWorkspaceScoped', () => {
});
describe('resolveExecutionTarget', () => {
+ it('keeps legacy bound platform agents on their remote device', () => {
+ const legacy = openClawCfg({ boundDeviceId: 'legacy-device' });
+
+ expect(resolveExecutionTarget(legacy, { clientExecutionAvailable: true })).toBe('device');
+ expect(resolveExecutionTarget(legacy, { clientExecutionAvailable: false })).toBe('device');
+ });
+
+ it('lets an explicit platform local target override its fallback binding', () => {
+ expect(
+ resolveExecutionTarget(
+ openClawCfg({ boundDeviceId: 'fallback-device', executionTarget: 'local' }),
+ { clientExecutionAvailable: true },
+ ),
+ ).toBe('local');
+ });
+
it('returns the stored target verbatim when set', () => {
expect(
resolveExecutionTarget(cfg({ executionTarget: 'device' }), {
@@ -378,6 +406,108 @@ describe('resolveRuntimeMode', () => {
});
describe('resolveExecutionPlan', () => {
+ it('uses a desktop hint only for a platform local target', () => {
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: openClawCfg({ executionTarget: 'local' }),
+ clientExecutionAvailable: true,
+ isHetero: true,
+ localDeviceId: 'this-desktop',
+ sandboxExecutionAvailable: false,
+ }),
+ ).toEqual({ deviceId: 'this-desktop', kind: 'device', target: 'local' });
+
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: openClawCfg({
+ boundDeviceId: 'remote-device',
+ executionTarget: 'device',
+ }),
+ clientExecutionAvailable: true,
+ isHetero: true,
+ localDeviceId: 'this-desktop',
+ sandboxExecutionAvailable: false,
+ }),
+ ).toEqual({ deviceId: 'remote-device', kind: 'device', target: 'device' });
+
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: openClawCfg({
+ boundDeviceId: 'stale-remote-device',
+ executionTarget: 'local',
+ }),
+ clientExecutionAvailable: true,
+ isHetero: true,
+ sandboxExecutionAvailable: false,
+ }),
+ ).toEqual({ kind: 'device-unrouted', reason: 'no-bound-device', target: 'local' });
+
+ // Schedules, bots, and other server-only triggers have no "this desktop".
+ // A local platform target must fail closed instead of picking an arbitrary
+ // online device; users must bind an explicit remote device for those runs.
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: openClawCfg({ executionTarget: 'local' }),
+ clientExecutionAvailable: false,
+ isHetero: true,
+ onlineDeviceIds: ['some-online-device'],
+ sandboxExecutionAvailable: false,
+ }),
+ ).toEqual({ kind: 'none', target: 'none' });
+
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: openClawCfg({ boundDeviceId: 'legacy-device' }),
+ clientExecutionAvailable: false,
+ isHetero: true,
+ sandboxExecutionAvailable: false,
+ }),
+ ).toEqual({ deviceId: 'legacy-device', kind: 'device', target: 'device' });
+
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: openClawCfg({
+ boundDeviceId: 'workspace-device',
+ executionTarget: 'device',
+ executionTargetSelectionPolicy: 'fixed',
+ }),
+ clientExecutionAvailable: true,
+ isHetero: true,
+ localDeviceId: 'this-desktop',
+ requestedDeviceId: 'member-device',
+ sandboxExecutionAvailable: false,
+ }),
+ ).toEqual({ deviceId: 'workspace-device', kind: 'device', target: 'device' });
+
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: openClawCfg({
+ boundDeviceId: 'author-desktop',
+ executionTarget: 'local',
+ executionTargetSelectionPolicy: 'fixed',
+ }),
+ clientExecutionAvailable: true,
+ isHetero: true,
+ localDeviceId: 'member-desktop',
+ sandboxExecutionAvailable: false,
+ }),
+ ).toEqual({ deviceId: 'author-desktop', kind: 'device', target: 'local' });
+ });
+
+ it('does not dispatch a stale platform binding for none or unsupported sandbox', () => {
+ for (const executionTarget of ['none', 'sandbox'] as const) {
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: openClawCfg({ boundDeviceId: 'stale-device', executionTarget }),
+ clientExecutionAvailable: executionTarget !== 'none',
+ isHetero: true,
+ localDeviceId: 'this-desktop',
+ sandboxExecutionAvailable: false,
+ }),
+ ).toEqual({ kind: 'none', target: 'none' });
+ }
+ });
+
const ONLINE_A = ['device-a'];
const ONLINE_AB = ['device-a', 'device-b'];
diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.ts
index 637b697e390..ffad0ef3374 100644
--- a/src/helpers/executionTarget.ts
+++ b/src/helpers/executionTarget.ts
@@ -1,3 +1,4 @@
+import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
import type {
AgentDeviceOverride,
DeviceExecutionTarget,
@@ -112,7 +113,11 @@ export interface ResolveExecutionTargetOptions {
/** Whether a heterogeneous provider can run in LobeHub's cloud sandbox. */
export const isHeterogeneousSandboxExecutionAvailable = (type: string | undefined): boolean =>
- type !== 'amp' && type !== 'opencode' && type !== 'pi';
+ type !== 'amp' &&
+ type !== 'hermes' &&
+ type !== 'opencode' &&
+ type !== 'openclaw' &&
+ type !== 'pi';
/**
* Single source of truth for where an agent executes β€” one global
@@ -177,6 +182,15 @@ export const resolveExecutionTarget = (
sandboxExecutionAvailable ??
isHeterogeneousSandboxExecutionAvailable(agencyConfig?.heterogeneousProvider?.type);
const stored = agencyConfig?.executionTarget;
+ // Compatibility for platform agents created before execution-target selection
+ // was introduced: their bound device was the complete routing contract.
+ if (
+ stored === undefined &&
+ agencyConfig?.boundDeviceId &&
+ isRemoteHeterogeneousType(agencyConfig.heterogeneousProvider?.type ?? '')
+ ) {
+ return 'device';
+ }
let effective = stored ?? (clientAvailable ? 'local' : 'none');
if (
!clientAvailable &&
@@ -327,6 +341,8 @@ export interface ResolveExecutionPlanParams {
/** See {@link ResolveExecutionTargetOptions.clientExecutionAvailable}. */
clientExecutionAvailable: boolean;
isHetero?: boolean;
+ /** This desktop's device ID. Used only when the resolved target is `local`. */
+ localDeviceId?: string;
/**
* Online device ids from the device gateway. Pass `undefined` to skip
* online checks and single-device auto-activation entirely β€” the binding is
@@ -382,6 +398,7 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): Execut
chatConfig,
clientExecutionAvailable,
isHetero,
+ localDeviceId,
onlineDeviceIds,
requestedDeviceId,
sandboxExecutionAvailable,
@@ -411,6 +428,7 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): Execut
// route the run somewhere else.
const effectiveRequestedDeviceId =
agencyConfig?.executionTargetSelectionPolicy === 'fixed' ? undefined : requestedDeviceId;
+ const isFixedSelection = agencyConfig?.executionTargetSelectionPolicy === 'fixed';
const wantsDevice =
!!effectiveRequestedDeviceId || target === 'device' || target === 'local' || target === 'auto';
@@ -429,8 +447,16 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): Execut
// is what `device` mode is for) β€” ignore it so `auto` always picks fresh and
// a stale binding left over from a previous `device` selection can't pin the
// run. An explicit `requestedDeviceId` still wins everywhere.
+ const isPlatformTask = isRemoteHeterogeneousType(agencyConfig?.heterogeneousProvider?.type ?? '');
const boundDeviceId =
- effectiveRequestedDeviceId || (target === 'auto' ? undefined : agencyConfig?.boundDeviceId);
+ effectiveRequestedDeviceId ||
+ (target === 'local'
+ ? isFixedSelection
+ ? agencyConfig?.boundDeviceId
+ : localDeviceId || (isPlatformTask ? undefined : agencyConfig?.boundDeviceId)
+ : target === 'auto'
+ ? undefined
+ : agencyConfig?.boundDeviceId);
// requestedDeviceId may force device routing over a non-device stored target;
// keep `auto` / `local` distinct, everything else collapses to `device`.
const effectiveTarget = target === 'local' ? 'local' : target === 'auto' ? 'auto' : 'device';
diff --git a/src/hooks/useRemoteAgentDeviceGuard.test.ts b/src/hooks/useRemoteAgentDeviceGuard.test.ts
index 63d9698df32..8c6ebb82d97 100644
--- a/src/hooks/useRemoteAgentDeviceGuard.test.ts
+++ b/src/hooks/useRemoteAgentDeviceGuard.test.ts
@@ -12,6 +12,7 @@ vi.mock('@/services/device', () => ({
}));
const mockedUseEffectiveAgencyConfig = vi.mocked(useEffectiveAgencyConfig);
+const mockedCheckCapability = vi.mocked(deviceService.checkCapability);
const mockedListDevices = vi.mocked(deviceService.listDevices);
describe('useRemoteAgentDeviceGuard', () => {
@@ -63,6 +64,52 @@ describe('useRemoteAgentDeviceGuard', () => {
await waitFor(() => expect(result.current.status).toBe('device-offline'));
});
+ it('defers an unknown author-personal binding to authoritative server routing', async () => {
+ mockedUseEffectiveAgencyConfig.mockReturnValue({
+ agencyConfig: {
+ boundDeviceId: 'author-device',
+ heterogeneousProvider: { type: 'openclaw' },
+ },
+ canDisplayExecutionTarget: true,
+ canSelectExecutionTarget: true,
+ isPreferenceLoading: false,
+ workspaceScoped: true,
+ });
+ mockedListDevices.mockResolvedValue([]);
+
+ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }));
+
+ await waitFor(() => expect(result.current.status).toBe('ok'));
+ expect(mockedCheckCapability).not.toHaveBeenCalled();
+ });
+
+ it('probes a personal device through the personal gateway principal', async () => {
+ mockedUseEffectiveAgencyConfig.mockReturnValue({
+ agencyConfig: {
+ boundDeviceId: 'member-device',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'hermes' },
+ },
+ canDisplayExecutionTarget: true,
+ canSelectExecutionTarget: true,
+ isPreferenceLoading: false,
+ workspaceScoped: false,
+ });
+ mockedListDevices.mockResolvedValue([
+ { deviceId: 'member-device', online: true, scope: 'personal' },
+ ] as never);
+ mockedCheckCapability.mockResolvedValue({ available: true });
+
+ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }));
+
+ await waitFor(() => expect(result.current.status).toBe('ok'));
+ expect(mockedCheckCapability).toHaveBeenCalledWith({
+ deviceId: 'member-device',
+ platform: 'hermes',
+ scope: 'personal',
+ });
+ });
+
it('stays in checking (and does not probe) while the workspace preference loads', async () => {
mockedUseEffectiveAgencyConfig.mockReturnValue({
agencyConfig: {
diff --git a/src/hooks/useRemoteAgentDeviceGuard.ts b/src/hooks/useRemoteAgentDeviceGuard.ts
index d08dc82ac1b..eb0b6edc143 100644
--- a/src/hooks/useRemoteAgentDeviceGuard.ts
+++ b/src/hooks/useRemoteAgentDeviceGuard.ts
@@ -19,7 +19,7 @@ interface UseRemoteAgentDeviceGuardResult {
}
/**
- * Checks whether the bound device is online and, for remote-only hetero
+ * Checks whether the bound device is online and, for notify-based hetero
* platforms, whether that platform is available on the device. Used in
* HeterogeneousChatInput before device-dispatched hetero runs.
*/
@@ -61,7 +61,15 @@ export const useRemoteAgentDeviceGuard = ({
const devices = await deviceService.listDevices();
const device = devices.find((d) => d.deviceId === boundDeviceId);
- if (!device || !device.online) {
+ // A shared/legacy binding may point at the author's personal principal,
+ // which is intentionally absent from the caller-scoped device list. The
+ // server owns that routing decision; absence here is not proof of offline.
+ if (!device) {
+ setStatus('ok');
+ return;
+ }
+
+ if (!device.online) {
setStatus('device-offline');
return;
}
@@ -70,6 +78,7 @@ export const useRemoteAgentDeviceGuard = ({
const capability = await deviceService.checkCapability({
deviceId: boundDeviceId,
platform: providerType,
+ scope: device.scope,
});
setStatus(capability.available ? 'ok' : 'platform-unavailable');
} else {
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
index a0139e5378f..199a6618d1e 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
@@ -1,9 +1,6 @@
'use client';
-import {
- HETEROGENEOUS_TYPE_LABELS,
- isRemoteHeterogeneousType,
-} from '@lobechat/heterogeneous-agents';
+import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';
import { type ChatInputActionsProps } from '@lobehub/editor/react';
import { Alert, Flexbox } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
@@ -106,7 +103,6 @@ const HeterogeneousChatInput = memo(() => {
clientExecutionAvailable: isDesktop,
workspaceScoped,
});
- const isRemoteAgent = !!providerType && isRemoteHeterogeneousType(providerType);
const deviceSelectionRequired =
!!providerType &&
!isHeterogeneousSandboxExecutionAvailable(providerType) &&
@@ -146,13 +142,11 @@ const HeterogeneousChatInput = memo(() => {
[showHeteroModel],
);
- // A run goes to an `lh connect` device when the provider is a remote-only type
- // (openclaw / hermes) OR a local-CLI type (claude-code / codex) resolves to a
- // bound device (including desktop "local" opened from web). Either way the
+ // A run goes to an `lh connect` device when its execution target resolves to a
+ // bound device (including desktop "local" opened from web). The
// bound device must be online before we let the user send β€” guard it here
// instead of failing at dispatch time.
- const isDeviceExecution =
- isRemoteAgent || (executionTarget === 'device' && !!agencyConfig?.boundDeviceId);
+ const isDeviceExecution = executionTarget === 'device' && !!agencyConfig?.boundDeviceId;
const { status, refresh } = useRemoteAgentDeviceGuard({ agentId, enabled: isDeviceExecution });
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index 4b34ee66276..4cfdd810fcb 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -68,6 +68,7 @@ export interface ExecAgentTaskParams {
existingMessageIds?: string[];
/** File IDs of already-uploaded attachments to attach to the new user message */
fileIds?: string[];
+ localDeviceId?: string;
/**
* Agents the user @-mentioned in this message (multi-mention). The server
* enables the callAgent tool and injects the mentioned-agents delegation
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index ad23bd39846..92cf0ebd5c2 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -37,10 +37,14 @@ const mockToolInterventionConfig = vi.hoisted(() => ({
allowList: [] as string[],
approvalMode: 'manual' as 'allow-list' | 'auto-run' | 'manual',
}));
+const mockUserState = vi.hoisted(() => ({
+ profile: { id: 'user-1' },
+ workspaceUserPreference: { agentDeviceOverrides: {} as Record<string, any> },
+}));
vi.mock('@/store/user', () => ({
useUserStore: {
- getState: vi.fn(() => ({})),
+ getState: vi.fn(() => mockUserState),
},
}));
@@ -54,6 +58,9 @@ vi.mock('@/store/user/selectors', () => ({
allowList: () => mockToolInterventionConfig.allowList,
approvalMode: () => mockToolInterventionConfig.approvalMode,
},
+ userProfileSelectors: {
+ userId: (state: typeof mockUserState) => state.profile.id,
+ },
}));
// ─── Local-device activation (本机) test seams ───
@@ -85,6 +92,11 @@ vi.mock('@/services/electron/gatewayConnection', () => ({
vi.mock('@/store/agent', () => ({ getAgentStoreState: () => mockAgentStore.state }));
vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById: (agentId: string) => (state: any) =>
+ state.agentMap?.[agentId]?.agencyConfig,
+ getAgentById: (agentId: string) => (state: any) => state.agentMap?.[agentId],
+ },
agentSelectors: { currentAgentWorkingDirectory: () => () => undefined },
chatConfigByIdSelectors: {
getChatConfigById: (agentId: string) => (state: any) =>
@@ -1036,7 +1048,10 @@ describe('GatewayActionImpl', () => {
// Server task was created before the signal flipped β€” best-effort
// interrupt must fire so the agent run stops server-side.
- expect(interruptTaskSpy).toHaveBeenCalledWith({ operationId: 'server-op-cancel' });
+ expect(interruptTaskSpy).toHaveBeenCalledWith({
+ operationId: 'server-op-cancel',
+ topicId: 'topic-1',
+ });
// No child op, no message association, no WS connect, no parent complete
// β€” the cancel must short-circuit the whole hand-off.
@@ -1397,9 +1412,15 @@ describe('GatewayActionImpl', () => {
mockRuntime.isLocal = false;
mockRuntime.isChatMode = false;
mockGateway.getDeviceInfo.mockReset();
+ mockAgentStore.state.agentMap = {};
+ mockUserState.workspaceUserPreference.agentDeviceOverrides = {};
});
const send = async () => {
+ mockAgentStore.state.agentMap['agent-1'] ??= {
+ agencyConfig: { executionTarget: mockRuntime.isLocal ? 'local' : 'sandbox' },
+ userId: 'user-1',
+ };
const { action } = createExecuteTestAction();
vi.mocked(aiAgentService.execAgentTask).mockResolvedValue(successResult);
await action.executeGatewayAgent({
@@ -1430,9 +1451,8 @@ describe('GatewayActionImpl', () => {
await send();
expect(mockGateway.getDeviceInfo).not.toHaveBeenCalled();
- expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
- expect.objectContaining({ deviceId: undefined }),
- expect.anything(),
+ expect(vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0]).not.toHaveProperty(
+ 'deviceId',
);
});
@@ -1447,9 +1467,8 @@ describe('GatewayActionImpl', () => {
await send();
expect(mockGateway.getDeviceInfo).not.toHaveBeenCalled();
- expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
- expect.objectContaining({ deviceId: undefined }),
- expect.anything(),
+ expect(vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0]).not.toHaveProperty(
+ 'deviceId',
);
});
@@ -1460,10 +1479,94 @@ describe('GatewayActionImpl', () => {
await send();
expect(mockGateway.getDeviceInfo).not.toHaveBeenCalled();
+ expect(vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0]).not.toHaveProperty(
+ 'deviceId',
+ );
+ });
+
+ it('uses a workspace member local override instead of the shared remote device', async () => {
+ mockEnv.isDesktop = true;
+ mockGateway.getDeviceInfo.mockResolvedValue({ deviceId: 'device-local-member' });
+ mockAgentStore.state.agentMap['agent-1'] = {
+ agencyConfig: { boundDeviceId: 'workspace-device', executionTarget: 'device' },
+ userId: 'workspace-owner',
+ visibility: 'public',
+ workspaceId: 'workspace-1',
+ };
+ mockUserState.workspaceUserPreference.agentDeviceOverrides['agent-1'] = {
+ boundDeviceId: 'device-local-member',
+ executionTarget: 'local',
+ };
+
+ await send();
+
+ expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'device-local-member' }),
+ expect.anything(),
+ );
+ });
+
+ it('does not preset this desktop for a workspace member remote override', async () => {
+ mockEnv.isDesktop = true;
+ mockAgentStore.state.agentMap['agent-1'] = {
+ agencyConfig: { executionTarget: 'local' },
+ userId: 'workspace-owner',
+ visibility: 'public',
+ workspaceId: 'workspace-1',
+ };
+ mockUserState.workspaceUserPreference.agentDeviceOverrides['agent-1'] = {
+ boundDeviceId: 'remote-device',
+ executionTarget: 'device',
+ };
+
+ await send();
+
+ expect(mockGateway.getDeviceInfo).not.toHaveBeenCalled();
+ expect(vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0]).not.toHaveProperty(
+ 'deviceId',
+ );
+ });
+
+ it('sends a distinct local device hint for a local platform agent', async () => {
+ mockEnv.isDesktop = true;
+ mockGateway.getDeviceInfo.mockResolvedValue({ deviceId: 'this-desktop' });
+ mockAgentStore.state.agentMap['agent-1'] = {
+ agencyConfig: {
+ executionTarget: 'local',
+ heterogeneousProvider: { type: 'openclaw' },
+ },
+ userId: 'user-1',
+ };
+
+ await send();
+
expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
- expect.objectContaining({ deviceId: undefined }),
+ expect.objectContaining({ localDeviceId: 'this-desktop' }),
expect.anything(),
);
+ expect(vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0]).not.toHaveProperty(
+ 'deviceId',
+ );
+ });
+
+ it('sends a harmless desktop hint without overriding a remote platform target', async () => {
+ mockEnv.isDesktop = true;
+ mockGateway.getDeviceInfo.mockResolvedValue({ deviceId: 'this-desktop' });
+ mockAgentStore.state.agentMap['agent-1'] = {
+ agencyConfig: {
+ boundDeviceId: 'remote-device',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'hermes' },
+ },
+ userId: 'user-1',
+ };
+
+ await send();
+
+ expect(mockGateway.getDeviceInfo).toHaveBeenCalled();
+ const request = vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0];
+ expect(request).not.toHaveProperty('deviceId');
+ expect(request).toHaveProperty('localDeviceId', 'this-desktop');
});
});
});
diff --git a/src/store/chat/slices/agentRun/actions/dispatch/agentDispatcher.ts b/src/store/chat/slices/agentRun/actions/dispatch/agentDispatcher.ts
index fb9197b3ee8..af7ac82d014 100644
--- a/src/store/chat/slices/agentRun/actions/dispatch/agentDispatcher.ts
+++ b/src/store/chat/slices/agentRun/actions/dispatch/agentDispatcher.ts
@@ -104,9 +104,10 @@ export const selectRuntimeType = (
{ isDesktop = defaultIsDesktop }: SelectRuntimeTypeOptions = {},
): AgentRuntimeType => {
if (ctx.parentRuntime) return ctx.parentRuntime;
- // Remote device agents (openclaw / hermes) always use the gateway path regardless of
- // desktop/web β€” they communicate via a device connected with `lh connect`, not via
- // local desktop IPC. No special desktop handling needed.
+ // Notify-based platform agents (openclaw / hermes) use the gateway transport for both
+ // targets: `local` presets this desktop's personal device ID on the request, while
+ // `device` dispatches to the configured remote device. They do not implement the
+ // JSONL/session protocol consumed by the in-process `hetero` transport.
if (ctx.heterogeneousProvider && isRemoteHeterogeneousType(ctx.heterogeneousProvider.type)) {
return 'gateway';
}
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 5249878fe56..bd9bfd2440f 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -4,6 +4,7 @@ import {
type AgentStreamEvent,
type ConnectionStatus,
} from '@lobechat/agent-gateway-client';
+import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
import type {
ChatTopicMetadata,
ConversationContext,
@@ -11,8 +12,10 @@ import type {
MessageMetadata,
RuntimeMentionedAgent,
} from '@lobechat/types';
+import { resolveAgentAgencyConfig } from '@lobechat/types';
import { isDesktop } from '@/const/version';
+import { resolveExecutionTarget, resolveWorkspaceScoped } from '@/helpers/executionTarget';
import {
aiAgentService,
type ResumeApprovalParam,
@@ -22,7 +25,7 @@ import { gatewayConnectionService } from '@/services/electron/gatewayConnection'
import { messageService } from '@/services/message';
import { topicService } from '@/services/topic';
import { getAgentStoreState } from '@/store/agent';
-import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { consumePendingTopicRepos, getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';
import { topicSelectors } from '@/store/chat/selectors';
import type { ChatStore } from '@/store/chat/store';
@@ -30,7 +33,11 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import type { StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
-import { settingsSelectors, toolInterventionSelectors } from '@/store/user/selectors';
+import {
+ settingsSelectors,
+ toolInterventionSelectors,
+ userProfileSelectors,
+} from '@/store/user/selectors';
import { isTrpcErrorCode } from '@/utils/trpcError';
import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';
@@ -56,24 +63,53 @@ import { createGatewayMemberStreamHandler } from './gatewayMemberStreamHandler';
* device-resolution heuristics. We don't pre-check online status here β€” an
* offline id simply fails the server's `onlineDevices` guard and stays unrouted.
*/
-const resolveLocalDeviceId = async (agentId?: string): Promise<string | undefined> => {
- if (!isDesktop || !agentId) return undefined;
+const resolveDesktopDeviceHints = async (
+ agentId?: string,
+): Promise<{ deviceId?: string; localDeviceId?: string }> => {
+ if (!isDesktop || !agentId) return {};
const agentState = getAgentStoreState();
// Chat mode means "no execution environment" β€” never resolve a device, even
// when the target is `local`. The server enforces this too (it auto-activates
// a single online device), but skipping the deviceId round-trip here avoids
// sending an id the server would only discard.
- if (chatConfigByIdSelectors.isChatModeById(agentId)(agentState)) return undefined;
-
- const isLocal = chatConfigByIdSelectors.isLocalSystemEnabledById(agentId)(agentState);
- if (!isLocal) return undefined;
+ if (chatConfigByIdSelectors.isChatModeById(agentId)(agentState)) return {};
+
+ const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
+ const userState = useUserStore.getState();
+ const currentUserId = userProfileSelectors.userId(userState);
+ const isAuthor = !!currentUserId && agent?.userId === currentUserId;
+ const usesWorkspaceMemberSelection =
+ !!agent?.workspaceId && agent.visibility !== 'private' && !isAuthor;
+ const deviceOverride = usesWorkspaceMemberSelection
+ ? userState.workspaceUserPreference.agentDeviceOverrides?.[agentId]
+ : undefined;
+ const agencyConfig = resolveAgentAgencyConfig(
+ agentByIdSelectors.getAgencyConfigById(agentId)(agentState),
+ deviceOverride,
+ {
+ canManage: isAuthor,
+ visibility: agent?.visibility,
+ workspaceId: agent?.workspaceId,
+ },
+ );
+ const isPlatformTask = isRemoteHeterogeneousType(agencyConfig?.heterogeneousProvider?.type ?? '');
+ const executionTarget = resolveExecutionTarget(agencyConfig, {
+ clientExecutionAvailable: true,
+ isHetero: !!agencyConfig?.heterogeneousProvider,
+ workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),
+ });
+ // Platform hints are capability claims, not routing overrides. Always send
+ // this desktop best-effort and let the server's authoritative execution plan
+ // decide whether the effective target may consume it.
+ if (!isPlatformTask && executionTarget !== 'local') return {};
try {
const info = await gatewayConnectionService.getDeviceInfo();
- return info?.deviceId;
+ if (!info?.deviceId) return {};
+ return isPlatformTask ? { localDeviceId: info.deviceId } : { deviceId: info.deviceId };
} catch {
- return undefined;
+ return {};
}
};
@@ -521,7 +557,7 @@ export class GatewayActionImpl {
? this.#get().getOperationAbortSignal(parentOperationId)
: undefined;
- const localDeviceId = await resolveLocalDeviceId(executionContext.agentId);
+ const desktopDeviceHints = await resolveDesktopDeviceHints(executionContext.agentId);
const userInterventionConfig = {
approvalMode: toolInterventionSelectors.approvalMode(useUserStore.getState()),
allowList: toolInterventionSelectors.allowList(useUserStore.getState()),
@@ -556,7 +592,7 @@ export class GatewayActionImpl {
threadId: executionContext.threadId,
topicId: executionContext.topicId,
},
- deviceId: localDeviceId,
+ ...desktopDeviceHints,
fileIds,
mentionedAgents,
parentMessageId,
@@ -574,7 +610,7 @@ export class GatewayActionImpl {
if (abortSignal?.aborted) {
// Cancel arrived after execAgentTask resolved β€” server task exists.
aiAgentService
- .interruptTask({ operationId: result.operationId })
+ .interruptTask({ operationId: result.operationId, topicId: result.topicId })
.catch((err) => console.error('[Gateway] interruptTask after cancel failed:', err));
throw abortSignal.reason ?? new DOMException('Aborted', 'AbortError');
}
@@ -621,7 +657,7 @@ export class GatewayActionImpl {
if (abortSignal?.aborted) {
aiAgentService
- .interruptTask({ operationId: result.operationId })
+ .interruptTask({ operationId: result.operationId, topicId: result.topicId })
.catch((err) => console.error('[Gateway] interruptTask after cancel failed:', err));
throw abortSignal.reason ?? new DOMException('Aborted', 'AbortError');
}