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(cli): offer Computer Use from `lh connect --auv` (#20983)

Neko6f6e0f7d2519
diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.ts
index da7b863c716..8211335e96f 100644
--- a/apps/cli/src/commands/connect.test.ts
+++ b/apps/cli/src/commands/connect.test.ts
@@ -1,3 +1,7 @@
+import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
import type * as DeviceControlModule from '@lobechat/device-control';
import { GatewayClient } from '@lobechat/device-gateway-client';
import { Command } from 'commander';
@@ -381,7 +385,7 @@ describe('connect command', () => {
const program = createProgram();
await program.parseAsync(['node', 'test', 'connect']);
- clientEventHandlers['system_info_request']?.({
+ await clientEventHandlers['system_info_request']?.({
requestId: 'req-2',
type: 'system_info_request',
});
@@ -391,6 +395,8 @@ describe('connect command', () => {
expect(lastSentSystemInfoResponse.result.success).toBe(true);
expect(lastSentSystemInfoResponse.result.systemInfo).toHaveProperty('homePath');
expect(lastSentSystemInfoResponse.result.systemInfo).toHaveProperty('arch');
+ // `getShellInfo` is async; reading `displayName` off the promise sent nothing.
+ expect(lastSentSystemInfoResponse.result.systemInfo.defaultShell).toEqual(expect.any(String));
});
it('should handle auth_failed', async () => {
@@ -583,7 +589,7 @@ describe('connect command', () => {
const program = createProgram();
await program.parseAsync(['node', 'test', 'connect']);
- clientEventHandlers['system_info_request']?.({
+ await clientEventHandlers['system_info_request']?.({
requestId: 'req-3',
type: 'system_info_request',
});
@@ -597,6 +603,78 @@ describe('connect command', () => {
}
});
+ describe.skipIf(process.platform === 'win32')('--auv', () => {
+ let auvDir: string;
+ let auvBinary: string;
+
+ beforeEach(async () => {
+ auvDir = await mkdtemp(path.join(os.tmpdir(), 'lh-connect-auv-'));
+ auvBinary = path.join(auvDir, 'auv');
+ await writeFile(auvBinary, `#!/bin/sh\nprintf '{"ok":true}'\n`);
+ await chmod(auvBinary, 0o755);
+ });
+
+ afterEach(async () => {
+ await rm(auvDir, { force: true, recursive: true });
+ });
+
+ const computerUseCall = {
+ requestId: 'req-cu',
+ toolCall: {
+ apiName: 'runCommand',
+ arguments: JSON.stringify({ argv: ['invoke', 'display.list'] }),
+ identifier: 'lobe-computer-use',
+ },
+ type: 'tool_call_request',
+ };
+
+ it('advertises Computer Use and runs it with the given binary', async () => {
+ await createProgram().parseAsync(['node', 'test', 'connect', '--auv', auvBinary]);
+
+ await clientEventHandlers['system_info_request']?.({
+ requestId: 'r',
+ type: 'system_info_request',
+ });
+ expect(lastSentSystemInfoResponse.result.systemInfo.supportedTools).toEqual([
+ 'lobe-computer-use',
+ ]);
+
+ // `runCommand` is also the shell tool's apiName; the identifier decides.
+ await clientEventHandlers['tool_call_request']?.(computerUseCall);
+ expect(executeToolCall).not.toHaveBeenCalled();
+ expect(lastSentToolResponse.result).toMatchObject({
+ state: { exitCode: 0, output: { ok: true } },
+ success: true,
+ });
+ });
+
+ it('does not advertise or run Computer Use without --auv', async () => {
+ await createProgram().parseAsync(['node', 'test', 'connect']);
+
+ await clientEventHandlers['system_info_request']?.({
+ requestId: 'r',
+ type: 'system_info_request',
+ });
+ expect(lastSentSystemInfoResponse.result.systemInfo).not.toHaveProperty('supportedTools');
+
+ await clientEventHandlers['tool_call_request']?.(computerUseCall);
+ expect(executeToolCall).not.toHaveBeenCalled();
+ expect(lastSentToolResponse.result).toMatchObject({
+ error: expect.stringContaining('--auv'),
+ success: false,
+ });
+ });
+
+ it('passes the absolute binary path to the daemon child', async () => {
+ const relative = path.relative(process.cwd(), auvBinary);
+ await createProgram().parseAsync(['node', 'test', 'connect', '--daemon', '--auv', relative]);
+
+ expect(vi.mocked(spawnDaemon).mock.calls[0]?.[0]).toEqual(
+ expect.arrayContaining(['--auv', auvBinary]),
+ );
+ });
+ });
+
describe('--daemon flag', () => {
it('should spawn daemon and exit', async () => {
const program = createProgram();
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index c635fe7b011..747707eca93 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -11,27 +11,21 @@ import {
executeDeviceRpc,
pushMetrics,
} from '@lobechat/device-control';
+import { COMPUTER_USE_IDENTIFIER } from '@lobechat/device-control/computer-use';
import type {
AgentRunRequestMessage,
- DeviceSystemInfo,
RpcRequestMessage,
SystemInfoRequestMessage,
ToolCallRequestMessage,
} from '@lobechat/device-gateway-client';
import { GatewayClient } from '@lobechat/device-gateway-client';
import { listHeterogeneousAgentModels } from '@lobechat/heterogeneous-agents/models';
-import { getShellInfo } from '@lobechat/local-file-shell';
import type { Command } from 'commander';
import { createLambdaClient } from '../api/client';
import { resolveToken } from '../auth/resolveToken';
import { CLI_API_KEY_ENV } from '../constants/auth';
-import {
- CLI_CONFIG_DIR_NAME,
- CLI_CONNECT_SERVICE_NAME,
- CLI_DISPLAY_NAME,
- CLI_PRIMARY_BIN,
-} from '../constants/identity';
+import { CLI_CONNECT_SERVICE_NAME, CLI_DISPLAY_NAME, CLI_PRIMARY_BIN } from '../constants/identity';
import { OFFICIAL_GATEWAY_URL } from '../constants/urls';
import { CliMaintenance } from '../daemon/maintenance';
import {
@@ -56,6 +50,7 @@ import {
resolveDeviceIdentity,
resolveWorkspaceDeviceIdentity,
} from '../device/register';
+import { collectSystemInfo } from '../device/systemInfo';
import { TerminalSessionManager } from '../device/terminal';
import {
CONNECT_RETRYABLE_EXIT_CODE,
@@ -78,6 +73,7 @@ import {
saveSettings,
} from '../settings';
import { executeToolCall } from '../tools';
+import { executeComputerUseCall, resolveComputerUseDevice } from '../tools/computerUse';
import { cleanupAllProcesses, getActiveShellCount } from '../tools/shell';
import { log, setVerbose } from '../utils/logger';
import { sweepLocalTraces } from '../utils/traceMaintenance';
@@ -87,6 +83,8 @@ const SHUTDOWN_METRICS_FLUSH_MS = 3000;
const CONNECT_SERVICE_NAME = CLI_CONNECT_SERVICE_NAME;
interface ConnectOptions {
+ /** `auv` binary that runs Computer Use on this device; see `resolveComputerUseDevice`. */
+ auv?: string;
daemon?: boolean;
daemonChild?: boolean;
deviceId?: string;
@@ -112,6 +110,7 @@ export function registerConnectCommand(program: Command) {
'--public',
'With --workspace: enroll into the shared pool visible to every member (default: private, visible only to you)',
)
+ .option('--auv <binary>', 'Offer Computer Use by running this AUV binary (`auv invoke`)')
.option('-v, --verbose', 'Enable verbose logging')
.option('-d, --daemon', 'Run as a background daemon process')
.option('--daemon-child', 'Internal: runs as the daemon child process')
@@ -188,6 +187,7 @@ export function registerConnectCommand(program: Command) {
.option('--token <jwt>', 'JWT access token')
.option('--gateway <url>', 'Device gateway URL')
.option('--device-id <id>', 'Device ID')
+ .option('--auv <binary>', 'Offer Computer Use by running this AUV binary (`auv invoke`)')
.option('-v, --verbose', 'Enable verbose logging')
.action(async (options: ConnectOptions) => {
const wasStopped = stopDaemon();
@@ -209,6 +209,7 @@ export function registerConnectCommand(program: Command) {
'--public',
'With --workspace: enroll into the shared pool visible to every member (default: private, visible only to you)',
)
+ // TODO: `--auv` is not forwarded to the service unit; add it when a service-mode device needs Computer Use.
.action((options: Pick<ConnectOptions, 'public' | 'workspace'>) => {
installConnectService({ public: options.public, workspace: options.workspace });
log.info(
@@ -332,6 +333,7 @@ function buildDaemonArgs(options: ConnectOptions): string[] {
if (options.deviceId) args.push('--device-id', options.deviceId);
if (options.workspace) args.push('--workspace', options.workspace);
if (options.public) args.push('--public');
+ if (options.auv) args.push('--auv', path.resolve(options.auv));
if (options.verbose) args.push('--verbose');
return args;
@@ -357,6 +359,13 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
const resolvedGatewayUrl = gatewayUrl || OFFICIAL_GATEWAY_URL;
+ // Fail before connecting rather than advertise a tool this device cannot run.
+ const computerUse = await resolveComputerUseDevice(options.auv).catch((err: Error) => {
+ log.error(err.message);
+ process.exit(1);
+ throw err;
+ });
+
// Workspace enrollment: the device joins a workspace pool (reachable by all
// members) instead of the personal pool. It authenticates with a minted
// workspace-device token (carrying the `workspace_id` claim) and uses a
@@ -514,6 +523,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
};
const handlerContext: GatewayHandlerContext = {
+ computerUse,
deps: deviceControlDeps,
error,
// Read at dispatch time β€” `auth` may be refreshed mid-session.
@@ -934,6 +944,8 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
/** Everything a gateway connection's request handlers need from the host process. */
interface GatewayHandlerContext {
+ /** Present when `--auv` enabled Computer Use on this device. */
+ computerUse?: Awaited<ReturnType<typeof resolveComputerUseDevice>>;
deps: DeviceControlDeps;
error: (msg: string) => void;
/** Read at dispatch time β€” the underlying auth may be refreshed mid-session. */
@@ -955,12 +967,13 @@ function bindGatewayClientHandlers(
ctx: GatewayHandlerContext,
connectionWorkspaceId?: string,
) {
- const { deps, error, getAuth, info, isDaemonChild, maintenance, recordRequest } = ctx;
+ const { computerUse, deps, error, getAuth, info, isDaemonChild, maintenance, recordRequest } =
+ ctx;
// Handle system info requests
- client.on('system_info_request', (request: SystemInfoRequestMessage) => {
+ client.on('system_info_request', async (request: SystemInfoRequestMessage) => {
info(`Received system_info_request: requestId=${request.requestId}`);
- const systemInfo = collectSystemInfo();
+ const systemInfo = await collectSystemInfo(computerUse);
client.sendSystemInfoResponse({
requestId: request.requestId,
result: { success: true, systemInfo },
@@ -984,7 +997,12 @@ function bindGatewayClientHandlers(
// slow transport.
const startedAt = performance.now();
const result = await maintenance
- .run(() => executeToolCall(toolCall.apiName, toolCall.arguments, timeout, getAuth()))
+ .run(() =>
+ // Computer Use's `runCommand` shares its apiName with the shell tool.
+ toolCall.identifier === COMPUTER_USE_IDENTIFIER
+ ? executeComputerUseCall(computerUse, toolCall.apiName, toolCall.arguments, timeout)
+ : executeToolCall(toolCall.apiName, toolCall.arguments, timeout, getAuth()),
+ )
.catch((err: Error) => ({
content: '',
error: err.message,
@@ -1163,24 +1181,3 @@ function scheduleProactiveRefresh(
}
}
}
-
-function collectSystemInfo(): DeviceSystemInfo {
- const home = os.homedir();
- const platform = process.platform;
- const videosDir = platform === 'linux' ? 'Videos' : 'Movies';
-
- return {
- arch: os.arch(),
- // Tell the server-side prompt builder which shell runCommand spawns here.
- defaultShell: getShellInfo().displayName,
- desktopPath: path.join(home, 'Desktop'),
- documentsPath: path.join(home, 'Documents'),
- downloadsPath: path.join(home, 'Downloads'),
- homePath: home,
- musicPath: path.join(home, 'Music'),
- picturesPath: path.join(home, 'Pictures'),
- userDataPath: path.join(home, CLI_CONFIG_DIR_NAME),
- videosPath: path.join(home, videosDir),
- workingDirectory: process.cwd(),
- };
-}
diff --git a/apps/cli/src/device/systemInfo.ts b/apps/cli/src/device/systemInfo.ts
new file mode 100644
index 00000000000..5aae6a2844d
--- /dev/null
+++ b/apps/cli/src/device/systemInfo.ts
@@ -0,0 +1,38 @@
+import os from 'node:os';
+import path from 'node:path';
+
+import { COMPUTER_USE_IDENTIFIER } from '@lobechat/device-control/computer-use';
+import type { DeviceSystemInfo } from '@lobechat/device-gateway-client';
+import { getShellInfo } from '@lobechat/local-file-shell';
+
+import { CLI_CONFIG_DIR_NAME } from '../constants/identity';
+import type { ComputerUseDevice } from '../tools/computerUse';
+
+/**
+ * The answer to a gateway `system_info_request`. `supportedTools` lists the
+ * opt-in tools this device can run; the server refuses those tools on a
+ * device that does not list them.
+ */
+export async function collectSystemInfo(
+ computerUse?: ComputerUseDevice,
+): Promise<DeviceSystemInfo> {
+ const home = os.homedir();
+ const platform = process.platform;
+ const videosDir = platform === 'linux' ? 'Videos' : 'Movies';
+
+ return {
+ arch: os.arch(),
+ // Tell the server-side prompt builder which shell runCommand spawns here.
+ defaultShell: (await getShellInfo()).displayName,
+ desktopPath: path.join(home, 'Desktop'),
+ documentsPath: path.join(home, 'Documents'),
+ downloadsPath: path.join(home, 'Downloads'),
+ homePath: home,
+ musicPath: path.join(home, 'Music'),
+ picturesPath: path.join(home, 'Pictures'),
+ ...(computerUse && { supportedTools: [COMPUTER_USE_IDENTIFIER] }),
+ userDataPath: path.join(home, CLI_CONFIG_DIR_NAME),
+ videosPath: path.join(home, videosDir),
+ workingDirectory: process.cwd(),
+ };
+}
diff --git a/apps/cli/src/tools/computerUse.test.ts b/apps/cli/src/tools/computerUse.test.ts
new file mode 100644
index 00000000000..0cf5e21d1ee
--- /dev/null
+++ b/apps/cli/src/tools/computerUse.test.ts
@@ -0,0 +1,103 @@
+import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { executeComputerUseCall, resolveComputerUseDevice } from './computerUse';
+
+// A stand-in `auv` that echoes its arguments, or fails like AUV does with a
+// JSON envelope on stdout for the `fail.now` command.
+const FAKE_AUV = `#!/bin/sh
+if [ "$2" = "fail.now" ]; then printf '{"error":"window_not_found"}'; echo 'no window' >&2; exit 4; fi
+printf '{"args":"%s"}' "$*"
+`;
+
+describe.skipIf(process.platform === 'win32')('Computer Use on lh connect', () => {
+ let dir: string;
+ let binary: string;
+
+ beforeEach(async () => {
+ dir = await mkdtemp(path.join(os.tmpdir(), 'lh-auv-'));
+ binary = path.join(dir, 'auv');
+ await writeFile(binary, FAKE_AUV);
+ await chmod(binary, 0o755);
+ });
+
+ afterEach(async () => {
+ await rm(dir, { force: true, recursive: true });
+ });
+
+ describe('resolveComputerUseDevice', () => {
+ it('leaves Computer Use off without --auv', async () => {
+ await expect(resolveComputerUseDevice(undefined)).resolves.toBeUndefined();
+ });
+
+ it('stores runs under the CLI config directory', async () => {
+ await expect(resolveComputerUseDevice(binary)).resolves.toEqual({
+ binaryPath: binary,
+ storeRoot: path.join(os.homedir(), '.lobehub', 'auv', 'runs'),
+ });
+ });
+
+ it('rejects a missing or non-executable binary', async () => {
+ await expect(resolveComputerUseDevice(path.join(dir, 'missing'))).rejects.toThrow(
+ 'no file at',
+ );
+ await chmod(binary, 0o644);
+ await expect(resolveComputerUseDevice(binary)).rejects.toThrow('is not executable');
+ });
+ });
+
+ describe('executeComputerUseCall', () => {
+ it('runs auv invoke with --json and the managed store root', async () => {
+ const device = { binaryPath: binary, storeRoot: path.join(dir, 'runs') };
+
+ const result = await executeComputerUseCall(
+ device,
+ 'runCommand',
+ JSON.stringify({ argv: ['invoke', 'display.capture'], reasoning: 'look' }),
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.state).toEqual({
+ argv: ['invoke', 'display.capture'],
+ exitCode: 0,
+ output: { args: `invoke display.capture --json --store-root ${device.storeRoot}` },
+ });
+ });
+
+ it('returns a failed command with its structured output', async () => {
+ const device = { binaryPath: binary, storeRoot: path.join(dir, 'runs') };
+
+ const result = await executeComputerUseCall(
+ device,
+ 'runCommand',
+ JSON.stringify({ argv: ['invoke', 'fail.now'] }),
+ );
+
+ expect(result).toMatchObject({
+ error: 'no window',
+ state: { exitCode: 4, output: { error: 'window_not_found' } },
+ success: false,
+ });
+ });
+
+ it('refuses calls when Computer Use is off or the argv is not allowed', async () => {
+ const off = await executeComputerUseCall(
+ undefined,
+ 'runCommand',
+ JSON.stringify({ argv: ['invoke', 'display.list'] }),
+ );
+ expect(off).toMatchObject({ error: expect.stringContaining('--auv'), success: false });
+
+ const device = { binaryPath: binary, storeRoot: path.join(dir, 'runs') };
+ const shell = await executeComputerUseCall(
+ device,
+ 'runCommand',
+ JSON.stringify({ argv: ['serve'] }),
+ );
+ expect(shell.success).toBe(false);
+ });
+ });
+});
diff --git a/apps/cli/src/tools/computerUse.ts b/apps/cli/src/tools/computerUse.ts
new file mode 100644
index 00000000000..96ba4cb79f2
--- /dev/null
+++ b/apps/cli/src/tools/computerUse.ts
@@ -0,0 +1,95 @@
+import { execFile } from 'node:child_process';
+import { constants } from 'node:fs';
+import { access, stat } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { promisify } from 'node:util';
+
+import {
+ type AuvRunCommandParams,
+ normalizeAuvArgv,
+ runAuvCommand,
+ toAuvToolOutput,
+} from '@lobechat/device-control/computer-use';
+
+import { CLI_CONFIG_DIR_NAME } from '../constants/identity';
+
+const execFileAsync = promisify(execFile);
+
+/** How this device runs Computer Use: an `auv` binary the user provided. */
+export interface ComputerUseDevice {
+ binaryPath: string;
+ /** AUV run store for this device's commands; image artifacts are read from here. */
+ storeRoot: string;
+}
+
+// Matches the tool manifest's `defaultTimeoutMs` for `runCommand`.
+const DEFAULT_TIMEOUT_MS = 120_000;
+
+/**
+ * Enables Computer Use for `lh connect --auv <binary>`. Returns `undefined`
+ * without `--auv`, so the device does not advertise the tool.
+ *
+ * `lh` only runs `auv invoke`; the AUV daemon it reaches (default local
+ * endpoint or `AUV_ENDPOINT`) is the user's to start, unlike the desktop app,
+ * which owns a private daemon.
+ *
+ * NOTICE: on macOS, Accessibility and Screen Recording are granted to the
+ * process that launches `auv` β€” the terminal for a foreground `lh connect`,
+ * nobody for a launchd/daemon one. Only Linux has been verified. Delegating
+ * those permissions to a signed AUV helper app is not done here.
+ */
+export const resolveComputerUseDevice = async (
+ binary: string | undefined,
+): Promise<ComputerUseDevice | undefined> => {
+ if (!binary) return undefined;
+
+ const binaryPath = path.resolve(binary);
+ const stats = await stat(binaryPath).catch(() => undefined);
+ if (!stats?.isFile()) throw new Error(`--auv: no file at ${binaryPath}`);
+ await access(binaryPath, constants.X_OK).catch(() => {
+ throw new Error(`--auv: ${binaryPath} is not executable`);
+ });
+
+ return {
+ binaryPath,
+ storeRoot: path.join(os.homedir(), CLI_CONFIG_DIR_NAME, 'auv', 'runs'),
+ };
+};
+
+/**
+ * Runs one `lobe-computer-use` tool call with the device's `auv` binary and
+ * returns the same tool result the desktop app does.
+ */
+export const executeComputerUseCall = async (
+ device: ComputerUseDevice | undefined,
+ apiName: string,
+ argsStr: string,
+ timeout?: number,
+) => {
+ try {
+ if (!device) {
+ throw new Error(
+ 'Computer Use is not enabled on this device. Restart `lh connect` with --auv <binary>.',
+ );
+ }
+ if (apiName !== 'runCommand') {
+ throw new Error(`Computer Use tool "${apiName}" is not available on this device`);
+ }
+
+ const params = JSON.parse(argsStr) as AuvRunCommandParams;
+ const argv = normalizeAuvArgv(params);
+ const result = await runAuvCommand(params, argv, (cliArgv) =>
+ execFileAsync(device.binaryPath, [...cliArgv, '--store-root', device.storeRoot], {
+ encoding: 'utf8',
+ maxBuffer: 4 * 1024 * 1024,
+ timeout: typeof timeout === 'number' && timeout > 0 ? timeout : DEFAULT_TIMEOUT_MS,
+ windowsHide: true,
+ }),
+ );
+ return toAuvToolOutput(result);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ return { content: '', error: message, state: undefined, success: false };
+ }
+};
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index 810dbdc2028..e65541580be 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -4,6 +4,10 @@ import os from 'node:os';
import path from 'node:path';
import type { DeviceControlDeps } from '@lobechat/device-control';
+import {
+ COMPUTER_USE_IDENTIFIER as AuvIdentifier,
+ toAuvToolOutput,
+} from '@lobechat/device-control/computer-use';
import type { AgentRunRequestMessage, GatewayMcpParams } from '@lobechat/device-gateway-client';
import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';
import type { HeterogeneousAgentCancellationSignal } from '@lobechat/heterogeneous-agents/protocol';
@@ -50,7 +54,6 @@ type AvailableRemotePlatformRuntime = Extract<RemotePlatformCommandRuntime, { av
// Hardcoded (not imported) so the desktop main process keeps zero builtin-tool
// package deps β€” importing one risks the @lobechat/types stub runtime leak.
const BrowserIdentifier = 'lobe-browser';
-const AuvIdentifier = 'lobe-computer-use';
function parseHermesSessionId(stderr: string): string | undefined {
for (const line of stderr.split(/\r?\n/).reverse()) {
@@ -621,15 +624,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
throw new Error(`AUV tool "${apiName}" is not available on this device`);
}
- const result = await this.auvService.runCommand(args as AuvRunCommandParams);
- return {
- content: JSON.stringify(result),
- ...(result.exitCode !== 0 && {
- error: result.stderr || `Computer Use exited with code ${result.exitCode}`,
- }),
- state: result,
- success: result.exitCode === 0,
- };
+ return toAuvToolOutput(await this.auvService.runCommand(args as AuvRunCommandParams));
}
/**
diff --git a/apps/desktop/src/main/services/auvSrv.ts b/apps/desktop/src/main/services/auvSrv.ts
index df4bbf2ef97..a6f89316723 100644
--- a/apps/desktop/src/main/services/auvSrv.ts
+++ b/apps/desktop/src/main/services/auvSrv.ts
@@ -1,4 +1,4 @@
-import { execFile, type ExecFileException } from 'node:child_process';
+import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { access, chmod, mkdtemp, rmdir } from 'node:fs/promises';
import os from 'node:os';
@@ -14,6 +14,12 @@ import type {
RunnerClass,
startAuv,
} from '@auv-js/sdk/node';
+import {
+ type AuvRunCommandParams,
+ type AuvRunCommandResult,
+ normalizeAuvArgv,
+ runAuvCommand,
+} from '@lobechat/device-control/computer-use';
import type { App } from '@/core/App';
import { createLogger } from '@/utils/logger';
@@ -45,17 +51,7 @@ export interface AuvRunnerClassInfo {
supportedLifecycles: RunnerClass['supportedLifecycles'];
}
-export interface AuvRunCommandParams {
- argv: string[];
-}
-
-export interface AuvRunCommandResult {
- argv: string[];
- /** Process exit status, not verification of the requested UI effect. */
- exitCode: number;
- output: unknown;
- stderr?: string;
-}
+export type { AuvRunCommandParams, AuvRunCommandResult };
export interface AuvCliExecutionOptions {
argv: string[];
@@ -150,63 +146,6 @@ const normalizeHostname = (hostname: string) => hostname.replace(/\.(?:lan|local
const serializeError = (error: unknown) => (error instanceof Error ? error.message : String(error));
-const MAX_CLI_ARGUMENTS = 128;
-const MAX_CLI_ARGUMENT_LENGTH = 16_384;
-const AUV_COMMAND_ID = /^[a-z][A-Za-z0-9]*(?:\.[A-Za-z][A-Za-z0-9]*)+$/;
-
-const normalizeCliArgv = (params: AuvRunCommandParams): string[] => {
- if (!Array.isArray(params.argv)) throw new Error('AUV argv must be an array');
- if (params.argv.length < 2) {
- throw new Error('AUV argv must include "invoke" and a command or --help');
- }
- if (params.argv.length > MAX_CLI_ARGUMENTS) {
- throw new Error(`AUV argv cannot contain more than ${MAX_CLI_ARGUMENTS} arguments`);
- }
-
- const argv = params.argv.map((argument) => {
- if (typeof argument !== 'string') throw new Error('Every AUV argument must be a string');
- if (argument.includes('\0')) throw new Error('AUV arguments cannot contain NUL bytes');
- if (argument.length > MAX_CLI_ARGUMENT_LENGTH) {
- throw new Error(`AUV arguments cannot exceed ${MAX_CLI_ARGUMENT_LENGTH} characters`);
- }
- return argument;
- });
-
- if (argv[0] !== 'invoke') {
- throw new Error('Only "auv invoke" commands are allowed');
- }
- if (
- argv.some((argument) => argument === '--store-root' || argument.startsWith('--store-root='))
- ) {
- throw new Error('AUV --store-root is managed by LobeHub');
- }
-
- const command = argv[1]!;
- if (
- command !== '--help' &&
- command !== '-h' &&
- command !== 'help' &&
- !AUV_COMMAND_ID.test(command)
- ) {
- throw new Error(`Invalid AUV invoke command: ${command}`);
- }
-
- const isHelp = argv.includes('--help') || argv.includes('-h') || command === 'help';
- if (!isHelp && !argv.includes('--json')) argv.push('--json');
- return argv;
-};
-
-const parseCliOutput = (stdout: string): unknown => {
- const output = stdout.trim();
- if (!output) return null;
-
- try {
- return JSON.parse(output);
- } catch {
- return output;
- }
-};
-
/**
* Owns the AUV SDK connection and, when needed, the embedded daemon lifecycle.
* Renderer callers only receive serializable snapshots; raw SDK and child-process
@@ -312,37 +251,20 @@ export default class AuvService extends ServiceModule {
* -> private app-owned CLI invocation; preserve output on nonzero exits.
*/
async runCommand(params: AuvRunCommandParams): Promise<AuvRunCommandResult> {
- const argv = normalizeCliArgv(params);
+ const argv = normalizeAuvArgv(params);
await this.getClient();
- if (!this.binaryPath || !this.ipcEndpoint) throw new Error('AUV is not connected');
+ const binaryPath = this.binaryPath;
+ const endpoint = this.ipcEndpoint;
+ if (!binaryPath || !endpoint) throw new Error('AUV is not connected');
- let stdout: string;
- let stderr: string;
- let exitCode = 0;
- try {
- ({ stderr, stdout } = await this.dependencies.runCli({
- argv,
- binaryPath: this.binaryPath,
- endpoint: this.ipcEndpoint,
+ return runAuvCommand(params, argv, (cliArgv) =>
+ this.dependencies.runCli({
+ argv: cliArgv,
+ binaryPath,
+ endpoint,
storeRoot: path.join(this.app.appStoragePath, 'auv', 'runs'),
- }));
- } catch (error) {
- // execFile rejects nonzero exits even when stdout contains AUV's structured
- // failure. Return that envelope over IPC; spawn/timeout failures still throw.
- const failure = error as ExecFileException & { stdout?: string; stderr?: string };
- if (typeof failure?.code !== 'number' || failure.killed) throw error;
- exitCode = failure.code;
- stdout = failure.stdout ?? '';
- stderr = failure.stderr ?? '';
- }
- const stderrOutput = stderr.trim();
-
- return {
- argv: [...params.argv],
- exitCode,
- output: parseCliOutput(stdout),
- ...(stderrOutput && { stderr: stderrOutput }),
- };
+ }),
+ );
}
destroy() {
diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
index 8ce7441c0f8..e9a5ec65809 100644
--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts
+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
@@ -8,6 +8,7 @@ import type {
EnrollWorkspaceResult,
UnenrollWorkspaceParams,
} from '@lobechat/device-control';
+import { COMPUTER_USE_IDENTIFIER } from '@lobechat/device-control/computer-use';
import type { DeviceMetricsSampler } from '@lobechat/device-control/metrics';
import type {
AgentRunRequestMessage,
@@ -867,7 +868,7 @@ export default class GatewayConnectionService extends ServiceModule {
private async collectSystemInfo(): Promise<DeviceSystemInfo> {
const { getShellInfo } = await import('@lobechat/local-file-shell/shell');
return {
- supportedTools: ['lobe-computer-use'],
+ supportedTools: [COMPUTER_USE_IDENTIFIER],
arch: os.arch(),
// Tell the server-side prompt builder which shell runCommand spawns here.
defaultShell: (await getShellInfo()).displayName,
diff --git a/apps/server/src/services/deviceGateway/__tests__/clientKinds.test.ts b/apps/server/src/services/deviceGateway/__tests__/clientKinds.test.ts
index 3e76b33e664..8887bb2f8e4 100644
--- a/apps/server/src/services/deviceGateway/__tests__/clientKinds.test.ts
+++ b/apps/server/src/services/deviceGateway/__tests__/clientKinds.test.ts
@@ -7,14 +7,19 @@ 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']);
});
+ // Which of the two serves a call is chosen per device by `auvRuntime`, from
+ // the client that reports the capability.
+ it('lets both clients run Computer Use', () => {
+ expect(
+ resolveDeviceClientKinds({ identifier: AuvIdentifier, kind: 'tool', type: 'tool' }),
+ ).toEqual(['desktop', 'cli']);
+ });
+
it('lets any client run tools both clients implement', () => {
expect(
resolveDeviceClientKinds({ identifier: LocalSystemIdentifier, kind: 'tool', type: 'tool' }),
diff --git a/apps/server/src/services/deviceGateway/authorizedToolCall.ts b/apps/server/src/services/deviceGateway/authorizedToolCall.ts
index fe366f90bf8..5e3fd0bec00 100644
--- a/apps/server/src/services/deviceGateway/authorizedToolCall.ts
+++ b/apps/server/src/services/deviceGateway/authorizedToolCall.ts
@@ -1,5 +1,6 @@
import type { LobeChatDatabase } from '@lobechat/database';
import type { DeviceToolCallResult } from '@lobechat/device-gateway-client';
+import type { DeviceClient } from '@lobechat/types';
import { resolveDeviceDispatchAuthorizationFailure } from './dispatchAuthorization';
import { deviceGateway } from './index';
@@ -18,7 +19,14 @@ import { deviceGateway } from './index';
*/
export const executeAuthorizedDeviceToolCall = async (
serverDB: LobeChatDatabase | undefined,
- params: { deviceId: string; operationId?: string; userId: string; workspaceId?: string },
+ params: {
+ /** Device clients that may serve the call; see `deviceGateway.executeToolCall`. */
+ clientKinds?: DeviceClient[];
+ deviceId: string;
+ operationId?: string;
+ userId: string;
+ workspaceId?: string;
+ },
toolCall: { apiName: string; arguments: string; identifier: string },
timeout?: number,
): Promise<DeviceToolCallResult> => {
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 2eca45bca91..d3ffd1ab5a0 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -2019,7 +2019,13 @@ export class DeviceGateway {
}
async executeToolCall(
- params: { deviceId: string; operationId?: string; userId: string; workspaceId?: string },
+ params: {
+ clientKinds?: DeviceClient[];
+ deviceId: string;
+ operationId?: string;
+ userId: string;
+ workspaceId?: string;
+ },
toolCall: { apiName: string; arguments: string; identifier: string },
timeout = 30_000,
): Promise<DeviceToolCallResult> {
@@ -2042,16 +2048,7 @@ export class DeviceGateway {
);
try {
- return await client.executeToolCall(
- {
- deviceId: params.deviceId,
- operationId: params.operationId,
- timeout,
- userId: params.userId,
- workspaceId: params.workspaceId,
- },
- toolCall,
- );
+ return await client.executeToolCall({ ...params, timeout }, toolCall);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
log('executeToolCall: error β€” %s', message);
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 9fb894d9355..915eb7489a2 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/auv.test.ts
@@ -29,6 +29,10 @@ vi.mock('@/server/services/deviceGateway/deviceChannels', () => ({
const { auvRuntime } = await import('../auv');
+const computerUse = { ok: true, systemInfo: { supportedTools: [AuvIdentifier] } } as const;
+const noComputerUse = { ok: true, systemInfo: { arch: 'arm64' } } as const;
+const noConnection = { ok: false, reason: 'NO_CAPABLE_CONNECTION' } as const;
+
const baseContext: ToolExecutionContext = {
activeDeviceId: 'device-1',
toolManifestMap: {},
@@ -56,7 +60,9 @@ describe('auvRuntime', () => {
});
it('rejects old clients before forwarding a tool call', async () => {
- readDeviceSystemInfoMock.mockResolvedValueOnce({ ok: true, systemInfo: { arch: 'arm64' } });
+ readDeviceSystemInfoMock
+ .mockResolvedValueOnce(noComputerUse) // desktop
+ .mockResolvedValueOnce(noComputerUse); // cli
const runtime = auvRuntime.factory(baseContext);
await expect(runtime.runCommand({ argv: ['invoke', 'display.list'] })).rejects.toThrow(
'does not support Computer Use',
@@ -80,6 +86,7 @@ describe('auvRuntime', () => {
expect(auvRuntime.identifier).toBe(AuvIdentifier);
expect(executeToolCallMock).toHaveBeenCalledWith(
{
+ clientKinds: ['desktop'],
deviceId: 'device-1',
operationId: 'operation-1',
userId: 'user-1',
@@ -109,7 +116,9 @@ describe('auvRuntime', () => {
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' });
+ readDeviceSystemInfoMock
+ .mockResolvedValueOnce({ ok: false, reason: 'TIMEOUT' })
+ .mockResolvedValueOnce(noConnection);
const runtime = auvRuntime.factory(baseContext);
const result = await runtime.runCommand({ argv: ['invoke', 'display.list'] });
@@ -119,8 +128,10 @@ describe('auvRuntime', () => {
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' });
+ it('does not dispatch to a CLI-only device without --auv and names the flag', async () => {
+ readDeviceSystemInfoMock
+ .mockResolvedValueOnce({ ok: false, reason: 'TIMEOUT' })
+ .mockResolvedValueOnce(noComputerUse);
resolveDeviceClientKindMock.mockResolvedValueOnce('cli-only');
const runtime = auvRuntime.factory(baseContext);
@@ -132,10 +143,13 @@ describe('auvRuntime', () => {
success: false,
});
expect(result.content).toContain('`lh connect` CLI');
+ expect(result.content).toContain('--auv');
});
- it('does not dispatch when the device also runs the CLI, which the gateway prefers', async () => {
- readDeviceSystemInfoMock.mockResolvedValueOnce({ ok: false, reason: 'TIMEOUT' });
+ it('does not dispatch when the desktop is silent and the CLI lacks --auv', async () => {
+ readDeviceSystemInfoMock
+ .mockResolvedValueOnce({ ok: false, reason: 'TIMEOUT' })
+ .mockResolvedValueOnce(noComputerUse);
resolveDeviceClientKindMock.mockResolvedValueOnce('mixed');
const runtime = auvRuntime.factory(baseContext);
@@ -147,11 +161,13 @@ describe('auvRuntime', () => {
success: false,
});
expect(result.content).toContain('TIMEOUT');
- expect(result.content).toContain('stop `lh connect`');
+ expect(result.content).toContain('--auv');
});
it('reports the gateway reason, not a missing capability, when presence is unknown', async () => {
- readDeviceSystemInfoMock.mockResolvedValueOnce({ ok: false, reason: 'DEVICE_NOT_FOUND' });
+ readDeviceSystemInfoMock
+ .mockResolvedValueOnce({ ok: false, reason: 'DEVICE_NOT_FOUND' })
+ .mockResolvedValueOnce({ ok: false, reason: 'DEVICE_NOT_FOUND' });
resolveDeviceClientKindMock.mockResolvedValueOnce('unknown');
const runtime = auvRuntime.factory(baseContext);
@@ -163,4 +179,49 @@ describe('auvRuntime', () => {
expect(result.content).not.toContain('does not support');
});
});
+
+ describe('choosing the client on the device', () => {
+ const dispatchedClientKinds = () => executeToolCallMock.mock.calls[0]?.[0]?.clientKinds;
+
+ // ROOT CAUSE:
+ //
+ // The runtime read the capability only from the desktop app and the tool
+ // routed only to it, so a device running just `lh connect --auv` was told
+ // the CLI cannot run Computer Use.
+ //
+ // The fix asks the CLI when the desktop app does not offer it, and sends
+ // the call to the client that does.
+ it('runs on `lh connect --auv` when the device has no desktop app', async () => {
+ readDeviceSystemInfoMock
+ .mockResolvedValueOnce(noConnection) // desktop
+ .mockResolvedValueOnce(computerUse); // cli
+
+ const result = await auvRuntime
+ .factory(baseContext)
+ .runCommand({ argv: ['invoke', 'display.list'] });
+
+ expect(readDeviceSystemInfoMock).toHaveBeenLastCalledWith('user-1', 'device-1', undefined, {
+ clientKinds: ['cli'],
+ });
+ expect(dispatchedClientKinds()).toEqual(['cli']);
+ expect(result).toEqual({ content: 'ok', success: true });
+ });
+
+ it('prefers the desktop app when both clients offer Computer Use', async () => {
+ await auvRuntime.factory(baseContext).runCommand({ argv: ['invoke', 'display.list'] });
+
+ expect(readDeviceSystemInfoMock).toHaveBeenCalledTimes(1);
+ expect(dispatchedClientKinds()).toEqual(['desktop']);
+ });
+
+ it('falls back to `lh connect --auv` beside a desktop app that predates Computer Use', async () => {
+ readDeviceSystemInfoMock
+ .mockResolvedValueOnce(noComputerUse) // desktop
+ .mockResolvedValueOnce(computerUse); // cli
+
+ await auvRuntime.factory(baseContext).runCommand({ argv: ['invoke', 'display.list'] });
+
+ expect(dispatchedClientKinds()).toEqual(['cli']);
+ });
+ });
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/auv.ts b/apps/server/src/services/toolExecution/serverRuntimes/auv.ts
index d9f91bc0144..4039883b042 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/auv.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/auv.ts
@@ -1,4 +1,5 @@
-import { AuvApiName, AuvIdentifier, AuvManifest } from '@lobechat/builtin-tool-auv';
+import { AuvApiName, AuvIdentifier } from '@lobechat/builtin-tool-auv';
+import type { DeviceClient } from '@lobechat/types';
import { deviceGateway } from '@/server/services/deviceGateway';
import { executeAuthorizedDeviceToolCall } from '@/server/services/deviceGateway/authorizedToolCall';
@@ -13,10 +14,13 @@ import { withoutDeviceReplay } from './withoutDeviceReplay';
export const COMPUTER_USE_DEVICE_UNAVAILABLE_ERROR_CODE = 'COMPUTER_USE_DEVICE_UNAVAILABLE';
+const CLI_WITHOUT_COMPUTER_USE =
+ 'the `lh connect` CLI, which offers Computer Use only when started with `--auv <binary>`';
+
/**
- * 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.
+ * The capability check could not run (the desktop app did not answer it), no
+ * `lh connect` on the device offers Computer Use, 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 = (
@@ -25,15 +29,14 @@ const buildUnverifiedDeviceResult = (
) => {
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.`
+ ? `The active device (${deviceId}) is connected only through ${CLI_WITHOUT_COMPUTER_USE}. ` +
+ `Nothing was run. Ask the user to open the LobeHub desktop app on that machine, or to ` +
+ `restart \`lh connect\` with \`--auv\`, 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: the ` +
+ `desktop app did not answer the capability check (${reason}), and the device also runs ` +
+ `${CLI_WITHOUT_COMPUTER_USE}. Nothing was run. Retry shortly; if it keeps failing, ask ` +
+ `the user to check that the LobeHub desktop app is running and connected.`
: `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 ` +
@@ -57,7 +60,8 @@ export const auvRuntime: ServerRuntimeRegistration = {
return {
/**
- * Proxies one typed AUV CLI command to the active desktop device.
+ * Proxies one typed AUV CLI command to the client on the active device
+ * that runs Computer Use: the desktop app, or `lh connect --auv`.
*
* Triggering workflow:
*
@@ -69,65 +73,74 @@ export const auvRuntime: ServerRuntimeRegistration = {
* - Server-side builtin tool execution for `lobe-computer-use/runCommand`
*
* Downstream:
- * - {@link deviceGateway.readDeviceSystemInfo}
- * - {@link resolveDeviceClientKind} when the device does not answer that read
- * - {@link deviceGateway.executeToolCall}
+ * - {@link deviceGateway.readDeviceSystemInfo}, per client kind
+ * - {@link resolveDeviceClientKind} when the desktop app does not answer that read
+ * - {@link deviceGateway.executeToolCall}, constrained to the chosen client kind
*/
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`):
- // 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(
+ const dispatch = async (clientKinds: DeviceClient[]) =>
+ withoutDeviceReplay(
+ await executeAuthorizedDeviceToolCall(
+ context.serverDB,
+ {
+ clientKinds,
+ deviceId: context.activeDeviceId!,
+ operationId: context.operationId,
+ userId: context.userId!,
+ workspaceId,
+ },
+ {
+ apiName: AuvApiName.runCommand,
+ arguments: JSON.stringify(args ?? {}),
+ identifier: AuvIdentifier,
+ },
+ context.executionTimeoutMs,
+ ),
+ );
+ // Ask each client separately: one device can hold the desktop app and
+ // `lh connect` at once, and only a client that lists the capability can
+ // serve the call. A gateway that predates `clientKinds` ignores it.
+ const readFrom = (kind: DeviceClient) =>
+ deviceGateway.readDeviceSystemInfo(
context.userId!,
context.activeDeviceId!,
workspaceId,
+ { clientKinds: [kind] },
);
- if (clientKind !== 'desktop') {
- return buildUnverifiedDeviceResult(context.activeDeviceId!, {
- clientKind,
- reason: read.reason,
- });
- }
+
+ // The desktop app comes first: it owns its daemon and the OS permissions.
+ const desktop = await readFrom('desktop');
+ if (desktop.ok && desktop.systemInfo.supportedTools?.includes(AuvIdentifier)) {
+ return dispatch(['desktop']);
+ }
+ const cli = await readFrom('cli');
+ if (cli.ok && cli.systemInfo.supportedTools?.includes(AuvIdentifier)) {
+ return dispatch(['cli']);
}
- const result = await executeAuthorizedDeviceToolCall(
- context.serverDB,
- {
- deviceId: context.activeDeviceId!,
- operationId: context.operationId,
- userId: context.userId!,
- workspaceId,
- },
- {
- apiName: AuvApiName.runCommand,
- arguments: JSON.stringify(args ?? {}),
- identifier: AuvIdentifier,
- },
- context.executionTimeoutMs,
+ // An answer without the capability is an old desktop app.
+ if (desktop.ok) {
+ throw new Error(
+ 'The selected device does not support Computer Use. Update the desktop app and reconnect.',
+ );
+ }
+
+ // No desktop 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.
+ const clientKind = await resolveDeviceClientKind(
+ context.userId!,
+ context.activeDeviceId!,
+ workspaceId,
);
+ if (clientKind === 'desktop') return dispatch(['desktop']);
- return withoutDeviceReplay(result);
+ return buildUnverifiedDeviceResult(context.activeDeviceId!, {
+ clientKind,
+ reason: desktop.reason,
+ });
},
};
},
diff --git a/packages/builtin-tool-auv/src/manifest.ts b/packages/builtin-tool-auv/src/manifest.ts
index fe7467b40ba..f40c60903a4 100644
--- a/packages/builtin-tool-auv/src/manifest.ts
+++ b/packages/builtin-tool-auv/src/manifest.ts
@@ -4,8 +4,9 @@ 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'],
+ // The desktop app always can; `lh connect` only when started with `--auv`. The
+ // server runtime picks the client that reports the capability (see `auvRuntime`).
+ deviceClients: ['desktop', 'cli'],
executors: ['client', 'server'],
api: [
{
diff --git a/packages/device-control/package.json b/packages/device-control/package.json
index b1645aa442f..fc0bd71711c 100644
--- a/packages/device-control/package.json
+++ b/packages/device-control/package.json
@@ -5,6 +5,7 @@
"sideEffects": false,
"exports": {
".": "./src/index.ts",
+ "./computer-use": "./src/computerUse.ts",
"./file-preview": "./src/filePreview.ts",
"./metrics": "./src/metrics/index.ts",
"./project-file-index": "./src/projectFileIndex.ts",
diff --git a/packages/device-control/src/computerUse.test.ts b/packages/device-control/src/computerUse.test.ts
new file mode 100644
index 00000000000..76bb273b986
--- /dev/null
+++ b/packages/device-control/src/computerUse.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { normalizeAuvArgv, runAuvCommand, toAuvToolOutput } from './computerUse';
+
+describe('normalizeAuvArgv', () => {
+ it('adds --json to an invoke command', () => {
+ expect(normalizeAuvArgv({ argv: ['invoke', 'display.capture'] })).toEqual([
+ 'invoke',
+ 'display.capture',
+ '--json',
+ ]);
+ });
+
+ it('leaves help requests as text', () => {
+ expect(normalizeAuvArgv({ argv: ['invoke', '--help'] })).toEqual(['invoke', '--help']);
+ expect(normalizeAuvArgv({ argv: ['invoke', 'display.capture', '-h'] })).toEqual([
+ 'invoke',
+ 'display.capture',
+ '-h',
+ ]);
+ });
+
+ it.each([
+ [['serve', '--help'], 'Only "auv invoke" commands are allowed'],
+ [['invoke'], 'AUV argv must include "invoke" and a command or --help'],
+ [['invoke', 'display.capture', '--store-root', '/tmp/other'], 'managed by LobeHub'],
+ [['invoke', 'display.capture', '--store-root=/tmp/other'], 'managed by LobeHub'],
+ [['invoke', '; rm -rf /'], 'Invalid AUV invoke command'],
+ [['invoke', 'display.capture', 'a\0b'], 'NUL bytes'],
+ ])('rejects %j', (argv, message) => {
+ expect(() => normalizeAuvArgv({ argv })).toThrow(message);
+ });
+});
+
+describe('runAuvCommand', () => {
+ it('parses JSON output and keeps the caller argv', async () => {
+ const exec = vi.fn().mockResolvedValue({ stderr: '', stdout: '{"run_id":"run-1"}\n' });
+
+ await expect(
+ runAuvCommand(
+ { argv: ['invoke', 'display.list'] },
+ ['invoke', 'display.list', '--json'],
+ exec,
+ ),
+ ).resolves.toEqual({
+ argv: ['invoke', 'display.list'],
+ exitCode: 0,
+ output: { run_id: 'run-1' },
+ });
+ expect(exec).toHaveBeenCalledWith(['invoke', 'display.list', '--json']);
+ });
+
+ it('returns a nonzero exit as a result with its structured output', async () => {
+ const exec = vi.fn().mockRejectedValue(
+ Object.assign(new Error('exit 2'), {
+ code: 2,
+ stderr: 'window not found\n',
+ stdout: '{"error":"window_not_found"}',
+ }),
+ );
+
+ await expect(
+ runAuvCommand({ argv: ['invoke', 'x.y'] }, ['invoke', 'x.y'], exec),
+ ).resolves.toEqual({
+ argv: ['invoke', 'x.y'],
+ exitCode: 2,
+ output: { error: 'window_not_found' },
+ stderr: 'window not found',
+ });
+ });
+
+ it('rethrows spawn failures and timeouts', async () => {
+ const spawnFailure = Object.assign(new Error('spawn ENOENT'), { code: 'ENOENT' });
+ await expect(
+ runAuvCommand({ argv: ['invoke', 'x.y'] }, ['invoke', 'x.y'], () =>
+ Promise.reject(spawnFailure),
+ ),
+ ).rejects.toBe(spawnFailure);
+
+ const timeout = Object.assign(new Error('killed'), { code: 1, killed: true });
+ await expect(
+ runAuvCommand({ argv: ['invoke', 'x.y'] }, ['invoke', 'x.y'], () => Promise.reject(timeout)),
+ ).rejects.toBe(timeout);
+ });
+});
+
+describe('toAuvToolOutput', () => {
+ it('marks a nonzero exit as a failed tool call and keeps the result as state', () => {
+ const result = { argv: ['invoke', 'x.y'], exitCode: 3, output: null, stderr: 'boom' };
+
+ expect(toAuvToolOutput(result)).toEqual({
+ content: JSON.stringify(result),
+ error: 'boom',
+ state: result,
+ success: false,
+ });
+ });
+});
diff --git a/packages/device-control/src/computerUse.ts b/packages/device-control/src/computerUse.ts
new file mode 100644
index 00000000000..8b88574b0b2
--- /dev/null
+++ b/packages/device-control/src/computerUse.ts
@@ -0,0 +1,133 @@
+/**
+ * The device side of the `lobe-computer-use/runCommand` tool: which AUV
+ * command lines a device accepts, how one runs, and what the tool returns.
+ * Shared by the desktop app and `lh connect` so both devices expose the same
+ * contract.
+ */
+
+/**
+ * Tool identifier a device lists in `supportedTools` when it can run Computer
+ * Use. Mirrors `AuvIdentifier` in `@lobechat/builtin-tool-auv`, which device
+ * runtimes do not import because it carries the React inspector.
+ */
+export const COMPUTER_USE_IDENTIFIER = 'lobe-computer-use';
+
+/** Arguments of one `runCommand` call, after the `auv` executable. */
+export interface AuvRunCommandParams {
+ argv: string[];
+}
+
+export interface AuvRunCommandResult {
+ argv: string[];
+ /** Process exit status, not verification of the requested UI effect. */
+ exitCode: number;
+ output: unknown;
+ stderr?: string;
+}
+
+/** Runs the AUV CLI once; rejects with an `execFile` error on a nonzero exit. */
+export type AuvCliExec = (argv: string[]) => Promise<{ stderr: string; stdout: string }>;
+
+const MAX_CLI_ARGUMENTS = 128;
+const MAX_CLI_ARGUMENT_LENGTH = 16_384;
+const AUV_COMMAND_ID = /^[a-z][A-Za-z0-9]*(?:\.[A-Za-z][A-Za-z0-9]*)+$/;
+
+/**
+ * Validates the model's argv and returns the command line to run: only
+ * `auv invoke <command>` or its help, never a caller-chosen `--store-root`, and
+ * `--json` added unless help is requested.
+ */
+export const normalizeAuvArgv = (params: AuvRunCommandParams): string[] => {
+ if (!Array.isArray(params.argv)) throw new Error('AUV argv must be an array');
+ if (params.argv.length < 2) {
+ throw new Error('AUV argv must include "invoke" and a command or --help');
+ }
+ if (params.argv.length > MAX_CLI_ARGUMENTS) {
+ throw new Error(`AUV argv cannot contain more than ${MAX_CLI_ARGUMENTS} arguments`);
+ }
+
+ const argv = params.argv.map((argument) => {
+ if (typeof argument !== 'string') throw new Error('Every AUV argument must be a string');
+ if (argument.includes('\0')) throw new Error('AUV arguments cannot contain NUL bytes');
+ if (argument.length > MAX_CLI_ARGUMENT_LENGTH) {
+ throw new Error(`AUV arguments cannot exceed ${MAX_CLI_ARGUMENT_LENGTH} characters`);
+ }
+ return argument;
+ });
+
+ if (argv[0] !== 'invoke') {
+ throw new Error('Only "auv invoke" commands are allowed');
+ }
+ if (
+ argv.some((argument) => argument === '--store-root' || argument.startsWith('--store-root='))
+ ) {
+ throw new Error('AUV --store-root is managed by LobeHub');
+ }
+
+ const command = argv[1]!;
+ if (
+ command !== '--help' &&
+ command !== '-h' &&
+ command !== 'help' &&
+ !AUV_COMMAND_ID.test(command)
+ ) {
+ throw new Error(`Invalid AUV invoke command: ${command}`);
+ }
+
+ const isHelp = argv.includes('--help') || argv.includes('-h') || command === 'help';
+ if (!isHelp && !argv.includes('--json')) argv.push('--json');
+ return argv;
+};
+
+const parseCliOutput = (stdout: string): unknown => {
+ const output = stdout.trim();
+ if (!output) return null;
+
+ try {
+ return JSON.parse(output);
+ } catch {
+ return output;
+ }
+};
+
+/**
+ * Runs a command line from {@link normalizeAuvArgv} and keeps AUV's structured
+ * failure: `execFile` rejects a nonzero exit even when stdout holds the failure
+ * envelope, so that exit becomes a result. Spawn failures and timeouts still throw.
+ */
+export const runAuvCommand = async (
+ params: AuvRunCommandParams,
+ argv: string[],
+ exec: AuvCliExec,
+): Promise<AuvRunCommandResult> => {
+ let stdout: string;
+ let stderr: string;
+ let exitCode = 0;
+ try {
+ ({ stderr, stdout } = await exec(argv));
+ } catch (error) {
+ const failure = error as { code?: unknown; killed?: boolean; stderr?: string; stdout?: string };
+ if (typeof failure?.code !== 'number' || failure.killed) throw error;
+ exitCode = failure.code;
+ stdout = failure.stdout ?? '';
+ stderr = failure.stderr ?? '';
+ }
+ const stderrOutput = stderr.trim();
+
+ return {
+ argv: [...params.argv],
+ exitCode,
+ output: parseCliOutput(stdout),
+ ...(stderrOutput && { stderr: stderrOutput }),
+ };
+};
+
+/** The gateway tool-call result for one `runCommand` run. */
+export const toAuvToolOutput = (result: AuvRunCommandResult) => ({
+ content: JSON.stringify(result),
+ ...(result.exitCode !== 0 && {
+ error: result.stderr || `Computer Use exited with code ${result.exitCode}`,
+ }),
+ state: result,
+ success: result.exitCode === 0,
+});
diff --git a/packages/device-gateway-client/src/http.clientKinds.test.ts b/packages/device-gateway-client/src/http.clientKinds.test.ts
new file mode 100644
index 00000000000..1fb98b1da7f
--- /dev/null
+++ b/packages/device-gateway-client/src/http.clientKinds.test.ts
@@ -0,0 +1,131 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GatewayHttpClient } from './http';
+
+describe('GatewayHttpClient clientKinds', () => {
+ let client: GatewayHttpClient;
+
+ beforeEach(() => {
+ client = new GatewayHttpClient({
+ gatewayUrl: 'https://gateway.test.com',
+ serviceToken: 'test-service-token',
+ });
+ vi.stubGlobal('fetch', vi.fn());
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ function mockFetch(response: Partial<Response>) {
+ const res = {
+ json: vi.fn().mockResolvedValue(response.json ? response.json() : {}),
+ ok: response.ok ?? true,
+ status: response.status ?? 200,
+ text: vi.fn().mockResolvedValue(''),
+ ...response,
+ };
+ // Re-bind json/text if the response object had them
+ if ('json' in response && typeof response.json === 'function') {
+ res.json = response.json;
+ }
+ if ('text' in response && typeof response.text === 'function') {
+ res.text = response.text;
+ }
+ vi.mocked(fetch).mockResolvedValue(res as any);
+ return res;
+ }
+
+ 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('sends clientKinds given by the caller instead of resolving them from the tool', async () => {
+ const { kindsClient, resolveClientKinds } = withResolver();
+ mockFetch({ json: vi.fn().mockResolvedValue({ content: 'ok', success: true }), ok: true });
+
+ await kindsClient.executeToolCall(
+ { clientKinds: ['cli'], deviceId: 'device-1', userId: 'user-1' },
+ { apiName: 'runCommand', arguments: '{}', identifier: 'lobe-computer-use' },
+ );
+
+ expect(bodyOf()).toMatchObject({ clientKinds: ['cli'] });
+ expect(resolveClientKinds).not.toHaveBeenCalled();
+ });
+
+ 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' });
+ });
+ });
+});
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index 73899b7ffc5..7e3650de5ba 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -795,86 +795,6 @@ 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 27e3f64a3bc..dfae4f1a396 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -145,6 +145,11 @@ export class GatewayHttpClient {
async executeToolCall(
params: {
+ /**
+ * The device clients that may serve this call, when the caller already
+ * knows; otherwise `resolveClientKinds` decides from the tool identifier.
+ */
+ clientKinds?: DeviceClient[];
deviceId?: string;
operationId?: string;
timeout?: number;
@@ -184,6 +189,7 @@ export class GatewayHttpClient {
private async postToolCall(
params: {
+ clientKinds?: DeviceClient[];
deviceId?: string;
operationId?: string;
timeout?: number;
@@ -207,11 +213,13 @@ export class GatewayHttpClient {
res = await this.post(
'/api/device/tool-call',
{
- clientKinds: this.clientKindsFor({
- identifier: toolCall.identifier,
- kind: 'tool',
- type: toolCall.type ?? 'tool',
- }),
+ clientKinds: params.clientKinds?.length
+ ? params.clientKinds
+ : this.clientKindsFor({
+ identifier: toolCall.identifier,
+ kind: 'tool',
+ type: toolCall.type ?? 'tool',
+ }),
deviceId: params.deviceId,
operationId: params.operationId,
timeout: params.timeout,