Skip to content

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

πŸ› fix(toolExecution): make no-active-device failures recoverable for agents (#19069)

Arvin Xu4bd9c9cd63b6
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts
new file mode 100644
index 00000000000..d5172ff72ed
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts
@@ -0,0 +1,114 @@
+import { BrowserIdentifier, BrowserManifest } from '@lobechat/builtin-tool-browser';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { type ToolExecutionContext } from '../../types';
+
+// Mock deviceGateway
+const mockExecuteToolCall = vi.fn();
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ executeToolCall: (...args: any[]) => mockExecuteToolCall(...args),
+ },
+}));
+
+// Import after mock setup
+const { browserRuntime } = await import('../browser');
+
+describe('browserRuntime', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should have the correct identifier', () => {
+ expect(browserRuntime.identifier).toBe(BrowserIdentifier);
+ });
+
+ describe('factory', () => {
+ it('should throw when userId is missing', () => {
+ const context: ToolExecutionContext = {
+ activeDeviceId: 'device-1',
+ toolManifestMap: {},
+ };
+
+ expect(() => browserRuntime.factory(context)).toThrow(
+ 'userId is required for Browser device proxy execution',
+ );
+ });
+
+ it('should throw when agentId is missing', () => {
+ const context: ToolExecutionContext = {
+ activeDeviceId: 'device-1',
+ toolManifestMap: {},
+ userId: 'user-1',
+ };
+
+ expect(() => browserRuntime.factory(context)).toThrow(
+ 'agentId is required for Browser device proxy execution',
+ );
+ });
+
+ it('should return a structured NO_ACTIVE_DEVICE result per API when activeDeviceId is missing', async () => {
+ const context: ToolExecutionContext = {
+ agentId: 'agt-1',
+ // Device-unrouted run WITH the picker still advertised: recovery via
+ // lobe-remote-device activation is possible.
+ toolManifestMap: { 'lobe-remote-device': {} as any },
+ userId: 'user-1',
+ };
+
+ const proxy = browserRuntime.factory(context) as Record<string, (args: any) => Promise<any>>;
+
+ // Every manifest API is present (not a throw), and each returns the
+ // structured, recoverable error instead of an opaque failure.
+ for (const api of BrowserManifest.api) {
+ expect(proxy[api.name]).toBeDefined();
+ expect(typeof proxy[api.name]).toBe('function');
+ }
+
+ const result = await proxy[BrowserManifest.api[0].name]({ url: 'https://example.com' });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({ code: 'NO_ACTIVE_DEVICE' });
+ expect(result.content).toContain('lobe-remote-device.listOnlineDevices');
+ expect(result.content).toContain('activateDevice');
+ expect(result.content).toContain('desktop application or cli');
+ // No device dispatch happened.
+ expect(mockExecuteToolCall).not.toHaveBeenCalled();
+ });
+
+ it('should point at user reconnection when the remote-device picker is not in the manifest', async () => {
+ const context: ToolExecutionContext = {
+ agentId: 'agt-1',
+ toolManifestMap: {
+ 'lobe-browser': {} as any,
+ },
+ userId: 'user-1',
+ };
+
+ const proxy = browserRuntime.factory(context) as Record<string, (args: any) => Promise<any>>;
+ const result = await proxy[BrowserManifest.api[0].name]({});
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({ code: 'NO_ACTIVE_DEVICE' });
+ expect(result.content).toContain('locked to a specific device');
+ expect(result.content).not.toContain('activateDevice');
+ });
+
+ it('should create a proxy with a function for each API in BrowserManifest when a device is active', () => {
+ const context: ToolExecutionContext = {
+ activeDeviceId: 'device-1',
+ agentId: 'agt-1',
+ topicId: 'tpc-1',
+ toolManifestMap: {},
+ userId: 'user-1',
+ };
+
+ const proxy = browserRuntime.factory(context) as Record<string, () => any>;
+
+ for (const api of BrowserManifest.api) {
+ expect(proxy[api.name]).toBeDefined();
+ expect(typeof proxy[api.name]).toBe('function');
+ }
+ });
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
index 949e67a4806..5f4eae8fbad 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.test.ts
@@ -39,15 +39,57 @@ describe('localSystemRuntime', () => {
);
});
- it('should throw when activeDeviceId is missing', () => {
+ it('should return a structured NO_ACTIVE_DEVICE result per API when activeDeviceId is missing', async () => {
const context: ToolExecutionContext = {
- toolManifestMap: {},
+ // Device-unrouted run WITH the picker still advertised: recovery via
+ // lobe-remote-device activation is possible.
+ toolManifestMap: { 'lobe-remote-device': {} as any },
userId: 'user-1',
};
- expect(() => localSystemRuntime.factory(context)).toThrow(
- 'activeDeviceId is required for Local System device proxy execution',
- );
+ const proxy = localSystemRuntime.factory(context) as Record<
+ string,
+ (args: any) => Promise<any>
+ >;
+
+ // Every manifest API is present (not a throw), and each returns the
+ // structured, recoverable error instead of an opaque failure.
+ for (const api of LocalSystemManifest.api) {
+ expect(proxy[api.name]).toBeDefined();
+ expect(typeof proxy[api.name]).toBe('function');
+ }
+
+ const result = await proxy[LocalSystemManifest.api[0].name]({});
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({ code: 'NO_ACTIVE_DEVICE' });
+ expect(result.content).toContain('lobe-remote-device.listOnlineDevices');
+ expect(result.content).toContain('activateDevice');
+ expect(result.content).toContain('desktop application or cli');
+ // No device dispatch happened.
+ expect(mockExecuteToolCall).not.toHaveBeenCalled();
+ });
+
+ it('should point at user reconnection when the remote-device picker is not in the manifest', async () => {
+ const context: ToolExecutionContext = {
+ toolManifestMap: {
+ // Device-locked run: only local-system is present, the picker is
+ // physically stripped, so recovery via activation is impossible.
+ 'lobe-local-system': {} as any,
+ },
+ userId: 'user-1',
+ };
+
+ const proxy = localSystemRuntime.factory(context) as Record<
+ string,
+ (args: any) => Promise<any>
+ >;
+ const result = await proxy[LocalSystemManifest.api[0].name]({});
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({ code: 'NO_ACTIVE_DEVICE' });
+ expect(result.content).toContain('locked to a specific device');
+ expect(result.content).not.toContain('activateDevice');
});
it('should create a proxy with a function for each API in LocalSystemManifest', () => {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/browser.ts b/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
index ee0c729b1c2..71be48daed6 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
@@ -2,6 +2,7 @@ import { BrowserIdentifier, BrowserManifest } from '@lobechat/builtin-tool-brows
import { deviceGateway } from '@/server/services/deviceGateway';
+import { buildNoActiveDeviceResult, REMOTE_DEVICE_TOOL_IDENTIFIER } from './noActiveDevice';
import { resolveRunWorkspaceId } from './resolveWorkspaceScope';
import { type ServerRuntimeRegistration } from './types';
@@ -24,8 +25,25 @@ export const browserRuntime: ServerRuntimeRegistration = {
if (!context.userId) {
throw new Error('userId is required for Browser device proxy execution');
}
+ // No active device: `activeDeviceId` is legitimately empty in device-capable
+ // runs (never bound yet, or the device dropped offline mid-run and the plan
+ // re-resolved to `device-unrouted`). Historically this guard threw a bare
+ // error string with no recovery path β€” the model kept stalling on it (see
+ // agent vent reports). Return a structured, actionable result per API call
+ // instead: the model is told exactly how to recover (activate a device, or
+ // ask the user to reconnect) rather than hitting an opaque failure.
if (!context.activeDeviceId) {
- throw new Error('activeDeviceId is required for Browser device proxy execution');
+ const noDevice = buildNoActiveDeviceResult('Browser device proxy', {
+ remoteDeviceToolAvailable: context.toolManifestMap
+ ? REMOTE_DEVICE_TOOL_IDENTIFIER in context.toolManifestMap
+ : true,
+ });
+
+ const proxy: Record<string, (args: any) => Promise<any>> = {};
+ for (const api of BrowserManifest.api) {
+ proxy[api.name] = async () => noDevice;
+ }
+ return proxy;
}
if (!context.agentId) {
throw new Error('agentId is required for Browser device proxy execution');
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
index 942b3b957dc..1cb80b8e153 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
@@ -7,6 +7,7 @@ import {
import { deviceGateway } from '@/server/services/deviceGateway';
import { buildDeviceLhEnv } from '@/server/services/toolExecution/preprocessLhCommand';
+import { buildNoActiveDeviceResult, REMOTE_DEVICE_TOOL_IDENTIFIER } from './noActiveDevice';
import { resolveContentWorkspaceId, resolveRunWorkspaceId } from './resolveWorkspaceScope';
import { type ServerRuntimeRegistration } from './types';
@@ -46,8 +47,25 @@ export const localSystemRuntime: ServerRuntimeRegistration = {
if (!context.userId) {
throw new Error('userId is required for Local System device proxy execution');
}
+ // No active device: `activeDeviceId` is legitimately empty in device-capable
+ // runs (never bound yet, or the device dropped offline mid-run and the plan
+ // re-resolved to `device-unrouted`). Historically this guard threw a bare
+ // error string with no recovery path β€” the model kept stalling on it (see
+ // agent vent reports). Return a structured, actionable result per API call
+ // instead: the model is told exactly how to recover (activate a device, or
+ // ask the user to reconnect) rather than hitting an opaque failure.
if (!context.activeDeviceId) {
- throw new Error('activeDeviceId is required for Local System device proxy execution');
+ const noDevice = buildNoActiveDeviceResult('Local System', {
+ remoteDeviceToolAvailable: context.toolManifestMap
+ ? REMOTE_DEVICE_TOOL_IDENTIFIER in context.toolManifestMap
+ : true,
+ });
+
+ const proxy: Record<string, (args: any) => Promise<any>> = {};
+ for (const api of LocalSystemManifest.api) {
+ proxy[api.name] = async () => noDevice;
+ }
+ return proxy;
}
// Resolve the workspace scope the same way `remote-device` does, recovering
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/noActiveDevice.ts b/apps/server/src/services/toolExecution/serverRuntimes/noActiveDevice.ts
new file mode 100644
index 00000000000..2975102a8c1
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/noActiveDevice.ts
@@ -0,0 +1,55 @@
+import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
+
+/**
+ * Structured "no active device" tool result for the device-proxy server
+ * runtimes (local-system / browser).
+ *
+ * These runtimes are registered only in device-capable runs, but
+ * `context.activeDeviceId` can legitimately be empty:
+ *
+ * - Type 1 β€” never bound: a `device-unrouted` run advertises the device tools
+ * on purpose (mid-run activation via `lobe-remote-device` is a supported
+ * flow), so a call can arrive before any device was activated.
+ * - Type 2 β€” lost mid-run: the device dropped offline between steps, the next
+ * operation re-resolves its plan to `device-unrouted`
+ * (`bound-device-offline`), and `metadata.activeDeviceId` is cleared.
+ *
+ * Historically the runtime factory guards threw a bare
+ * `activeDeviceId is required for ...` error string. The model received no
+ * recovery path (multiple agent vent reports across different users/topics
+ * show agents stalling on exactly this), so the guards now return this
+ * structured, actionable result instead:
+ *
+ * - When the remote-device picker is reachable (its manifest is in the tool
+ * set), the error points the model at `listOnlineDevices` +
+ * `activateDevice`. Note the NEXT call takes effect: the activated device id
+ * folds back into run metadata at the next step boundary.
+ * - When the picker is NOT reachable (device-locked run whose device went
+ * offline β€” the picker is physically stripped), the only path is the user
+ * reconnecting the desktop application or cli, so the message says to tell the user.
+ */
+export const NO_ACTIVE_DEVICE_ERROR_CODE = 'NO_ACTIVE_DEVICE';
+
+export const buildNoActiveDeviceResult = (
+ toolLabel: string,
+ {
+ remoteDeviceToolAvailable = true,
+ }: {
+ remoteDeviceToolAvailable?: boolean;
+ } = {},
+): { content: string; error: { code: string; message: string }; success: false } => {
+ const recovery = remoteDeviceToolAvailable
+ ? `Call lobe-remote-device.listOnlineDevices to refresh the device list, then activateDevice with an online device id. The activation takes effect on the NEXT step β€” after it succeeds, retry this call. If no device is online, tell the user to connect the desktop application or cli.`
+ : `This conversation is locked to a specific device that is currently offline β€” the device picker is not available. Tell the user to reconnect the desktop application or cli, then retry.`;
+
+ const message = `No active device for ${toolLabel} execution. ${recovery}`;
+
+ return {
+ content: message,
+ error: { code: NO_ACTIVE_DEVICE_ERROR_CODE, message },
+ success: false,
+ };
+};
+
+/** Manifest identifier of the remote-device picker, for reachability checks. */
+export const REMOTE_DEVICE_TOOL_IDENTIFIER: string = RemoteDeviceManifest.identifier;
diff --git a/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.test.ts
new file mode 100644
index 00000000000..6b2e22c8c48
--- /dev/null
+++ b/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from 'vitest';
+
+import { RemoteDeviceExecutionRuntime } from './index';
+
+const makeRuntime = (devices: any[]) =>
+ new RemoteDeviceExecutionRuntime({
+ queryDeviceList: async () => devices,
+ });
+
+describe('RemoteDeviceExecutionRuntime', () => {
+ describe('listOnlineDevices', () => {
+ it('filters offline devices and returns the online ones', async () => {
+ const runtime = makeRuntime([
+ { deviceId: 'd1', hostname: 'online-host', online: true, platform: 'darwin' },
+ { deviceId: 'd2', hostname: 'offline-host', online: false, platform: 'win32' },
+ ]);
+
+ const result = await runtime.listOnlineDevices();
+
+ expect(result.success).toBe(true);
+ expect(JSON.parse(result.content)).toEqual([expect.objectContaining({ deviceId: 'd1' })]);
+ });
+
+ it('returns an actionable hint when no devices are online', async () => {
+ const runtime = makeRuntime([
+ { deviceId: 'd2', hostname: 'offline-host', online: false, platform: 'win32' },
+ ]);
+
+ const result = await runtime.listOnlineDevices();
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('desktop application');
+ });
+ });
+
+ describe('activateDevice', () => {
+ it('activates an online device and returns metadata.activeDeviceId', async () => {
+ const runtime = makeRuntime([
+ { deviceId: 'd1', hostname: 'host', online: true, platform: 'darwin' },
+ ]);
+
+ const result = await runtime.activateDevice({ deviceId: 'd1' });
+
+ expect(result.success).toBe(true);
+ expect(result.state).toMatchObject({
+ metadata: { activeDeviceId: 'd1' },
+ });
+ });
+
+ it('returns a refresh-list recovery hint when the device is not online (stale list)', async () => {
+ const runtime = makeRuntime([
+ // The device the model saw as "online" moments ago is now gone β€” the
+ // stale-list race. The error must point at listOnlineDevices, not be a
+ // dead end that invites blind retries.
+ { deviceId: 'd1', hostname: 'host', online: false, platform: 'darwin' },
+ ]);
+
+ const result = await runtime.activateDevice({ deviceId: 'd1' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('not online or does not exist');
+ expect(result.content).toContain('listOnlineDevices');
+ expect(result.content).toContain('desktop application or cli');
+ });
+
+ it('returns the same recovery hint for an unknown device id', async () => {
+ const runtime = makeRuntime([]);
+
+ const result = await runtime.activateDevice({ deviceId: 'ghost' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('listOnlineDevices');
+ });
+ });
+});
diff --git a/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.ts b/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.ts
index 8e5faeacdb6..9164418ecfc 100644
--- a/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-remote-device/src/ExecutionRuntime/index.ts
@@ -41,8 +41,13 @@ export class RemoteDeviceExecutionRuntime {
const target = devices.find((d) => d.deviceId === args.deviceId && d.online);
if (!target) {
+ // The device list can go stale between listOnlineDevices and this call
+ // (a device that showed online may have dropped in between), so point
+ // the model at refreshing the list instead of leaving it with a dead
+ // end β€” repeated blind activateDevice retries against the same stale
+ // id are the observed failure mode (agent vent reports).
return {
- content: `Device "${args.deviceId}" is not online or does not exist.`,
+ content: `Device "${args.deviceId}" is not online or does not exist. Call listOnlineDevices to refresh the device list and activate a device from the fresh result. If no device is online, tell the user to connect the desktop application or cli.`,
success: false,
};
}
diff --git a/packages/builtin-tool-remote-device/vitest.config.mts b/packages/builtin-tool-remote-device/vitest.config.mts
new file mode 100644
index 00000000000..4ac6027d578
--- /dev/null
+++ b/packages/builtin-tool-remote-device/vitest.config.mts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'node',
+ },
+});