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): run the lobe-browser tool on lh connect devices via agent-browser (#21422)

Lobehub Coder2a1cee573c0b
diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.ts
index a2e082b3218..f0501833883 100644
--- a/apps/cli/src/commands/connect.test.ts
+++ b/apps/cli/src/commands/connect.test.ts
@@ -1,4 +1,4 @@
-import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
@@ -746,9 +746,12 @@ describe('connect command', () => {
auvBinary = path.join(auvDir, 'auv');
await writeFile(auvBinary, `#!/bin/sh\nprintf '{"ok":true}'\n`);
await chmod(auvBinary, 0o755);
+ // Keep a developer's own `agent-browser` on PATH out of `supportedTools`.
+ vi.stubEnv('PATH', [auvDir, '/usr/bin', '/bin'].join(path.delimiter));
});
afterEach(async () => {
+ vi.unstubAllEnvs();
await rm(auvDir, { force: true, recursive: true });
});
@@ -807,6 +810,101 @@ describe('connect command', () => {
expect.arrayContaining(['--auv', auvBinary]),
);
});
+
+ describe.skipIf(process.platform === 'win32')('browser tool', () => {
+ let binDir: string;
+ let binary: string;
+
+ beforeEach(async () => {
+ binDir = await mkdtemp(path.join(os.tmpdir(), 'lh-connect-browser-'));
+ binary = path.join(binDir, 'agent-browser');
+ // Records its argv, stdin and AGENT_BROWSER_* env, then answers like
+ // `agent-browser --json batch`.
+ await writeFile(
+ binary,
+ `#!/bin/sh\nprintf '%s ' "$@" > "$0.argv"\nenv | grep '^AGENT_BROWSER_' > "$0.env"\ncat > "$0.stdin"\nprintf '[{"command":["open"],"error":null,"result":{"title":"T","url":"https://e.com/"},"success":true}]'\n`,
+ );
+ await chmod(binary, 0o755);
+ vi.stubEnv('PATH', `${binDir}${path.delimiter}/bin${path.delimiter}/usr/bin`);
+ });
+
+ afterEach(async () => {
+ vi.unstubAllEnvs();
+ await rm(binDir, { force: true, recursive: true });
+ });
+
+ const navigateCall = {
+ requestId: 'req-browser',
+ toolCall: {
+ apiName: 'navigate',
+ arguments: JSON.stringify({ __topicId: 'tpc_1', url: 'https://e.com' }),
+ identifier: 'lobe-browser',
+ },
+ type: 'tool_call_request',
+ };
+
+ it('advertises the browser tool from agent-browser on PATH and runs calls with it', async () => {
+ // A user's own agent-browser profile must not reach the model's browser.
+ vi.stubEnv('AGENT_BROWSER_PROFILE', 'Default');
+ await createProgram().parseAsync(['node', 'test', 'connect']);
+
+ await clientEventHandlers['system_info_request']?.({
+ requestId: 'r',
+ type: 'system_info_request',
+ });
+ expect(lastSentSystemInfoResponse.result.systemInfo.supportedTools).toEqual([
+ 'lobe-browser',
+ ]);
+
+ await clientEventHandlers['tool_call_request']?.(navigateCall);
+ expect(executeToolCall).not.toHaveBeenCalled();
+ expect(lastSentToolResponse.result).toMatchObject({
+ state: { title: 'T', url: 'https://e.com/' },
+ success: true,
+ });
+ const argv = await readFile(`${binary}.argv`, 'utf8');
+ expect(argv).toMatch(
+ /^--namespace lobehub --config \S+agent-browser\.json --headed false --idle-timeout 10m --session lobehub-topic-tpc_1 --json batch --bail $/,
+ );
+ expect(await readFile(`${binary}.env`, 'utf8')).toBe('');
+ expect(JSON.parse(await readFile(`${binary}.stdin`, 'utf8'))).toEqual([
+ ['open', 'https://e.com'],
+ ]);
+ });
+
+ it('rejects browser calls when no agent-browser is available', async () => {
+ vi.stubEnv('PATH', '/nonexistent');
+ 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']?.(navigateCall);
+ expect(executeToolCall).not.toHaveBeenCalled();
+ expect(lastSentToolResponse.result).toMatchObject({
+ error: expect.stringContaining('agent-browser'),
+ success: false,
+ });
+ });
+
+ it('passes an explicit --agent-browser to the daemon child', async () => {
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'connect',
+ '--daemon',
+ '--agent-browser',
+ path.relative(process.cwd(), binary),
+ ]);
+
+ expect(vi.mocked(spawnDaemon).mock.calls[0]?.[0]).toEqual(
+ expect.arrayContaining(['--agent-browser', binary]),
+ );
+ });
+ });
});
describe('--daemon flag', () => {
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index 69086e6a699..d0a30a11053 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -11,6 +11,7 @@ import {
executeDeviceRpc,
pushMetrics,
} from '@lobechat/device-control';
+import { BROWSER_IDENTIFIER } from '@lobechat/device-control/agent-browser';
import { COMPUTER_USE_IDENTIFIER } from '@lobechat/device-control/computer-use';
import type {
AgentRunRequestMessage,
@@ -80,6 +81,7 @@ import {
resolveDeviceMetricsBacklogPath,
} from '../settings';
import { executeToolCall } from '../tools';
+import { closeBrowserSessions, executeBrowserCall, resolveBrowserDevice } from '../tools/browser';
import { executeComputerUseCall, resolveComputerUseDevice } from '../tools/computerUse';
import { cleanupAllProcesses, getActiveShellCount } from '../tools/shell';
import { log, setVerbose } from '../utils/logger';
@@ -90,6 +92,8 @@ const SHUTDOWN_METRICS_FLUSH_MS = 3000;
const CONNECT_SERVICE_NAME = CLI_CONNECT_SERVICE_NAME;
interface ConnectOptions {
+ /** `agent-browser` binary for the browser tool; see `resolveBrowserDevice`. */
+ agentBrowser?: string;
/** `auv` binary that runs Computer Use on this device; see `resolveComputerUseDevice`. */
auv?: string;
daemon?: boolean;
@@ -118,6 +122,10 @@ export function registerConnectCommand(program: Command) {
'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(
+ '--agent-browser <binary>',
+ 'Run the browser tool with this agent-browser binary (default: agent-browser on PATH)',
+ )
.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')
@@ -204,6 +212,10 @@ export function registerConnectCommand(program: Command) {
.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(
+ '--agent-browser <binary>',
+ 'Run the browser tool with this agent-browser binary (default: agent-browser on PATH)',
+ )
.option('-v, --verbose', 'Enable verbose logging')
.action(async (options: ConnectOptions) => {
const wasStopped = stopDaemon();
@@ -350,6 +362,7 @@ function buildDaemonArgs(options: ConnectOptions): string[] {
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.agentBrowser) args.push('--agent-browser', path.resolve(options.agentBrowser));
if (options.verbose) args.push('--verbose');
return args;
@@ -394,6 +407,12 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
process.exit(1);
throw err;
});
+ const browser = await resolveBrowserDevice(options.agentBrowser).catch((err: Error) => {
+ log.error(err.message);
+ process.exit(1);
+ throw err;
+ });
+ if (browser) info(`Browser tool enabled via ${browser.binaryPath}`);
// Workspace enrollment: the device joins a workspace pool (reachable by all
// members) instead of the personal pool. It authenticates with a minted
@@ -547,6 +566,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
const nativeRuntimes = createRuntimeProbeCache(probeNativeRuntimes);
const handlerContext: GatewayHandlerContext = {
+ browser,
computerUse,
deps: deviceControlDeps,
error,
@@ -917,7 +937,10 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
// (bounded) before the socket closes, so the device page doesn't show the
// final minutes as "not running".
const shutdown = async () => {
- await metricsSampler?.stop({ flushTimeoutMs: SHUTDOWN_METRICS_FLUSH_MS });
+ await Promise.all([
+ metricsSampler?.stop({ flushTimeoutMs: SHUTDOWN_METRICS_FLUSH_MS }),
+ closeBrowserSessions(browser),
+ ]);
cleanup();
process.exit(0);
};
@@ -973,6 +996,8 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
/** Everything a gateway connection's request handlers need from the host process. */
interface GatewayHandlerContext {
+ /** Present when an `agent-browser` binary enabled the browser tool on this device. */
+ browser?: Awaited<ReturnType<typeof resolveBrowserDevice>>;
/** Present when `--auv` enabled Computer Use on this device. */
computerUse?: Awaited<ReturnType<typeof resolveComputerUseDevice>>;
deps: DeviceControlDeps;
@@ -998,13 +1023,22 @@ function bindGatewayClientHandlers(
ctx: GatewayHandlerContext,
connectionWorkspaceId?: string,
) {
- const { computerUse, deps, error, getAuth, info, isDaemonChild, maintenance, recordRequest } =
- ctx;
+ const {
+ browser,
+ computerUse,
+ deps,
+ error,
+ getAuth,
+ info,
+ isDaemonChild,
+ maintenance,
+ recordRequest,
+ } = ctx;
// Handle system info requests
client.on('system_info_request', async (request: SystemInfoRequestMessage) => {
info(`Received system_info_request: requestId=${request.requestId}`);
- const systemInfo = await collectSystemInfo(ctx.nativeRuntimes, computerUse);
+ const systemInfo = await collectSystemInfo(ctx.nativeRuntimes, computerUse, browser);
client.sendSystemInfoResponse({
requestId: request.requestId,
result: { success: true, systemInfo },
@@ -1029,10 +1063,13 @@ function bindGatewayClientHandlers(
const startedAt = performance.now();
const result = await maintenance
.run(() =>
- // Computer Use's `runCommand` shares its apiName with the shell tool.
+ // Computer Use's `runCommand` shares its apiName with the shell tool, and
+ // the browser's apis (`click`, `screenshot`, …) are routed by identifier too.
toolCall.identifier === COMPUTER_USE_IDENTIFIER
? executeComputerUseCall(computerUse, toolCall.apiName, toolCall.arguments, timeout)
- : executeToolCall(toolCall.apiName, toolCall.arguments, timeout, getAuth()),
+ : toolCall.identifier === BROWSER_IDENTIFIER
+ ? executeBrowserCall(browser, toolCall.apiName, toolCall.arguments, timeout)
+ : executeToolCall(toolCall.apiName, toolCall.arguments, timeout, getAuth()),
)
.catch((err: Error) => ({
content: '',
diff --git a/apps/cli/src/device/systemInfo.ts b/apps/cli/src/device/systemInfo.ts
index 4984daeb962..0866c5436f4 100644
--- a/apps/cli/src/device/systemInfo.ts
+++ b/apps/cli/src/device/systemInfo.ts
@@ -1,6 +1,7 @@
import os from 'node:os';
import path from 'node:path';
+import { BROWSER_IDENTIFIER } from '@lobechat/device-control/agent-browser';
import { COMPUTER_USE_IDENTIFIER } from '@lobechat/device-control/computer-use';
import type { DeviceSystemInfo } from '@lobechat/device-gateway-client';
import { resolveHeteroSpawnCommand } from '@lobechat/heterogeneous-agents/resolveCliCommand';
@@ -10,6 +11,7 @@ import { getShellInfo } from '@lobechat/local-file-shell';
import { CLI_CONFIG_DIR_NAME } from '../constants/identity';
import { cliVersion } from '../pkg';
+import type { BrowserDevice } from '../tools/browser';
import type { ComputerUseDevice } from '../tools/computerUse';
/**
@@ -90,7 +92,12 @@ export async function probeNativeRuntimes(): Promise<string[]> {
export async function collectSystemInfo(
nativeRuntimes: RuntimeProbeCache,
computerUse?: ComputerUseDevice,
+ browser?: BrowserDevice,
): Promise<DeviceSystemInfo> {
+ const supportedTools = [
+ ...(computerUse ? [COMPUTER_USE_IDENTIFIER] : []),
+ ...(browser ? [BROWSER_IDENTIFIER] : []),
+ ];
const home = os.homedir();
const platform = process.platform;
const videosDir = platform === 'linux' ? 'Videos' : 'Movies';
@@ -106,7 +113,7 @@ export async function collectSystemInfo(
musicPath: path.join(home, 'Music'),
picturesPath: path.join(home, 'Pictures'),
supportedAgentRuntimes: await nativeRuntimes.get(),
- ...(computerUse && { supportedTools: [COMPUTER_USE_IDENTIFIER] }),
+ ...(supportedTools.length > 0 && { supportedTools }),
userDataPath: path.join(home, CLI_CONFIG_DIR_NAME),
videosPath: path.join(home, videosDir),
workingDirectory: process.cwd(),
diff --git a/apps/cli/src/tools/browser.test.ts b/apps/cli/src/tools/browser.test.ts
new file mode 100644
index 00000000000..a8d31a54d23
--- /dev/null
+++ b/apps/cli/src/tools/browser.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+
+import { toCmdShellArgv } from './browser';
+
+// Windows starts an npm `.cmd` shim only through cmd.exe, where Node joins argv
+// into one command line: an unquoted temp path with a space split into two
+// arguments, and cmd metacharacters would be interpreted.
+describe('toCmdShellArgv', () => {
+ it('quotes the binary and every argument', () => {
+ expect(
+ toCmdShellArgv('C:\\Program Files\\nodejs\\agent-browser.cmd', [
+ '--config',
+ 'C:\\Users\\John Doe\\AppData\\Local\\Temp\\lh-browser-x\\agent-browser.json',
+ '--session',
+ 'lobehub-topic-tpc_1',
+ ]),
+ ).toEqual({
+ args: [
+ '"--config"',
+ '"C:\\Users\\John Doe\\AppData\\Local\\Temp\\lh-browser-x\\agent-browser.json"',
+ '"--session"',
+ '"lobehub-topic-tpc_1"',
+ ],
+ command: '"C:\\Program Files\\nodejs\\agent-browser.cmd"',
+ });
+ });
+
+ it.each(['a"&calc', '%PATH%', 'x!y!', 'a^b', 'a\r\nb'])('refuses %j', (arg) => {
+ expect(() => toCmdShellArgv('agent-browser.cmd', ['--session', arg])).toThrow(
+ 'Unsafe argument',
+ );
+ });
+});
diff --git a/apps/cli/src/tools/browser.ts b/apps/cli/src/tools/browser.ts
new file mode 100644
index 00000000000..a6cca457be4
--- /dev/null
+++ b/apps/cli/src/tools/browser.ts
@@ -0,0 +1,215 @@
+import { spawn } from 'node:child_process';
+import { constants } from 'node:fs';
+import { access, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { type AgentBrowserExec, runAgentBrowserCall } from '@lobechat/device-control/agent-browser';
+
+/** How this device runs the browser tool: an `agent-browser` binary. */
+export interface BrowserDevice {
+ binaryPath: string;
+}
+
+// Covers a slow first launch of the browser plus a page load.
+const DEFAULT_TIMEOUT_MS = 90_000;
+const MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
+// Topic sessions nobody drives any more shut their browser down on their own.
+const IDLE_TIMEOUT = '10m';
+const CLOSE_TIMEOUT_MS = 10_000;
+/** Keeps LobeHub's daemons and sessions apart from the user's own agent-browser use. */
+const NAMESPACE = 'lobehub';
+
+/**
+ * The user's agent-browser setup must not reach the model: a profile, saved
+ * state, CDP target, cloud provider or headed mode from
+ * `~/.agent-browser/config.json`, `./agent-browser.json` or `AGENT_BROWSER_*`
+ * would hand it a signed-in or visible browser, while the tool promises a
+ * clean headless one. So every run gets an empty config, no `AGENT_BROWSER_*`
+ * variables, and explicit headless settings.
+ */
+const isolatedEnv = () =>
+ Object.fromEntries(
+ Object.entries(process.env).filter(([key]) => !key.startsWith('AGENT_BROWSER_')),
+ );
+
+const isolationArgs = (configPath: string) => [
+ '--namespace',
+ NAMESPACE,
+ '--config',
+ configPath,
+ '--headed',
+ 'false',
+ '--idle-timeout',
+ IDLE_TIMEOUT,
+];
+
+/** cmd.exe expands or splits on these even inside double quotes. */
+const CMD_UNSAFE = /["%!^\r\n]/;
+
+/**
+ * argv for a `.cmd` shim, which Windows only starts through cmd.exe. With
+ * `shell: true` Node joins argv into one command line, so every element is
+ * double-quoted (the temp `--config` path can contain spaces) and one that
+ * cmd.exe would still interpret is refused rather than escaped. Only the
+ * sanitized session name and our own temp paths reach argv; page text and
+ * other model input travel over stdin.
+ */
+export const toCmdShellArgv = (binaryPath: string, args: string[]) => {
+ const quoted = [binaryPath, ...args].map((arg) => {
+ if (CMD_UNSAFE.test(arg)) throw new Error(`Unsafe argument for agent-browser: ${arg}`);
+ return `"${arg}"`;
+ });
+ return { args: quoted.slice(1), command: quoted[0] };
+};
+
+const spawnAgentBrowser = (binaryPath: string, args: string[], timeoutMs: number) => {
+ const viaShell = process.platform === 'win32' && /\.(?:cmd|bat)$/i.test(binaryPath);
+ const argv = viaShell ? toCmdShellArgv(binaryPath, args) : { args, command: binaryPath };
+ return spawn(argv.command, argv.args, {
+ cwd: os.tmpdir(),
+ env: isolatedEnv(),
+ shell: viaShell,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ timeout: timeoutMs,
+ windowsHide: true,
+ });
+};
+
+const isExecutableFile = async (filePath: string) => {
+ const stats = await stat(filePath).catch(() => undefined);
+ if (!stats?.isFile()) return false;
+ return access(filePath, constants.X_OK).then(
+ () => true,
+ () => false,
+ );
+};
+
+const findOnPath = async (name: string): Promise<string | undefined> => {
+ // A real `.exe` needs no shell; the npm `.cmd` shim is the fallback.
+ const exts = process.platform === 'win32' ? ['.exe', '.cmd', ''] : [''];
+ for (const dir of (process.env.PATH ?? '').split(path.delimiter)) {
+ if (!dir) continue;
+ for (const ext of exts) {
+ const candidate = path.join(dir, name + ext);
+ if (await isExecutableFile(candidate)) return candidate;
+ }
+ }
+ return undefined;
+};
+
+/**
+ * Enables the `lobe-browser` tool for `lh connect`. `--agent-browser <binary>`
+ * names the binary and fails if it is missing; otherwise an `agent-browser` on
+ * PATH is used, and without one the device does not advertise the tool.
+ *
+ * The browser is headless with a clean profile per topic β€” unlike the desktop
+ * app's panel, the user cannot watch it and it carries no sign-ins.
+ */
+export const resolveBrowserDevice = async (
+ binary: string | undefined,
+): Promise<BrowserDevice | undefined> => {
+ if (binary) {
+ const binaryPath = path.resolve(binary);
+ if (!(await isExecutableFile(binaryPath))) {
+ throw new Error(`--agent-browser: ${binaryPath} is not an executable file`);
+ }
+ return { binaryPath };
+ }
+ const found = await findOnPath('agent-browser');
+ return found ? { binaryPath: found } : undefined;
+};
+
+/** One `agent-browser batch` run with the commands on stdin; see {@link AgentBrowserExec}. */
+const createExec =
+ (binaryPath: string, timeoutMs: number, configPath: string): AgentBrowserExec =>
+ (session, commands) =>
+ new Promise((resolve, reject) => {
+ const child = spawnAgentBrowser(
+ binaryPath,
+ [...isolationArgs(configPath), '--session', session, '--json', 'batch', '--bail'],
+ timeoutMs,
+ );
+ const stdout: Buffer[] = [];
+ const stderr: Buffer[] = [];
+ let size = 0;
+ child.stdout.on('data', (chunk: Buffer) => {
+ size += chunk.length;
+ if (size > MAX_OUTPUT_BYTES) child.kill();
+ else stdout.push(chunk);
+ });
+ child.stderr.on('data', (chunk: Buffer) => stderr.push(chunk));
+ child.on('error', reject);
+ child.on('close', (code, signal) => {
+ const out = Buffer.concat(stdout).toString('utf8').trim();
+ // A failed step still prints the JSON array (and exits 1); keep it.
+ if (out.startsWith('[')) return resolve(out);
+ const err = Buffer.concat(stderr).toString('utf8').trim();
+ reject(
+ new Error(
+ signal
+ ? `agent-browser was stopped (${signal}) after ${timeoutMs}ms`
+ : `agent-browser exited with ${code}: ${err || out || 'no output'}`,
+ ),
+ );
+ });
+ child.stdin.end(JSON.stringify(commands));
+ });
+
+/**
+ * Runs one `lobe-browser` tool call with the device's `agent-browser` and
+ * returns the same tool result the desktop app does.
+ */
+export const executeBrowserCall = async (
+ device: BrowserDevice | undefined,
+ apiName: string,
+ argsStr: string,
+ timeout?: number,
+) => {
+ if (!device) {
+ return {
+ content: '',
+ error:
+ 'The browser tool is not enabled on this device. Install agent-browser (`npm i -g agent-browser && agent-browser install`) and restart `lh connect`.',
+ state: undefined,
+ success: false,
+ };
+ }
+
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'lh-browser-'));
+ try {
+ const args = JSON.parse(argsStr || '{}') as Record<string, unknown>;
+ const timeoutMs = typeof timeout === 'number' && timeout > 0 ? timeout : DEFAULT_TIMEOUT_MS;
+ const configPath = path.join(dir, 'agent-browser.json');
+ await writeFile(configPath, '{}');
+ return await runAgentBrowserCall(apiName, args, {
+ exec: createExec(device.binaryPath, timeoutMs, configPath),
+ readFile,
+ screenshotPath: path.join(dir, 'screenshot.png'),
+ });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ return { content: '', error: message, state: undefined, success: false };
+ } finally {
+ await rm(dir, { force: true, recursive: true }).catch(() => {});
+ }
+};
+
+/**
+ * Closes every browser `lh connect` opened (`close --all` stays inside the
+ * LobeHub namespace), so stopping the device does not leave Chrome running
+ * until each session's idle timeout. Best-effort: resolves even on failure.
+ */
+export const closeBrowserSessions = async (device: BrowserDevice | undefined) => {
+ if (!device) return;
+ await new Promise<void>((resolve) => {
+ const child = spawnAgentBrowser(
+ device.binaryPath,
+ ['--namespace', NAMESPACE, 'close', '--all'],
+ CLOSE_TIMEOUT_MS,
+ );
+ child.on('error', () => resolve());
+ child.on('close', () => resolve());
+ child.stdin.end();
+ }).catch(() => {});
+};
diff --git a/apps/desktop/src/main/services/gatewaySystemInfo.ts b/apps/desktop/src/main/services/gatewaySystemInfo.ts
index c8380ebad23..0e228ebc0be 100644
--- a/apps/desktop/src/main/services/gatewaySystemInfo.ts
+++ b/apps/desktop/src/main/services/gatewaySystemInfo.ts
@@ -2,6 +2,7 @@ import { execFile } from 'node:child_process';
import os from 'node:os';
import { promisify } from 'node:util';
+import { BROWSER_IDENTIFIER } from '@lobechat/device-control/agent-browser';
import { COMPUTER_USE_IDENTIFIER } from '@lobechat/device-control/computer-use';
import type { DeviceSystemInfo } from '@lobechat/device-gateway-client';
import type { RuntimeProbeCache } from '@lobechat/heterogeneous-agents/runtimeProbeCache';
@@ -58,7 +59,7 @@ export const collectGatewaySystemInfo = async (
): Promise<DeviceSystemInfo> => {
const { getShellInfo } = await import('@lobechat/local-file-shell/shell');
return {
- supportedTools: [COMPUTER_USE_IDENTIFIER],
+ supportedTools: [COMPUTER_USE_IDENTIFIER, BROWSER_IDENTIFIER],
supportedAgentRuntimes: await agentRuntimes.get(),
arch: os.arch(),
// Tell the server-side prompt builder which shell runCommand spawns here.
diff --git a/apps/server/src/services/deviceGateway/__tests__/clientKinds.test.ts b/apps/server/src/services/deviceGateway/__tests__/clientKinds.test.ts
index 8887bb2f8e4..91b1c84a956 100644
--- a/apps/server/src/services/deviceGateway/__tests__/clientKinds.test.ts
+++ b/apps/server/src/services/deviceGateway/__tests__/clientKinds.test.ts
@@ -6,10 +6,12 @@ import { describe, expect, it } from 'vitest';
import { resolveDeviceClientKinds } from '../clientKinds';
describe('resolveDeviceClientKinds', () => {
- it('keeps desktop-only builtin tools off `lh connect`', () => {
+ // `lh connect` runs the browser with agent-browser; which client serves a
+ // call is chosen per device by `browserRuntime`, which pins `clientKinds`.
+ it('lets both clients run the browser tool', () => {
expect(
resolveDeviceClientKinds({ identifier: BrowserIdentifier, kind: 'tool', type: 'tool' }),
- ).toEqual(['desktop']);
+ ).toEqual(['cli', 'desktop']);
});
// Which of the two serves a call is chosen per device by `auvRuntime`, from
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts
index b5b2e16c466..8dd7681d4d7 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts
@@ -10,8 +10,12 @@ vi.mock('@/server/services/deviceGateway/authorizedToolCall', () => ({
}));
const mockQueryDeviceList = vi.fn();
+const mockReadDeviceSystemInfo = vi.fn();
vi.mock('@/server/services/deviceGateway', () => ({
- deviceGateway: { queryDeviceList: (...args: unknown[]) => mockQueryDeviceList(...args) },
+ deviceGateway: {
+ queryDeviceList: (...args: unknown[]) => mockQueryDeviceList(...args),
+ readDeviceSystemInfo: (...args: unknown[]) => mockReadDeviceSystemInfo(...args),
+ },
}));
const mockUploadBase64 = vi.fn();
@@ -37,6 +41,7 @@ describe('browserRuntime', () => {
beforeEach(() => {
vi.clearAllMocks();
mockQueryDeviceList.mockResolvedValue([]);
+ mockReadDeviceSystemInfo.mockResolvedValue({ ok: true, systemInfo: {} });
});
describe('device client kind', () => {
@@ -50,10 +55,10 @@ describe('browserRuntime', () => {
userId: 'user-1',
} as ToolExecutionContext;
- // Only the desktop app hosts the browser panel. `lh connect` answers every
- // browser api with `Unknown tool API: navigate`, which left agents retrying
- // blind after activating a CLI-only device (agent vent reports).
- it('does not dispatch to a device whose only live connection is the CLI', async () => {
+ // A CLI without agent-browser has no browser; dispatching there answered
+ // `Unknown tool API: navigate`, which left agents retrying blind after
+ // activating a CLI-only device (agent vent reports).
+ it('does not dispatch to a CLI-only device that does not offer the browser', async () => {
mockQueryDeviceList.mockResolvedValue([
{
channels: [{ channel: 'cli', connectedAt: 1, connectionId: 'c1' }],
@@ -70,6 +75,10 @@ describe('browserRuntime', () => {
expect(result.success).toBe(false);
expect(result.error.code).toBe('BROWSER_DEVICE_UNSUPPORTED');
expect(result.content).toContain('lh connect');
+ expect(result.content).toContain('agent-browser');
+ expect(mockReadDeviceSystemInfo).toHaveBeenCalledWith('user-1', 'vm-cli', undefined, {
+ clientKinds: ['cli'],
+ });
// lobe-web-browsing is not in this run's tool set, so it must not be offered.
expect(result.content).not.toContain('lobe-web-browsing');
});
@@ -89,7 +98,53 @@ describe('browserRuntime', () => {
expect(result.content).toContain('use lobe-web-browsing (search / crawl) instead');
});
- it('dispatches when the device also has a desktop connection', async () => {
+ it('dispatches to the CLI when it lists the browser in supportedTools', async () => {
+ mockQueryDeviceList.mockResolvedValue([
+ { channels: [{ channel: 'cli', connectedAt: 1, connectionId: 'c1' }], deviceId: 'vm-cli' },
+ ]);
+ mockReadDeviceSystemInfo.mockResolvedValue({
+ ok: true,
+ systemInfo: { supportedTools: [BrowserIdentifier] },
+ });
+ mockExecuteToolCall.mockResolvedValue({ content: 'ok', success: true });
+
+ const runtime = browserRuntime.factory(context);
+ await runtime.navigate({ url: 'https://example.com' });
+ await runtime.snapshot({});
+
+ expect(mockExecuteToolCall).toHaveBeenCalledTimes(2);
+ expect(mockExecuteToolCall.mock.calls[0][0]).toMatchObject({ clientKinds: ['cli'] });
+ // The target is resolved once per runtime, not per call.
+ expect(mockReadDeviceSystemInfo).toHaveBeenCalledTimes(1);
+ });
+
+ // A timed-out capability read was cached as "unsupported", so a CLI with
+ // agent-browser installed got install guidance for the rest of the run.
+ it('does not treat an unanswered capability read as missing support', async () => {
+ mockQueryDeviceList.mockResolvedValue([
+ { channels: [{ channel: 'cli', connectedAt: 1, connectionId: 'c1' }], deviceId: 'vm-cli' },
+ ]);
+ mockReadDeviceSystemInfo
+ .mockResolvedValueOnce({ ok: false, reason: 'TIMEOUT' })
+ .mockResolvedValueOnce({ ok: true, systemInfo: { supportedTools: [BrowserIdentifier] } });
+ mockExecuteToolCall.mockResolvedValue({ content: 'ok', success: true });
+
+ const runtime = browserRuntime.factory(context);
+ const first = await runtime.navigate({ url: 'https://example.com' });
+
+ expect(first.success).toBe(false);
+ expect(first.error.code).toBe('BROWSER_DEVICE_UNVERIFIED');
+ expect(first.content).toContain('TIMEOUT');
+ expect(first.content).not.toContain('install agent-browser');
+ expect(mockExecuteToolCall).not.toHaveBeenCalled();
+
+ const second = await runtime.navigate({ url: 'https://example.com' });
+
+ expect(second.success).toBe(true);
+ expect(mockExecuteToolCall.mock.calls[0][0]).toMatchObject({ clientKinds: ['cli'] });
+ });
+
+ it('dispatches to the desktop app when the device also has one', async () => {
mockQueryDeviceList.mockResolvedValue([
{
channels: [
@@ -107,6 +162,9 @@ describe('browserRuntime', () => {
const result = await runtime.navigate({ url: 'https://example.com' });
expect(mockExecuteToolCall).toHaveBeenCalledTimes(1);
+ // Both clients can serve lobe-browser now; the desktop's panel wins.
+ expect(mockExecuteToolCall.mock.calls[0][0]).toMatchObject({ clientKinds: ['desktop'] });
+ expect(mockReadDeviceSystemInfo).not.toHaveBeenCalled();
expect(result.success).toBe(true);
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/browser.ts b/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
index 40dade8fd0b..d28bfa9b5cc 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
@@ -1,7 +1,9 @@
import { BrowserIdentifier, BrowserManifest } from '@lobechat/builtin-tool-browser';
import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
+import type { DeviceClient } from '@lobechat/types';
import debug from 'debug';
+import { deviceGateway } from '@/server/services/deviceGateway';
import { executeAuthorizedDeviceToolCall } from '@/server/services/deviceGateway/authorizedToolCall';
import { resolveDeviceClientKind } from '@/server/services/deviceGateway/deviceChannels';
import { FileService } from '@/server/services/file';
@@ -16,9 +18,11 @@ import { withoutDeviceReplay } from './withoutDeviceReplay';
*
* A cloud agent run can't touch a device's renderer directly, so each browser
* api call is proxied back to the bound device through `deviceGateway`. The
- * device daemon forwards it to the desktop renderer, which runs the exact same
- * client `browserExecutor` (mount webview / snapshot / click / …) verified for
- * the local runtime β€” so there is one behavioral source of truth.
+ * desktop app forwards it to its renderer, which runs the exact same client
+ * `browserExecutor` (mount webview / snapshot / click / …) verified for the
+ * local runtime. A device with only `lh connect` runs it in a headless
+ * `agent-browser` instead, returning the same result shape β€” but only when it
+ * lists the tool in `supportedTools`.
*
* The browser session on the device is keyed by `topic:<topicId>`. The gateway
* tool-call envelope only carries `apiName` + `arguments`, so the runtime rides
@@ -118,10 +122,12 @@ const buildCliOnlyDeviceBrowserResult = (
: '';
const message =
`The active device (${deviceId}) is connected only through the \`lh connect\` CLI, ` +
- `which has no built-in browser, so lobe-browser cannot run there. ` +
+ `which has no browser installed, so lobe-browser cannot run there. ` +
publicPageHint +
- `If a signed-in browser session is required, ask the user to open the LobeHub desktop app ` +
- `on a machine and activate that device, then retry.`;
+ `To enable it, ask the user to install agent-browser on that machine ` +
+ `(\`npm i -g agent-browser && agent-browser install\`) and restart \`lh connect\`; ` +
+ `if a signed-in browser session is required, ask them to open the LobeHub desktop app ` +
+ `on a machine and activate that device instead, then retry.`;
return {
content: message,
error: { code: BROWSER_DEVICE_UNSUPPORTED_ERROR_CODE, message },
@@ -129,6 +135,28 @@ const buildCliOnlyDeviceBrowserResult = (
};
};
+export const BROWSER_DEVICE_UNVERIFIED_ERROR_CODE = 'BROWSER_DEVICE_UNVERIFIED';
+
+/**
+ * The CLI did not answer the capability read (timeout, reconnect gap, gateway
+ * error). That says nothing about whether agent-browser is installed, so it
+ * must not be reported as missing β€” the next call reads again.
+ */
+const buildUnverifiedCliBrowserResult = (deviceId: string, reason: string) => {
+ const message =
+ `Could not confirm whether the \`lh connect\` CLI on the active device (${deviceId}) ` +
+ `can run lobe-browser: its capability check did not answer (${reason}). ` +
+ `Nothing was sent to the device. Retry shortly; if it keeps failing, ask the user to check ` +
+ `that \`lh connect\` is still running on that machine.`;
+ return {
+ content: message,
+ error: { code: BROWSER_DEVICE_UNVERIFIED_ERROR_CODE, message },
+ success: false,
+ };
+};
+
+type BrowserTarget = DeviceClient[] | 'unsupported' | { unverified: string };
+
export const browserRuntime: ServerRuntimeRegistration = {
factory: (context) => {
if (!context.userId) {
@@ -164,26 +192,50 @@ export const browserRuntime: ServerRuntimeRegistration = {
let workspaceIdPromise: Promise<string | undefined> | undefined;
const getDeviceWorkspaceId = () => (workspaceIdPromise ??= resolveRunWorkspaceId(context));
- // Only the desktop app hosts the browser panel. A device whose only live
- // connection is `lh connect` answers every browser api with
- // `Unknown tool API: <api>`, which tells the model nothing β€” check the
- // client kind once per runtime and explain the dead end instead.
- let clientKindPromise: Promise<string> | undefined;
- const getClientKind = async () =>
- (clientKindPromise ??= getDeviceWorkspaceId().then((workspaceId) =>
- resolveDeviceClientKind(context.userId!, context.activeDeviceId!, workspaceId),
- ));
+ // Which client runs the call, resolved once per runtime. The desktop app
+ // comes first: the user can watch its panel and it carries their sign-ins.
+ // A device with only `lh connect` runs it when that CLI found an
+ // agent-browser; otherwise the dead end is explained instead of dispatched.
+ let targetPromise: Promise<BrowserTarget> | undefined;
+ const resolveTarget = async (): Promise<BrowserTarget> => {
+ const workspaceId = await getDeviceWorkspaceId();
+ const clientKind = await resolveDeviceClientKind(
+ context.userId!,
+ context.activeDeviceId!,
+ workspaceId,
+ );
+ // `unknown` keeps the desktop dispatch this runtime always made.
+ if (clientKind !== 'cli-only') return ['desktop'];
+
+ const cli = await deviceGateway.readDeviceSystemInfo(
+ context.userId!,
+ context.activeDeviceId!,
+ workspaceId,
+ { clientKinds: ['cli'] },
+ );
+ if (!cli.ok) return { unverified: cli.reason };
+ if (cli.systemInfo.supportedTools?.includes(BrowserIdentifier)) return ['cli'];
+ log('cli-only device %s does not offer the browser tool', context.activeDeviceId);
+ return 'unsupported';
+ };
const proxy: Record<string, (args: any) => Promise<any>> = {};
for (const api of BrowserManifest.api) {
proxy[api.name] = async (args: any) => {
- if ((await getClientKind()) === 'cli-only') {
+ const target = await (targetPromise ??= resolveTarget());
+ if (target === 'unsupported') {
return buildCliOnlyDeviceBrowserResult(context.activeDeviceId!, {
webBrowsingAvailable: WebBrowsingManifest.identifier in (context.toolManifestMap ?? {}),
});
}
+ if (!Array.isArray(target)) {
+ // Only a definite answer is kept for the rest of the run.
+ targetPromise = undefined;
+ return buildUnverifiedCliBrowserResult(context.activeDeviceId!, target.unverified);
+ }
+
// Carry the run identity so the device resolves the right browser
// session (`topic:<topicId>`); the agentId rides along so the device can
// decide whether revealing the panel would yank the user's view. Both
@@ -193,6 +245,7 @@ export const browserRuntime: ServerRuntimeRegistration = {
const result = await executeAuthorizedDeviceToolCall(
context.serverDB,
{
+ clientKinds: target,
deviceId: context.activeDeviceId!,
operationId: context.operationId,
userId: context.userId!,
diff --git a/packages/builtin-tool-browser/src/manifest.ts b/packages/builtin-tool-browser/src/manifest.ts
index 343ccbe450f..594fb9bff46 100644
--- a/packages/builtin-tool-browser/src/manifest.ts
+++ b/packages/builtin-tool-browser/src/manifest.ts
@@ -126,15 +126,15 @@ 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'],
+ // agent runs proxy each call back to the bound device via deviceGateway β€”
+ // the desktop app's panel, or a headless agent-browser under `lh connect`.
+ deviceClients: ['cli', 'desktop'],
executors: ['client', 'server'],
identifier: BrowserIdentifier,
meta: {
avatar: '🌐',
description:
- 'Drive the in-app browser sidebar: navigate, inspect pages via accessibility snapshots, click, fill forms, and capture screenshots β€” visible to the user in real time.',
+ 'Drive a browser on the device: navigate, inspect pages via accessibility snapshots, click, fill forms, and capture screenshots. In the desktop app it is the sidebar browser the user watches live; under the CLI it is a headless browser.',
title: 'Browser',
},
systemRole: systemPrompt,
diff --git a/packages/builtin-tool-browser/src/systemRole.ts b/packages/builtin-tool-browser/src/systemRole.ts
index 5cc87bb65d2..c10c9b10dcc 100644
--- a/packages/builtin-tool-browser/src/systemRole.ts
+++ b/packages/builtin-tool-browser/src/systemRole.ts
@@ -1,4 +1,4 @@
-export const systemPrompt = `You can drive the in-app browser shown in the user's sidebar. The user watches every action live and can take over at any time, so keep actions purposeful.
+export const systemPrompt = `You can drive a browser on the user's device. On the desktop app it is the in-app browser in the user's sidebar: the user watches every action live and can take over at any time, so keep actions purposeful. On a device connected only through the \`lh connect\` CLI it is a headless browser with a fresh profile per topic: nobody sees it, and it has no sign-ins.
Core workflow:
1. \`navigate\` to a URL (opens the browser panel if needed).
@@ -11,4 +11,4 @@ Notes:
- \`fill\` sets an input's value directly; pass \`submit: true\` to press Enter afterwards (search boxes, login forms).
- \`screenshot\` stores the capture as a file and returns it to you, and also renders it in the USER's chat. Use \`snapshot\` / \`readPage\` when the page structure or text is all you need.
- Prefer refs over coordinates. Coordinates are a fallback for canvas-like surfaces only.
-- The browser shares the user's logged-in profile. Never visit pages or perform actions the user did not ask for, and never extract credentials or other sensitive data.`;
+- On the desktop app the browser shares the user's logged-in profile; the headless CLI browser does not, so a login wall there means asking the user rather than retrying. Never visit pages or perform actions the user did not ask for, and never extract credentials or other sensitive data.`;
diff --git a/packages/device-control/package.json b/packages/device-control/package.json
index fc0bd71711c..82cd354c66b 100644
--- a/packages/device-control/package.json
+++ b/packages/device-control/package.json
@@ -5,6 +5,7 @@
"sideEffects": false,
"exports": {
".": "./src/index.ts",
+ "./agent-browser": "./src/agentBrowser.ts",
"./computer-use": "./src/computerUse.ts",
"./file-preview": "./src/filePreview.ts",
"./metrics": "./src/metrics/index.ts",
diff --git a/packages/device-control/src/agentBrowser.test.ts b/packages/device-control/src/agentBrowser.test.ts
new file mode 100644
index 00000000000..05615d55a81
--- /dev/null
+++ b/packages/device-control/src/agentBrowser.test.ts
@@ -0,0 +1,192 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ agentBrowserSessionName,
+ buildAgentBrowserCommands,
+ READ_PAGE_MAX_CHARS,
+ runAgentBrowserCall,
+} from './agentBrowser';
+
+const step = (command: string[], result: Record<string, unknown>) => ({
+ command,
+ error: null,
+ result,
+ success: true,
+});
+
+const run = (apiName: string, args: Record<string, unknown>, steps: unknown[]) => {
+ const exec = vi.fn().mockResolvedValue(JSON.stringify(steps));
+ const readFile = vi.fn();
+ const promise = runAgentBrowserCall(apiName, args, {
+ exec,
+ readFile,
+ screenshotPath: '/tmp/shot.png',
+ });
+ return { exec, promise, readFile };
+};
+
+describe('agentBrowserSessionName', () => {
+ it('keys the session by topic and strips unsafe characters', () => {
+ expect(agentBrowserSessionName('tpc_abc-1')).toBe('lobehub-topic-tpc_abc-1');
+ expect(agentBrowserSessionName('../x y')).toBe('lobehub-topic-___x_y');
+ expect(agentBrowserSessionName(undefined)).toBe('lobehub-default');
+ });
+});
+
+describe('buildAgentBrowserCommands', () => {
+ it('keeps flag-like text as a literal argv element', () => {
+ expect(
+ buildAgentBrowserCommands('fill', { ref: 'e1', submit: true, text: '--headed' }, '/s.png'),
+ ).toEqual([
+ ['fill', '@e1', '--headed'],
+ ['press', 'Enter'],
+ ]);
+ });
+
+ it('accepts the ref spellings a model copies from a snapshot', () => {
+ for (const ref of ['e12', '@e12', '[ref=e12]']) {
+ expect(buildAgentBrowserCommands('click', { ref }, '/s.png')[0]).toEqual(['click', '@e12']);
+ }
+ });
+
+ it('clicks by coordinates with a mouse press', () => {
+ expect(buildAgentBrowserCommands('click', { x: 10, y: 20 }, '/s.png').slice(0, 3)).toEqual([
+ ['mouse', 'move', '10', '20'],
+ ['mouse', 'down'],
+ ['mouse', 'up'],
+ ]);
+ });
+
+ it('scrolls with the wheel, defaulting dx to 0', () => {
+ expect(buildAgentBrowserCommands('scroll', { dy: 300 }, '/s.png')).toEqual([
+ ['mouse', 'wheel', '300', '0'],
+ ]);
+ });
+
+ it.each([
+ ['navigate', { url: 'file:///etc/passwd' }, 'absolute http(s) URL'],
+ ['click', { ref: 'body' }, 'Invalid ref'],
+ ['click', {}, 'x must be a number'],
+ ['fill', { ref: 'e1' }, 'text is required'],
+ ['unknown', {}, 'not available on this device'],
+ ])('rejects %s %j', (apiName, args, message) => {
+ expect(() => buildAgentBrowserCommands(apiName, args, '/s.png')).toThrow(message);
+ });
+});
+
+describe('runAgentBrowserCall', () => {
+ it('runs in the topic session without forwarding the run identity', async () => {
+ const { exec, promise } = run(
+ 'navigate',
+ { __agentId: 'agt', __topicId: 'tpc', url: 'https://example.com' },
+ [step(['open'], { title: 'Example Domain', url: 'https://example.com/' })],
+ );
+
+ await expect(promise).resolves.toEqual({
+ content: 'Opened https://example.com/ β€” "Example Domain".',
+ state: { title: 'Example Domain', url: 'https://example.com/' },
+ success: true,
+ });
+ expect(exec).toHaveBeenCalledWith('lobehub-topic-tpc', [['open', 'https://example.com']]);
+ });
+
+ it('returns the snapshot with the page header', async () => {
+ const { promise } = run('snapshot', {}, [
+ step(['snapshot'], { snapshot: '- link "Learn more" [ref=e1]' }),
+ step(['get', 'title'], { title: 'Example' }),
+ step(['get', 'url'], { url: 'https://example.com/' }),
+ ]);
+
+ await expect(promise).resolves.toMatchObject({
+ content: 'Page: Example (https://example.com/)\n- link "Learn more" [ref=e1]',
+ state: { snapshot: '- link "Learn more" [ref=e1]', title: 'Example' },
+ success: true,
+ });
+ });
+
+ it('caps readPage like the desktop', async () => {
+ const { promise } = run('readPage', {}, [
+ step(['read'], { content: 'a'.repeat(READ_PAGE_MAX_CHARS + 10) }),
+ step(['get', 'title'], { title: 'T' }),
+ step(['get', 'url'], { url: 'https://u/' }),
+ ]);
+
+ const result = await promise;
+ expect((result.state as { content: string }).content).toHaveLength(READ_PAGE_MAX_CHARS);
+ });
+
+ it('returns the screenshot as a PNG data URL with its size', async () => {
+ const png = new Uint8Array(24);
+ const view = new DataView(png.buffer);
+ view.setUint32(16, 1280);
+ view.setUint32(20, 720);
+ const { promise, readFile } = run('screenshot', {}, [
+ step(['screenshot'], { path: '/tmp/shot.png' }),
+ ]);
+ readFile.mockResolvedValue(png);
+
+ const result = await promise;
+ expect(readFile).toHaveBeenCalledWith('/tmp/shot.png');
+ expect(result).toMatchObject({ state: { height: 720, width: 1280 }, success: true });
+ expect((result.state as { dataUrl: string }).dataUrl).toMatch(/^data:image\/png;base64,/);
+ });
+
+ // `agent-browser fill` on a native <select> reports success but leaves the
+ // select blank, so the manifest's "option value or visible label" promise
+ // was silently broken on CLI devices.
+ it('fills a native select through `select`', async () => {
+ const exec = vi
+ .fn()
+ .mockResolvedValueOnce(
+ JSON.stringify([step(['get', 'html'], { html: '<option value="b">Banana</option>' })]),
+ )
+ .mockResolvedValueOnce(JSON.stringify([step(['select'], { selected: ['Banana'] })]));
+
+ const result = await runAgentBrowserCall(
+ 'fill',
+ { __topicId: 't', ref: 'e5', text: 'Banana' },
+ { exec, readFile: vi.fn(), screenshotPath: '/s.png' },
+ );
+
+ expect(exec).toHaveBeenNthCalledWith(1, 'lobehub-topic-t', [['get', 'html', '@e5']]);
+ expect(exec).toHaveBeenNthCalledWith(2, 'lobehub-topic-t', [['select', '@e5', 'Banana']]);
+ expect(result).toMatchObject({ content: 'Selected e5 with "Banana".', success: true });
+ });
+
+ it('fills a text field through `fill`', async () => {
+ const exec = vi
+ .fn()
+ .mockResolvedValueOnce(JSON.stringify([step(['get', 'html'], { html: '' })]))
+ .mockResolvedValueOnce(JSON.stringify([step(['fill'], { filled: '@e6' })]));
+
+ await runAgentBrowserCall(
+ 'fill',
+ { ref: 'e6', text: 'hello' },
+ { exec, readFile: vi.fn(), screenshotPath: '/s.png' },
+ );
+
+ expect(exec).toHaveBeenNthCalledWith(2, 'lobehub-default', [['fill', '@e6', 'hello']]);
+ });
+
+ it('reports the failing step', async () => {
+ const { promise } = run('click', { ref: 'e99' }, [
+ { command: ['click', '@e99'], error: 'Unknown ref: e99', result: null, success: false },
+ ]);
+
+ await expect(promise).resolves.toEqual({
+ content: '',
+ error: 'Unknown ref: e99',
+ success: false,
+ });
+ });
+
+ it('fails on unreadable output', async () => {
+ const exec = vi.fn().mockResolvedValue('Chrome not found');
+ await expect(
+ runAgentBrowserCall('snapshot', {}, { exec, readFile: vi.fn(), screenshotPath: '/s.png' }),
+ ).resolves.toMatchObject({
+ error: expect.stringContaining('Chrome not found'),
+ success: false,
+ });
+ });
+});
diff --git a/packages/device-control/src/agentBrowser.ts b/packages/device-control/src/agentBrowser.ts
new file mode 100644
index 00000000000..ea23447a2af
--- /dev/null
+++ b/packages/device-control/src/agentBrowser.ts
@@ -0,0 +1,277 @@
+/**
+ * The device side of the `lobe-browser` tool on a device without the desktop
+ * app's browser panel: each api call becomes one `agent-browser batch` run
+ * against a headless browser session keyed by the run's topic.
+ *
+ * The exec and file reads are injected so the mapping is testable without a
+ * browser; `lh connect` supplies the real `agent-browser` process.
+ */
+
+/**
+ * Tool identifier a device lists in `supportedTools` when it can run the
+ * browser tool. Mirrors `BrowserIdentifier` in `@lobechat/builtin-tool-browser`,
+ * which device runtimes do not import because it carries the React renders.
+ */
+export const BROWSER_IDENTIFIER = 'lobe-browser';
+
+/** Matches the desktop `readPage` cap so both devices hand the model the same budget. */
+export const READ_PAGE_MAX_CHARS = 12_000;
+
+/**
+ * Runs `agent-browser --session <session> --json batch --bail` once with the
+ * JSON command list on stdin and resolves its stdout, even on a nonzero exit:
+ * a failed step is reported inside the JSON array, not by the exit code alone.
+ */
+export type AgentBrowserExec = (session: string, commands: string[][]) => Promise<string>;
+
+export interface AgentBrowserCallOptions {
+ exec: AgentBrowserExec;
+ /** Reads the PNG the `screenshot` step wrote. */
+ readFile: (filePath: string) => Promise<Uint8Array>;
+ /** Where `screenshot` writes its capture; owned (and cleaned up) by the caller. */
+ screenshotPath: string;
+}
+
+export interface AgentBrowserToolResult {
+ content: string;
+ error?: string;
+ state?: Record<string, unknown>;
+ success: boolean;
+}
+
+interface BatchStep {
+ command: string[];
+ error: string | null;
+ result: Record<string, unknown> | null;
+ success: boolean;
+}
+
+/**
+ * Session name for a run's browser, matching the desktop's `topic:<topicId>`
+ * isolation: every topic drives its own page. agent-browser names sessions on
+ * disk, so the id is reduced to a safe charset.
+ */
+export const agentBrowserSessionName = (topicId: unknown): string => {
+ const id = typeof topicId === 'string' ? topicId.replaceAll(/[^\w-]/g, '_') : '';
+ return id ? `lobehub-topic-${id}` : 'lobehub-default';
+};
+
+/** Model refs come as `e12` (or `@e12`, or `[ref=e12]`); agent-browser wants `@e12`. */
+const toRef = (ref: unknown): string => {
+ if (typeof ref !== 'string' || !ref.trim()) throw new Error('ref is required');
+ const id = ref
+ .trim()
+ .replace(/^\[?ref=/, '')
+ .replace(/\]$/, '')
+ .replace(/^@/, '');
+ if (!/^e\d+$/.test(id))
+ throw new Error(`Invalid ref "${ref}"; use a ref from the latest snapshot, e.g. "e12"`);
+ return `@${id}`;
+};
+
+const toNumber = (value: unknown, name: string): string => {
+ if (typeof value !== 'number' || !Number.isFinite(value))
+ throw new Error(`${name} must be a number`);
+ return String(value);
+};
+
+const PAGE_INFO: string[][] = [
+ ['get', 'title'],
+ ['get', 'url'],
+];
+
+/**
+ * The agent-browser commands for one browser api call. Commands go as argv
+ * arrays over stdin, never through a shell or a command string: agent-browser
+ * has no `--` terminator, so text like `--headed` would otherwise parse as a flag.
+ */
+export const buildAgentBrowserCommands = (
+ apiName: string,
+ args: Record<string, unknown>,
+ screenshotPath: string,
+ /** `fill` only: the target is a native `<select>`; see {@link runAgentBrowserCall}. */
+ fillsSelect = false,
+): string[][] => {
+ switch (apiName) {
+ case 'navigate': {
+ const { url } = args;
+ if (typeof url !== 'string' || !/^https?:\/\//i.test(url)) {
+ throw new Error('url must be an absolute http(s) URL');
+ }
+ return [['open', url]];
+ }
+ case 'snapshot': {
+ return [['snapshot', '-i'], ...PAGE_INFO];
+ }
+ case 'click': {
+ if (args.ref !== undefined && args.ref !== '')
+ return [['click', toRef(args.ref)], ...PAGE_INFO];
+ const x = toNumber(args.x, 'x');
+ const y = toNumber(args.y, 'y');
+ return [['mouse', 'move', x, y], ['mouse', 'down'], ['mouse', 'up'], ...PAGE_INFO];
+ }
+ case 'fill': {
+ if (typeof args.text !== 'string') throw new Error('text is required');
+ // `fill` on a native <select> reports success but blanks it; `select`
+ // takes the option value or its visible label, as the manifest promises.
+ const commands = [[fillsSelect ? 'select' : 'fill', toRef(args.ref), args.text]];
+ if (args.submit) commands.push(['press', 'Enter']);
+ return commands;
+ }
+ case 'press': {
+ if (typeof args.key !== 'string' || !args.key) throw new Error('key is required');
+ return [['press', args.key]];
+ }
+ case 'scroll': {
+ return [['mouse', 'wheel', toNumber(args.dy, 'dy'), toNumber(args.dx ?? 0, 'dx')]];
+ }
+ case 'screenshot': {
+ return [['screenshot', screenshotPath]];
+ }
+ case 'readPage': {
+ return [['read'], ...PAGE_INFO];
+ }
+ default: {
+ throw new Error(`Browser tool "${apiName}" is not available on this device`);
+ }
+ }
+};
+
+const parseSteps = (stdout: string): BatchStep[] => {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(stdout);
+ } catch {
+ throw new Error(`agent-browser returned unreadable output: ${stdout.slice(0, 500)}`);
+ }
+ if (!Array.isArray(parsed)) throw new Error('agent-browser returned no batch results');
+ return parsed as BatchStep[];
+};
+
+/**
+ * Whether a ref points at a native `<select>`. agent-browser has no tag query,
+ * but `get html` returns the element's inner HTML, which for a select is its
+ * `<option>` list and for a text field is empty. A failed lookup falls back
+ * to `fill`, whose own step then reports the bad ref.
+ */
+const isNativeSelect = async (exec: AgentBrowserExec, session: string, ref: unknown) => {
+ const [step] = parseSteps(await exec(session, [['get', 'html', toRef(ref)]]));
+ const html = step?.success ? step.result?.html : undefined;
+ return typeof html === 'string' && /^\s*<(?:option|optgroup)\b/i.test(html);
+};
+
+/** PNG IHDR width/height, so the result reports the capture size like the desktop does. */
+const pngSize = (bytes: Uint8Array): { height?: number; width?: number } => {
+ if (bytes.length < 24) return {};
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ return { height: view.getUint32(20), width: view.getUint32(16) };
+};
+
+const toBase64 = (bytes: Uint8Array): string => {
+ let binary = '';
+ for (let i = 0; i < bytes.length; i += 0x80_00) {
+ binary += String.fromCharCode(...bytes.subarray(i, i + 0x80_00));
+ }
+ return btoa(binary);
+};
+
+const pageLabel = (title?: string, url?: string) => `Page: ${title ?? ''} (${url ?? ''})`;
+
+/**
+ * Runs one `lobe-browser` api call through agent-browser and returns the same
+ * `content` / `state` shape as the desktop client executor, so the server
+ * runtime (screenshot upload included) and the chat renders need no branch.
+ */
+export const runAgentBrowserCall = async (
+ apiName: string,
+ rawArgs: Record<string, unknown>,
+ options: AgentBrowserCallOptions,
+): Promise<AgentBrowserToolResult> => {
+ try {
+ // The server rides the run identity in the args; it is not an api parameter.
+ const { __agentId: _agentId, __topicId: topicId, ...args } = rawArgs;
+ const session = agentBrowserSessionName(topicId);
+ const commands = buildAgentBrowserCommands(
+ apiName,
+ args,
+ options.screenshotPath,
+ apiName === 'fill' && (await isNativeSelect(options.exec, session, args.ref)),
+ );
+ const steps = parseSteps(await options.exec(session, commands));
+
+ const failed = steps.find((step) => !step.success);
+ if (failed || steps.length < commands.length) {
+ throw new Error(failed?.error ?? `agent-browser stopped before ${apiName} finished`);
+ }
+
+ const result = (index: number) => steps[index]?.result ?? {};
+ const str = (value: unknown) => (typeof value === 'string' ? value : undefined);
+ // `get title` / `get url` are the last two steps wherever PAGE_INFO is appended.
+ const title = str(result(steps.length - 2).title);
+ const url = str(result(steps.length - 1).url);
+
+ switch (apiName) {
+ case 'navigate': {
+ const opened = result(0);
+ const openedTitle = str(opened.title);
+ const openedUrl = str(opened.url) ?? String(args.url);
+ return {
+ content: `Opened ${openedUrl}${openedTitle ? ` β€” "${openedTitle}"` : ''}.`,
+ state: { title: openedTitle, url: openedUrl },
+ success: true,
+ };
+ }
+ case 'snapshot': {
+ const snapshot = str(result(0).snapshot) ?? '';
+ const header = pageLabel(title, url);
+ // An empty snapshot is an answer, not a failure β€” see the desktop executor.
+ return {
+ content: snapshot
+ ? `${header}\n${snapshot}`
+ : `${header}\nNo interactive elements (links, buttons, form fields, headings) are visible on this page. Use readPage to read its text, or screenshot to see it.`,
+ state: { snapshot, title, url },
+ success: true,
+ };
+ }
+ case 'click': {
+ return {
+ content: `Clicked${args.ref ? ` ${String(args.ref)}` : ''}. Now at ${url}${title ? ` β€” "${title}"` : ''}. Take a new snapshot if the page changed.`,
+ state: { title, url },
+ success: true,
+ };
+ }
+ case 'fill': {
+ return {
+ content: `${commands[0][0] === 'select' ? 'Selected' : 'Filled'} ${String(args.ref)} with "${String(args.text)}"${args.submit ? ' and pressed Enter' : ''}.`,
+ success: true,
+ };
+ }
+ case 'press': {
+ return { content: `Pressed ${String(args.key)}.`, success: true };
+ }
+ case 'scroll': {
+ return { content: `Scrolled by ${String(args.dy)}px.`, success: true };
+ }
+ case 'screenshot': {
+ const bytes = await options.readFile(options.screenshotPath);
+ const { height, width } = pngSize(bytes);
+ return {
+ content: `Screenshot captured (${width}Γ—${height}).`,
+ state: { dataUrl: `data:image/png;base64,${toBase64(bytes)}`, height, width },
+ success: true,
+ };
+ }
+ default: {
+ const content = (str(result(0).content) ?? '').slice(0, READ_PAGE_MAX_CHARS);
+ return {
+ content: `${pageLabel(title, url)}\n${content}`,
+ state: { content, title, url },
+ success: true,
+ };
+ }
+ }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ return { content: '', error: message, success: false };
+ }
+};