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(device): route desktop-only device calls to the desktop client (#20575)

Neko5beeac403356
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index 7875f92336a..76684a4a8cf 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -108,6 +108,8 @@ drive / probe / capture / publish. Skip a row only when its surface AND runtime
| P89 | web | any | probe | A layout before/after on one live page: swap only the changed files and let HMR settle; `getComputedStyle().bottom` is a used value, read `el.style.bottom` |
| P82 | web | any | drive | Acceptance flow canvas through the production debug proxy: anonymous shared link, one uninterrupted script, canvas controls for clipped groups |
| P86 | electron, cli | any | env, auth | A session spawned by the desktop hetero runtime inherits `LOBEHUB_JWT` (production) and `ELECTRON_RUN_AS_NODE=1` β€” strip both before local Electron/CLI work |
+| P90 | any | gateway | env, fixture | Closed loop through a local device-gateway with desktop + `lh connect` on ONE device: gateway worktree + `.dev.vars`, `--device-id`, Responses stub |
+| P91 | any | any | env, probe | A server-side before/after needs a dev-server restart after the file swap; never install `apps/desktop` / `apps/cli` deps while the server runs |
## Choose the least invasive mechanism
@@ -2696,3 +2698,78 @@ matches nothing and the overlay reads as absent. Match on the inline style
For "does A cover B", assert the rectangles rather than eyeballing the capture:
`!(a.bottom <= b.top || b.bottom <= a.top)`. A banner whose top sliver is still
visible looks fine in a thumbnail and is still broken.
+
+#### P90 Β· A local device-gateway closed loop, with the desktop app and `lh connect` on one device
+
+**applies-to:** surface=any Β· runtime=gateway Β· phase=env, fixture
+
+**Situation:** verifying anything the server sends to a device through the device
+gateway β€” tool calls, system info, RPC, message API β€” including how the gateway
+picks a connection when one device holds several clients (`desktop` + `cli`).
+
+**Doesn't work:**
+
+- The production gateway: it verifies the device JWT against the production JWKS and
+ needs the production service token.
+- `local-device-gateway-setup.sh` from a worktree: it writes `.dev.vars` into the
+ sibling `../device-gateway`, which does not exist next to `lobehub-worktrees/`.
+- A plain `lh connect` beside the dev desktop: the CLI derives its `deviceId` from the
+ machine id, the dev Electron instance does not, so they show up as two devices.
+- Web without the local agent-gateway: a normal agent then runs in the client runtime,
+ and nothing reaches the server-side device runtimes (P03 β€” no `agent_operations` row).
+- The dev Electron golden profile: it is `storageMode: cloud`, and its first launch
+ auto-opens a cloud OIDC page in the default browser β€” approving it signs the instance
+ into the production account.
+
+**Works:**
+
+1. **Gateways.** Run the device-gateway from its own worktree with
+ `wrangler dev --port <p>`, and the agent-gateway the same way (references/agent-gateway.md).
+ Write each `.dev.vars` by hand: `JWKS_PUBLIC_KEY` is the run's
+ `.records/env/agent-testing-jwks.json` with `d,p,q,dp,dq,qi` stripped, and
+ `SERVICE_TOKEN` is a fresh token. device-gateway does not ignore `.dev.vars`, so add
+ it to `info/exclude` before anything is committed.
+2. **Server env.** Export `DEVICE_GATEWAY_URL` / `DEVICE_GATEWAY_SERVICE_TOKEN` and
+ `AGENT_GATEWAY_URL` / `AGENT_GATEWAY_SERVICE_TOKEN` / `ENABLE_AGENT_GATEWAY=1` before
+ `init-dev-env.sh dev`.
+3. **Desktop.** Start `electron-dev.sh start <id>` with `DEVICE_GATEWAY_URL` set, and with
+ `LOBE_LOGIN_STATE_DIR` / `LOBE_GOLDEN_PROFILE` pointed at empty directories. The user
+ signs in once through the self-host option (`http://localhost:3010`, the seeded
+ account) and closes any lobehub.com page that opens. Confirm
+ `lobehub-settings.json` reads `selfHost` before trusting the instance.
+4. **CLI on the same device.** From `apps/cli`, with the seeded CLI env
+ (`.records/env/agent-testing-cli.env`), run
+ `bun src/index.ts connect --gateway http://localhost:<p> --device-id <desktop deviceId>`.
+ Check `POST /api/device/devices` lists both channels (`cli`, `desktop-dev`).
+5. **Drive.** Bind an agent to the device (`agencyConfig.executionTarget: device`,
+ `boundDeviceId`), set `tool.humanIntervention.approvalMode` to `auto-run`, and point
+ openai at a Responses-API stub that emits `lobe-activator____activateTools` and then
+ the tool under test (P41 explains the SSE shape). The `lh connect -v` log
+ (`Received system_info_request`, `[TOOL]`) shows which connection served each call.
+
+`holds-while: devices pick a channel label per client (desktop / desktop-dev / cli); lh connect accepts --device-id; the gateway authenticates the device JWT with JWKS_PUBLIC_KEY.`
+
+#### P91 Β· A server-side before/after by file swap needs a dev-server restart
+
+**applies-to:** surface=any Β· runtime=any Β· phase=env, probe
+
+**Situation:** proving a server change against canary on the same running stack by
+swapping the changed files (`git show origin/canary:<file> > <file>`).
+
+**Doesn't work:**
+
+- Relying on HMR after the swap. Server modules reload per request chain, so one turn
+ can run the old version of one module and the new version of another. Observed: an
+ op-start system-info read still carried the fix's `clientKinds` while the swapped-back
+ `auv.ts` did not, which produced a half-fixed run that proves nothing.
+- Installing `apps/desktop` or `apps/cli` deps while the dev server runs. Every
+ `/trpc/lambda/*` request then fails 500 with `module factory is not available`
+ (es-toolkit via `packages/utils/src/merge.ts`), and the OIDC sign-in page shows
+ `HTTP ERROR 500`.
+
+**Works:** install every standalone app first, then start the server. For each side of an
+A/B, swap the files with a bash loop (zsh does not word-split `$FILES`), restart with
+`init-dev-env.sh stop-dev` and then `dev`, wait for `config.getGlobalConfig` to return
+200, and only then drive the case. Restore from a backup and check it with `cmp`.
+
+`holds-while: init-dev-env.sh dev runs next dev with Turbopack; apps/desktop and apps/cli keep standalone node_modules.`
diff --git a/apps/server/src/services/deviceGateway/__tests__/clientKinds.test.ts b/apps/server/src/services/deviceGateway/__tests__/clientKinds.test.ts
new file mode 100644
index 00000000000..3e76b33e664
--- /dev/null
+++ b/apps/server/src/services/deviceGateway/__tests__/clientKinds.test.ts
@@ -0,0 +1,47 @@
+import { AuvIdentifier } from '@lobechat/builtin-tool-auv';
+import { BrowserIdentifier } from '@lobechat/builtin-tool-browser';
+import { LocalSystemIdentifier } from '@lobechat/builtin-tool-local-system';
+import { describe, expect, it } from 'vitest';
+
+import { resolveDeviceClientKinds } from '../clientKinds';
+
+describe('resolveDeviceClientKinds', () => {
+ it('keeps desktop-only builtin tools off `lh connect`', () => {
+ expect(
+ resolveDeviceClientKinds({ identifier: AuvIdentifier, kind: 'tool', type: 'tool' }),
+ ).toEqual(['desktop']);
+ expect(
+ resolveDeviceClientKinds({ identifier: BrowserIdentifier, kind: 'tool', type: 'tool' }),
+ ).toEqual(['desktop']);
+ });
+
+ it('lets any client run tools both clients implement', () => {
+ expect(
+ resolveDeviceClientKinds({ identifier: LocalSystemIdentifier, kind: 'tool', type: 'tool' }),
+ ).toBeUndefined();
+ expect(
+ resolveDeviceClientKinds({ identifier: 'local', kind: 'tool', type: 'tool' }),
+ ).toBeUndefined();
+ });
+
+ it('routes MCP calls and the message API to the desktop app', () => {
+ expect(
+ resolveDeviceClientKinds({ identifier: 'some-mcp-server', kind: 'tool', type: 'mcp' }),
+ ).toEqual(['desktop']);
+ expect(resolveDeviceClientKinds({ kind: 'messageApi', platform: 'imessage' })).toEqual([
+ 'desktop',
+ ]);
+ });
+
+ it('reads RPC support from device-control', () => {
+ expect(resolveDeviceClientKinds({ kind: 'rpc', method: 'trashLocalFiles' })).toEqual([
+ 'desktop',
+ ]);
+ expect(resolveDeviceClientKinds({ kind: 'rpc', method: 'installAppUpdate' })).toEqual([
+ 'desktop',
+ ]);
+ for (const method of ['getCliUpdateState', 'checkCliUpdate', 'restartCli'])
+ expect(resolveDeviceClientKinds({ kind: 'rpc', method })).toEqual(['cli']);
+ expect(resolveDeviceClientKinds({ kind: 'rpc', method: 'getGitBranch' })).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/deviceGateway/__tests__/index.test.ts b/apps/server/src/services/deviceGateway/__tests__/index.test.ts
index 119e18d073b..c2a43832276 100644
--- a/apps/server/src/services/deviceGateway/__tests__/index.test.ts
+++ b/apps/server/src/services/deviceGateway/__tests__/index.test.ts
@@ -2,6 +2,7 @@ import type * as DeviceGatewayClientModule from '@lobechat/device-gateway-client
import { describe, expect, it, vi } from 'vitest';
// Import after mocks are set up
+import { resolveDeviceClientKinds } from '../clientKinds';
import { DeviceGateway } from '../index';
const mockEnv = vi.hoisted(() => ({
@@ -416,7 +417,9 @@ describe('DeviceGateway', () => {
const result = await proxy.queryDeviceSystemInfo('user-1', 'dev-1');
expect(result).toEqual(systemInfo);
- expect(mockClient.getDeviceSystemInfo).toHaveBeenCalledWith('user-1', 'dev-1', undefined);
+ expect(mockClient.getDeviceSystemInfo).toHaveBeenCalledWith('user-1', 'dev-1', undefined, {
+ clientKinds: ['desktop'],
+ });
});
it('should return undefined when result is not successful', async () => {
@@ -442,6 +445,82 @@ describe('DeviceGateway', () => {
});
});
+ describe('queryDeviceSystemInfo client preference', () => {
+ const configure = () => {
+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
+ };
+
+ it('falls back to any client when the device has no desktop app', async () => {
+ configure();
+ const systemInfo = { arch: 'arm64', userDataPath: '/home/u/.lobehub' };
+ mockClient.getDeviceSystemInfo
+ .mockResolvedValueOnce({ error: 'NO_CAPABLE_CONNECTION', success: false })
+ .mockResolvedValueOnce({ success: true, systemInfo });
+
+ const result = await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1', 'ws-1');
+
+ expect(result).toEqual(systemInfo);
+ expect(mockClient.getDeviceSystemInfo).toHaveBeenNthCalledWith(1, 'user-1', 'dev-1', 'ws-1', {
+ clientKinds: ['desktop'],
+ });
+ expect(mockClient.getDeviceSystemInfo).toHaveBeenNthCalledWith(
+ 2,
+ 'user-1',
+ 'dev-1',
+ 'ws-1',
+ undefined,
+ );
+ });
+
+ it.each(['TIMEOUT', 'DEVICE_OFFLINE'])(
+ 'asks any client when the desktop read fails with %s',
+ async (error) => {
+ configure();
+ const systemInfo = { arch: 'arm64', userDataPath: '/home/u/.lobehub' };
+ mockClient.getDeviceSystemInfo
+ .mockResolvedValueOnce({ error, success: false })
+ .mockResolvedValueOnce({ success: true, systemInfo });
+
+ const result = await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1');
+
+ expect(result).toEqual(systemInfo);
+ expect(mockClient.getDeviceSystemInfo).toHaveBeenNthCalledWith(
+ 2,
+ 'user-1',
+ 'dev-1',
+ undefined,
+ undefined,
+ );
+ },
+ );
+
+ it('asks any client when the desktop read throws', async () => {
+ configure();
+ const systemInfo = { arch: 'arm64' };
+ mockClient.getDeviceSystemInfo
+ .mockRejectedValueOnce(new Error('fetch failed'))
+ .mockResolvedValueOnce({ success: true, systemInfo });
+
+ const result = await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1');
+
+ expect(result).toEqual(systemInfo);
+ });
+
+ it('returns undefined when neither read is answered', async () => {
+ configure();
+ mockClient.getDeviceSystemInfo.mockResolvedValue({
+ error: 'DEVICE_NOT_FOUND',
+ success: false,
+ });
+
+ const result = await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1');
+
+ expect(result).toBeUndefined();
+ expect(mockClient.getDeviceSystemInfo).toHaveBeenCalledTimes(2);
+ });
+ });
+
describe('readDeviceSystemInfo', () => {
const configure = () => {
mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
@@ -461,7 +540,12 @@ describe('DeviceGateway', () => {
const result = await new DeviceGateway().readDeviceSystemInfo('user-1', 'dev-1', 'ws-1');
expect(result).toEqual({ ok: true, systemInfo });
- expect(mockClient.getDeviceSystemInfo).toHaveBeenCalledWith('user-1', 'dev-1', 'ws-1');
+ expect(mockClient.getDeviceSystemInfo).toHaveBeenCalledWith(
+ 'user-1',
+ 'dev-1',
+ 'ws-1',
+ undefined,
+ );
});
it("keeps the gateway's reason for an unanswered read", async () => {
@@ -1645,6 +1729,7 @@ describe('DeviceGateway', () => {
expect(MockGatewayHttpClient).toHaveBeenCalledTimes(1);
expect(MockGatewayHttpClient).toHaveBeenCalledWith({
gatewayUrl: 'https://gateway.example.com',
+ resolveClientKinds: resolveDeviceClientKinds,
serviceToken: 'token',
});
});
diff --git a/apps/server/src/services/deviceGateway/clientKinds.ts b/apps/server/src/services/deviceGateway/clientKinds.ts
new file mode 100644
index 00000000000..6b847034a24
--- /dev/null
+++ b/apps/server/src/services/deviceGateway/clientKinds.ts
@@ -0,0 +1,35 @@
+import { deviceRpcClients } from '@lobechat/device-control/rpc-clients';
+import type { GatewayDispatchTarget } from '@lobechat/device-gateway-client';
+import { deviceToolClients } from '@lobechat/mecha';
+import type { DeviceClient } from '@lobechat/types';
+
+const DESKTOP_ONLY: DeviceClient[] = ['desktop'];
+
+/**
+ * Which device clients can serve a gateway request, read from where each
+ * capability is declared rather than listed here:
+ *
+ * - builtin device tools β†’ the manifest's `deviceClients`
+ * - MCP calls β†’ desktop only (`lh connect` has no MCP client and would
+ * dispatch the call by `apiName` to a same-named local tool)
+ * - message API β†’ desktop only (only the desktop app implements a messenger)
+ * - RPC β†’ `deviceRpcClients` in `@lobechat/device-control`
+ *
+ * Sent to the gateway as `clientKinds` so a device holding both the desktop
+ * app and `lh connect` routes each call to a client that can run it.
+ */
+export const resolveDeviceClientKinds = (
+ target: GatewayDispatchTarget,
+): DeviceClient[] | undefined => {
+ switch (target.kind) {
+ case 'tool': {
+ return target.type === 'mcp' ? DESKTOP_ONLY : deviceToolClients(target.identifier);
+ }
+ case 'messageApi': {
+ return DESKTOP_ONLY;
+ }
+ case 'rpc': {
+ return deviceRpcClients(target.method);
+ }
+ }
+};
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index b62d34602d1..f83e7fd82bf 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -19,6 +19,7 @@ import type {
DeviceAppUpdateInstallResult,
DeviceAppUpdateState,
DeviceAppUpdateStateResult,
+ DeviceClient,
DeviceCliRestartParams,
DeviceCliUpdateState,
DeviceCliUpdateStateResult,
@@ -75,6 +76,8 @@ import { isAbsolute, relative, resolve } from 'pathe';
import { gatewayEnv } from '@/envs/gateway';
+import { resolveDeviceClientKinds } from './clientKinds';
+
const log = debug('lobe-server:device-gateway');
/**
@@ -266,13 +269,29 @@ export class DeviceGateway {
);
}
+ /**
+ * The device's system info, preferring the desktop app's answer: its
+ * `supportedTools` gate desktop-only tools, and when `lh connect` is up on the
+ * same device an unconstrained read is answered by the CLI, which reports
+ * none. When the desktop read fails for any reason, ask whichever client the
+ * device has: a device without the desktop app answers `NO_CAPABLE_CONNECTION`,
+ * and a desktop that timed out or whose socket is closing (`TIMEOUT`,
+ * `DEVICE_OFFLINE`) may still sit beside a live `lh connect`, which is the
+ * answer canary got. A gateway that predates `clientKinds` answers the first
+ * read as before.
+ */
async queryDeviceSystemInfo(
userId: string,
deviceId: string,
workspaceId?: string,
): Promise<DeviceSystemInfo | undefined> {
- const read = await this.readDeviceSystemInfo(userId, deviceId, workspaceId);
- return read.ok ? read.systemInfo : undefined;
+ const desktop = await this.readDeviceSystemInfo(userId, deviceId, workspaceId, {
+ clientKinds: ['desktop'],
+ });
+ if (desktop.ok) return desktop.systemInfo;
+
+ const any = await this.readDeviceSystemInfo(userId, deviceId, workspaceId);
+ return any.ok ? any.systemInfo : undefined;
}
/**
@@ -284,12 +303,13 @@ export class DeviceGateway {
userId: string,
deviceId: string,
workspaceId?: string,
+ options?: { clientKinds?: DeviceClient[] },
): Promise<DeviceSystemInfoRead> {
const client = this.getClient();
if (!client) return { ok: false, reason: 'GATEWAY_NOT_CONFIGURED' };
try {
- const result = await client.getDeviceSystemInfo(userId, deviceId, workspaceId);
+ const result = await client.getDeviceSystemInfo(userId, deviceId, workspaceId, options);
if (result.success && result.systemInfo) return { ok: true, systemInfo: result.systemInfo };
log(
'readDeviceSystemInfo: unanswered for userId=%s, deviceId=%s: %s',
@@ -2279,7 +2299,11 @@ export class DeviceGateway {
if (!url || !token) return null;
if (!this.client) {
- this.client = new GatewayHttpClient({ gatewayUrl: url, serviceToken: token });
+ this.client = new GatewayHttpClient({
+ gatewayUrl: url,
+ resolveClientKinds: resolveDeviceClientKinds,
+ serviceToken: token,
+ });
}
return this.client;
}
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.ts
index 27a8b5b2353..9fb894d9355 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.ts
@@ -96,6 +96,15 @@ describe('auvRuntime', () => {
expect(resolveDeviceClientKindMock).not.toHaveBeenCalled();
});
+ it('reads the capability from the desktop client, not a cli on the same device', async () => {
+ const runtime = auvRuntime.factory(baseContext);
+ await runtime.runCommand({ argv: ['invoke', 'display.list'] });
+
+ expect(readDeviceSystemInfoMock).toHaveBeenCalledWith('user-1', 'device-1', undefined, {
+ clientKinds: ['desktop'],
+ });
+ });
+
describe('when the device does not answer the capability check', () => {
it('dispatches to a device with a live desktop app instead of reporting it unsupported', async () => {
// Production: a busy desktop missed the 10s system-info deadline and the
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/auv.ts b/apps/server/src/services/toolExecution/serverRuntimes/auv.ts
index fc712423a60..d9f91bc0144 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/auv.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/auv.ts
@@ -1,4 +1,4 @@
-import { AuvApiName, AuvIdentifier } from '@lobechat/builtin-tool-auv';
+import { AuvApiName, AuvIdentifier, AuvManifest } from '@lobechat/builtin-tool-auv';
import { deviceGateway } from '@/server/services/deviceGateway';
import { executeAuthorizedDeviceToolCall } from '@/server/services/deviceGateway/authorizedToolCall';
@@ -75,10 +75,14 @@ export const auvRuntime: ServerRuntimeRegistration = {
*/
runCommand: async (args: unknown) => {
const workspaceId = await getDeviceWorkspaceId();
+ // Ask the client that would run the call: with `lh connect` up beside the
+ // desktop app, an unconstrained read is answered by the CLI, which reports
+ // no `supportedTools`. A gateway that predates `clientKinds` ignores it.
const read = await deviceGateway.readDeviceSystemInfo(
context.userId!,
context.activeDeviceId!,
workspaceId,
+ { clientKinds: AuvManifest.deviceClients },
);
if (read.ok) {
// An answer without the capability is an old client (or `lh connect`):
diff --git a/package.json b/package.json
index b6c90e11eba..953444ce067 100644
--- a/package.json
+++ b/package.json
@@ -292,6 +292,7 @@
"@lobechat/conversation-flow": "workspace:*",
"@lobechat/database": "workspace:*",
"@lobechat/desktop-bridge": "workspace:*",
+ "@lobechat/device-control": "workspace:*",
"@lobechat/device-gateway-client": "workspace:*",
"@lobechat/edge-config": "workspace:*",
"@lobechat/editor-runtime": "workspace:*",
diff --git a/packages/builtin-tool-auv/src/manifest.ts b/packages/builtin-tool-auv/src/manifest.ts
index 62949822ca5..fe7467b40ba 100644
--- a/packages/builtin-tool-auv/src/manifest.ts
+++ b/packages/builtin-tool-auv/src/manifest.ts
@@ -4,6 +4,8 @@ import { systemPrompt } from './systemRole';
import { AuvApiName, AuvIdentifier } from './types';
export const AuvManifest: BuiltinToolManifest = {
+ // Only the desktop app runs auv; `lh connect` would treat runCommand as a shell call.
+ deviceClients: ['desktop'],
executors: ['client', 'server'],
api: [
{
diff --git a/packages/builtin-tool-browser/src/manifest.ts b/packages/builtin-tool-browser/src/manifest.ts
index 7c86821cef8..343ccbe450f 100644
--- a/packages/builtin-tool-browser/src/manifest.ts
+++ b/packages/builtin-tool-browser/src/manifest.ts
@@ -127,6 +127,8 @@ export const BrowserManifest: BuiltinToolManifest = {
],
// `client`: runs in the desktop renderer (local runtime). `server`: cloud
// agent runs proxy each call back to the bound device via deviceGateway.
+ // The browser panel lives in the desktop app; `lh connect` has none.
+ deviceClients: ['desktop'],
executors: ['client', 'server'],
identifier: BrowserIdentifier,
meta: {
diff --git a/packages/device-control/package.json b/packages/device-control/package.json
index cd2dac5e189..b1645aa442f 100644
--- a/packages/device-control/package.json
+++ b/packages/device-control/package.json
@@ -8,6 +8,7 @@
"./file-preview": "./src/filePreview.ts",
"./metrics": "./src/metrics/index.ts",
"./project-file-index": "./src/projectFileIndex.ts",
+ "./rpc-clients": "./src/rpcClients.ts",
"./skill-directory": "./src/skillDirectory.ts",
"./workspace": "./src/workspace.ts"
},
diff --git a/packages/device-control/src/__tests__/dispatch.test.ts b/packages/device-control/src/__tests__/dispatch.test.ts
index 76e8b63ca2e..f41b091f5ae 100644
--- a/packages/device-control/src/__tests__/dispatch.test.ts
+++ b/packages/device-control/src/__tests__/dispatch.test.ts
@@ -8,6 +8,7 @@ import {
APP_UPDATE_UNSUPPORTED_MESSAGE,
CLI_UPDATE_UNSUPPORTED_MESSAGE,
DEVICE_RPC_METHODS,
+ deviceRpcClients,
executeDeviceRpc,
TERMINAL_UNSUPPORTED_MESSAGE,
TRASH_UNSUPPORTED_MESSAGE,
@@ -689,3 +690,29 @@ describe('executeDeviceRpc', () => {
});
});
});
+
+describe('deviceRpcClients', () => {
+ const desktopOnly = [
+ 'trashLocalFiles',
+ 'getAppUpdateState',
+ 'checkAppUpdate',
+ 'installAppUpdate',
+ ];
+ const cliOnly = ['getCliUpdateState', 'checkCliUpdate', 'restartCli'];
+
+ it.each(desktopOnly)('routes %s, which the CLI rejects, to the desktop', (method) => {
+ expect(deviceRpcClients(method)).toEqual(['desktop']);
+ });
+
+ it.each(cliOnly)('routes %s, which the desktop rejects, to the CLI', (method) => {
+ expect(deviceRpcClients(method)).toEqual(['cli']);
+ });
+
+ it('lets any client serve the other methods', () => {
+ const shared = DEVICE_RPC_METHODS.filter(
+ (method) => !desktopOnly.includes(method) && !cliOnly.includes(method),
+ );
+ for (const method of shared) expect(deviceRpcClients(method)).toBeUndefined();
+ expect(deviceRpcClients('unknownMethod')).toBeUndefined();
+ });
+});
diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.ts
index 12f974e532c..7b76a484a3d 100644
--- a/packages/device-control/src/dispatch.ts
+++ b/packages/device-control/src/dispatch.ts
@@ -141,6 +141,8 @@ export const DEVICE_RPC_METHODS = [
export type DeviceRpcMethod = (typeof DEVICE_RPC_METHODS)[number];
+export { deviceRpcClients } from './rpcClients';
+
/** Why a client without the app-update handlers rejects those RPCs. */
export const APP_UPDATE_UNSUPPORTED_MESSAGE = 'This device client does not support remote updates';
diff --git a/packages/device-control/src/index.ts b/packages/device-control/src/index.ts
index 052701f81e2..a704fe068d9 100644
--- a/packages/device-control/src/index.ts
+++ b/packages/device-control/src/index.ts
@@ -3,6 +3,7 @@ export {
APP_UPDATE_UNSUPPORTED_MESSAGE,
CLI_UPDATE_UNSUPPORTED_MESSAGE,
DEVICE_RPC_METHODS,
+ deviceRpcClients,
type DeviceRpcMethod,
executeDeviceRpc,
TERMINAL_UNSUPPORTED_MESSAGE,
diff --git a/packages/device-control/src/rpcClients.ts b/packages/device-control/src/rpcClients.ts
new file mode 100644
index 00000000000..7248339503e
--- /dev/null
+++ b/packages/device-control/src/rpcClients.ts
@@ -0,0 +1,38 @@
+import type { DeviceClient } from '@lobechat/types';
+
+import type { DeviceRpcMethod } from './dispatch';
+
+// Dependency-free on purpose: the server imports this through the
+// `@lobechat/device-control/rpc-clients` subpath. The package root pulls in
+// the local file shell and native agent runtimes, which would be traced into
+// every serverless function.
+
+/**
+ * RPC methods only the desktop app implements: the CLI daemon passes no
+ * handler for them (no recoverable trash, no self-update), so a call that lands
+ * on `lh connect` is rejected.
+ */
+const DESKTOP_ONLY_RPC_METHODS: ReadonlySet<string> = new Set<DeviceRpcMethod>([
+ 'trashLocalFiles',
+ 'getAppUpdateState',
+ 'checkAppUpdate',
+ 'installAppUpdate',
+]);
+
+/**
+ * RPC methods only the CLI daemon (`lh connect`) implements: the desktop app
+ * passes no CLI self-update or restart handler, so a call that lands on the
+ * desktop is rejected.
+ */
+const CLI_ONLY_RPC_METHODS: ReadonlySet<string> = new Set<DeviceRpcMethod>([
+ 'getCliUpdateState',
+ 'checkCliUpdate',
+ 'restartCli',
+]);
+
+/** Device clients that can serve `method`; `undefined` means any client. */
+export const deviceRpcClients = (method: string): DeviceClient[] | undefined => {
+ if (DESKTOP_ONLY_RPC_METHODS.has(method)) return ['desktop'];
+ if (CLI_ONLY_RPC_METHODS.has(method)) return ['cli'];
+ return undefined;
+};
diff --git a/packages/device-gateway-client/src/deviceTransportError.test.ts b/packages/device-gateway-client/src/deviceTransportError.test.ts
index 0d1bde105b9..9cbbc9dfef2 100644
--- a/packages/device-gateway-client/src/deviceTransportError.test.ts
+++ b/packages/device-gateway-client/src/deviceTransportError.test.ts
@@ -116,6 +116,35 @@ describe('describeGatewayResponseFailure', () => {
});
});
+describe('describeGatewayResponseFailure NO_CAPABLE_CONNECTION', () => {
+ it('says which client is needed instead of advising retries', () => {
+ const body = JSON.stringify({
+ channels: ['cli'],
+ clientKinds: ['desktop'],
+ error: 'NO_CAPABLE_CONNECTION',
+ success: false,
+ });
+
+ const failure = describeGatewayResponseFailure(503, body, 'tool call');
+
+ expect(failure.code).toBe(DeviceTransportErrorCode.NoCapableClient);
+ expect(failure.content).toContain('the LobeHub desktop app');
+ expect(failure.content).toContain('only cli is connected');
+ expect(failure.content).toContain('Nothing ran');
+ expect(failure.content).not.toContain('retry up to');
+ expect(failure.error).toBe(body);
+ });
+
+ it('keeps other 503 answers on the reconnect path', () => {
+ const failure = describeGatewayResponseFailure(
+ 503,
+ JSON.stringify({ error: 'DEVICE_OFFLINE', success: false }),
+ 'tool call',
+ );
+ expect(failure.code).toBe(DeviceTransportErrorCode.DeviceChannelUnavailable);
+ });
+});
+
describe('describeGatewayRequestFailure', () => {
it('treats a client-side abort like a 504 β€” the call may have landed', () => {
const failure = describeGatewayRequestFailure(
diff --git a/packages/device-gateway-client/src/deviceTransportError.ts b/packages/device-gateway-client/src/deviceTransportError.ts
index 6e233998b3e..109572d1885 100644
--- a/packages/device-gateway-client/src/deviceTransportError.ts
+++ b/packages/device-gateway-client/src/deviceTransportError.ts
@@ -29,6 +29,11 @@ export const DeviceTransportErrorCode = {
DeviceChannelUnavailable: 'DEVICE_CHANNEL_UNAVAILABLE',
/** The gateway has no record of the addressed device. */
DeviceNotFound: 'DEVICE_NOT_FOUND',
+ /**
+ * The device is online, but none of its connections belongs to a client that
+ * can serve the request (e.g. only `lh connect` while the desktop app is needed).
+ */
+ NoCapableClient: 'DEVICE_NO_CAPABLE_CLIENT',
/** Delivered to the device, but no answer before the deadline. */
DeviceResponseTimeout: 'DEVICE_RESPONSE_TIMEOUT',
/** The gateway itself failed (5xx that is not a routing failure). */
@@ -127,6 +132,49 @@ const describeStatus = (
}
};
+const CLIENT_LABEL: Record<string, string> = {
+ cli: 'the `lh connect` CLI',
+ desktop: 'the LobeHub desktop app',
+};
+
+const describeClients = (kinds: unknown[]) =>
+ kinds.map((kind) => CLIENT_LABEL[String(kind)] ?? `\`${String(kind)}\``).join(' or ');
+
+/**
+ * A 503 `NO_CAPABLE_CONNECTION` is not a connection drop: the device is online,
+ * but no connected client can run this request. Retrying cannot help until the
+ * right client connects, so it must not get the generic "retry up to 8 times".
+ */
+const describeNoCapableClient = (
+ status: number,
+ detail: string | undefined,
+ operation: DeviceTransportOperation,
+): DeviceTransportFailure | undefined => {
+ if (status !== 503 || !detail) return undefined;
+ let body: { channels?: unknown; clientKinds?: unknown; error?: unknown };
+ try {
+ body = JSON.parse(detail);
+ } catch {
+ return undefined;
+ }
+ if (body?.error !== 'NO_CAPABLE_CONNECTION') return undefined;
+
+ const needed = Array.isArray(body.clientKinds) ? describeClients(body.clientKinds) : '';
+ const connected = Array.isArray(body.channels)
+ ? body.channels.filter((channel): channel is string => typeof channel === 'string')
+ : [];
+ return {
+ code: DeviceTransportErrorCode.NoCapableClient,
+ content:
+ `The device is online, but none of its connected clients can run this ${operation}` +
+ (needed ? ` β€” it needs ${needed}` : '') +
+ (connected.length > 0 ? ` and only ${connected.join(', ')} is connected` : '') +
+ `. Nothing ran on the device, and retrying will not help until that client connects: ` +
+ `tell the user to open ${needed || 'the required client'} on that machine, then retry.`,
+ error: detail,
+ };
+};
+
/**
* Describe a non-ok gateway HTTP response.
*
@@ -150,8 +198,11 @@ export const describeGatewayResponseFailure = (
operation: DeviceTransportOperation,
target?: DeviceTransportTarget,
): DeviceTransportFailure => {
- const { code, content } = describeStatus(status, operation);
const detail = body?.trim();
+ const noCapableClient = describeNoCapableClient(status, detail, operation);
+ if (noCapableClient) return noCapableClient;
+
+ const { code, content } = describeStatus(status, operation);
const data =
code === DeviceTransportErrorCode.DeviceNotFound && target?.deviceId
? {
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index 7e3650de5ba..73899b7ffc5 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -795,6 +795,86 @@ describe('GatewayHttpClient', () => {
});
});
+ describe('clientKinds', () => {
+ const bodyOf = (call = 0) =>
+ JSON.parse(vi.mocked(fetch).mock.calls[call][1]!.body as string) as Record<string, unknown>;
+
+ const withResolver = () => {
+ const resolveClientKinds = vi.fn((target: { kind: string; method?: string }) =>
+ target.kind === 'rpc' && target.method === 'listSkills' ? [] : (['desktop'] as const),
+ );
+ const kindsClient = new GatewayHttpClient({
+ gatewayUrl: 'https://gateway.test.com',
+ resolveClientKinds: resolveClientKinds as never,
+ serviceToken: 'test-token',
+ });
+ return { kindsClient, resolveClientKinds };
+ };
+
+ it('sends the resolved clientKinds with a tool call, tagged by identifier and type', async () => {
+ const { kindsClient, resolveClientKinds } = withResolver();
+ mockFetch({ json: vi.fn().mockResolvedValue({ content: 'ok', success: true }), ok: true });
+
+ await kindsClient.executeToolCall(
+ { deviceId: 'device-1', userId: 'user-1' },
+ { apiName: 'runCommand', arguments: '{}', identifier: 'lobe-computer-use' },
+ );
+
+ expect(resolveClientKinds).toHaveBeenCalledWith({
+ identifier: 'lobe-computer-use',
+ kind: 'tool',
+ type: 'tool',
+ });
+ expect(bodyOf()).toMatchObject({ clientKinds: ['desktop'] });
+ });
+
+ it('resolves MCP calls, the message API and RPC by their own target', async () => {
+ const { kindsClient, resolveClientKinds } = withResolver();
+ mockFetch({ json: vi.fn().mockResolvedValue({ success: true }), ok: true });
+
+ await kindsClient.executeMcpCall({
+ apiName: 'search',
+ arguments: '{}',
+ identifier: 'mcp-server',
+ params: {} as never,
+ userId: 'user-1',
+ });
+ await kindsClient.executeMessageApi(
+ { userId: 'user-1' },
+ { apiName: 'sendMessage', payload: {}, platform: 'imessage' },
+ );
+ await kindsClient.invokeRpc({ userId: 'user-1' }, { method: 'trashLocalFiles' });
+
+ expect(resolveClientKinds.mock.calls.map(([target]) => target)).toEqual([
+ { identifier: 'mcp-server', kind: 'tool', type: 'mcp' },
+ { kind: 'messageApi', platform: 'imessage' },
+ { kind: 'rpc', method: 'trashLocalFiles' },
+ ]);
+ for (const call of [0, 1, 2]) expect(bodyOf(call).clientKinds).toEqual(['desktop']);
+ });
+
+ it('omits clientKinds when any client can serve the request', async () => {
+ const { kindsClient } = withResolver();
+ mockFetch({ json: vi.fn().mockResolvedValue({ success: true }), ok: true });
+
+ await kindsClient.invokeRpc({ userId: 'user-1' }, { method: 'listSkills' });
+ await client.invokeRpc({ userId: 'user-1' }, { method: 'trashLocalFiles' });
+
+ expect(bodyOf(0)).not.toHaveProperty('clientKinds');
+ expect(bodyOf(1)).not.toHaveProperty('clientKinds');
+ });
+
+ it('passes clientKinds given for a system-info read', async () => {
+ mockFetch({ json: vi.fn().mockResolvedValue({ success: true, systemInfo: {} }), ok: true });
+
+ await client.getDeviceSystemInfo('user-1', 'device-1', undefined, {
+ clientKinds: ['desktop'],
+ });
+
+ expect(bodyOf()).toMatchObject({ clientKinds: ['desktop'], deviceId: 'device-1' });
+ });
+ });
+
describe('getDeviceSystemInfo', () => {
it('should return system info on success', async () => {
const systemInfo = {
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index 0aa12fd9624..27e3f64a3bc 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -1,4 +1,4 @@
-import type { DeviceMetricSample } from '@lobechat/types';
+import type { DeviceClient, DeviceMetricSample } from '@lobechat/types';
import {
describeGatewayRequestFailure,
@@ -82,17 +82,32 @@ const toFailedToolCallResult = (failure: DeviceTransportFailure): DeviceToolCall
success: false,
});
+/** What a request asks a device to do, for choosing which client may serve it. */
+export type GatewayDispatchTarget =
+ | { identifier: string; kind: 'tool'; type: GatewayToolCallType }
+ | { kind: 'messageApi'; platform: string }
+ | { kind: 'rpc'; method: string };
+
export interface GatewayHttpClientOptions {
gatewayUrl: string;
+ /**
+ * Which device clients can serve a request, sent to the gateway as
+ * `clientKinds` so it skips connections of other clients (one device can
+ * hold the desktop app and `lh connect` at once). Return `undefined` when
+ * any client can. A gateway that predates `clientKinds` ignores it.
+ */
+ resolveClientKinds?: (target: GatewayDispatchTarget) => DeviceClient[] | undefined;
serviceToken: string;
}
export class GatewayHttpClient {
private gatewayUrl: string;
+ private resolveClientKinds?: GatewayHttpClientOptions['resolveClientKinds'];
private serviceToken: string;
constructor(options: GatewayHttpClientOptions) {
this.gatewayUrl = options.gatewayUrl;
+ this.resolveClientKinds = options.resolveClientKinds;
this.serviceToken = options.serviceToken;
}
@@ -192,6 +207,11 @@ export class GatewayHttpClient {
res = await this.post(
'/api/device/tool-call',
{
+ clientKinds: this.clientKindsFor({
+ identifier: toolCall.identifier,
+ kind: 'tool',
+ type: toolCall.type ?? 'tool',
+ }),
deviceId: params.deviceId,
operationId: params.operationId,
timeout: params.timeout,
@@ -256,6 +276,7 @@ export class GatewayHttpClient {
): Promise<DeviceMessageApiResult> {
const res = await this.post('/api/device/message-api', {
api,
+ clientKinds: this.clientKindsFor({ kind: 'messageApi', platform: api.platform }),
deviceId: params.deviceId,
timeout: params.timeout,
userId: params.userId,
@@ -361,6 +382,7 @@ export class GatewayHttpClient {
'/api/device/rpc',
{
channel: params.channel,
+ clientKinds: this.clientKindsFor({ kind: 'rpc', method: rpc.method }),
deviceId: params.deviceId,
method: rpc.method,
params: rpc.params,
@@ -385,14 +407,19 @@ export class GatewayHttpClient {
return { data: data.data, error: data.error, success: data.success ?? false };
}
+ /**
+ * `options.clientKinds` asks for the info of a connection of those clients β€”
+ * e.g. the desktop app's `supportedTools` when `lh connect` is up as well.
+ */
async getDeviceSystemInfo(
userId: string,
deviceId: string,
workspaceId?: string,
+ options?: { clientKinds?: DeviceClient[] },
): Promise<{ error?: string; success: boolean; systemInfo?: DeviceSystemInfo }> {
const res = await this.post(
'/api/device/system-info',
- { deviceId, userId, workspaceId },
+ { clientKinds: options?.clientKinds, deviceId, userId, workspaceId },
{ timeout: DEVICE_QUERY_TIMEOUT_MS },
);
if (!res.ok) {
@@ -493,6 +520,11 @@ export class GatewayHttpClient {
return true;
}
+ private clientKindsFor(target: GatewayDispatchTarget): DeviceClient[] | undefined {
+ const kinds = this.resolveClientKinds?.(target);
+ return kinds && kinds.length > 0 ? kinds : undefined;
+ }
+
private post(path: string, body: unknown, options?: { timeout?: number }): Promise<Response> {
return fetch(`${this.gatewayUrl}${path}`, {
body: JSON.stringify(body),
diff --git a/packages/device-gateway-client/src/index.ts b/packages/device-gateway-client/src/index.ts
index 070a349ddea..0b9ad17a0f0 100644
--- a/packages/device-gateway-client/src/index.ts
+++ b/packages/device-gateway-client/src/index.ts
@@ -15,6 +15,7 @@ export type {
DeviceRpcResult,
DeviceStatusResult,
DeviceToolCallResult,
+ GatewayDispatchTarget,
GatewayHttpClientOptions,
} from './http';
export { GatewayHttpClient } from './http';
diff --git a/packages/mecha/src/toolSet/deviceTools.ts b/packages/mecha/src/toolSet/deviceTools.ts
index 6848cd68622..70d50911be0 100644
--- a/packages/mecha/src/toolSet/deviceTools.ts
+++ b/packages/mecha/src/toolSet/deviceTools.ts
@@ -2,7 +2,7 @@ import { AuvManifest } from '@lobechat/builtin-tool-auv';
import { BrowserManifest } from '@lobechat/builtin-tool-browser';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
-import type { LobeBuiltinTool } from '@lobechat/types';
+import type { DeviceClient, LobeBuiltinTool } from '@lobechat/types';
/** Builtin tools that only exist for a run with a device (local machine or routed device). */
export const DEVICE_TOOL_MANIFESTS = [
@@ -24,6 +24,17 @@ export const REMOTE_DEVICE_TOOL_IDENTIFIERS: ReadonlySet<string> = new Set([
export const isDeviceToolIdentifier = (identifier: string): boolean =>
DEVICE_TOOL_IDENTIFIERS.has(identifier);
+const DEVICE_TOOL_CLIENTS: ReadonlyMap<string, DeviceClient[] | undefined> = new Map(
+ DEVICE_TOOL_MANIFESTS.map((m) => [m.identifier, m.deviceClients]),
+);
+
+/**
+ * Device clients that can run a device tool, from its manifest's
+ * `deviceClients`; `undefined` means any client (or not a device tool).
+ */
+export const deviceToolClients = (identifier: string): DeviceClient[] | undefined =>
+ DEVICE_TOOL_CLIENTS.get(identifier);
+
export interface DeviceToolWallParams {
/** The run's access policy allows a device at all (external bot senders do not). */
canUseDevice: boolean;
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index 397b44c5109..f910e561c03 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -253,9 +253,25 @@ export const LobeChatPluginApiSchema = z.object({
work: PluginApiWorkConfigSchema.optional(),
});
+/**
+ * A program that holds a device-gateway connection for a device: the LobeHub
+ * desktop app, or the `lh connect` CLI. One device can hold both at once.
+ */
+export type DeviceClient = 'cli' | 'desktop';
+
export interface BuiltinToolManifest {
api: LobeChatPluginApi[];
+ /**
+ * Device clients that can run this tool when it executes on a device. The
+ * gateway is told to skip connections of any other client β€” e.g. Computer
+ * Use and the browser panel live only in the desktop app, so a call must not
+ * land on `lh connect` running on the same machine.
+ *
+ * When omitted, any device client can run it.
+ */
+ deviceClients?: DeviceClient[];
+
/**
* Supported execution environments for this tool.
* - `'client'`: executed in-process by an embedded Electron runtime that
@@ -295,6 +311,7 @@ export interface BuiltinToolManifest {
export const BuiltinToolManifestSchema = z.object({
api: z.array(LobeChatPluginApiSchema),
+ deviceClients: z.array(z.enum(['cli', 'desktop'])).optional(),
executors: z.array(z.enum(['client', 'server'])).optional(),
humanIntervention: ExtendedHumanInterventionConfigSchema.optional(),
identifier: z.string(),