π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(device): stop sending browser and MCP calls to CLI-only devices (#20076)
Arvin Xu943bcadb8d0f
diff --git a/apps/server/src/services/deviceGateway/deviceChannels.ts b/apps/server/src/services/deviceGateway/deviceChannels.tsnew file mode 100644index 00000000000..2455b3dd617--- /dev/null+++ b/apps/server/src/services/deviceGateway/deviceChannels.ts@@ -0,0 +1,42 @@+import debug from 'debug';++import { deviceGateway } from './index';++const log = debug('lobe-server:device-channels');++const DESKTOP_CHANNELS = new Set(['desktop', 'desktop-dev']);++/**+ * What kind of client is live on a device:+ * - `desktop` β the LobeHub desktop app is connected (browser panel, MCP tunnel, β¦)+ * - `cli-only` β only `lh connect` is connected; it handles local-system+ * file/shell calls and answers anything else with `Unknown tool API`+ * - `unknown` β the device is not in the live list or reports no channel+ * labels (older gateway); callers keep their previous behaviour+ */+export type DeviceClientKind = 'cli-only' | 'desktop' | 'unknown';++/**+ * Resolve which client kind is live on `deviceId`, from the gateway's+ * presence list (the same source the run-target picker reads).+ *+ * Tool calls that only the desktop app can serve (browser, MCP tunnel) must+ * check this before dispatch: the gateway delivers a call to whichever+ * connection the device holds, and a CLI-only device cannot run it.+ */+export const resolveDeviceClientKind = async (+ userId: string,+ deviceId: string,+ workspaceId?: string,+): Promise<DeviceClientKind> => {+ try {+ const devices = await deviceGateway.queryDeviceList(userId, workspaceId);+ const device = devices.find((d) => d.deviceId === deviceId);+ const channels = (device?.channels ?? []).map((c) => c.channel).filter((c): c is string => !!c);+ if (channels.length === 0) return 'unknown';+ return channels.some((c) => DESKTOP_CHANNELS.has(c)) ? 'desktop' : 'cli-only';+ } catch (error) {+ log('device presence lookup failed for %s: %O', deviceId, error);+ return 'unknown';+ }+};diff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.tsindex 32edc6cc7c1..ebac7b4939a 100644--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts@@ -512,6 +512,76 @@ describe('ToolExecutionService', () => {);});+ // `lh connect` answers `mcp` tool calls with `Unknown tool API: <tool>` β an+ // active device that is CLI-only must not receive the tunnel (Honcho-Memory+ // vents: calls worked until the agent activated a CLI-only Mac mini).+ it('skips a CLI-only active device and tunnels to the newest desktop device', async () => {+ vi.mocked(deviceGateway.queryDeviceList).mockResolvedValue([+ { channels: [{ channel: 'cli' }], deviceId: 'mac-mini-cli' },+ ] as any);+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([+ { channels: [{ channel: 'cli' }], deviceId: 'mac-mini-cli', online: true },+ { channels: [{ channel: 'desktop' }], deviceId: 'macbook', online: true },+ ] as any);+ const service = makeService();++ const result = await service.executeTool(+ mcpPayload,+ contextWith(+ { name: 'Honcho-Memory', type: 'http', url: 'http://localhost:8787/' },+ { activeDeviceId: 'mac-mini-cli' },+ ),+ );++ expect(result.success).toBe(true);+ expect(deviceGateway.executeMcpCall).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: 'macbook' }),+ undefined,+ );+ });++ it('fails with an actionable error when only CLI devices are online', async () => {+ vi.mocked(deviceGateway.queryDeviceList).mockResolvedValue([+ { channels: [{ channel: 'cli' }], deviceId: 'mac-mini-cli' },+ ] as any);+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([+ { channels: [{ channel: 'cli' }], deviceId: 'mac-mini-cli', online: true },+ ] as any);+ const service = makeService();++ const result = await service.executeTool(+ mcpPayload,+ contextWith(+ { name: 'Honcho-Memory', type: 'http', url: 'http://localhost:8787/' },+ { activeDeviceId: 'mac-mini-cli' },+ ),+ );++ expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();+ expect(result.success).toBe(false);+ expect((result.error as any)?.code).toBe('MCP_DEVICE_UNAVAILABLE');+ expect(result.content).toContain('lh connect');+ });++ it('fails closed for a workspace run whose active device is CLI-only', async () => {+ vi.mocked(deviceGateway.queryDeviceList).mockResolvedValue([+ { channels: [{ channel: 'cli' }], deviceId: 'ws-cli' },+ ] as any);+ const service = makeService();++ const result = await service.executeTool(+ mcpPayload,+ contextWith(+ { args: [], command: 'npx', name: 'my-mcp', type: 'stdio' },+ { activeDeviceId: 'ws-cli', workspaceId: 'ws-1' },+ ),+ );++ expect(deviceGateway.queryDeviceList).toHaveBeenCalledWith('user-1', 'ws-1');+ expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();+ expect((result.error as any)?.code).toBe('MCP_DEVICE_UNAVAILABLE');+ });+it('addresses the workspace pool for a plan-routed device in a workspace run', async () => {// Workspace devices live under the `workspace:<id>` principal in the// gateway β the tunneled call must carry the scope or an onlinediff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.tsindex 90e18697c70..81fd90f603e 100644--- a/apps/server/src/services/toolExecution/index.ts+++ b/apps/server/src/services/toolExecution/index.ts@@ -14,6 +14,7 @@ import {getConnectorToolPermission,} from '@/libs/mcp/connectorPermissionCheck';import { deviceGateway } from '@/server/services/deviceGateway';+import { resolveDeviceClientKind } from '@/server/services/deviceGateway/deviceChannels';import { resolveDeviceDispatchAuthorizationFailure } from '@/server/services/deviceGateway/dispatchAuthorization';import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';import { contentBlocksToString } from '@/server/services/mcp/contentProcessor';@@ -309,7 +310,7 @@ export class ToolExecutionService {: undefined;if (!tunnelTarget) {log('Device-only MCP %s:%s has no reachable device β failing fast', identifier, apiName);- const message = `MCP server '${identifier}' only your own machine can reach (stdio or local network). No online device was found to run it β open the LobeHub desktop app on the machine that hosts this MCP server, then retry.`;+ const message = `MCP server '${identifier}' only your own machine can reach (stdio or local network). No online LobeHub desktop app was found to run it (a device connected only through the \`lh connect\` CLI cannot run MCP servers) β open the LobeHub desktop app on the machine that hosts this MCP server, then retry.`;return {content: message,error: { code: 'MCP_DEVICE_UNAVAILABLE', message },@@ -371,7 +372,18 @@ export class ToolExecutionService {// do (respects a personal-scope active device, recovers the agent's// workspace when the run context lost it).const workspaceId = await resolveRunWorkspaceId(context);- if (context.activeDeviceId) return { deviceId: context.activeDeviceId, workspaceId };+ if (context.activeDeviceId) {+ // Only the desktop app handles `mcp` tool calls; a device whose only+ // live connection is `lh connect` answers them with `Unknown tool API`.+ // Such an active device is skipped: personal runs fall through to the+ // newest desktop device below, workspace runs fail closed.+ const clientKind =+ context.userId !== undefined+ ? await resolveDeviceClientKind(context.userId, context.activeDeviceId, workspaceId)+ : 'unknown';+ if (clientKind !== 'cli-only') return { deviceId: context.activeDeviceId, workspaceId };+ log('Active device %s is CLI-only; not tunneling MCP to it', context.activeDeviceId);+ }// The implicit fallback is PERSONAL-scope only. In a workspace run the// connector may have been authorized by ANOTHER member, and tunneling its// params (stdio env / HTTP auth) to the caller's own newest device woulddiff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.tsindex ab15a475f17..7e751b0d7ea 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts@@ -9,6 +9,11 @@ vi.mock('@/server/services/deviceGateway/authorizedToolCall', () => ({mockExecuteToolCall(...args),}));+const mockQueryDeviceList = vi.fn();+vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: { queryDeviceList: (...args: unknown[]) => mockQueryDeviceList(...args) },+}));+const mockUploadBase64 = vi.fn();vi.mock('@/server/services/file', () => ({FileService: vi.fn(function () {@@ -22,6 +27,89 @@ const { browserRuntime } = await import('../browser');describe('browserRuntime', () => {beforeEach(() => {vi.clearAllMocks();+ mockQueryDeviceList.mockResolvedValue([]);+ });++ describe('device client kind', () => {+ const context = {+ activeDeviceId: 'vm-cli',+ agentId: 'agt-1',+ operationId: 'op-1',+ serverDB: {} as any,+ toolManifestMap: {},+ topicId: 'tpc-1',+ userId: 'user-1',+ } as ToolExecutionContext;++ // Only the desktop app hosts the browser panel. `lh connect` answers every+ // browser api with `Unknown tool API: navigate`, which left agents retrying+ // blind after activating a CLI-only device (agent vent reports).+ it('does not dispatch to a device whose only live connection is the CLI', async () => {+ mockQueryDeviceList.mockResolvedValue([+ {+ channels: [{ channel: 'cli', connectedAt: 1, connectionId: 'c1' }],+ deviceId: 'vm-cli',+ hostname: 'VM-6-135-ubuntu',+ platform: 'linux',+ },+ ]);++ const runtime = browserRuntime.factory(context);+ const result = await runtime.navigate({ url: 'https://example.com' });++ expect(mockExecuteToolCall).not.toHaveBeenCalled();+ expect(result.success).toBe(false);+ expect(result.error.code).toBe('BROWSER_DEVICE_UNSUPPORTED');+ expect(result.content).toContain('lh connect');+ // lobe-web-browsing is not in this run's tool set, so it must not be offered.+ expect(result.content).not.toContain('lobe-web-browsing');+ });++ it('points at lobe-web-browsing only when the run can call it', async () => {+ mockQueryDeviceList.mockResolvedValue([+ { channels: [{ channel: 'cli', connectedAt: 1, connectionId: 'c1' }], deviceId: 'vm-cli' },+ ]);++ const runtime = browserRuntime.factory({+ ...context,+ toolManifestMap: { 'lobe-web-browsing': {} as any },+ });+ const result = await runtime.navigate({ url: 'https://example.com' });++ expect(result.error.code).toBe('BROWSER_DEVICE_UNSUPPORTED');+ expect(result.content).toContain('use lobe-web-browsing (search / crawl) instead');+ });++ it('dispatches when the device also has a desktop connection', async () => {+ mockQueryDeviceList.mockResolvedValue([+ {+ channels: [+ { channel: 'cli', connectedAt: 1, connectionId: 'c1' },+ { channel: 'desktop', connectedAt: 2, connectionId: 'd1' },+ ],+ deviceId: 'vm-cli',+ hostname: 'mac',+ platform: 'darwin',+ },+ ]);+ mockExecuteToolCall.mockResolvedValue({ content: 'ok', success: true });++ const runtime = browserRuntime.factory(context);+ const result = await runtime.navigate({ url: 'https://example.com' });++ expect(mockExecuteToolCall).toHaveBeenCalledTimes(1);+ expect(result.success).toBe(true);+ });++ it('keeps dispatching when the device presence is unknown', async () => {+ mockQueryDeviceList.mockRejectedValue(new Error('gateway down'));+ mockExecuteToolCall.mockResolvedValue({ content: 'ok', success: true });++ const runtime = browserRuntime.factory(context);+ await runtime.navigate({ url: 'https://example.com' });++ expect(mockExecuteToolCall).toHaveBeenCalledTimes(1);+ });});describe('screenshot', () => {diff --git a/apps/server/src/services/toolExecution/serverRuntimes/browser.ts b/apps/server/src/services/toolExecution/serverRuntimes/browser.tsindex 2b0dc5520b7..b870f752e7d 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/browser.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/browser.ts@@ -1,7 +1,9 @@import { BrowserIdentifier, BrowserManifest } from '@lobechat/builtin-tool-browser';+import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';import debug from 'debug';import { executeAuthorizedDeviceToolCall } from '@/server/services/deviceGateway/authorizedToolCall';+import { resolveDeviceClientKind } from '@/server/services/deviceGateway/deviceChannels';import { FileService } from '@/server/services/file';import { buildNoActiveDeviceResult, REMOTE_DEVICE_TOOL_IDENTIFIER } from './noActiveDevice';@@ -102,6 +104,30 @@ const storeScreenshot = async (}};+export const BROWSER_DEVICE_UNSUPPORTED_ERROR_CODE = 'BROWSER_DEVICE_UNSUPPORTED';++const buildCliOnlyDeviceBrowserResult = (+ deviceId: string,+ { webBrowsingAvailable }: { webBrowsingAvailable: boolean },+) => {+ // Only point at lobe-web-browsing when this run can actually call it β+ // custom / exclusive-tool / share runs may enable the browser without it.+ const publicPageHint = webBrowsingAvailable+ ? `For public pages use ${WebBrowsingManifest.identifier} (search / crawl) instead. `+ : '';+ const message =+ `The active device (${deviceId}) is connected only through the \`lh connect\` CLI, ` ++ `which has no built-in browser, so lobe-browser cannot run there. ` ++ publicPageHint ++ `If a signed-in browser session is required, ask the user to open the LobeHub desktop app ` ++ `on a machine and activate that device, then retry.`;+ return {+ content: message,+ error: { code: BROWSER_DEVICE_UNSUPPORTED_ERROR_CODE, message },+ success: false,+ };+};+export const browserRuntime: ServerRuntimeRegistration = {factory: (context) => {if (!context.userId) {@@ -137,10 +163,26 @@ export const browserRuntime: ServerRuntimeRegistration = {let workspaceIdPromise: Promise<string | undefined> | undefined;const getDeviceWorkspaceId = () => (workspaceIdPromise ??= resolveRunWorkspaceId(context));+ // Only the desktop app hosts the browser panel. A device whose only live+ // connection is `lh connect` answers every browser api with+ // `Unknown tool API: <api>`, which tells the model nothing β check the+ // client kind once per runtime and explain the dead end instead.+ let clientKindPromise: Promise<string> | undefined;+ const getClientKind = async () =>+ (clientKindPromise ??= getDeviceWorkspaceId().then((workspaceId) =>+ resolveDeviceClientKind(context.userId!, context.activeDeviceId!, workspaceId),+ ));+const proxy: Record<string, (args: any) => Promise<any>> = {};for (const api of BrowserManifest.api) {proxy[api.name] = async (args: any) => {+ if ((await getClientKind()) === 'cli-only') {+ return buildCliOnlyDeviceBrowserResult(context.activeDeviceId!, {+ webBrowsingAvailable: WebBrowsingManifest.identifier in (context.toolManifestMap ?? {}),+ });+ }+// Carry the run identity so the device resolves the right browser// session (`topic:<topicId>`); the agentId rides along so the device can// decide whether revealing the panel would yank the user's view. Both