π€― 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 reporting a busy device as lacking Computer Use (#20540)
Nekod05af54aed7c
diff --git a/apps/server/src/services/deviceGateway/__tests__/deviceChannels.test.ts b/apps/server/src/services/deviceGateway/__tests__/deviceChannels.test.tsnew file mode 100644index 00000000000..27b6022a1e4--- /dev/null+++ b/apps/server/src/services/deviceGateway/__tests__/deviceChannels.test.ts@@ -0,0 +1,44 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const queryDeviceListMock = vi.fn();+vi.mock('../index', () => ({+ deviceGateway: {+ queryDeviceList: (...args: unknown[]) => queryDeviceListMock(...args),+ },+}));++const { resolveDeviceClientKind } = await import('../deviceChannels');++const withChannels = (...channels: string[]) => [+ { channels: channels.map((channel) => ({ channel })), deviceId: 'device-1' },+];++describe('resolveDeviceClientKind', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('reports a device whose only clients are the desktop app as desktop', async () => {+ queryDeviceListMock.mockResolvedValueOnce(withChannels('desktop', 'desktop-dev'));+ await expect(resolveDeviceClientKind('user-1', 'device-1')).resolves.toBe('desktop');+ });++ it('reports desktop plus `lh connect` as mixed, since the gateway prefers the CLI', async () => {+ queryDeviceListMock.mockResolvedValueOnce(withChannels('cli', 'desktop'));+ await expect(resolveDeviceClientKind('user-1', 'device-1', 'ws-1')).resolves.toBe('mixed');+ expect(queryDeviceListMock).toHaveBeenCalledWith('user-1', 'ws-1');+ });++ it('reports a device with only CLI channels as cli-only', async () => {+ queryDeviceListMock.mockResolvedValueOnce(withChannels('cli', 'cli-dev'));+ await expect(resolveDeviceClientKind('user-1', 'device-1')).resolves.toBe('cli-only');+ });++ it('reports unknown when the device is absent or the lookup fails', async () => {+ queryDeviceListMock.mockResolvedValueOnce([]);+ await expect(resolveDeviceClientKind('user-1', 'device-1')).resolves.toBe('unknown');++ queryDeviceListMock.mockRejectedValueOnce(new Error('gateway down'));+ await expect(resolveDeviceClientKind('user-1', 'device-1')).resolves.toBe('unknown');+ });+});diff --git a/apps/server/src/services/deviceGateway/__tests__/index.test.ts b/apps/server/src/services/deviceGateway/__tests__/index.test.tsindex 765089aa20a..89cc2e0d06a 100644--- a/apps/server/src/services/deviceGateway/__tests__/index.test.ts+++ b/apps/server/src/services/deviceGateway/__tests__/index.test.ts@@ -365,6 +365,49 @@ describe('DeviceGateway', () => {});});+ describe('readDeviceSystemInfo', () => {+ const configure = () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ };++ it('reports an unconfigured gateway', async () => {+ const result = await new DeviceGateway().readDeviceSystemInfo('user-1', 'dev-1');+ expect(result).toEqual({ ok: false, reason: 'GATEWAY_NOT_CONFIGURED' });+ });++ it('returns systemInfo on success', async () => {+ configure();+ const systemInfo = { arch: 'arm64', supportedTools: ['lobe-computer-use'] };+ mockClient.getDeviceSystemInfo.mockResolvedValue({ success: true, systemInfo });++ 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');+ });++ it("keeps the gateway's reason for an unanswered read", async () => {+ configure();+ mockClient.getDeviceSystemInfo.mockResolvedValue({ error: 'TIMEOUT', success: false });++ const result = await new DeviceGateway().readDeviceSystemInfo('user-1', 'dev-1');++ expect(result).toEqual({ ok: false, reason: 'TIMEOUT' });+ });++ it('classifies a client-side timeout', async () => {+ configure();+ mockClient.getDeviceSystemInfo.mockRejectedValue(+ Object.assign(new Error('The operation timed out.'), { name: 'TimeoutError' }),+ );++ const result = await new DeviceGateway().readDeviceSystemInfo('user-1', 'dev-1');++ expect(result).toEqual({ ok: false, reason: 'DEVICE_RESPONSE_TIMEOUT' });+ });+ });+describe('queryDeviceMetrics', () => {const params = { deviceId: 'dev-1', since: 1000, userId: 'user-1', workspaceId: 'ws-1' };const configure = () => {diff --git a/apps/server/src/services/deviceGateway/deviceChannels.ts b/apps/server/src/services/deviceGateway/deviceChannels.tsindex 2455b3dd617..a4a8911454a 100644--- a/apps/server/src/services/deviceGateway/deviceChannels.ts+++ b/apps/server/src/services/deviceGateway/deviceChannels.ts@@ -8,13 +8,16 @@ 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, β¦)+ * - `desktop` β only the LobeHub desktop app is connected (browser panel, MCP tunnel, β¦)+ * - `mixed` β the desktop app and `lh connect` are both connected. The gateway+ * prefers the CLI channel and tool calls carry no channel hint, so a+ * desktop-only call may still land on the CLI* - `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';+export type DeviceClientKind = 'cli-only' | 'desktop' | 'mixed' | 'unknown';/*** Resolve which client kind is live on `deviceId`, from the gateway's@@ -34,7 +37,9 @@ export const resolveDeviceClientKind = async (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';+ const desktopChannels = channels.filter((c) => DESKTOP_CHANNELS.has(c)).length;+ if (desktopChannels === 0) return 'cli-only';+ return desktopChannels === channels.length ? 'desktop' : 'mixed';} catch (error) {log('device presence lookup failed for %s: %O', deviceId, error);return 'unknown';diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex 6f37f911ea6..e7304768ca3 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -130,6 +130,13 @@ const assertNotWorkspaceRoot = (export type { DeviceAttachment, DeviceStatusResult, DeviceSystemInfo };+/**+ * Outcome of a device system-info read. `reason` is the gateway's code when it+ * gave one (`TIMEOUT`, `DEVICE_OFFLINE`, `DEVICE_NOT_FOUND`), otherwise a local one.+ */+export type DeviceSystemInfoRead =+ { ok: true; systemInfo: DeviceSystemInfo } | { ok: false; reason: string };+interface AppUpdateRpcParams {deviceId: string;timeout?: number;@@ -246,15 +253,36 @@ export class DeviceGateway {deviceId: string,workspaceId?: string,): Promise<DeviceSystemInfo | undefined> {+ const read = await this.readDeviceSystemInfo(userId, deviceId, workspaceId);+ return read.ok ? read.systemInfo : undefined;+ }++ /**+ * Like {@link queryDeviceSystemInfo}, but a failed read says why. Use it when+ * "the device did not answer" must not be mistaken for "the device answered+ * without this capability" β e.g. gating a tool on `supportedTools`.+ */+ async readDeviceSystemInfo(+ userId: string,+ deviceId: string,+ workspaceId?: string,+ ): Promise<DeviceSystemInfoRead> {const client = this.getClient();- if (!client) return undefined;+ if (!client) return { ok: false, reason: 'GATEWAY_NOT_CONFIGURED' };try {const result = await client.getDeviceSystemInfo(userId, deviceId, workspaceId);- return result.success ? result.systemInfo : undefined;- } catch {- log('queryDeviceSystemInfo: failed for userId=%s, deviceId=%s', userId, deviceId);- return undefined;+ if (result.success && result.systemInfo) return { ok: true, systemInfo: result.systemInfo };+ log(+ 'readDeviceSystemInfo: unanswered for userId=%s, deviceId=%s: %s',+ userId,+ deviceId,+ result.error,+ );+ return { ok: false, reason: result.error ?? 'NO_SYSTEM_INFO' };+ } catch (error) {+ log('readDeviceSystemInfo: failed for userId=%s, deviceId=%s: %O', userId, deviceId, error);+ return { ok: false, reason: describeGatewayRequestFailure(error, 'RPC call').code };}}diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.tsindex 1f546cb7115..27a8b5b2353 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.ts@@ -3,24 +3,47 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { type ToolExecutionContext } from '../../types';+type SystemInfoRead =+ { ok: true; systemInfo: Record<string, unknown> } | { ok: false; reason: string };+const executeToolCallMock = vi.fn();-const queryDeviceSystemInfoMock = vi.fn();+const readDeviceSystemInfoMock = vi.fn<(...args: unknown[]) => Promise<SystemInfoRead>>();+const resolveDeviceClientKindMock = vi.fn();vi.mock('@/server/services/deviceGateway', () => ({deviceGateway: {- queryDeviceSystemInfo: (...args: unknown[]) => queryDeviceSystemInfoMock(...args),+ // Mirrors the service: the lossy read is the detailed one minus the reason.+ queryDeviceSystemInfo: async (...args: unknown[]) => {+ const read = await readDeviceSystemInfoMock(...args);+ return read.ok ? read.systemInfo : undefined;+ },+ readDeviceSystemInfo: (...args: unknown[]) => readDeviceSystemInfoMock(...args),},}));vi.mock('@/server/services/deviceGateway/authorizedToolCall', () => ({executeAuthorizedDeviceToolCall: (_serverDB: unknown, ...args: unknown[]) =>executeToolCallMock(...args),}));+vi.mock('@/server/services/deviceGateway/deviceChannels', () => ({+ resolveDeviceClientKind: (...args: unknown[]) => resolveDeviceClientKindMock(...args),+}));const { auvRuntime } = await import('../auv');+const baseContext: ToolExecutionContext = {+ activeDeviceId: 'device-1',+ toolManifestMap: {},+ userId: 'user-1',+};+describe('auvRuntime', () => {beforeEach(() => {vi.clearAllMocks();- queryDeviceSystemInfoMock.mockResolvedValue({ supportedTools: [AuvIdentifier] });+ readDeviceSystemInfoMock.mockResolvedValue({+ ok: true,+ systemInfo: { supportedTools: [AuvIdentifier] },+ });+ resolveDeviceClientKindMock.mockResolvedValue('desktop');+ executeToolCallMock.mockResolvedValue({ content: 'ok', success: true });});it('requires a user and active device', () => {@@ -33,12 +56,8 @@ describe('auvRuntime', () => {});it('rejects old clients before forwarding a tool call', async () => {- queryDeviceSystemInfoMock.mockResolvedValueOnce({ arch: 'arm64' });- const runtime = auvRuntime.factory({- userId: 'user-1',- activeDeviceId: 'device-1',- toolManifestMap: {},- });+ readDeviceSystemInfoMock.mockResolvedValueOnce({ ok: true, systemInfo: { arch: 'arm64' } });+ const runtime = auvRuntime.factory(baseContext);await expect(runtime.runCommand({ argv: ['invoke', 'display.list'] })).rejects.toThrow('does not support Computer Use',);@@ -47,10 +66,8 @@ describe('auvRuntime', () => {it('proxies runCommand to the active desktop device', async () => {const context: ToolExecutionContext = {- activeDeviceId: 'device-1',+ ...baseContext,operationId: 'operation-1',- toolManifestMap: {},- userId: 'user-1',workspaceId: 'workspace-1',};const args = { argv: ['invoke', 'display.capture'] };@@ -76,5 +93,65 @@ describe('auvRuntime', () => {undefined,);expect(result).toEqual(expected);+ expect(resolveDeviceClientKindMock).not.toHaveBeenCalled();+ });++ 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+ // call failed as "does not support Computer Use" without being sent.+ readDeviceSystemInfoMock.mockResolvedValueOnce({ ok: false, reason: 'TIMEOUT' });++ const runtime = auvRuntime.factory(baseContext);+ const result = await runtime.runCommand({ argv: ['invoke', 'display.list'] });++ expect(resolveDeviceClientKindMock).toHaveBeenCalledWith('user-1', 'device-1', undefined);+ expect(executeToolCallMock).toHaveBeenCalledTimes(1);+ expect(result).toEqual({ content: 'ok', success: true });+ });++ it('does not dispatch to a CLI-only device and names the CLI', async () => {+ readDeviceSystemInfoMock.mockResolvedValueOnce({ ok: false, reason: 'TIMEOUT' });+ resolveDeviceClientKindMock.mockResolvedValueOnce('cli-only');++ const runtime = auvRuntime.factory(baseContext);+ const result = await runtime.runCommand({ argv: ['invoke', 'display.list'] });++ expect(executeToolCallMock).not.toHaveBeenCalled();+ expect(result).toMatchObject({+ error: { code: 'COMPUTER_USE_DEVICE_UNAVAILABLE' },+ success: false,+ });+ expect(result.content).toContain('`lh connect` CLI');+ });++ it('does not dispatch when the device also runs the CLI, which the gateway prefers', async () => {+ readDeviceSystemInfoMock.mockResolvedValueOnce({ ok: false, reason: 'TIMEOUT' });+ resolveDeviceClientKindMock.mockResolvedValueOnce('mixed');++ const runtime = auvRuntime.factory(baseContext);+ const result = await runtime.runCommand({ argv: ['invoke', 'display.list'] });++ expect(executeToolCallMock).not.toHaveBeenCalled();+ expect(result).toMatchObject({+ error: { code: 'COMPUTER_USE_DEVICE_UNAVAILABLE' },+ success: false,+ });+ expect(result.content).toContain('TIMEOUT');+ expect(result.content).toContain('stop `lh connect`');+ });++ it('reports the gateway reason, not a missing capability, when presence is unknown', async () => {+ readDeviceSystemInfoMock.mockResolvedValueOnce({ ok: false, reason: 'DEVICE_NOT_FOUND' });+ resolveDeviceClientKindMock.mockResolvedValueOnce('unknown');++ const runtime = auvRuntime.factory(baseContext);+ const result = await runtime.runCommand({ argv: ['invoke', 'display.list'] });++ expect(executeToolCallMock).not.toHaveBeenCalled();+ expect(result.success).toBe(false);+ expect(result.content).toContain('DEVICE_NOT_FOUND');+ expect(result.content).not.toContain('does not support');+ });});});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/auv.ts b/apps/server/src/services/toolExecution/serverRuntimes/auv.tsindex 23440446e53..fc712423a60 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/auv.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/auv.ts@@ -2,11 +2,49 @@ import { AuvApiName, AuvIdentifier } from '@lobechat/builtin-tool-auv';import { deviceGateway } from '@/server/services/deviceGateway';import { executeAuthorizedDeviceToolCall } from '@/server/services/deviceGateway/authorizedToolCall';+import {+ type DeviceClientKind,+ resolveDeviceClientKind,+} from '@/server/services/deviceGateway/deviceChannels';import { resolveRunWorkspaceId } from './resolveWorkspaceScope';import { type ServerRuntimeRegistration } from './types';import { withoutDeviceReplay } from './withoutDeviceReplay';+export const COMPUTER_USE_DEVICE_UNAVAILABLE_ERROR_CODE = 'COMPUTER_USE_DEVICE_UNAVAILABLE';++/**+ * The capability check could not run (the device did not answer it), and the+ * presence list does not show the desktop app as the device's only client β so+ * nothing was sent.+ * Says which of those it was instead of claiming the device lacks the feature.+ */+const buildUnverifiedDeviceResult = (+ deviceId: string,+ { clientKind, reason }: { clientKind: Exclude<DeviceClientKind, 'desktop'>; reason: string },+) => {+ const message =+ clientKind === 'cli-only'+ ? `The active device (${deviceId}) is connected only through the \`lh connect\` CLI, ` ++ `which cannot run Computer Use. Nothing was run. Ask the user to open the LobeHub ` ++ `desktop app on that machine, then retry.`+ : clientKind === 'mixed'+ ? `Could not confirm that the active device (${deviceId}) can run Computer Use: it did ` ++ `not answer the capability check (${reason}). Nothing was run, because the device is ` ++ `connected through both the LobeHub desktop app and the \`lh connect\` CLI, and the ` ++ `call could be routed to the CLI, which cannot run Computer Use. Retry shortly; if it ` ++ `keeps failing, ask the user to stop \`lh connect\` on that machine.`+ : `Could not confirm that the active device (${deviceId}) can run Computer Use: it did ` ++ `not answer the capability check (${reason}). Nothing was run. The device may be busy ` ++ `or reconnecting β retry shortly, and if it keeps failing, ask the user to check that ` ++ `the LobeHub desktop app is running and connected.`;+ return {+ content: message,+ error: { code: COMPUTER_USE_DEVICE_UNAVAILABLE_ERROR_CODE, message },+ success: false,+ };+};+export const auvRuntime: ServerRuntimeRegistration = {factory: (context) => {if (!context.userId) throw new Error('userId is required for AUV device proxy execution');@@ -31,21 +69,44 @@ export const auvRuntime: ServerRuntimeRegistration = {* - Server-side builtin tool execution for `lobe-computer-use/runCommand`** Downstream:- * - {@link deviceGateway.queryDeviceSystemInfo}+ * - {@link deviceGateway.readDeviceSystemInfo}+ * - {@link resolveDeviceClientKind} when the device does not answer that read* - {@link deviceGateway.executeToolCall}*/runCommand: async (args: unknown) => {const workspaceId = await getDeviceWorkspaceId();- const systemInfo = await deviceGateway.queryDeviceSystemInfo(+ const read = await deviceGateway.readDeviceSystemInfo(context.userId!,context.activeDeviceId!,workspaceId,);- if (!systemInfo?.supportedTools?.includes(AuvIdentifier)) {- throw new Error(- 'The selected device does not support Computer Use. Update the desktop app and reconnect.',+ if (read.ok) {+ // An answer without the capability is an old client (or `lh connect`):+ // both route by apiName alone and would treat `runCommand` as a shell call.+ if (!read.systemInfo.supportedTools?.includes(AuvIdentifier)) {+ throw new Error(+ 'The selected device does not support Computer Use. Update the desktop app and reconnect.',+ );+ }+ } else {+ // No answer (busy device timing out, a reconnect gap) says nothing about+ // the capability. A device whose only live client is the desktop app is+ // enough to dispatch: the tool call has its own deadline and reconnect+ // recovery, which this read does not. A device that also runs+ // `lh connect` stays closed β the gateway would prefer the CLI.+ const clientKind = await resolveDeviceClientKind(+ context.userId!,+ context.activeDeviceId!,+ workspaceId,);+ if (clientKind !== 'desktop') {+ return buildUnverifiedDeviceResult(context.activeDeviceId!, {+ clientKind,+ reason: read.reason,+ });+ }}+const result = await executeAuthorizedDeviceToolCall(context.serverDB,{diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.tsindex c63d66163d2..7e3650de5ba 100644--- a/packages/device-gateway-client/src/http.test.ts+++ b/packages/device-gateway-client/src/http.test.ts@@ -827,6 +827,17 @@ describe('GatewayHttpClient', () => {expect(result).toEqual({ success: false });});+ it('keeps the gateway reason on a non-ok response', async () => {+ mockFetch({+ json: vi.fn().mockResolvedValue({ error: 'TIMEOUT', success: false }),+ ok: false,+ });++ const result = await client.getDeviceSystemInfo('user-1', 'device-1');++ expect(result).toEqual({ error: 'TIMEOUT', success: false });+ });+it('bounds the read with a timeout', async () => {mockFetch({ json: vi.fn().mockResolvedValue({ success: true, systemInfo: {} }), ok: true });diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.tsindex 7f064142674..0aa12fd9624 100644--- a/packages/device-gateway-client/src/http.ts+++ b/packages/device-gateway-client/src/http.ts@@ -389,18 +389,22 @@ export class GatewayHttpClient {userId: string,deviceId: string,workspaceId?: string,- ): Promise<{ success: boolean; systemInfo?: DeviceSystemInfo }> {+ ): Promise<{ error?: string; success: boolean; systemInfo?: DeviceSystemInfo }> {const res = await this.post('/api/device/system-info',{ deviceId, userId, workspaceId },{ timeout: DEVICE_QUERY_TIMEOUT_MS },);if (!res.ok) {- return { success: false };+ // Keep the gateway's reason (`TIMEOUT`, `DEVICE_OFFLINE`, `DEVICE_NOT_FOUND`):+ // a device that did not answer is not a device that lacks a capability.+ const data = (await res.json().catch(() => undefined)) as { error?: string } | undefined;+ return { error: data?.error, success: false };}const data = await res.json();return {+ error: data.error,success: data.success ?? false,systemInfo: data.systemInfo,};