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(desktop): agent browser-use — control gateway & cloud path (#17020)

Arvin Xub4e3d0b1d5a4
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index 864a8601ad7..312778ae158 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -973,3 +973,14 @@ nodeintegration, plugins, disablewebsecurity, allowpopups, preload, …`). The h
to the `webview` target (`agent-browser screenshot` there) when the embedded page's visual
matters. Use host-page screenshots only for the app chrome around the webview. Cause of the
black compositing not established (OOPIF surface not composited into the host capture).
+### E18. Cloud-connected desktop routes even `local` agents to the SERVER runtime — force client with `disableGatewayMode`
+
+- **Situation**: verifying a **client-only** builtin tool (`executors: ['client']`) via a real agent turn on the desktop. The agent's `executionTarget` is `local` and the tool-enable gate (`isLocalSystemEnabled` = runtime `local`) passes, so it _looks_ like it will run client-side.
+- **Doesn't work**: sending the message as-is. On a cloud-connected desktop, gateway mode is on by default, so the run dispatches to `execServerAgentRuntime` (server/queue path) even for a `local` agent. The client-only tool isn't executable there — the model flails and returns a non-answer (e.g. "browser closed") with no real tool effect. Confirm the path by reading the running op's `type` in `window.__LOBE_STORES.chat().operations` (`execServerAgentRuntime` = server; `executeToolCall` = client).
+- **Works**: set the agent's `chatConfig.disableGatewayMode = true` (via `agentStore.updateAgentChatConfigById(id, { disableGatewayMode: true })`) before sending. The run then goes through `executeToolCall` (client runtime); the composer's runtime chip flips to "Local device" and the client executor runs. The gate (`isLocalSystemEnabled`) and the transport (`disableGatewayMode`) are INDEPENDENT — enabling the tool does not force client execution.
+
+### E19. Desktop has no classic session store — reconfigure the existing agent, don't `createSession`
+
+- **Situation**: wanting a throwaway agent for a real-turn test without polluting the user's agent.
+- **Doesn't work**: `sessionStore.createSession({...})` — the desktop app doesn't use the classic session store (`sessions` is `[]`, `activeId` is `'inbox'`); agents are a server-backed model in `agentStore.agentMap` keyed by `agt_...`. The created session never becomes the active agent.
+- **Works**: back up the active agent's full config (`model`, `provider`, `agencyConfig`, relevant `chatConfig`), reconfigure it in place (`updateAgentConfigById` + `updateAgentChatConfigById`), run the test, then restore every field and clear any injected key-vault entry. Also: `chat.sendMessage` requires `context: { agentId, topicId, isNew }` or it throws `Cannot destructure property 'agentId' of 'context'`. Reads right after an `updateAgent*` can be stale — re-read after \~1.5s to confirm persistence.
diff --git a/apps/desktop/src/main/controllers/BrowserControlCtr.ts b/apps/desktop/src/main/controllers/BrowserControlCtr.ts
new file mode 100644
index 00000000000..ef6be393c1b
--- /dev/null
+++ b/apps/desktop/src/main/controllers/BrowserControlCtr.ts
@@ -0,0 +1,388 @@
+import type {
+ BrowserControlClickParams,
+ BrowserControlClickResult,
+ BrowserControlFillParams,
+ BrowserControlParams,
+ BrowserControlPressParams,
+ BrowserControlReadPageResult,
+ BrowserControlResult,
+ BrowserControlScreenshotResult,
+ BrowserControlScrollParams,
+ BrowserControlSnapshotResult,
+ BrowserControlWaitForParams,
+ BrowserGatewayToolResultParams,
+ BrowserToolCallResult,
+} from '@lobechat/electron-client-ipc';
+import type { WebContents } from 'electron';
+
+import { createLogger } from '@/utils/logger';
+
+import BrowserSidebarCtr from './BrowserSidebarCtr';
+import { ControllerModule, IpcMethod } from './index';
+
+const logger = createLogger('controllers:BrowserControlCtr');
+
+/** How long the renderer cursor animation gets before the real click lands. */
+const CURSOR_TRAVEL_MS = 450;
+/** Idle window after the last action before the "agent controlling" chip hides. */
+const CONTROL_IDLE_MS = 1500;
+const MAX_WAIT_MS = 10_000;
+const SCREENSHOT_MAX_WIDTH = 1200;
+const READ_PAGE_MAX_CHARS = 12_000;
+// A gateway-proxied browser call may include a navigation + mount, so give the
+// renderer executor generous headroom before giving up.
+const GATEWAY_CALL_TIMEOUT_MS = 60_000;
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/**
+ * Runs inside the guest page. Builds a compact interactive-element snapshot and
+ * caches the elements on `window.__lobeBrowserRefs` so later actions can
+ * resolve `ref` ids without re-querying.
+ */
+const SNAPSHOT_SCRIPT = `(() => {
+ const MAX = 250;
+ const refs = {};
+ let counter = 0;
+ const lines = [];
+ const isVisible = (el) => {
+ const r = el.getBoundingClientRect();
+ if (r.width < 2 || r.height < 2) return false;
+ const s = getComputedStyle(el);
+ return s.visibility !== 'hidden' && s.display !== 'none';
+ };
+ const tagRoles = { A: 'link', BUTTON: 'button', H1: 'heading', H2: 'heading', H3: 'heading', SELECT: 'combobox', SUMMARY: 'button', TEXTAREA: 'textbox' };
+ const roleOf = (el) => {
+ const explicit = el.getAttribute('role');
+ if (explicit) return explicit;
+ if (el.tagName === 'INPUT') {
+ const type = (el.getAttribute('type') || 'text').toLowerCase();
+ if (type === 'hidden') return null;
+ if (type === 'checkbox' || type === 'radio') return type;
+ if (type === 'submit' || type === 'button') return 'button';
+ return 'textbox';
+ }
+ if (el.isContentEditable) return 'textbox';
+ return tagRoles[el.tagName] || null;
+ };
+ // Never serialize the value of secret fields (autofilled passwords, card
+ // numbers, OTPs) into the snapshot — it goes to the model and is persisted
+ // in the tool result.
+ const isSensitive = (el) => {
+ if (el.tagName !== 'INPUT') return false;
+ const type = (el.getAttribute('type') || '').toLowerCase();
+ if (type === 'password') return true;
+ if (/(cc-number|cc-csc|cc-exp|current-password|new-password|one-time-code)/i.test(el.getAttribute('autocomplete') || '')) return true;
+ return /(password|passwd|pwd|secret|token|otp|cvv|pin)/i.test((el.getAttribute('name') || '') + ' ' + (el.id || ''));
+ };
+ const nameOf = (el) =>
+ (el.getAttribute('aria-label') || el.innerText || (isSensitive(el) ? '' : el.value) || el.placeholder || el.title || el.getAttribute('alt') || '')
+ .trim().replaceAll(/\\s+/g, ' ').slice(0, 80);
+ const candidates = document.querySelectorAll('a,button,input,select,textarea,summary,h1,h2,h3,[role],[onclick],[contenteditable=true]');
+ const seen = new Set();
+ for (const el of candidates) {
+ if (counter >= MAX) break;
+ if (seen.has(el) || !isVisible(el)) continue;
+ seen.add(el);
+ const role = roleOf(el);
+ if (!role || role === 'presentation' || role === 'none') continue;
+ const name = nameOf(el);
+ if (!name && !['checkbox', 'combobox', 'radio', 'textbox'].includes(role)) continue;
+ counter += 1;
+ const ref = 'e' + counter;
+ refs[ref] = el;
+ let line = '- ' + role + ' "' + name + '" [ref=' + ref + ']';
+ if (el.disabled) line += ' [disabled]';
+ if (role === 'textbox' && el.value) line += isSensitive(el) ? ' [value=<redacted>]' : ' [value="' + String(el.value).slice(0, 40) + '"]';
+ if ((role === 'checkbox' || role === 'radio') && el.checked) line += ' [checked]';
+ lines.push(line);
+ }
+ window.__lobeBrowserRefs = refs;
+ return JSON.stringify({ snapshot: lines.join('\\n'), title: document.title, url: location.href });
+})()`;
+
+const resolveRefScript = (ref: string) => `((ref) => {
+ const el = window.__lobeBrowserRefs && window.__lobeBrowserRefs[ref];
+ if (!el || !el.isConnected) return JSON.stringify({ error: 'ref not found — take a new snapshot first' });
+ el.scrollIntoView({ behavior: 'instant', block: 'center', inline: 'center' });
+ const r = el.getBoundingClientRect();
+ return JSON.stringify({ x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) });
+})(${JSON.stringify(ref)})`;
+
+const fillScript = (ref: string, text: string) => `((ref, text) => {
+ const el = window.__lobeBrowserRefs && window.__lobeBrowserRefs[ref];
+ if (!el || !el.isConnected) return JSON.stringify({ error: 'ref not found — take a new snapshot first' });
+ el.scrollIntoView({ behavior: 'instant', block: 'center', inline: 'center' });
+ el.focus();
+ if (el.isContentEditable) {
+ el.textContent = text;
+ el.dispatchEvent(new InputEvent('input', { bubbles: true }));
+ return JSON.stringify({ ok: true });
+ }
+ const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
+ const setter = Object.getOwnPropertyDescriptor(proto, 'value') && Object.getOwnPropertyDescriptor(proto, 'value').set;
+ if (!setter) return JSON.stringify({ error: 'element is not fillable' });
+ setter.call(el, text);
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+ el.dispatchEvent(new Event('change', { bubbles: true }));
+ return JSON.stringify({ ok: true });
+})(${JSON.stringify(ref)}, ${JSON.stringify(text)})`;
+
+const READ_PAGE_SCRIPT = `JSON.stringify({
+ content: (document.body ? document.body.innerText : '').replaceAll(/\\n{3,}/g, '\\n\\n').slice(0, ${READ_PAGE_MAX_CHARS}),
+ title: document.title,
+ url: location.href,
+})`;
+
+const containsTextScript = (text: string) =>
+ `document.body ? document.body.innerText.includes(${JSON.stringify(text)}) : false`;
+
+export default class BrowserControlCtr extends ControllerModule {
+ static override readonly groupName = 'browserControl';
+
+ private idleTimers = new Map<string, NodeJS.Timeout>();
+ private pendingGatewayCalls = new Map<
+ string,
+ { reject: (reason: Error) => void; resolve: (result: BrowserToolCallResult) => void }
+ >();
+ private gatewayCallSeq = 0;
+
+ /**
+ * Entry for cloud-agent (gateway) browser tool calls routed back to this
+ * device. Forwards the call to the renderer, which runs the same client
+ * `browserExecutor` used for local runs — so the mount / snapshot / click
+ * logic has one source of truth. Resolves with the executor's result.
+ */
+ async runGatewayToolCall(
+ apiName: string,
+ args: Record<string, unknown>,
+ ): Promise<BrowserToolCallResult> {
+ const { __agentId: agentId, ...toolArgs } = args as { __agentId?: string };
+ if (!agentId) {
+ return { content: 'Browser tool call is missing the agent context', success: false };
+ }
+
+ const win = this.app.browserManager.getMainWindow();
+ if (!win) {
+ return { content: 'The desktop app window is not available', success: false };
+ }
+
+ this.gatewayCallSeq += 1;
+ const requestId = `bgw_${this.gatewayCallSeq}`;
+
+ return new Promise<BrowserToolCallResult>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pendingGatewayCalls.delete(requestId);
+ reject(new Error('Browser tool call timed out'));
+ }, GATEWAY_CALL_TIMEOUT_MS);
+
+ this.pendingGatewayCalls.set(requestId, {
+ reject: (reason) => {
+ clearTimeout(timer);
+ reject(reason);
+ },
+ resolve: (result) => {
+ clearTimeout(timer);
+ resolve(result);
+ },
+ });
+
+ win.broadcast('browserSidebarGatewayToolCall', {
+ agentId,
+ apiName,
+ args: toolArgs,
+ requestId,
+ });
+ }).catch((error: Error) => ({ content: error.message, success: false }));
+ }
+
+ /** Renderer reports the executor result for a proxied gateway tool call. */
+ @IpcMethod()
+ reportGatewayToolResult(params: BrowserGatewayToolResultParams): void {
+ const pending = this.pendingGatewayCalls.get(params.requestId);
+ if (!pending) return;
+ this.pendingGatewayCalls.delete(params.requestId);
+ pending.resolve(params.result);
+ }
+
+ @IpcMethod()
+ async snapshot(params: BrowserControlParams): Promise<BrowserControlSnapshotResult> {
+ return this.withGuest(params.sessionId, async (guest) => {
+ const raw = await guest.executeJavaScript(SNAPSHOT_SCRIPT);
+ const parsed = JSON.parse(raw);
+ return { success: true, ...parsed };
+ });
+ }
+
+ @IpcMethod()
+ async click(params: BrowserControlClickParams): Promise<BrowserControlClickResult> {
+ return this.withGuest(params.sessionId, async (guest) => {
+ let { x, y } = params;
+
+ if (params.ref) {
+ const raw = await guest.executeJavaScript(resolveRefScript(params.ref));
+ const resolved = JSON.parse(raw);
+ if (resolved.error) return { error: resolved.error, success: false };
+ x = resolved.x;
+ y = resolved.y;
+ // scrollIntoView may animate layout; let the rect settle.
+ await sleep(80);
+ }
+
+ if (typeof x !== 'number' || typeof y !== 'number') {
+ return { error: 'click needs a ref or x/y coordinates', success: false };
+ }
+
+ this.markControlling(params.sessionId);
+ this.broadcastCursor(params.sessionId, x, y, true);
+ await sleep(CURSOR_TRAVEL_MS);
+
+ guest.sendInputEvent({ type: 'mouseMove', x, y });
+ guest.sendInputEvent({ button: 'left', clickCount: 1, type: 'mouseDown', x, y });
+ guest.sendInputEvent({ button: 'left', clickCount: 1, type: 'mouseUp', x, y });
+
+ await sleep(300);
+ return { success: true, title: guest.getTitle(), url: guest.getURL() };
+ });
+ }
+
+ @IpcMethod()
+ async fill(params: BrowserControlFillParams): Promise<BrowserControlResult> {
+ return this.withGuest(params.sessionId, async (guest) => {
+ this.markControlling(params.sessionId);
+ const raw = await guest.executeJavaScript(fillScript(params.ref, params.text));
+ const result = JSON.parse(raw);
+ if (result.error) return { error: result.error, success: false };
+
+ if (params.submit) {
+ await sleep(80);
+ this.sendKey(guest, 'Enter');
+ }
+
+ return { success: true };
+ });
+ }
+
+ @IpcMethod()
+ async press(params: BrowserControlPressParams): Promise<BrowserControlResult> {
+ return this.withGuest(params.sessionId, (guest) => {
+ this.markControlling(params.sessionId);
+ this.sendKey(guest, params.key);
+ return { success: true };
+ });
+ }
+
+ @IpcMethod()
+ async scroll(params: BrowserControlScrollParams): Promise<BrowserControlResult> {
+ return this.withGuest(params.sessionId, async (guest) => {
+ this.markControlling(params.sessionId);
+ await guest.executeJavaScript(
+ `window.scrollBy({ behavior: 'smooth', left: ${Number(params.dx) || 0}, top: ${Number(params.dy) || 0} })`,
+ );
+ await sleep(350);
+ return { success: true };
+ });
+ }
+
+ @IpcMethod()
+ async screenshot(params: BrowserControlParams): Promise<BrowserControlScreenshotResult> {
+ return this.withGuest(params.sessionId, async (guest) => {
+ let image = await guest.capturePage();
+ const size = image.getSize();
+ if (size.width > SCREENSHOT_MAX_WIDTH) image = image.resize({ width: SCREENSHOT_MAX_WIDTH });
+ const resized = image.getSize();
+ const dataUrl = `data:image/jpeg;base64,${image.toJPEG(80).toString('base64')}`;
+ return { dataUrl, height: resized.height, success: true, width: resized.width };
+ });
+ }
+
+ @IpcMethod()
+ async readPage(params: BrowserControlParams): Promise<BrowserControlReadPageResult> {
+ return this.withGuest(params.sessionId, async (guest) => {
+ const raw = await guest.executeJavaScript(READ_PAGE_SCRIPT);
+ return { success: true, ...JSON.parse(raw) };
+ });
+ }
+
+ @IpcMethod()
+ async waitFor(params: BrowserControlWaitForParams): Promise<BrowserControlResult> {
+ return this.withGuest(params.sessionId, async (guest) => {
+ const deadline = Date.now() + Math.min(params.ms ?? 3000, MAX_WAIT_MS);
+
+ if (!params.text) {
+ await sleep(Math.max(deadline - Date.now(), 0));
+ return { success: true };
+ }
+
+ while (Date.now() < deadline) {
+ if (guest.isDestroyed()) return { error: 'Browser page was closed', success: false };
+ const found = await guest.executeJavaScript(containsTextScript(params.text));
+ if (found) return { success: true };
+ await sleep(250);
+ }
+
+ return { error: `Timed out waiting for text: ${params.text}`, success: false };
+ });
+ }
+
+ private get sidebar() {
+ return this.app.getController(BrowserSidebarCtr);
+ }
+
+ private async withGuest<T extends BrowserControlResult>(
+ sessionId: string,
+ action: (guest: WebContents) => T | Promise<T>,
+ ): Promise<T> {
+ const guest = this.sidebar.getSessionWebContents(sessionId);
+ if (!guest) {
+ return {
+ error: 'Browser is not open for this conversation — navigate to a URL first',
+ success: false,
+ } as T;
+ }
+
+ try {
+ return await action(guest);
+ } catch (error) {
+ logger.error(`Browser control action failed for ${sessionId}:`, error);
+ return { error: (error as Error).message, success: false } as T;
+ }
+ }
+
+ private sendKey(guest: WebContents, key: string) {
+ guest.focus();
+ guest.sendInputEvent({ keyCode: key, type: 'keyDown' });
+ if (key.length === 1 || key === 'Enter') guest.sendInputEvent({ keyCode: key, type: 'char' });
+ guest.sendInputEvent({ keyCode: key, type: 'keyUp' });
+ }
+
+ private broadcastCursor(sessionId: string, x: number, y: number, click?: boolean) {
+ this.app.browserManager.broadcastToAllWindows('browserSidebarAgentCursor', {
+ click,
+ sessionId,
+ x,
+ y,
+ });
+ }
+
+ private markControlling(sessionId: string) {
+ const existing = this.idleTimers.get(sessionId);
+ if (existing) clearTimeout(existing);
+ else
+ this.app.browserManager.broadcastToAllWindows('browserSidebarAgentState', {
+ active: true,
+ sessionId,
+ });
+
+ this.idleTimers.set(
+ sessionId,
+ setTimeout(() => {
+ this.idleTimers.delete(sessionId);
+ this.app.browserManager.broadcastToAllWindows('browserSidebarAgentState', {
+ active: false,
+ sessionId,
+ });
+ }, CONTROL_IDLE_MS),
+ );
+ }
+}
diff --git a/apps/desktop/src/main/controllers/BrowserSidebarCtr.ts b/apps/desktop/src/main/controllers/BrowserSidebarCtr.ts
index 5b3be8879cd..331bf024d63 100644
--- a/apps/desktop/src/main/controllers/BrowserSidebarCtr.ts
+++ b/apps/desktop/src/main/controllers/BrowserSidebarCtr.ts
@@ -329,6 +329,11 @@ export default class BrowserSidebarCtr extends ControllerModule {
return webContents;
}
+ /** Guest accessor for sibling controllers (BrowserControlCtr drives it). */
+ getSessionWebContents(sessionId: string): WebContents | undefined {
+ return this.getLiveWebContents(sessionId);
+ }
+
private snapshot(sessionId: string): BrowserSidebarState {
const page = this.ensurePage(sessionId);
const webContents = this.getLiveWebContents(sessionId);
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index d616d357516..d8bc24dd5b7 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -31,6 +31,7 @@ import ImessageBridgeService from '@/services/imessageBridgeSrv';
import { createLogger } from '@/utils/logger';
import { setDesktopUserAgentHeader } from '@/utils/user-agent';
+import BrowserControlCtr from './BrowserControlCtr';
import HeterogeneousAgentCtr from './HeterogeneousAgentCtr';
import { ControllerModule, IpcMethod } from './index';
import LocalFileCtr from './LocalFileCtr';
@@ -40,6 +41,11 @@ import ShellCommandCtr from './ShellCommandCtr';
const logger = createLogger('controllers:GatewayConnectionCtr');
+// Mirror of `BrowserManifest.identifier` from `@lobechat/builtin-tool-browser`.
+// 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';
+
/**
* Inject the lh-notify protocol into the first turn of a new hetero-agent session.
* Tells the agent binary how to push results back to the LobeHub chat UI via `lh notify`.
@@ -201,7 +207,9 @@ export default class GatewayConnectionCtr extends ControllerModule {
srv.setTokenRefresher(() => this.remoteServerConfigCtr.refreshAccessToken());
// Wire up tool call handler
- srv.setToolCallHandler((apiName, args) => this.executeToolCall(apiName, args));
+ srv.setToolCallHandler((identifier, apiName, args) =>
+ this.executeToolCall(identifier, apiName, args),
+ );
// Wire up MCP call handler (tunneled stdio MCP calls from the cloud server)
srv.setMcpCallHandler((mcpCall) => this.executeMcpCall(mcpCall));
@@ -412,9 +420,24 @@ export default class GatewayConnectionCtr extends ControllerModule {
}
private async executeToolCall(
+ identifier: string | undefined,
apiName: string,
args: unknown,
): Promise<BuiltinServerRuntimeOutput> {
+ // Browser is a renderer-resident tool: forward to the client executor via
+ // BrowserControlCtr instead of the local-system apiName switch below.
+ if (identifier === BrowserIdentifier) {
+ const result = await this.app
+ .getController(BrowserControlCtr)
+ .runGatewayToolCall(apiName, (args ?? {}) as Record<string, unknown>);
+ return {
+ content: result.content ?? '',
+ error: result.error,
+ state: result.state,
+ success: result.success,
+ };
+ }
+
const runtime = this.getLocalSystemRuntime();
const normalized = LEGACY_API_ALIASES[apiName] ?? apiName;
diff --git a/apps/desktop/src/main/controllers/registry.ts b/apps/desktop/src/main/controllers/registry.ts
index bfb45c64554..150f498f316 100644
--- a/apps/desktop/src/main/controllers/registry.ts
+++ b/apps/desktop/src/main/controllers/registry.ts
@@ -2,6 +2,7 @@ import type { CreateServicesResult, IpcServiceConstructor, MergeIpcService } fro
import AuthCtr from './AuthCtr';
import BinaryCtr from './BinaryCtr';
+import BrowserControlCtr from './BrowserControlCtr';
import BrowserSidebarCtr from './BrowserSidebarCtr';
import BrowserWindowsCtr from './BrowserWindowsCtr';
import CliCtr from './CliCtr';
@@ -30,6 +31,7 @@ import WorkspaceCtr from './WorkspaceCtr';
export const controllerIpcConstructors = [
HeterogeneousAgentCtr,
AuthCtr,
+ BrowserControlCtr,
BrowserSidebarCtr,
BrowserWindowsCtr,
CliCtr,
diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
index 7346a387d6f..410cfd1d80b 100644
--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts
+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
@@ -50,7 +50,7 @@ interface MessageApiHandler {
}
interface ToolCallHandler {
- (apiName: string, args: unknown): Promise<ToolCallResult>;
+ (identifier: string | undefined, apiName: string, args: unknown): Promise<ToolCallResult>;
}
/**
@@ -783,7 +783,7 @@ export default class GatewayConnectionService extends ServiceModule {
throw new Error('No tool call handler configured');
}
const args = JSON.parse(argsStr);
- result = await this.toolCallHandler(apiName, args);
+ result = await this.toolCallHandler(identifier, apiName, args);
}
// Forward the typed envelope unchanged. Critically, do NOT stringify the
diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
index 0aa82febb50..1eb9e1bfee8 100644
--- a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
@@ -9,6 +9,7 @@
* - Gets model capabilities from provided function
* - No dependency on frontend stores (useToolStore, useAgentStore, etc.)
*/
+import { BrowserManifest } from '@lobechat/builtin-tool-browser';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { KnowledgeBaseManifest } from '@lobechat/builtin-tool-knowledge-base';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
@@ -262,6 +263,13 @@ export const createServerAgentToolsEngine = (
hasDeviceProxy &&
!!deviceContext?.deviceOnline &&
!!deviceContext?.autoActivated,
+ // Browser drives the device's in-app browser — same device gate as
+ // local-system: local runtime routed to an online, auto-activated device.
+ [BrowserManifest.identifier]:
+ runtimeMode === 'local' &&
+ hasDeviceProxy &&
+ !!deviceContext?.deviceOnline &&
+ !!deviceContext?.autoActivated,
[MemoryManifest.identifier]: globalMemoryEnabled,
// Only auto-enable in bot conversations; otherwise let user's plugin selection take effect
...(isBotConversation && { [MessageManifest.identifier]: true }),
diff --git a/apps/server/src/services/aiAgent/deviceToolRegistry.test.ts b/apps/server/src/services/aiAgent/deviceToolRegistry.test.ts
index acce09d219a..ae7811380d5 100644
--- a/apps/server/src/services/aiAgent/deviceToolRegistry.test.ts
+++ b/apps/server/src/services/aiAgent/deviceToolRegistry.test.ts
@@ -1,3 +1,4 @@
+import { BrowserManifest } from '@lobechat/builtin-tool-browser';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
import { builtinTools } from '@lobechat/builtin-tools';
@@ -10,15 +11,20 @@ import {
} from './deviceToolRegistry';
describe('deviceToolRegistry', () => {
- it('pins the device tool set to exactly local-system + remote-device', () => {
+ it('pins the device tool set to exactly local-system + remote-device + browser', () => {
expect([...DEVICE_TOOL_IDENTIFIERS].sort()).toEqual(
- [LocalSystemManifest.identifier, RemoteDeviceManifest.identifier].sort(),
+ [
+ LocalSystemManifest.identifier,
+ RemoteDeviceManifest.identifier,
+ BrowserManifest.identifier,
+ ].sort(),
);
});
- it('isDeviceToolIdentifier recognises both device tools', () => {
+ it('isDeviceToolIdentifier recognises the device tools', () => {
expect(isDeviceToolIdentifier(LocalSystemManifest.identifier)).toBe(true);
expect(isDeviceToolIdentifier(RemoteDeviceManifest.identifier)).toBe(true);
+ expect(isDeviceToolIdentifier(BrowserManifest.identifier)).toBe(true);
expect(isDeviceToolIdentifier('web-browsing')).toBe(false);
expect(isDeviceToolIdentifier('')).toBe(false);
});
diff --git a/apps/server/src/services/aiAgent/deviceToolRegistry.ts b/apps/server/src/services/aiAgent/deviceToolRegistry.ts
index 88de17349a9..2efb345dc80 100644
--- a/apps/server/src/services/aiAgent/deviceToolRegistry.ts
+++ b/apps/server/src/services/aiAgent/deviceToolRegistry.ts
@@ -19,11 +19,16 @@
* because the manifest was still resolvable in the engine even when
* the rule-layer gate denied it).
*/
+import { BrowserManifest } from '@lobechat/builtin-tool-browser';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
import { builtinTools } from '@lobechat/builtin-tools';
-export const DEVICE_TOOL_MANIFESTS = [LocalSystemManifest, RemoteDeviceManifest] as const;
+export const DEVICE_TOOL_MANIFESTS = [
+ LocalSystemManifest,
+ RemoteDeviceManifest,
+ BrowserManifest,
+] as const;
export const DEVICE_TOOL_IDENTIFIERS: ReadonlySet<string> = new Set(
DEVICE_TOOL_MANIFESTS.map((m) => m.identifier),
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/browser.ts b/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
new file mode 100644
index 00000000000..224a121af7c
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
@@ -0,0 +1,65 @@
+import { BrowserIdentifier, BrowserManifest } from '@lobechat/builtin-tool-browser';
+
+import { deviceGateway } from '@/server/services/deviceGateway';
+
+import { resolveRunWorkspaceId } from './resolveWorkspaceScope';
+import { type ServerRuntimeRegistration } from './types';
+
+/**
+ * Browser tool server runtime.
+ *
+ * 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.
+ *
+ * The browser session on the device is keyed by `agent:<agentId>`. The gateway
+ * tool-call envelope only carries `apiName` + `arguments`, so the runtime rides
+ * the agentId in the args (mirroring how localSystem injects `cwd`); the device
+ * strips it back out before invoking the executor.
+ */
+export const browserRuntime: ServerRuntimeRegistration = {
+ factory: (context) => {
+ if (!context.userId) {
+ throw new Error('userId is required for Browser device proxy execution');
+ }
+ if (!context.activeDeviceId) {
+ throw new Error('activeDeviceId is required for Browser device proxy execution');
+ }
+ if (!context.agentId) {
+ throw new Error('agentId is required for Browser device proxy execution');
+ }
+
+ let workspaceIdPromise: Promise<string | undefined> | undefined;
+ const getDeviceWorkspaceId = () => (workspaceIdPromise ??= resolveRunWorkspaceId(context));
+
+ const proxy: Record<string, (args: any) => Promise<any>> = {};
+
+ for (const api of BrowserManifest.api) {
+ proxy[api.name] = async (args: any) => {
+ // Carry the agent identity so the device resolves the right browser
+ // session (`agent:<agentId>`). `__agentId` is stripped device-side.
+ const finalArgs = { ...args, __agentId: context.agentId };
+
+ return deviceGateway.executeToolCall(
+ {
+ deviceId: context.activeDeviceId!,
+ operationId: context.operationId,
+ userId: context.userId!,
+ workspaceId: await getDeviceWorkspaceId(),
+ },
+ {
+ apiName: api.name,
+ arguments: JSON.stringify(finalArgs),
+ identifier: BrowserIdentifier,
+ },
+ context.executionTimeoutMs,
+ );
+ };
+ }
+
+ return proxy;
+ },
+ identifier: BrowserIdentifier,
+};
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/index.ts
index eeb2630e0b6..01039de422a 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/index.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/index.ts
@@ -16,6 +16,7 @@ import { agentSignalReflectionRuntime } from './agentSignalReflection';
import { agentSignalReviewRuntime } from './agentSignalReview';
import { agentSignalSkillManagementRuntime } from './agentSignalSkillManagement';
import { briefRuntime } from './brief';
+import { browserRuntime } from './browser';
import { calculatorRuntime } from './calculator';
import { cloudSandboxRuntime } from './cloudSandbox';
import { credsRuntime } from './creds';
@@ -71,6 +72,7 @@ registerRuntimes([
activatorRuntime,
messageRuntime,
localSystemRuntime,
+ browserRuntime,
remoteDeviceRuntime,
briefRuntime,
taskRuntime,
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 7f337caefbf..75e9b05a8b0 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1284,10 +1284,14 @@
"workingPanel.browser.actions.reload": "Reload",
"workingPanel.browser.actions.stop": "Stop loading",
"workingPanel.browser.addressPlaceholder": "Search or enter address",
+ "workingPanel.browser.agentControlling": "Agent is using the browser",
+ "workingPanel.browser.agentCursor": "Agent",
"workingPanel.browser.desktopOnly": "The in-app browser is only available in the desktop app",
"workingPanel.browser.empty.desc": "Enter an address or search above to open a page",
"workingPanel.browser.empty.title": "Start browsing",
"workingPanel.browser.title": "Browser",
+ "workingPanel.browser.tool.elements_one": "{{count}} element",
+ "workingPanel.browser.tool.elements_other": "{{count}} elements",
"workingPanel.documents.close": "Close",
"workingPanel.documents.discard": "Discard",
"workingPanel.documents.edit": "Edit",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 52edf643209..0a20e252b5f 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1284,10 +1284,14 @@
"workingPanel.browser.actions.reload": "刷新",
"workingPanel.browser.actions.stop": "停止加载",
"workingPanel.browser.addressPlaceholder": "搜索或输入网址",
+ "workingPanel.browser.agentControlling": "智能体正在使用浏览器",
+ "workingPanel.browser.agentCursor": "Agent",
"workingPanel.browser.desktopOnly": "内置浏览器仅在桌面端可用",
"workingPanel.browser.empty.desc": "在上方输入网址或搜索以打开页面",
"workingPanel.browser.empty.title": "开始浏览",
"workingPanel.browser.title": "浏览器",
+ "workingPanel.browser.tool.elements_one": "{{count}} 个元素",
+ "workingPanel.browser.tool.elements_other": "{{count}} 个元素",
"workingPanel.documents.close": "关闭",
"workingPanel.documents.discard": "放弃",
"workingPanel.documents.edit": "编辑",
diff --git a/package.json b/package.json
index 568a4f7f4ee..c444e199eb9 100644
--- a/package.json
+++ b/package.json
@@ -224,6 +224,7 @@
"@lobechat/builtin-tool-agent-management": "workspace:*",
"@lobechat/builtin-tool-agent-signal": "workspace:*",
"@lobechat/builtin-tool-brief": "workspace:*",
+ "@lobechat/builtin-tool-browser": "workspace:*",
"@lobechat/builtin-tool-calculator": "workspace:*",
"@lobechat/builtin-tool-claude-code": "workspace:*",
"@lobechat/builtin-tool-cloud-sandbox": "workspace:*",
diff --git a/packages/builtin-tool-browser/package.json b/packages/builtin-tool-browser/package.json
new file mode 100644
index 00000000000..ee72ef9cdd5
--- /dev/null
+++ b/packages/builtin-tool-browser/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "@lobechat/builtin-tool-browser",
+ "version": "1.0.0",
+ "private": true,
+ "exports": {
+ ".": "./src/index.ts",
+ "./client": "./src/client/index.ts",
+ "./client/executor": "./src/client/executor/index.ts"
+ },
+ "main": "./src/index.ts",
+ "dependencies": {
+ "@lobechat/electron-client-ipc": "workspace:*"
+ },
+ "devDependencies": {
+ "@lobechat/types": "workspace:*"
+ },
+ "peerDependencies": {
+ "@lobehub/ui": "^5",
+ "antd-style": "*",
+ "lucide-react": "*",
+ "react": "*",
+ "react-i18next": "*"
+ }
+}
diff --git a/packages/builtin-tool-browser/src/client/Render/PageAction.tsx b/packages/builtin-tool-browser/src/client/Render/PageAction.tsx
new file mode 100644
index 00000000000..cbf3dd0547c
--- /dev/null
+++ b/packages/builtin-tool-browser/src/client/Render/PageAction.tsx
@@ -0,0 +1,43 @@
+import type { BuiltinRenderProps } from '@lobechat/types';
+import { Flexbox, Text } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { Globe } from 'lucide-react';
+import { memo } from 'react';
+
+import type { BrowserPageState } from '../../types';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ container: css`
+ padding-block: 6px;
+ padding-inline: 10px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 8px;
+ `,
+ url: css`
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+/** Compact "acted on this page" row used by navigate/click/fill/press/scroll. */
+const PageAction = memo<BuiltinRenderProps<unknown, BrowserPageState, string>>(
+ ({ content, pluginState }) => {
+ return (
+ <Flexbox className={styles.container} gap={2}>
+ <Flexbox horizontal align={'center'} gap={6}>
+ <Globe size={14} />
+ <Text ellipsis>{content || pluginState?.title || 'Browser action'}</Text>
+ </Flexbox>
+ {pluginState?.url && (
+ <Text ellipsis className={styles.url}>
+ {pluginState.url}
+ </Text>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+PageAction.displayName = 'BrowserPageAction';
+
+export default PageAction;
diff --git a/packages/builtin-tool-browser/src/client/Render/Screenshot.tsx b/packages/builtin-tool-browser/src/client/Render/Screenshot.tsx
new file mode 100644
index 00000000000..2365b81005e
--- /dev/null
+++ b/packages/builtin-tool-browser/src/client/Render/Screenshot.tsx
@@ -0,0 +1,26 @@
+import type { BuiltinRenderProps } from '@lobechat/types';
+import { Block, Image } from '@lobehub/ui';
+import { memo } from 'react';
+
+import type { BrowserScreenshotState } from '../../types';
+
+/** Screenshot: render the captured JPEG data URL inline for the user. */
+const Screenshot = memo<BuiltinRenderProps<unknown, BrowserScreenshotState, string>>(
+ ({ pluginState }) => {
+ if (!pluginState?.dataUrl) return null;
+
+ return (
+ <Block style={{ overflow: 'hidden', padding: 4 }} variant={'outlined'}>
+ <Image
+ alt={'Browser screenshot'}
+ src={pluginState.dataUrl}
+ style={{ borderRadius: 4, width: '100%' }}
+ />
+ </Block>
+ );
+ },
+);
+
+Screenshot.displayName = 'BrowserScreenshot';
+
+export default Screenshot;
diff --git a/packages/builtin-tool-browser/src/client/Render/Snapshot.tsx b/packages/builtin-tool-browser/src/client/Render/Snapshot.tsx
new file mode 100644
index 00000000000..7366c444d8f
--- /dev/null
+++ b/packages/builtin-tool-browser/src/client/Render/Snapshot.tsx
@@ -0,0 +1,48 @@
+import type { BuiltinRenderProps } from '@lobechat/types';
+import { Flexbox, Text } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { ScanText } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { BrowserSnapshotState } from '../../types';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ container: css`
+ padding-block: 6px;
+ padding-inline: 10px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 8px;
+ `,
+ meta: css`
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+/** Snapshot / readPage: show the page identity + element count, not the dump. */
+const Snapshot = memo<BuiltinRenderProps<unknown, BrowserSnapshotState, string>>(
+ ({ pluginState }) => {
+ const { t } = useTranslation('chat');
+ const count = pluginState?.snapshot
+ ? pluginState.snapshot.split('\n').filter(Boolean).length
+ : 0;
+
+ return (
+ <Flexbox className={styles.container} gap={2}>
+ <Flexbox horizontal align={'center'} gap={6}>
+ <ScanText size={14} />
+ <Text ellipsis>{pluginState?.title || t('workingPanel.browser.title')}</Text>
+ </Flexbox>
+ <Text ellipsis className={styles.meta}>
+ {pluginState?.url}
+ {count > 0 ? ` · ${t('workingPanel.browser.tool.elements', { count })}` : ''}
+ </Text>
+ </Flexbox>
+ );
+ },
+);
+
+Snapshot.displayName = 'BrowserSnapshot';
+
+export default Snapshot;
diff --git a/packages/builtin-tool-browser/src/client/Render/index.ts b/packages/builtin-tool-browser/src/client/Render/index.ts
new file mode 100644
index 00000000000..ea50a32eae4
--- /dev/null
+++ b/packages/builtin-tool-browser/src/client/Render/index.ts
@@ -0,0 +1,18 @@
+import { BrowserApiName } from '../../types';
+import PageAction from './PageAction';
+import Screenshot from './Screenshot';
+import Snapshot from './Snapshot';
+
+/**
+ * Browser Tool Render Components Registry — keyed by api name.
+ */
+export const BrowserRenders = {
+ [BrowserApiName.click]: PageAction,
+ [BrowserApiName.fill]: PageAction,
+ [BrowserApiName.navigate]: PageAction,
+ [BrowserApiName.press]: PageAction,
+ [BrowserApiName.readPage]: Snapshot,
+ [BrowserApiName.screenshot]: Screenshot,
+ [BrowserApiName.scroll]: PageAction,
+ [BrowserApiName.snapshot]: Snapshot,
+};
diff --git a/packages/builtin-tool-browser/src/client/executor/index.ts b/packages/builtin-tool-browser/src/client/executor/index.ts
new file mode 100644
index 00000000000..b2804b337a6
--- /dev/null
+++ b/packages/builtin-tool-browser/src/client/executor/index.ts
@@ -0,0 +1,299 @@
+import type { BuiltinToolContext, BuiltinToolResult } from '@lobechat/types';
+import { BaseExecutor } from '@lobechat/types';
+
+import type {
+ BrowserClickArgs,
+ BrowserFillArgs,
+ BrowserNavigateArgs,
+ BrowserPressArgs,
+ BrowserScrollArgs,
+} from '../../types';
+import { BrowserIdentifier } from '../../types';
+
+const BrowserApiEnum = {
+ click: 'click' as const,
+ fill: 'fill' as const,
+ navigate: 'navigate' as const,
+ press: 'press' as const,
+ readPage: 'readPage' as const,
+ screenshot: 'screenshot' as const,
+ scroll: 'scroll' as const,
+ snapshot: 'snapshot' as const,
+};
+
+const ATTACH_TIMEOUT_MS = 12_000;
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/**
+ * Browser Tool Executor (client / desktop only)
+ *
+ * Drives the WorkingSidebar in-app browser through the Electron IPC control
+ * gateway. The browser session is shared with the UI (`agent:<agentId>`), so
+ * the user watches every action live in the sidebar.
+ */
+class BrowserExecutor extends BaseExecutor<typeof BrowserApiEnum> {
+ readonly identifier = BrowserIdentifier;
+ protected readonly apiEnum = BrowserApiEnum;
+
+ /**
+ * Every execution path funnels through this executor (local runtime, the
+ * DesktopBrowserGatewayBridge for cloud runs, and the CC MCP bridge), so a
+ * single Labs-toggle gate here covers them all: with the in-app browser lab
+ * off, the sidebar tab is hidden and driving it would be invisible to the
+ * user.
+ */
+ private async labDisabledFailure(): Promise<BuiltinToolResult | undefined> {
+ const [{ useUserStore }, { labPreferSelectors }] = await Promise.all([
+ import('@/store/user'),
+ import('@/store/user/selectors'),
+ ]);
+ if (labPreferSelectors.enableInAppBrowser(useUserStore.getState())) return undefined;
+ return this.failure(
+ 'The in-app browser is disabled. Ask the user to enable "In-App Browser" under Settings → Advanced → Labs, then retry.',
+ );
+ }
+
+ navigate = async (params: BrowserNavigateArgs, ctx?: BuiltinToolContext) => {
+ try {
+ const disabled = await this.labDisabledFailure();
+ if (disabled) return disabled;
+ const sessionId = this.sessionIdOf(ctx);
+ const { electronBrowserSidebarService } = await import('@/services/electron/browserSidebar');
+
+ const state = await electronBrowserSidebarService.getState({ sessionId });
+
+ if (state.attached) {
+ await this.revealBrowserTab();
+ const result = await electronBrowserSidebarService.navigate({
+ sessionId,
+ url: params.url,
+ });
+ if (!result.success) return this.failure(result.error ?? 'Navigation failed');
+ } else {
+ // No webview yet — mount it through the store request, which also opens
+ // the right panel and switches to the browser tab.
+ const { useGlobalStore } = await import('@/store/global');
+ useGlobalStore.getState().openInBrowserTab(params.url);
+
+ const attached = await this.waitForAttach(sessionId);
+ if (!attached)
+ return this.failure(
+ 'The in-app browser did not open. Make sure the conversation is visible in the desktop app.',
+ );
+ }
+
+ // Let the page settle before reporting where we landed.
+ await this.waitForLoad(sessionId);
+ const next = await electronBrowserSidebarService.getState({ sessionId });
+ return this.success(`Opened ${next.url}${next.title ? ` — "${next.title}"` : ''}`, {
+ title: next.title,
+ url: next.url,
+ });
+ } catch (error) {
+ return this.errorResult(error);
+ }
+ };
+
+ snapshot = async (_params: object, ctx?: BuiltinToolContext) => {
+ try {
+ const disabled = await this.labDisabledFailure();
+ if (disabled) return disabled;
+ const { electronBrowserControlService } = await import('@/services/electron/browserControl');
+ const result = await electronBrowserControlService.snapshot({
+ sessionId: this.sessionIdOf(ctx),
+ });
+ if (!result.success || !result.snapshot)
+ return this.failure(result.error ?? 'Snapshot failed');
+
+ const header = `Page: ${result.title ?? ''} (${result.url ?? ''})`;
+ return this.success(`${header}\n${result.snapshot}`, {
+ snapshot: result.snapshot,
+ title: result.title,
+ url: result.url,
+ });
+ } catch (error) {
+ return this.errorResult(error);
+ }
+ };
+
+ click = async (params: BrowserClickArgs, ctx?: BuiltinToolContext) => {
+ try {
+ const disabled = await this.labDisabledFailure();
+ if (disabled) return disabled;
+ await this.revealBrowserTab();
+ const { electronBrowserControlService } = await import('@/services/electron/browserControl');
+ const result = await electronBrowserControlService.click({
+ ref: params.ref,
+ sessionId: this.sessionIdOf(ctx),
+ x: params.x,
+ y: params.y,
+ });
+ if (!result.success) return this.failure(result.error ?? 'Click failed');
+
+ return this.success(
+ `Clicked${params.ref ? ` ${params.ref}` : ''}. Now at ${result.url}${result.title ? ` — "${result.title}"` : ''}. Take a new snapshot if the page changed.`,
+ { title: result.title, url: result.url },
+ );
+ } catch (error) {
+ return this.errorResult(error);
+ }
+ };
+
+ fill = async (params: BrowserFillArgs, ctx?: BuiltinToolContext) => {
+ try {
+ const disabled = await this.labDisabledFailure();
+ if (disabled) return disabled;
+ await this.revealBrowserTab();
+ const { electronBrowserControlService } = await import('@/services/electron/browserControl');
+ const result = await electronBrowserControlService.fill({
+ ref: params.ref,
+ sessionId: this.sessionIdOf(ctx),
+ submit: params.submit,
+ text: params.text,
+ });
+ if (!result.success) return this.failure(result.error ?? 'Fill failed');
+
+ return this.success(
+ `Filled ${params.ref} with "${params.text}"${params.submit ? ' and pressed Enter' : ''}.`,
+ );
+ } catch (error) {
+ return this.errorResult(error);
+ }
+ };
+
+ press = async (params: BrowserPressArgs, ctx?: BuiltinToolContext) => {
+ try {
+ const disabled = await this.labDisabledFailure();
+ if (disabled) return disabled;
+ const { electronBrowserControlService } = await import('@/services/electron/browserControl');
+ const result = await electronBrowserControlService.press({
+ key: params.key,
+ sessionId: this.sessionIdOf(ctx),
+ });
+ if (!result.success) return this.failure(result.error ?? 'Key press failed');
+ return this.success(`Pressed ${params.key}.`);
+ } catch (error) {
+ return this.errorResult(error);
+ }
+ };
+
+ scroll = async (params: BrowserScrollArgs, ctx?: BuiltinToolContext) => {
+ try {
+ const disabled = await this.labDisabledFailure();
+ if (disabled) return disabled;
+ const { electronBrowserControlService } = await import('@/services/electron/browserControl');
+ const result = await electronBrowserControlService.scroll({
+ dx: params.dx,
+ dy: params.dy,
+ sessionId: this.sessionIdOf(ctx),
+ });
+ if (!result.success) return this.failure(result.error ?? 'Scroll failed');
+ return this.success(`Scrolled by ${params.dy}px.`);
+ } catch (error) {
+ return this.errorResult(error);
+ }
+ };
+
+ screenshot = async (_params: object, ctx?: BuiltinToolContext) => {
+ try {
+ const disabled = await this.labDisabledFailure();
+ if (disabled) return disabled;
+ await this.revealBrowserTab();
+ const { electronBrowserControlService } = await import('@/services/electron/browserControl');
+ const result = await electronBrowserControlService.screenshot({
+ sessionId: this.sessionIdOf(ctx),
+ });
+ if (!result.success || !result.dataUrl)
+ return this.failure(result.error ?? 'Screenshot failed');
+
+ return this.success(
+ `Screenshot captured (${result.width}×${result.height}) and shown to the user.`,
+ { dataUrl: result.dataUrl, height: result.height, width: result.width },
+ );
+ } catch (error) {
+ return this.errorResult(error);
+ }
+ };
+
+ readPage = async (_params: object, ctx?: BuiltinToolContext) => {
+ try {
+ const disabled = await this.labDisabledFailure();
+ if (disabled) return disabled;
+ const { electronBrowserControlService } = await import('@/services/electron/browserControl');
+ const result = await electronBrowserControlService.readPage({
+ sessionId: this.sessionIdOf(ctx),
+ });
+ if (!result.success) return this.failure(result.error ?? 'Read page failed');
+
+ return this.success(
+ `Page: ${result.title ?? ''} (${result.url ?? ''})\n${result.content ?? ''}`,
+ { content: result.content ?? '', title: result.title, url: result.url },
+ );
+ } catch (error) {
+ return this.errorResult(error);
+ }
+ };
+
+ // ==================== Helpers ====================
+
+ private sessionIdOf(ctx?: BuiltinToolContext): string {
+ if (!ctx?.agentId) throw new Error('Browser tool requires an agent context');
+ return `agent:${ctx.agentId}`;
+ }
+
+ /** Keep the user in the loop: surface the browser tab whenever the agent acts. */
+ private async revealBrowserTab() {
+ const { useGlobalStore } = await import('@/store/global');
+ const store = useGlobalStore.getState();
+ store.toggleRightPanel(true);
+ store.setWorkingSidebarTab('browser');
+ }
+
+ private async waitForAttach(sessionId: string): Promise<boolean> {
+ const { electronBrowserSidebarService } = await import('@/services/electron/browserSidebar');
+ const deadline = Date.now() + ATTACH_TIMEOUT_MS;
+ while (Date.now() < deadline) {
+ const state = await electronBrowserSidebarService.getState({ sessionId });
+ if (state.attached) return true;
+ await sleep(300);
+ }
+ return false;
+ }
+
+ private async waitForLoad(sessionId: string, timeoutMs = 8000): Promise<void> {
+ const { electronBrowserSidebarService } = await import('@/services/electron/browserSidebar');
+ const deadline = Date.now() + timeoutMs;
+ // Give the navigation a beat to start before sampling isLoading.
+ await sleep(500);
+ while (Date.now() < deadline) {
+ const state = await electronBrowserSidebarService.getState({ sessionId });
+ if (!state.isLoading) return;
+ await sleep(300);
+ }
+ }
+
+ private success(content: string, state?: unknown): BuiltinToolResult {
+ return { content, state, success: true };
+ }
+
+ private failure(message: string): BuiltinToolResult {
+ return {
+ content: message,
+ error: { message, type: 'PluginServerError' },
+ success: false,
+ };
+ }
+
+ private errorResult(error: unknown): BuiltinToolResult {
+ const message = (error as Error).message;
+ return {
+ content: message,
+ error: { body: error, message, type: 'PluginServerError' },
+ success: false,
+ };
+ }
+}
+
+// Export the executor instance for registration
+export const browserExecutor = new BrowserExecutor();
diff --git a/packages/builtin-tool-browser/src/client/index.ts b/packages/builtin-tool-browser/src/client/index.ts
new file mode 100644
index 00000000000..66dbca20ea5
--- /dev/null
+++ b/packages/builtin-tool-browser/src/client/index.ts
@@ -0,0 +1,4 @@
+export { BrowserManifest } from '../manifest';
+export { BrowserApiName, BrowserIdentifier } from '../types';
+export * from '../types';
+export { BrowserRenders } from './Render';
diff --git a/packages/builtin-tool-browser/src/index.ts b/packages/builtin-tool-browser/src/index.ts
new file mode 100644
index 00000000000..520f5c0fb0f
--- /dev/null
+++ b/packages/builtin-tool-browser/src/index.ts
@@ -0,0 +1,3 @@
+export { BrowserManifest } from './manifest';
+export { systemPrompt } from './systemRole';
+export * from './types';
diff --git a/packages/builtin-tool-browser/src/manifest.ts b/packages/builtin-tool-browser/src/manifest.ts
new file mode 100644
index 00000000000..8a293535496
--- /dev/null
+++ b/packages/builtin-tool-browser/src/manifest.ts
@@ -0,0 +1,140 @@
+import type { BuiltinToolManifest } from '@lobechat/types';
+
+import { systemPrompt } from './systemRole';
+import { BrowserApiName, BrowserIdentifier } from './types';
+
+export const BrowserManifest: BuiltinToolManifest = {
+ api: [
+ {
+ description:
+ 'Open a URL in the in-app browser sidebar. Opens the panel automatically if it is closed.',
+ name: BrowserApiName.navigate,
+ parameters: {
+ properties: {
+ url: {
+ description: 'Absolute URL to open (http/https).',
+ type: 'string',
+ },
+ },
+ required: ['url'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Capture an accessibility snapshot of the current page: interactive elements (links, buttons, inputs, headings) with stable refs like [ref=e12] for use in click/fill. Always snapshot before acting, and re-snapshot after the page changes.',
+ name: BrowserApiName.snapshot,
+ parameters: {
+ properties: {},
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Click an element. Prefer a ref from the latest snapshot; viewport x/y coordinates are a fallback for canvas-like surfaces.',
+ name: BrowserApiName.click,
+ parameters: {
+ properties: {
+ ref: {
+ description: 'Element ref from the latest snapshot, e.g. "e12".',
+ type: 'string',
+ },
+ x: {
+ description: 'Viewport x coordinate (only when no ref is available).',
+ type: 'number',
+ },
+ y: {
+ description: 'Viewport y coordinate (only when no ref is available).',
+ type: 'number',
+ },
+ },
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Fill a text input, textarea, or contenteditable identified by a snapshot ref. Set submit=true to press Enter afterwards.',
+ name: BrowserApiName.fill,
+ parameters: {
+ properties: {
+ ref: {
+ description: 'Element ref from the latest snapshot.',
+ type: 'string',
+ },
+ submit: {
+ description: 'Press Enter after filling (submit search/login forms).',
+ type: 'boolean',
+ },
+ text: {
+ description: 'Text to fill.',
+ type: 'string',
+ },
+ },
+ required: ['ref', 'text'],
+ type: 'object',
+ },
+ },
+ {
+ description: 'Send a keyboard key to the page, e.g. Enter, Tab, Escape, ArrowDown.',
+ name: BrowserApiName.press,
+ parameters: {
+ properties: {
+ key: {
+ description: 'KeyboardEvent.key value (Enter, Tab, Escape, ArrowDown, ...).',
+ type: 'string',
+ },
+ },
+ required: ['key'],
+ type: 'object',
+ },
+ },
+ {
+ description: 'Scroll the page vertically (positive dy scrolls down) or horizontally.',
+ name: BrowserApiName.scroll,
+ parameters: {
+ properties: {
+ dx: {
+ description: 'Horizontal pixels to scroll.',
+ type: 'number',
+ },
+ dy: {
+ description: 'Vertical pixels to scroll. Positive scrolls down.',
+ type: 'number',
+ },
+ },
+ required: ['dy'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Capture a screenshot of the current page for the USER to see in chat. You cannot see the image yourself — use snapshot/readPage for perception.',
+ name: BrowserApiName.screenshot,
+ parameters: {
+ properties: {},
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Extract the readable text content of the current page (for quoting or summarizing).',
+ name: BrowserApiName.readPage,
+ parameters: {
+ properties: {},
+ type: 'object',
+ },
+ },
+ ],
+ // `client`: runs in the desktop renderer (local runtime). `server`: cloud
+ // agent runs proxy each call back to the bound device via deviceGateway.
+ 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.',
+ title: 'Browser',
+ },
+ systemRole: systemPrompt,
+ type: 'builtin',
+};
diff --git a/packages/builtin-tool-browser/src/systemRole.ts b/packages/builtin-tool-browser/src/systemRole.ts
new file mode 100644
index 00000000000..4d940902e28
--- /dev/null
+++ b/packages/builtin-tool-browser/src/systemRole.ts
@@ -0,0 +1,14 @@
+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.
+
+Core workflow:
+1. \`navigate\` to a URL (opens the browser panel if needed).
+2. \`snapshot\` to perceive the page — it returns interactive elements with stable refs like \`[ref=e12]\`.
+3. Act with \`click\` / \`fill\` / \`press\` / \`scroll\` using those refs.
+4. Re-\`snapshot\` after anything that changes the page (navigation, dialogs, dynamic content). Refs are invalidated by navigation.
+5. \`readPage\` extracts the page text when you need to quote or summarize content.
+
+Notes:
+- \`fill\` sets an input's value directly; pass \`submit: true\` to press Enter afterwards (search boxes, login forms).
+- \`screenshot\` renders a visual for the USER's chat — you cannot see it. Use \`snapshot\` / \`readPage\` for your own perception.
+- 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.`;
diff --git a/packages/builtin-tool-browser/src/types.ts b/packages/builtin-tool-browser/src/types.ts
new file mode 100644
index 00000000000..3c8dbca0679
--- /dev/null
+++ b/packages/builtin-tool-browser/src/types.ts
@@ -0,0 +1,62 @@
+export const BrowserIdentifier = 'lobe-browser';
+
+export const BrowserApiName = {
+ click: 'click',
+ fill: 'fill',
+ navigate: 'navigate',
+ press: 'press',
+ readPage: 'readPage',
+ screenshot: 'screenshot',
+ scroll: 'scroll',
+ snapshot: 'snapshot',
+} as const;
+
+export type BrowserApiNameType = (typeof BrowserApiName)[keyof typeof BrowserApiName];
+
+export interface BrowserPageState {
+ title?: string;
+ url?: string;
+}
+
+export interface BrowserNavigateState extends BrowserPageState {}
+
+export interface BrowserSnapshotState extends BrowserPageState {
+ snapshot: string;
+}
+
+export interface BrowserClickState extends BrowserPageState {}
+
+export interface BrowserScreenshotState {
+ dataUrl: string;
+ height?: number;
+ width?: number;
+}
+
+export interface BrowserReadPageState extends BrowserPageState {
+ content: string;
+}
+
+export interface BrowserNavigateArgs {
+ url: string;
+}
+
+export interface BrowserClickArgs {
+ ref?: string;
+ x?: number;
+ y?: number;
+}
+
+export interface BrowserFillArgs {
+ ref: string;
+ submit?: boolean;
+ text: string;
+}
+
+export interface BrowserPressArgs {
+ key: string;
+}
+
+export interface BrowserScrollArgs {
+ dx?: number;
+ dy: number;
+}
diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.json
index 8f8b94acdb2..97fef0b559d 100644
--- a/packages/builtin-tools/package.json
+++ b/packages/builtin-tools/package.json
@@ -25,6 +25,7 @@
"@lobechat/builtin-tool-agent-management": "workspace:*",
"@lobechat/builtin-tool-agent-signal": "workspace:*",
"@lobechat/builtin-tool-brief": "workspace:*",
+ "@lobechat/builtin-tool-browser": "workspace:*",
"@lobechat/builtin-tool-claude-code": "workspace:*",
"@lobechat/builtin-tool-cloud-sandbox": "workspace:*",
"@lobechat/builtin-tool-creds": "workspace:*",
diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.ts
index 453adda20d3..8ba6da49bf2 100644
--- a/packages/builtin-tools/src/identifiers.ts
+++ b/packages/builtin-tools/src/identifiers.ts
@@ -8,6 +8,7 @@ import {
agentSignalReviewManifest,
agentSignalSkillManagementManifest,
} from '@lobechat/builtin-tool-agent-signal';
+import { BrowserManifest } from '@lobechat/builtin-tool-browser';
import { CalculatorManifest } from '@lobechat/builtin-tool-calculator';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { CredsManifest } from '@lobechat/builtin-tool-creds';
@@ -39,6 +40,7 @@ export const builtinToolIdentifiers: string[] = [
GroupAgentBuilderManifest.identifier,
GroupManagementManifest.identifier,
KnowledgeBaseManifest.identifier,
+ BrowserManifest.identifier,
LocalSystemManifest.identifier,
MemoryManifest.identifier,
NotebookManifest.identifier,
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index 9aa18fea28c..33a09373276 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -9,6 +9,7 @@ import {
agentSignalSkillManagementManifest,
} from '@lobechat/builtin-tool-agent-signal';
import { BriefManifest } from '@lobechat/builtin-tool-brief';
+import { BrowserManifest } from '@lobechat/builtin-tool-browser';
import { CalculatorManifest } from '@lobechat/builtin-tool-calculator';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { CredsManifest } from '@lobechat/builtin-tool-creds';
@@ -47,6 +48,7 @@ export const defaultToolIds = [
KnowledgeBaseManifest.identifier,
MemoryManifest.identifier,
LocalSystemManifest.identifier,
+ BrowserManifest.identifier,
CloudSandboxManifest.identifier,
TopicReferenceManifest.identifier,
AgentDocumentsManifest.identifier,
@@ -146,6 +148,7 @@ export const groupSupervisorToolIds = [GroupManagementManifest.identifier];
* `src/helpers/toolEngineering/index.ts`.
*/
export const runtimeManagedToolIds = [
+ BrowserManifest.identifier,
CloudSandboxManifest.identifier,
KnowledgeBaseManifest.identifier,
LocalSystemManifest.identifier,
@@ -229,6 +232,13 @@ const builtinToolRegistry: LobeBuiltinTool[] = [
manifest: agentSignalSkillManagementManifest,
type: 'builtin',
},
+ {
+ discoverable: isDesktop,
+ hidden: true,
+ identifier: BrowserManifest.identifier,
+ manifest: BrowserManifest,
+ type: 'builtin',
+ },
{
discoverable: isDesktop,
hidden: true,
diff --git a/packages/builtin-tools/src/register.ts b/packages/builtin-tools/src/register.ts
index eb5e71b9457..e601422248b 100644
--- a/packages/builtin-tools/src/register.ts
+++ b/packages/builtin-tools/src/register.ts
@@ -22,6 +22,7 @@ import {
AgentManagementRenders,
AgentManagementStreamings,
} from '@lobechat/builtin-tool-agent-management/client';
+import { BrowserManifest, BrowserRenders } from '@lobechat/builtin-tool-browser/client';
import {
ClaudeCodeIdentifier,
ClaudeCodeInspectors,
@@ -183,6 +184,7 @@ export const registerBuiltinToolSurfaces = (): void => {
string,
BuiltinRender
>,
+ [BrowserManifest.identifier]: BrowserRenders as Record<string, BuiltinRender>,
[LocalSystemManifest.identifier]: LocalSystemRenders as Record<string, BuiltinRender>,
[MemoryManifest.identifier]: MemoryRenders as Record<string, BuiltinRender>,
[MessageManifest.identifier]: MessageRenders as Record<string, BuiltinRender>,
diff --git a/packages/electron-client-ipc/src/events/browserSidebar.ts b/packages/electron-client-ipc/src/events/browserSidebar.ts
index 90863822ff5..36461413b15 100644
--- a/packages/electron-client-ipc/src/events/browserSidebar.ts
+++ b/packages/electron-client-ipc/src/events/browserSidebar.ts
@@ -1,5 +1,13 @@
+import type {
+ BrowserGatewayToolCallPayload,
+ BrowserSidebarAgentCursorPayload,
+ BrowserSidebarAgentStatePayload,
+} from '../types/browserControl';
import type { BrowserSidebarState } from '../types/browserSidebar';
export interface BrowserSidebarBroadcastEvents {
+ browserSidebarAgentCursor: (data: BrowserSidebarAgentCursorPayload) => void;
+ browserSidebarAgentState: (data: BrowserSidebarAgentStatePayload) => void;
+ browserSidebarGatewayToolCall: (data: BrowserGatewayToolCallPayload) => void;
browserSidebarStateChanged: (data: BrowserSidebarState) => void;
}
diff --git a/packages/electron-client-ipc/src/types/browserControl.ts b/packages/electron-client-ipc/src/types/browserControl.ts
new file mode 100644
index 00000000000..f7de9ec8564
--- /dev/null
+++ b/packages/electron-client-ipc/src/types/browserControl.ts
@@ -0,0 +1,98 @@
+export interface BrowserControlParams {
+ sessionId: string;
+}
+
+export interface BrowserControlResult {
+ error?: string;
+ success: boolean;
+}
+
+export interface BrowserControlPageInfo {
+ title?: string;
+ url?: string;
+}
+
+export interface BrowserControlSnapshotResult extends BrowserControlResult, BrowserControlPageInfo {
+ snapshot?: string;
+}
+
+export interface BrowserControlClickParams extends BrowserControlParams {
+ /** Element ref from the latest snapshot (e.g. `e12`). Preferred over coordinates. */
+ ref?: string;
+ /** Viewport coordinates fallback when no ref is available. */
+ x?: number;
+ y?: number;
+}
+
+export interface BrowserControlClickResult extends BrowserControlResult, BrowserControlPageInfo {}
+
+export interface BrowserControlFillParams extends BrowserControlParams {
+ ref: string;
+ /** Press Enter after filling (submit forms / search boxes). */
+ submit?: boolean;
+ text: string;
+}
+
+export interface BrowserControlPressParams extends BrowserControlParams {
+ /** KeyboardEvent.key value, e.g. `Enter`, `Tab`, `Escape`, `ArrowDown`. */
+ key: string;
+}
+
+export interface BrowserControlScrollParams extends BrowserControlParams {
+ dx?: number;
+ dy: number;
+}
+
+export interface BrowserControlScreenshotResult extends BrowserControlResult {
+ /** JPEG data URL, downscaled to a model-friendly width. */
+ dataUrl?: string;
+ height?: number;
+ width?: number;
+}
+
+export interface BrowserControlReadPageResult extends BrowserControlResult, BrowserControlPageInfo {
+ content?: string;
+}
+
+export interface BrowserControlWaitForParams extends BrowserControlParams {
+ /** Milliseconds to wait (capped). */
+ ms?: number;
+ /** Resolve early once this text appears in the page. */
+ text?: string;
+}
+
+export interface BrowserToolCallResult {
+ content?: string;
+ error?: { body?: unknown; message: string; type: string };
+ state?: unknown;
+ success: boolean;
+}
+
+/**
+ * A browser tool call proxied from a cloud agent run back to this device.
+ * The renderer runs the client `browserExecutor` and reports the result via
+ * `reportGatewayToolResult`, keyed by `requestId`.
+ */
+export interface BrowserGatewayToolCallPayload {
+ agentId: string;
+ apiName: string;
+ args: Record<string, unknown>;
+ requestId: string;
+}
+
+export interface BrowserGatewayToolResultParams {
+ requestId: string;
+ result: BrowserToolCallResult;
+}
+
+export interface BrowserSidebarAgentStatePayload {
+ active: boolean;
+ sessionId: string;
+}
+
+export interface BrowserSidebarAgentCursorPayload {
+ click?: boolean;
+ sessionId: string;
+ x: number;
+ y: number;
+}
diff --git a/packages/electron-client-ipc/src/types/index.ts b/packages/electron-client-ipc/src/types/index.ts
index d55bf02a80d..f4356d35754 100644
--- a/packages/electron-client-ipc/src/types/index.ts
+++ b/packages/electron-client-ipc/src/types/index.ts
@@ -1,4 +1,5 @@
export * from './binary';
+export * from './browserControl';
export * from './browserSidebar';
export * from './dataSync';
export * from './git';
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index ee6898a02f9..538e26f5eb6 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1354,10 +1354,14 @@ export default {
'workingPanel.browser.actions.reload': 'Reload',
'workingPanel.browser.actions.stop': 'Stop loading',
'workingPanel.browser.addressPlaceholder': 'Search or enter address',
+ 'workingPanel.browser.agentControlling': 'Agent is using the browser',
+ 'workingPanel.browser.agentCursor': 'Agent',
'workingPanel.browser.desktopOnly': 'The in-app browser is only available in the desktop app',
'workingPanel.browser.empty.desc': 'Enter an address or search above to open a page',
'workingPanel.browser.empty.title': 'Start browsing',
'workingPanel.browser.title': 'Browser',
+ 'workingPanel.browser.tool.elements_one': '{{count}} element',
+ 'workingPanel.browser.tool.elements_other': '{{count}} elements',
'workingPanel.progress': 'Progress',
'workingPanel.progress.allCompleted': 'All tasks completed',
'workingPanel.resources': 'Resources',
diff --git a/src/features/DesktopBrowserGatewayBridge/index.tsx b/src/features/DesktopBrowserGatewayBridge/index.tsx
new file mode 100644
index 00000000000..1138a9845ea
--- /dev/null
+++ b/src/features/DesktopBrowserGatewayBridge/index.tsx
@@ -0,0 +1,64 @@
+'use client';
+
+import { useWatchBroadcast } from '@lobechat/electron-client-ipc';
+import { memo, useCallback } from 'react';
+
+import { electronBrowserControlService } from '@/services/electron/browserControl';
+import { invokeExecutor } from '@/store/tool/slices/builtin/executors';
+
+const BROWSER_IDENTIFIER = 'lobe-browser';
+
+/**
+ * Desktop-only bridge for cloud-agent (gateway) browser tool calls.
+ *
+ * When an agent runs server-side, its browser tool calls are proxied back to
+ * this device by the main process, which broadcasts `browserSidebarGatewayToolCall`.
+ * Here we run the exact same client `browserExecutor` used for local runs (so
+ * the mount / snapshot / click behavior has one source of truth) and report the
+ * result back to the main process, keyed by requestId.
+ */
+const DesktopBrowserGatewayBridge = memo(() => {
+ const handleToolCall = useCallback(
+ async ({
+ agentId,
+ apiName,
+ args,
+ requestId,
+ }: {
+ agentId: string;
+ apiName: string;
+ args: Record<string, unknown>;
+ requestId: string;
+ }) => {
+ try {
+ const result = await invokeExecutor(BROWSER_IDENTIFIER, apiName, args, {
+ agentId,
+ messageId: `gateway-${requestId}`,
+ });
+ await electronBrowserControlService.reportGatewayToolResult({
+ requestId,
+ result: {
+ content: result.content,
+ error: result.error,
+ state: result.state,
+ success: result.success,
+ },
+ });
+ } catch (error) {
+ await electronBrowserControlService.reportGatewayToolResult({
+ requestId,
+ result: { content: (error as Error).message, success: false },
+ });
+ }
+ },
+ [],
+ );
+
+ useWatchBroadcast('browserSidebarGatewayToolCall', handleToolCall);
+
+ return null;
+});
+
+DesktopBrowserGatewayBridge.displayName = 'DesktopBrowserGatewayBridge';
+
+export default DesktopBrowserGatewayBridge;
diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.ts
index 241c571b56e..a2411a930df 100644
--- a/src/helpers/toolEngineering/index.test.ts
+++ b/src/helpers/toolEngineering/index.test.ts
@@ -145,6 +145,9 @@ vi.mock('@/store/user', () => ({
}));
vi.mock('@/store/user/selectors', () => ({
+ labPreferSelectors: {
+ enableInAppBrowser: () => false,
+ },
settingsSelectors: {
memoryEnabled: () => false,
},
diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.ts
index 9450c06673d..8702eb57129 100644
--- a/src/helpers/toolEngineering/index.ts
+++ b/src/helpers/toolEngineering/index.ts
@@ -1,6 +1,7 @@
/**
* Tools Engineering - Unified tools processing using ToolsEngine
*/
+import { BrowserManifest } from '@lobechat/builtin-tool-browser';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { KnowledgeBaseManifest } from '@lobechat/builtin-tool-knowledge-base';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
@@ -30,7 +31,7 @@ import {
} from '@/store/tool/selectors';
import { connectorSelectors } from '@/store/tool/slices/connector';
import { useUserStore } from '@/store/user';
-import { settingsSelectors } from '@/store/user/selectors';
+import { labPreferSelectors, settingsSelectors } from '@/store/user/selectors';
import { getSearchConfig } from '../getSearchConfig';
import { isCanUseFC } from '../isCanUseFC';
@@ -241,6 +242,13 @@ export const createAgentToolsEngine = (
// Always-on builtin tools
...Object.fromEntries(alwaysOnToolIds.map((id) => [id, true])),
// System-level rules (may override user selection for specific tools)
+ // Browser rides the same local-runtime gate as local-system (the control
+ // IPC only exists in the desktop main process), plus the in-app browser
+ // Labs toggle that also governs the sidebar tab — with the lab off the
+ // tool would drive a pane the user can't see.
+ [BrowserManifest.identifier]:
+ agentChatConfigSelectors.isLocalSystemEnabled(agentState) &&
+ labPreferSelectors.enableInAppBrowser(useUserStore.getState()),
[CloudSandboxManifest.identifier]: agentChatConfigSelectors.isCloudSandboxEnabled(agentState),
[KnowledgeBaseManifest.identifier]: kbEnabled,
[LocalSystemManifest.identifier]: agentChatConfigSelectors.isLocalSystemEnabled(agentState),
diff --git a/src/routes/(main)/_layout/index.tsx b/src/routes/(main)/_layout/index.tsx
index e9aa741ef90..faf81628bc5 100644
--- a/src/routes/(main)/_layout/index.tsx
+++ b/src/routes/(main)/_layout/index.tsx
@@ -13,6 +13,7 @@ import WorkspaceContextSlot from '@/business/client/WorkspaceContextSlot';
import Loading from '@/components/Loading/BrandTextLoading';
import { isDesktop } from '@/const/version';
import { BANNER_HEIGHT } from '@/features/AlertBanner/CloudBanner';
+import DesktopBrowserGatewayBridge from '@/features/DesktopBrowserGatewayBridge';
import DesktopFileMenuBridge from '@/features/DesktopFileMenuBridge';
import DesktopNavigationBridge from '@/features/DesktopNavigationBridge';
import AuthRequiredModal from '@/features/Electron/AuthRequiredModal';
@@ -39,9 +40,7 @@ import RegisterHotkeys from './RegisterHotkeys';
import { styles } from './style';
const CloudBanner = dynamic(() => import('@/features/AlertBanner/CloudBanner'));
-const GlobalApprovalNotification = dynamic(
- () => import('@/features/GlobalApprovalNotification'),
-);
+const GlobalApprovalNotification = dynamic(() => import('@/features/GlobalApprovalNotification'));
const Layout: FC = () => {
const { isPWA } = usePlatform();
@@ -56,6 +55,7 @@ const Layout: FC = () => {
{isDesktop && <DesktopAutoOidcOnFirstOpen />}
{isDesktop && <DesktopNavigationBridge />}
{isDesktop && <DesktopFileMenuBridge />}
+ {isDesktop && <DesktopBrowserGatewayBridge />}
{isDesktop && <OverlaySnapshotPublisher />}
{isDesktop && <OverlayCaptureUploader />}
{isDesktop && <OverlayMessageDispatcher />}
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/AgentOverlay.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/AgentOverlay.tsx
new file mode 100644
index 00000000000..3f0a3e97a5c
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/AgentOverlay.tsx
@@ -0,0 +1,183 @@
+import { useWatchBroadcast } from '@lobechat/electron-client-ipc';
+import { Flexbox } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ chip: css`
+ pointer-events: none;
+
+ position: absolute;
+ z-index: 20;
+ inset-block-start: 8px;
+ inset-inline-start: 50%;
+ transform: translateX(-50%);
+
+ display: flex;
+ gap: 6px;
+ align-items: center;
+
+ padding-block: 4px;
+ padding-inline: 10px;
+ border-radius: 16px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextLightSolid};
+
+ background: ${cssVar.colorBgMask};
+ backdrop-filter: blur(4px);
+ `,
+ cursor: css`
+ pointer-events: none;
+
+ position: absolute;
+ z-index: 20;
+
+ margin-block-start: -4px;
+ margin-inline-start: -4px;
+
+ transition:
+ inset-inline-start 0.4s cubic-bezier(0.3, 0.9, 0.4, 1),
+ inset-block-start 0.4s cubic-bezier(0.3, 0.9, 0.4, 1);
+ `,
+ cursorLabel: css`
+ position: absolute;
+ inset-block-start: 18px;
+ inset-inline-start: 13px;
+
+ padding-block: 2px;
+ padding-inline: 8px;
+ border-radius: 20px;
+
+ font-size: 12px;
+ font-weight: 500;
+ line-height: 18px;
+ color: #fff;
+ white-space: nowrap;
+
+ background: ${cssVar.geekblue};
+ box-shadow: 0 1px 4px rgb(0 0 0 / 15%);
+ `,
+ cursorSvg: css`
+ display: block;
+ color: ${cssVar.geekblue};
+ filter: drop-shadow(0 1px 2px rgb(0 0 0 / 30%));
+ `,
+ dot: css`
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+
+ background: ${cssVar.colorSuccess};
+
+ animation: lobe-browser-agent-pulse 1.2s ease-in-out infinite;
+
+ @keyframes lobe-browser-agent-pulse {
+ 50% {
+ opacity: 0.3;
+ }
+ }
+ `,
+ ripple: css`
+ position: absolute;
+ inset-block-start: -10px;
+ inset-inline-start: -10px;
+
+ width: 28px;
+ height: 28px;
+ border: 2px solid ${cssVar.geekblue};
+ border-radius: 50%;
+
+ opacity: 0;
+
+ animation: lobe-browser-agent-ripple 0.5s ease-out 0.45s;
+
+ @keyframes lobe-browser-agent-ripple {
+ 0% {
+ transform: scale(0.4);
+ opacity: 1;
+ }
+
+ 100% {
+ transform: scale(1.2);
+ opacity: 0;
+ }
+ }
+ `,
+}));
+
+interface AgentOverlayProps {
+ sessionId: string;
+}
+
+/**
+ * Draws the agent-control affordances above the webview: a floating cursor
+ * that glides to each click target (broadcast by BrowserControlCtr before the
+ * real input event lands) and a "controlling" status chip.
+ */
+const AgentOverlay = memo<AgentOverlayProps>(({ sessionId }) => {
+ const { t } = useTranslation('chat');
+ const [controlling, setControlling] = useState(false);
+ const [cursor, setCursor] = useState<{ visible: boolean; x: number; y: number }>({
+ visible: false,
+ x: 0,
+ y: 0,
+ });
+ // Remount the ripple animation per click.
+ const [clickSeq, setClickSeq] = useState(0);
+
+ useWatchBroadcast('browserSidebarAgentState', (data) => {
+ if (data.sessionId !== sessionId) return;
+ setControlling(data.active);
+ if (!data.active) setCursor((prev) => ({ ...prev, visible: false }));
+ });
+
+ useWatchBroadcast('browserSidebarAgentCursor', (data) => {
+ if (data.sessionId !== sessionId) return;
+ setCursor({ visible: true, x: data.x, y: data.y });
+ if (data.click) setClickSeq((n) => n + 1);
+ });
+
+ return (
+ <>
+ {controlling && (
+ <Flexbox horizontal className={styles.chip}>
+ <span className={styles.dot} />
+ {t('workingPanel.browser.agentControlling')}
+ </Flexbox>
+ )}
+ {cursor.visible && (
+ <div
+ className={styles.cursor}
+ style={{ insetBlockStart: cursor.y, insetInlineStart: cursor.x }}
+ >
+ {clickSeq > 0 && <div className={styles.ripple} key={clickSeq} />}
+ <svg className={styles.cursorSvg} fill="none" height={22} viewBox="0 0 24 24" width={22}>
+ {/* White halo underneath the body. */}
+ <path
+ d="M5 3l14 8-6.5 1.5L9 19 5 3z"
+ stroke="#fff"
+ strokeLinejoin="round"
+ strokeWidth={2.2}
+ />
+ {/* A same-color round-joined stroke softens the arrow's sharp
+ vertices with a ~0.4 corner radius (radius = width / 2). */}
+ <path
+ d="M5 3l14 8-6.5 1.5L9 19 5 3z"
+ fill="currentColor"
+ stroke="currentColor"
+ strokeLinejoin="round"
+ strokeWidth={0.8}
+ />
+ </svg>
+ <div className={styles.cursorLabel}>{t('workingPanel.browser.agentCursor')}</div>
+ </div>
+ )}
+ </>
+ );
+});
+
+AgentOverlay.displayName = 'AgentOverlay';
+
+export default AgentOverlay;
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/index.tsx
index 578b524baf4..bb5bd07c2cd 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/index.tsx
@@ -18,6 +18,7 @@ import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import { electronBrowserSidebarService } from '@/services/electron/browserSidebar';
import { useGlobalStore } from '@/store/global';
+import AgentOverlay from './AgentOverlay';
import { BROWSER_WEBVIEW_PARTITION, BROWSER_WEBVIEW_SESSION_ATTRIBUTE } from './const';
import { useBrowserSidebarState } from './useBrowserSidebarState';
import { normalizeBrowserUrl } from './utils';
@@ -228,6 +229,7 @@ const BrowserPane = memo<BrowserPaneProps>(({ sessionId }) => {
/>
</Flexbox>
<Flexbox className={styles.container}>
+ <AgentOverlay sessionId={sessionId} />
{initialUrl ? (
<webview
className={styles.webview}
diff --git a/src/services/electron/browserControl.ts b/src/services/electron/browserControl.ts
new file mode 100644
index 00000000000..5016331ecf4
--- /dev/null
+++ b/src/services/electron/browserControl.ts
@@ -0,0 +1,60 @@
+import type {
+ BrowserControlClickParams,
+ BrowserControlClickResult,
+ BrowserControlFillParams,
+ BrowserControlParams,
+ BrowserControlPressParams,
+ BrowserControlReadPageResult,
+ BrowserControlResult,
+ BrowserControlScreenshotResult,
+ BrowserControlScrollParams,
+ BrowserControlSnapshotResult,
+ BrowserControlWaitForParams,
+ BrowserGatewayToolResultParams,
+} from '@lobechat/electron-client-ipc';
+
+import { ensureElectronIpc } from '@/utils/electron/ipc';
+
+class ElectronBrowserControlService {
+ private get ipc() {
+ return ensureElectronIpc();
+ }
+
+ reportGatewayToolResult(params: BrowserGatewayToolResultParams): Promise<void> {
+ return this.ipc.browserControl.reportGatewayToolResult(params);
+ }
+
+ click(params: BrowserControlClickParams): Promise<BrowserControlClickResult> {
+ return this.ipc.browserControl.click(params);
+ }
+
+ fill(params: BrowserControlFillParams): Promise<BrowserControlResult> {
+ return this.ipc.browserControl.fill(params);
+ }
+
+ press(params: BrowserControlPressParams): Promise<BrowserControlResult> {
+ return this.ipc.browserControl.press(params);
+ }
+
+ readPage(params: BrowserControlParams): Promise<BrowserControlReadPageResult> {
+ return this.ipc.browserControl.readPage(params);
+ }
+
+ screenshot(params: BrowserControlParams): Promise<BrowserControlScreenshotResult> {
+ return this.ipc.browserControl.screenshot(params);
+ }
+
+ scroll(params: BrowserControlScrollParams): Promise<BrowserControlResult> {
+ return this.ipc.browserControl.scroll(params);
+ }
+
+ snapshot(params: BrowserControlParams): Promise<BrowserControlSnapshotResult> {
+ return this.ipc.browserControl.snapshot(params);
+ }
+
+ waitFor(params: BrowserControlWaitForParams): Promise<BrowserControlResult> {
+ return this.ipc.browserControl.waitFor(params);
+ }
+}
+
+export const electronBrowserControlService = new ElectronBrowserControlService();
diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.ts
index 11d978ac394..17ec32e98dc 100644
--- a/src/store/tool/slices/builtin/executors/index.ts
+++ b/src/store/tool/slices/builtin/executors/index.ts
@@ -8,6 +8,7 @@
import { agentBuilderExecutor } from '@lobechat/builtin-tool-agent-builder/executor';
import { agentManagementExecutor } from '@lobechat/builtin-tool-agent-management/executor';
+import { browserExecutor } from '@lobechat/builtin-tool-browser/client/executor';
import { calculatorExecutor } from '@lobechat/builtin-tool-calculator/executor';
import { cloudSandboxExecutor } from '@lobechat/builtin-tool-cloud-sandbox/executor';
import { credsExecutor } from '@lobechat/builtin-tool-creds/executor';
@@ -151,6 +152,7 @@ export const registerBuiltinToolExecutors = (): void => {
groupAgentBuilderExecutor,
groupManagementExecutor,
knowledgeBaseExecutor,
+ browserExecutor,
localSystemExecutor,
memoryExecutor,
messageExecutor,