Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): add embedded browser automation capabilities (#696)

DavidShenXDa1e1bd53ed66
diff --git a/apps/desktop/src/main/__tests__/webview-security.test.ts b/apps/desktop/src/main/__tests__/webview-security.test.ts
index 5592f9acb2..407b460e3b 100644
--- a/apps/desktop/src/main/__tests__/webview-security.test.ts
+++ b/apps/desktop/src/main/__tests__/webview-security.test.ts
@@ -65,6 +65,7 @@ describe('applyWebviewHardening', () => {
expect(webPreferences.allowRunningInsecureContent).toBe(false);
expect(webPreferences.webviewTag).toBe(false);
expect(webPreferences.plugins).toBe(false);
+ expect(webPreferences.disableDialogs).toBe(false);
expect(webPreferences.disablePopups).toBe(false);
// 比 tY 多一步 preload 删除(未传 commentPreloadPath 的回落分支)
expect('preload' in webPreferences).toBe(false);
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 71ac7103ee..3ab6e34331 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -356,6 +356,7 @@ import {
import {
disposeBrowserRuntime,
registerBrowserBackendIpc,
+ setBrowserSessionUploadRootResolver,
setMainWindowAccessorForBackend,
setEnsureHostForBackend,
setIsDetachedForBackend,
@@ -1097,6 +1098,15 @@ registerTabOpResultHandler({
setMainWindowAccessorForBackend(() => rsbWindowController.getHostWebContents());
setEnsureHostForBackend(() => rsbWindowController.ensureOpenForAutomation());
setIsDetachedForBackend(() => readRsbWindowSettings().detached);
+setBrowserSessionUploadRootResolver(async (sessionId) => {
+ try {
+ const meta = await getMakerCore().getSessionMeta(sessionId);
+ if (!meta?.workDir || meta.remoteHostId) return [];
+ return [meta.workDir];
+ } catch {
+ return [];
+ }
+});
registerBrowserBackendIpc();
// ── 应用级快捷键 override 存储 IPC ──────────────────────────────────────
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-artifacts.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-artifacts.test.ts
new file mode 100644
index 0000000000..1cfd48d857
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-artifacts.test.ts
@@ -0,0 +1,361 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { WebContents } from 'electron';
+
+import { RsbWebviewArtifacts } from '../rsb-webview-artifacts.js';
+
+function artifactHarness() {
+ const listeners = new Map<string, Set<(...args: unknown[]) => void>>();
+ const session = {
+ on: (event: string, listener: (...args: unknown[]) => void) => {
+ const group = listeners.get(event) ?? new Set();
+ group.add(listener);
+ listeners.set(event, group);
+ },
+ removeListener: (event: string, listener: (...args: unknown[]) => void) => {
+ listeners.get(event)?.delete(listener);
+ },
+ };
+ const wc = { session } as unknown as WebContents;
+ const emitDownload = (item: ReturnType<typeof downloadItem>) => {
+ for (const listener of listeners.get('will-download') ?? []) {
+ listener({}, item, wc);
+ }
+ };
+ return { wc, emitDownload };
+}
+
+function downloadItem(
+ finalState: 'completed' | 'cancelled' | 'interrupted',
+ options: { totalBytes?: number; receivedBytes?: number } = {},
+) {
+ let savePath = '';
+ let doneListener: ((...args: unknown[]) => void) | undefined;
+ let updateListener: ((...args: unknown[]) => void) | undefined;
+ let receivedBytes = options.receivedBytes ?? options.totalBytes ?? 5;
+ return {
+ getFilename: () => '../unsafe?.txt',
+ getURL: () => 'https://example.test/download',
+ getMimeType: () => 'text/plain',
+ getTotalBytes: () => options.totalBytes ?? 5,
+ getReceivedBytes: () => receivedBytes,
+ setSavePath: vi.fn((value: string) => {
+ savePath = value;
+ fs.writeFileSync(value, 'hello');
+ }),
+ cancel: vi.fn(),
+ on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
+ if (event === 'updated') updateListener = listener;
+ }),
+ once: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
+ if (event === 'done') doneListener = listener;
+ }),
+ finish: () => doneListener?.({}, finalState),
+ update: (value: number) => {
+ receivedBytes = value;
+ updateListener?.();
+ },
+ savedPath: () => savePath,
+ };
+}
+
+let root = '';
+
+beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-browser-artifact-test-'));
+});
+
+afterEach(() => {
+ fs.rmSync(root, { recursive: true, force: true });
+});
+
+describe('RsbWebviewArtifacts', () => {
+ it('reclaims artifact roots left by a dead process before reuse', async () => {
+ const staleRoot = path.join(root, 'process-99999999');
+ await fs.promises.mkdir(staleRoot, { recursive: true });
+ await fs.promises.writeFile(path.join(staleRoot, 'stale.txt'), 'stale');
+ const harness = artifactHarness();
+ const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() }, 0);
+
+ await artifacts.capture(
+ harness.wc,
+ { sessionId: 'startup-cleanup', timeoutMs: 1000 },
+ async () => undefined,
+ );
+
+ expect(fs.existsSync(staleRoot)).toBe(false);
+ });
+
+ it('stores a completed download in an isolated directory with a safe name', async () => {
+ const harness = artifactHarness();
+ const item = downloadItem('completed');
+ const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });
+
+ const result = await artifacts.capture(
+ harness.wc,
+ { sessionId: 'session/one', timeoutMs: 1000 },
+ async () => {
+ harness.emitDownload(item);
+ setTimeout(() => item.finish(), 0);
+ return 'clicked';
+ },
+ );
+
+ expect(result.value).toBe('clicked');
+ expect(result.downloads).toEqual([
+ expect.objectContaining({
+ fileName: 'unsafe.txt',
+ state: 'completed',
+ bytes: 5,
+ }),
+ ]);
+ expect(result.downloads[0].path).toBe(item.savedPath());
+ expect(fs.readFileSync(item.savedPath(), 'utf8')).toBe('hello');
+ });
+
+ it('removes partial files after a cancelled download', async () => {
+ const harness = artifactHarness();
+ const item = downloadItem('cancelled');
+ const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });
+
+ const result = await artifacts.capture(
+ harness.wc,
+ { sessionId: 'session-two', timeoutMs: 1000 },
+ async () => {
+ harness.emitDownload(item);
+ setTimeout(() => item.finish(), 0);
+ },
+ );
+
+ expect(result.downloads[0]).toMatchObject({ state: 'cancelled' });
+ expect(result.downloads[0].path).toBeUndefined();
+ expect(fs.existsSync(item.savedPath())).toBe(false);
+ });
+
+ it('does not intercept downloads outside an active agent action', async () => {
+ const harness = artifactHarness();
+ const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });
+ await artifacts.capture(harness.wc, { sessionId: 'session-three' }, async () => undefined);
+
+ const item = downloadItem('completed');
+ harness.emitDownload(item);
+
+ expect(item.setSavePath).not.toHaveBeenCalled();
+ });
+
+ it('captures a download that starts after the action returns', async () => {
+ const harness = artifactHarness();
+ const item = downloadItem('completed');
+ const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });
+
+ const result = await artifacts.capture(
+ harness.wc,
+ { sessionId: 'delayed-download', timeoutMs: 2_000 },
+ async () => {
+ setTimeout(() => {
+ harness.emitDownload(item);
+ setTimeout(() => item.finish(), 0);
+ }, 300);
+ return 'clicked';
+ },
+ );
+
+ expect(result.downloads).toHaveLength(1);
+ expect(result.downloads[0].state).toBe('completed');
+ });
+
+ it('limits artifact diagnostics to the requested session', async () => {
+ const harness = artifactHarness();
+ const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });
+
+ for (const sessionId of ['session-a', 'session-b']) {
+ const item = downloadItem('completed');
+ await artifacts.capture(
+ harness.wc,
+ { sessionId, timeoutMs: 1_000 },
+ async () => {
+ harness.emitDownload(item);
+ setTimeout(() => item.finish(), 0);
+ },
+ );
+ }
+
+ expect(artifacts.diagnostics('session-a').recentArtifacts).toHaveLength(1);
+ expect(artifacts.diagnostics('session-b').recentArtifacts).toHaveLength(1);
+ expect(artifacts.diagnostics('session-c').recentArtifacts).toHaveLength(0);
+ });
+
+ it('cancels a download that exceeds the per-file quota before saving', async () => {
+ const harness = artifactHarness();
+ const item = downloadItem('cancelled', { totalBytes: 32 * 1024 * 1024 + 1 });
+ const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });
+
+ const result = await artifacts.capture(
+ harness.wc,
+ { sessionId: 'quota-file', timeoutMs: 1000 },
+ async () => {
+ harness.emitDownload(item);
+ setTimeout(() => item.finish(), 0);
+ },
+ );
+
+ expect(item.cancel).toHaveBeenCalledTimes(1);
+ expect(item.setSavePath).not.toHaveBeenCalled();
+ expect(result.downloads[0]).toMatchObject({ state: 'cancelled' });
+ });
+
+ it('cancels a download that crosses the quota while streaming', async () => {
+ const harness = artifactHarness();
+ const item = downloadItem('cancelled', { totalBytes: 0, receivedBytes: 0 });
+ const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });
+
+ const result = await artifacts.capture(
+ harness.wc,
+ { sessionId: 'quota-stream', timeoutMs: 1000 },
+ async () => {
+ harness.emitDownload(item);
+ item.update(32 * 1024 * 1024 + 1);
+ setTimeout(() => item.finish(), 0);
+ },
+ );
+
+ expect(item.setSavePath).toHaveBeenCalledTimes(1);
+ expect(item.cancel).toHaveBeenCalledTimes(1);
+ expect(result.downloads[0]).toMatchObject({ state: 'cancelled' });
+ expect(fs.existsSync(item.savedPath())).toBe(false);
+ });
+
+ it('counts streaming bytes beyond a declared total toward the capture quota', async () => {
+ const harness = artifactHarness();
+ const items = Array.from({ length: 4 }, () => (
+ downloadItem('completed', { totalBytes: 16 * 1024 * 1024 })
+ ));
+ const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });
+
+ const result = await artifacts.capture(
+ harness.wc,
+ { sessionId: 'quota-known-total-overrun', timeoutMs: 1000 },
+ async () => {
+ for (const item of items) harness.emitDownload(item);
+ items[3].update(17 * 1024 * 1024);
+ setTimeout(() => {
+ for (const item of items) item.finish();
+ }, 0);
+ },
+ );
+
+ expect(items[3].cancel).toHaveBeenCalledTimes(1);
+ expect(result.downloads.map((artifact) => artifact.state)).toEqual([
+ 'completed',
+ 'completed',
+ 'completed',
+ 'cancelled',
+ ]);
+ });
+
+ it('bounds both download count and total bytes for one action', async () => {
+ const harness = artifactHarness();
+ const items = Array.from({ length: 9 }, () => (
+ downloadItem('completed', { totalBytes: 20 * 1024 * 1024 })
+ ));
+ const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });
+
+ const result = await artifacts.capture(
+ harness.wc,
+ { sessionId: 'quota-capture', timeoutMs: 1000 },
+ async () => {
+ for (const item of items) harness.emitDownload(item);
+ setTimeout(() => {
+ for (const item of items) item.finish();
+ }, 0);
+ },
+ );
+
+ expect(result.downloads).toHaveLength(8);
+ expect(items.slice(0, 3).every((item) => item.setSavePath.mock.calls.length === 1)).toBe(true);
+ expect(items[3].cancel).toHaveBeenCalledTimes(1);
+ expect(items[8].cancel).toHaveBeenCalledTimes(1);
+ expect(result.downloads.slice(3).every((artifact) => artifact.state === 'cancelled')).toBe(true);
+ });
+
+ it('releases reserved bytes after a download is cancelled', async () => {
+ const harness = artifactHarness();
+ const cancelled = downloadItem('cancelled', { totalBytes: 32 * 1024 * 1024 });
+ const later = [
+ downloadItem('completed', { totalBytes: 32 * 1024 * 1024 }),
+ downloadItem('completed', { totalBytes: 32 * 1024 * 1024 }),
+ ];
+ const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });
+
+ const result = await artifacts.capture(
+ harness.wc,
+ { sessionId: 'quota-release', timeoutMs: 1000 },
+ async () => {
+ harness.emitDownload(cancelled);
+ cancelled.finish();
+ for (const item of later) harness.emitDownload(item);
+ setTimeout(() => {
+ for (const item of later) item.finish();
+ }, 0);
+ },
+ );
+
+ expect(later.every((item) => item.setSavePath.mock.calls.length === 1)).toBe(true);
+ expect(result.downloads.map((artifact) => artifact.state)).toEqual([
+ 'cancelled',
+ 'completed',
+ 'completed',
+ ]);
+ });
+
+ it('removes retained artifacts when the backend is disposed', async () => {
+ const harness = artifactHarness();
+ const item = downloadItem('completed');
+ const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });
+
+ const result = await artifacts.capture(
+ harness.wc,
+ { sessionId: 'dispose-cleanup', timeoutMs: 1000 },
+ async () => {
+ harness.emitDownload(item);
+ setTimeout(() => item.finish(), 0);
+ },
+ );
+ const artifactPath = result.downloads[0].path;
+
+ expect(artifactPath).toBeDefined();
+ await artifacts.dispose();
+ expect(fs.existsSync(artifactPath!)).toBe(false);
+ });
+
+ it('evicts the oldest files when retained bytes exceed the global budget', async () => {
+ const harness = artifactHarness();
+ const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() }, 0);
+ const savedPaths: string[] = [];
+
+ for (let captureIndex = 0; captureIndex < 5; captureIndex += 1) {
+ const items = [
+ downloadItem('completed', { totalBytes: 32 * 1024 * 1024 }),
+ downloadItem('completed', { totalBytes: 32 * 1024 * 1024 }),
+ ];
+ await artifacts.capture(
+ harness.wc,
+ { sessionId: 'quota-retained', timeoutMs: 1000 },
+ async () => {
+ for (const item of items) harness.emitDownload(item);
+ setTimeout(() => {
+ for (const item of items) item.finish();
+ }, 0);
+ },
+ );
+ savedPaths.push(...items.map((item) => item.savedPath()));
+ }
+
+ expect(fs.existsSync(savedPaths[0])).toBe(false);
+ expect(fs.existsSync(savedPaths[1])).toBe(false);
+ expect(fs.existsSync(savedPaths.at(-1)!)).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-automation.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-automation.test.ts
new file mode 100644
index 0000000000..1e7224038c
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-automation.test.ts
@@ -0,0 +1,707 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { WebContents } from 'electron';
+
+import { RsbWebviewAutomation } from '../rsb-webview-automation.js';
+
+interface DebuggerHarness {
+ wc: WebContents;
+ sendCommand: ReturnType<typeof vi.fn>;
+ executeJavaScript: ReturnType<typeof vi.fn>;
+ attach: ReturnType<typeof vi.fn>;
+ detach: ReturnType<typeof vi.fn>;
+}
+
+function debuggerHarness(
+ handler: (method: string, params?: Record<string, unknown>) => unknown | Promise<unknown>,
+ alreadyAttached = false,
+): DebuggerHarness {
+ let attached = alreadyAttached;
+ const attach = vi.fn(() => {
+ attached = true;
+ });
+ const detach = vi.fn(() => {
+ attached = false;
+ });
+ const sendCommand = vi.fn(handler);
+ const executeJavaScript = vi.fn(async () => ({ ok: true }));
+ const wc = {
+ getURL: () => 'https://example.test/form',
+ executeJavaScript,
+ debugger: {
+ isAttached: vi.fn(() => attached),
+ attach,
+ detach,
+ sendCommand,
+ },
+ } as unknown as WebContents;
+ return { wc, sendCommand, executeJavaScript, attach, detach };
+}
+
+function automation(): RsbWebviewAutomation {
+ return new RsbWebviewAutomation({ warn: vi.fn() });
+}
+
+const AX_TREE = {
+ nodes: [
+ {
+ nodeId: 'root',
+ role: { value: 'RootWebArea' },
+ name: { value: 'Example' },
+ backendDOMNodeId: 1,
+ childIds: ['button', 'textbox'],
+ },
+ {
+ nodeId: 'button',
+ role: { value: 'button' },
+ name: { value: 'Submit' },
+ backendDOMNodeId: 2,
+ childIds: [],
+ },
+ {
+ nodeId: 'textbox',
+ role: { value: 'textbox' },
+ name: { value: 'Email' },
+ value: { value: '[email protected]' },
+ backendDOMNodeId: 3,
+ childIds: [],
+ },
+ ],
+};
+
+describe('RsbWebviewAutomation snapshot', () => {
+ it('builds an AI role snapshot with actionable refs and releases its debugger', async () => {
+ const harness = debuggerHarness(async (method) => {
+ if (method === 'Accessibility.enable') return {};
+ if (method === 'Accessibility.getFullAXTree') return AX_TREE;
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ const result = await automation().snapshot('tab-1', harness.wc, {
+ action: 'snapshot',
+ interactive: true,
+ });
+
+ expect(result).toMatchObject({
+ format: 'ai',
+ targetId: 'tab-1',
+ url: 'https://example.test/form',
+ refs: {
+ e1: { role: 'button', name: 'Submit', backendDOMNodeId: 2 },
+ e2: { role: 'textbox', name: 'Email', backendDOMNodeId: 3 },
+ },
+ stats: { refs: 2, interactive: 2 },
+ });
+ expect(result.snapshot).toContain('- button "Submit" [ref=e1]');
+ expect(result.snapshot).toContain('- textbox "Email" [ref=e2]');
+ expect(harness.attach).toHaveBeenCalledWith('1.3');
+ expect(harness.detach).toHaveBeenCalledTimes(1);
+ });
+
+ it('supports aria output, selector scoping and limits', async () => {
+ const harness = debuggerHarness(async (method) => {
+ if (method === 'Runtime.evaluate') return { result: { objectId: 'selector-object' } };
+ if (method === 'DOM.describeNode') return { node: { backendNodeId: 2 } };
+ if (method === 'Accessibility.enable') return {};
+ if (method === 'Accessibility.getPartialAXTree') return AX_TREE;
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ const result = await automation().snapshot('tab-1', harness.wc, {
+ action: 'snapshot',
+ snapshotFormat: 'aria',
+ selector: '#form',
+ limit: 1,
+ });
+
+ expect(result.format).toBe('aria');
+ expect(result.nodes).toHaveLength(1);
+ expect(harness.sendCommand).toHaveBeenCalledWith('Accessibility.getPartialAXTree', {
+ backendNodeId: 2,
+ fetchRelatives: true,
+ });
+ expect(harness.sendCommand).toHaveBeenCalledWith('Runtime.releaseObject', {
+ objectId: 'selector-object',
+ });
+ });
+
+ it('returns a bounded resource list and authorizes only the latest snapshot URLs', async () => {
+ const instance = automation();
+ const harness = debuggerHarness(async (method, params) => {
+ if (method === 'Runtime.evaluate') {
+ expect(params?.expression).toContain('document.querySelectorAll');
+ return {
+ result: {
+ value: {
+ resources: [
+ {
+ kind: 'image',
+ url: 'https://cdn.example.test/image.png',
+ label: 'Preview',
+ },
+ ],
+ },
+ },
+ };
+ }
+ if (method === 'Accessibility.enable') return {};
+ if (method === 'Accessibility.getFullAXTree') return AX_TREE;
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ const result = await instance.snapshot('tab-1', harness.wc, {
+ action: 'snapshot',
+ urls: true,
+ });
+
+ expect(result.resources).toEqual([
+ {
+ kind: 'image',
+ url: 'https://cdn.example.test/image.png',
+ label: 'Preview',
+ },
+ ]);
+ expect(() =>
+ instance.assertResource('tab-1', 'https://cdn.example.test/image.png'),
+ ).not.toThrow();
+ expect(() => instance.assertResource('tab-1', 'https://other.example.test/file.zip')).toThrow(
+ 'not present in the latest page resource list',
+ );
+ });
+
+ it('returns a structured verification barrier without creating action refs', async () => {
+ const harness = debuggerHarness(async (method) => {
+ if (method === 'Runtime.evaluate') {
+ return {
+ result: {
+ value: {
+ resources: [],
+ barrier: {
+ kind: 'human-verification',
+ evidence: ['page contains a verification control'],
+ },
+ },
+ },
+ };
+ }
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ const result = await automation().snapshot('tab-1', harness.wc, {
+ action: 'snapshot',
+ });
+
+ expect(result).toMatchObject({
+ barrier: {
+ kind: 'human-verification',
+ evidence: ['page contains a verification control'],
+ },
+ stats: { refs: 0, interactive: 0 },
+ });
+ expect(harness.sendCommand).not.toHaveBeenCalledWith('Accessibility.enable');
+ });
+});
+
+describe('RsbWebviewAutomation act', () => {
+ it('rejects negative element query indexes before polling the page', async () => {
+ const harness = debuggerHarness(async () => {
+ throw new Error('query should fail before debugger evaluation');
+ });
+
+ await expect(
+ automation().act('tab-1', harness.wc, {
+ kind: 'click',
+ query: { role: 'button', index: -1 },
+ }),
+ ).rejects.toThrow('element query index must be a non-negative integer');
+ expect(harness.sendCommand).not.toHaveBeenCalled();
+ });
+
+ it('uses native keyboard input for browser-default navigation keys', async () => {
+ const harness = debuggerHarness(async () => {
+ throw new Error('unexpected debugger command');
+ });
+ const sendInputEvent = vi.fn();
+ Object.assign(harness.wc, { sendInputEvent });
+
+ await automation().act(
+ 'tab-1',
+ harness.wc,
+ {
+ kind: 'press',
+ key: 'Ctrl+A',
+ },
+ {
+ nativeKeyDispatch: async (type, keyCode, modifiers) => {
+ sendInputEvent({ type, keyCode, modifiers });
+ },
+ },
+ );
+
+ expect(sendInputEvent).toHaveBeenNthCalledWith(1, {
+ type: 'keyDown',
+ keyCode: 'A',
+ modifiers: ['control'],
+ });
+ expect(sendInputEvent).toHaveBeenNthCalledWith(2, {
+ type: 'keyUp',
+ keyCode: 'A',
+ modifiers: ['control'],
+ });
+ expect(harness.executeJavaScript.mock.calls[0][0]).toContain('"type":"validate"');
+ });
+
+ it('treats maxChars zero as unlimited', async () => {
+ const harness = debuggerHarness(async (method) => {
+ if (method === 'Accessibility.enable') return {};
+ if (method === 'Accessibility.getFullAXTree') return AX_TREE;
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ const result = await automation().snapshot('tab-1', harness.wc, {
+ action: 'snapshot',
+ maxChars: 0,
+ });
+
+ expect(result.snapshot).toContain('[ref=e1]');
+ expect(result.stats.lines).toBeGreaterThan(0);
+ });
+
+ it('applies efficient snapshot defaults and rejects unsupported labels', async () => {
+ const harness = debuggerHarness(async (method, params) => {
+ if (method === 'Accessibility.enable') return {};
+ if (method === 'Accessibility.getFullAXTree') return AX_TREE;
+ throw new Error(`unexpected command: ${method} ${JSON.stringify(params)}`);
+ });
+
+ const efficient = await automation().snapshot('tab-1', harness.wc, {
+ action: 'snapshot',
+ mode: 'efficient',
+ });
+ expect(efficient.snapshot).toContain('[ref=e1]');
+ expect(efficient.stats.lines).toBeGreaterThan(0);
+
+ await expect(
+ automation().snapshot('tab-1', harness.wc, {
+ action: 'snapshot',
+ labels: true,
+ }),
+ ).rejects.toThrow('snapshot labels are unavailable');
+ });
+
+ it('scopes snapshots to the requested frame', async () => {
+ const harness = debuggerHarness(async (method, params) => {
+ if (method === 'Runtime.evaluate') return { result: { objectId: 'frame-object' } };
+ if (method === 'DOM.describeNode') {
+ expect(params).toMatchObject({ backendNodeId: 20, depth: 1 });
+ return {
+ node: {
+ frameId: 'frame-owner',
+ contentDocument: { frameId: 'frame-document', nodeId: 21 },
+ },
+ };
+ }
+ if (method === 'Accessibility.enable') return {};
+ if (method === 'Accessibility.getFullAXTree') {
+ expect(params).toEqual({ frameId: 'frame-document' });
+ return AX_TREE;
+ }
+ throw new Error(`unexpected command: ${method}`);
+ });
+ harness.sendCommand.mockImplementation(async (method, params) => {
+ if (method === 'Runtime.evaluate') return { result: { objectId: 'frame-object' } };
+ if (method === 'DOM.describeNode' && params?.objectId === 'frame-object') {
+ return { node: { backendNodeId: 20 } };
+ }
+ if (method === 'DOM.describeNode' && params?.backendNodeId === 20) {
+ return {
+ node: {
+ frameId: 'frame-owner',
+ contentDocument: { frameId: 'frame-document', nodeId: 21 },
+ },
+ };
+ }
+ if (method === 'Accessibility.enable') return {};
+ if (method === 'Accessibility.getFullAXTree') {
+ expect(params).toEqual({ frameId: 'frame-document' });
+ return AX_TREE;
+ }
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ const result = await automation().snapshot('tab-1', harness.wc, {
+ action: 'snapshot',
+ frame: 'iframe#widget',
+ });
+
+ expect(result).toMatchObject({ stats: { refs: 2 } });
+ expect(harness.sendCommand).toHaveBeenCalledWith('Accessibility.getFullAXTree', {
+ frameId: 'frame-document',
+ });
+ });
+
+ it('clicks a snapshot ref at the center of its DOM box', async () => {
+ const instance = automation();
+ let phase: 'snapshot' | 'click' = 'snapshot';
+ const harness = debuggerHarness(async (method) => {
+ if (phase === 'snapshot') {
+ if (method === 'Accessibility.enable') return {};
+ if (method === 'Accessibility.getFullAXTree') return AX_TREE;
+ } else {
+ if (method === 'DOM.resolveNode') return { object: { objectId: 'button-object' } };
+ if (method === 'Runtime.callFunctionOn') return { result: { value: { ok: true } } };
+ if (method === 'DOM.getBoxModel') {
+ return { model: { content: [10, 20, 30, 20, 30, 40, 10, 40] } };
+ }
+ }
+ throw new Error(`unexpected command during ${phase}: ${method}`);
+ });
+ await instance.snapshot('tab-1', harness.wc, {
+ action: 'snapshot',
+ interactive: true,
+ });
+ phase = 'click';
+ harness.sendCommand.mockClear();
+
+ const result = await instance.act('tab-1', harness.wc, {
+ kind: 'click',
+ ref: 'e1',
+ });
+
+ expect(result).toMatchObject({ tabId: 'tab-1', kind: 'click', x: 20, y: 30 });
+ expect(harness.sendCommand).not.toHaveBeenCalledWith(
+ 'Input.dispatchMouseEvent',
+ expect.anything(),
+ );
+ expect(harness.executeJavaScript).toHaveBeenCalledTimes(2);
+ expect(harness.executeJavaScript.mock.calls[0][0]).toContain(
+ '"method":"Input.dispatchMouseEvent","params":{"type":"mousePressed"',
+ );
+ expect(harness.executeJavaScript.mock.calls[0][1]).toBe(false);
+ expect(harness.executeJavaScript.mock.calls[1][0]).toContain(
+ '"method":"Input.dispatchMouseEvent","params":{"type":"mouseReleased"',
+ );
+ expect(harness.executeJavaScript.mock.calls[1][1]).toBe(true);
+ expect(harness.sendCommand).toHaveBeenCalledWith(
+ 'Runtime.releaseObject',
+ { objectId: 'button-object' },
+ );
+ });
+
+ it('types into a selector and optionally submits', async () => {
+ const harness = debuggerHarness(async (method, params) => {
+ if (method === 'Runtime.evaluate') return { result: { objectId: 'input-object' } };
+ if (method === 'DOM.describeNode') return { node: { backendNodeId: 5 } };
+ if (method === 'Runtime.callFunctionOn') {
+ const declaration = String(params?.functionDeclaration ?? '');
+ return {
+ result: {
+ value:
+ declaration.includes('options.editable') ||
+ declaration.includes('function(requireEditable)')
+ ? { ok: true }
+ : false,
+ },
+ };
+ }
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ const result = await automation().act('tab-1', harness.wc, {
+ kind: 'type',
+ selector: 'input[type=email]',
+ submit: true,
+ });
+
+ expect(result).toMatchObject({
+ tabId: 'tab-1',
+ kind: 'type',
+ textLength: 18,
+ });
+ expect(harness.executeJavaScript).toHaveBeenCalledTimes(3);
+ const insertTextCall = harness.executeJavaScript.mock.calls.find(([script]) =>
+ String(script).includes('"method":"Input.insertText","params":{"text":"[email protected]"}'),
+ );
+ expect(insertTextCall?.[0]).toContain('"targetTicket":"rsb-');
+ const enterKeyDownCall = harness.executeJavaScript.mock.calls.find(([script]) =>
+ String(script).includes(
+ '"method":"Input.dispatchKeyEvent","params":{"type":"keyDown","key":"Enter"',
+ ),
+ );
+ expect(enterKeyDownCall).toBeDefined();
+ expect(harness.sendCommand).not.toHaveBeenCalledWith(
+ expect.stringMatching(/^Input\./),
+ expect.anything(),
+ );
+ });
+
+ it('fills browser-native date inputs', async () => {
+ const harness = debuggerHarness(async (method, params) => {
+ if (method === 'Runtime.evaluate') return { result: { objectId: 'date-input' } };
+ if (method === 'DOM.describeNode') return { node: { backendNodeId: 6 } };
+ if (method === 'Runtime.callFunctionOn') {
+ if (String(params?.functionDeclaration).includes('requireEditable')) {
+ expect(String(params?.functionDeclaration)).toContain('"date", "datetime-local"');
+ }
+ return { result: { value: { ok: true } } };
+ }
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ const result = await automation().act('tab-1', harness.wc, {
+ kind: 'fill',
+ selector: 'input[type=date]',
+ text: '2026-07-27',
+ });
+
+ expect(result).toMatchObject({ kind: 'fill', textLength: 10 });
+ const fillCall = harness.sendCommand.mock.calls.find(
+ ([method, params]) =>
+ method === 'Runtime.callFunctionOn' &&
+ String((params as { functionDeclaration?: unknown })?.functionDeclaration).includes(
+ 'const type =',
+ ),
+ );
+ expect(fillCall?.[1]).toMatchObject({
+ arguments: [{ value: '2026-07-27' }, { value: undefined }],
+ });
+ expect(fillCall).toBeDefined();
+ });
+
+ it('fills the shared multi-field form shape', async () => {
+ const instance = automation();
+ const harness = debuggerHarness(async (method, params) => {
+ if (method === 'Runtime.evaluate') return { result: { objectId: 'field-object' } };
+ if (method === 'Accessibility.enable') return {};
+ if (method === 'Accessibility.getFullAXTree') return AX_TREE;
+ if (method === 'DOM.describeNode') return { node: { backendNodeId: 6 } };
+ if (method === 'DOM.resolveNode') return { object: { objectId: 'field-object' } };
+ if (method === 'Runtime.callFunctionOn') {
+ if (String(params?.functionDeclaration).includes('const type =')) {
+ expect(params?.arguments).toEqual([{ value: 'Ada' }, { value: 'text' }]);
+ return { result: { value: undefined } };
+ }
+ return { result: { value: { ok: true } } };
+ }
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ await instance.snapshot('tab-1', harness.wc, {
+ action: 'snapshot',
+ interactive: true,
+ });
+ const result = await instance.act('tab-1', harness.wc, {
+ kind: 'fill',
+ fields: [{ ref: 'e2', type: 'text', value: 'Ada' }],
+ });
+
+ expect(result).toMatchObject({ kind: 'fill', filled: 1 });
+ const fillCall = harness.sendCommand.mock.calls.find(
+ ([method, params]) =>
+ method === 'Runtime.callFunctionOn' &&
+ String((params as { functionDeclaration?: string })?.functionDeclaration).includes(
+ 'HTMLInputElement.prototype',
+ ),
+ );
+ expect(fillCall).toBeDefined();
+ });
+
+ it('hovers without focusing the target', async () => {
+ const harness = debuggerHarness(async (method, params) => {
+ if (method === 'Runtime.evaluate') return { result: { objectId: 'hover-target' } };
+ if (method === 'DOM.describeNode') return { node: { backendNodeId: 9 } };
+ if (method === 'Runtime.callFunctionOn') {
+ expect(String(params?.functionDeclaration)).not.toContain('this.focus()');
+ return { result: { value: { ok: true } } };
+ }
+ if (method === 'DOM.getBoxModel') {
+ return { model: { content: [0, 0, 20, 0, 20, 10, 0, 10] } };
+ }
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ await expect(
+ automation().act('tab-1', harness.wc, {
+ kind: 'hover',
+ selector: '#hover-target',
+ }),
+ ).resolves.toMatchObject({ kind: 'hover', x: 10, y: 5 });
+ });
+
+ it('resolves a semantic query and waits for an actionable target', async () => {
+ const harness = debuggerHarness(async (method, params) => {
+ if (method === 'Runtime.evaluate') {
+ expect(params?.expression).toContain('"role":"button"');
+ expect(params?.expression).toContain('"name":"Continue"');
+ return { result: { objectId: 'button-object' } };
+ }
+ if (method === 'DOM.describeNode') return { node: { backendNodeId: 7 } };
+ if (method === 'Runtime.callFunctionOn') return { result: { value: { ok: true } } };
+ if (method === 'DOM.getBoxModel') {
+ return { model: { content: [0, 0, 20, 0, 20, 10, 0, 10] } };
+ }
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ const result = await automation().act('tab-1', harness.wc, {
+ kind: 'click',
+ query: { role: 'button', name: 'Continue', exact: true },
+ timeoutMs: 750,
+ });
+
+ expect(result).toMatchObject({ kind: 'click', x: 10, y: 5 });
+ const pageCalls = harness.sendCommand.mock.calls.filter(
+ ([method]) => method === 'Runtime.callFunctionOn',
+ );
+ expect(
+ pageCalls.some(([, params]) =>
+ String(params?.functionDeclaration).includes('target is not visible'),
+ ),
+ ).toBe(true);
+ });
+
+ it('surfaces page-side query failures before attempting input', async () => {
+ const harness = debuggerHarness(async (method) => {
+ if (method === 'Runtime.evaluate') {
+ return {
+ result: { subtype: 'error' },
+ exceptionDetails: {
+ exception: { description: 'Error: element query matched 2 elements; provide index' },
+ },
+ };
+ }
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ await expect(
+ automation().act('tab-1', harness.wc, {
+ kind: 'click',
+ query: { role: 'button', name: 'Continue' },
+ }),
+ ).rejects.toThrow('element query matched 2 elements; provide index');
+ expect(harness.executeJavaScript).not.toHaveBeenCalled();
+ });
+
+ it('rejects query options that do not identify an element', async () => {
+ const harness = debuggerHarness(async (method) => {
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ await expect(
+ automation().act('tab-1', harness.wc, {
+ kind: 'click',
+ query: { exact: true, index: 0 },
+ }),
+ ).rejects.toThrow('element query requires at least one field');
+ expect(harness.sendCommand).not.toHaveBeenCalled();
+ });
+
+ it('resets an overridden viewport when resize omits dimensions', async () => {
+ const harness = debuggerHarness(async (method) => {
+ if (method === 'Emulation.clearDeviceMetricsOverride') return {};
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ const result = await automation().act('tab-1', harness.wc, { kind: 'resize' });
+
+ expect(result).toMatchObject({ kind: 'resize', reset: true });
+ expect(harness.sendCommand).toHaveBeenCalledWith('Emulation.clearDeviceMetricsOverride');
+ });
+
+ it('sets validated files on a resolved file input', async () => {
+ const harness = debuggerHarness(async (method) => {
+ if (method === 'Runtime.evaluate') return { result: { objectId: 'file-input' } };
+ if (method === 'DOM.describeNode') return { node: { backendNodeId: 12 } };
+ if (method === 'Runtime.callFunctionOn') {
+ return { result: { value: { ok: true, multiple: true } } };
+ }
+ if (method === 'DOM.setFileInputFiles') return {};
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ const result = await automation().setFiles('tab-1', harness.wc, {
+ paths: ['C:\\safe\\one.txt', 'C:\\safe\\two.txt'],
+ query: { label: 'Attachments' },
+ });
+
+ expect(result).toEqual({ tabId: 'tab-1', uploadedFiles: 2 });
+ expect(harness.sendCommand).toHaveBeenCalledWith('DOM.setFileInputFiles', {
+ files: ['C:\\safe\\one.txt', 'C:\\safe\\two.txt'],
+ objectId: 'file-input',
+ });
+ });
+
+ it('does not place multiple files into a single-file input', async () => {
+ const harness = debuggerHarness(async (method) => {
+ if (method === 'Runtime.evaluate') return { result: { objectId: 'file-input' } };
+ if (method === 'DOM.describeNode') return { node: { backendNodeId: 12 } };
+ if (method === 'Runtime.callFunctionOn') {
+ return { result: { value: { ok: true, multiple: false } } };
+ }
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ await expect(
+ automation().setFiles('tab-1', harness.wc, {
+ paths: ['C:\\safe\\one.txt', 'C:\\safe\\two.txt'],
+ element: 'input[type=file]',
+ }),
+ ).rejects.toThrow('accepts only one file');
+ expect(harness.sendCommand).not.toHaveBeenCalledWith(
+ 'DOM.setFileInputFiles',
+ expect.anything(),
+ );
+ });
+
+ it('dispatches coordinate clicks without requiring a snapshot', async () => {
+ const harness = debuggerHarness(async (method) => {
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ const result = await automation().act('tab-1', harness.wc, {
+ kind: 'clickCoords',
+ x: 12.5,
+ y: 24,
+ button: 'right',
+ });
+
+ expect(result).toMatchObject({ kind: 'clickCoords', x: 12.5, y: 24 });
+ expect(harness.executeJavaScript.mock.calls[0][0]).toContain(
+ '"method":"Input.dispatchMouseEvent","params":{"type":"mousePressed"',
+ );
+ expect(harness.executeJavaScript.mock.calls[0][0]).toContain('"button":"right"');
+ });
+
+ it('waits for page conditions inside the guest and returns observed state', async () => {
+ const harness = debuggerHarness(async (method, params) => {
+ if (method === 'Runtime.evaluate') {
+ expect(params?.expression).toContain('"selector":"#ready"');
+ return { result: { value: { url: 'https://example.test/form', readyState: 'complete' } } };
+ }
+ throw new Error(`unexpected command: ${method}`);
+ });
+
+ const result = await automation().act('tab-1', harness.wc, {
+ kind: 'wait',
+ selector: '#ready',
+ loadState: 'load',
+ timeoutMs: 500,
+ });
+
+ expect(result).toMatchObject({
+ kind: 'wait',
+ state: { url: 'https://example.test/form', readyState: 'complete' },
+ });
+ });
+
+ it('rejects stale refs and still detaches the debugger', async () => {
+ const harness = debuggerHarness(async () => {
+ throw new Error('sendCommand should not run');
+ });
+
+ await expect(
+ automation().act('tab-1', harness.wc, { kind: 'click', ref: 'e999' }),
+ ).rejects.toThrow(/unknown or stale snapshot ref/);
+ expect(harness.detach).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-backend.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-backend.test.ts
index cc06c4a320..fc117c053c 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-backend.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-backend.test.ts
@@ -3,7 +3,13 @@
// - tabs reads from TabRegistry + safeTabMeta on each WebContents
// - open / focus / close round-trip through dispatchTabOp (renderer bridge)
// - navigate / screenshot / pdf go straight to the guest WebContents
-// - unsupported actions yield a structured error (no throw)
+// - snapshot / non-evaluate act actions use the bounded CDP automation helper
+// - advanced unsupported actions yield a structured error (no throw)
+
+import fs from 'node:fs/promises';
+import { writeFileSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { WebContents } from 'electron';
@@ -396,13 +402,35 @@ describe('RsbWebviewBackend — direct WebContents actions', () => {
describe('RsbWebviewBackend — act:evaluate', () => {
function buildEvalEnv(initialReturn: unknown) {
+ let attached = false;
+ const sendCommand = vi.fn(async (
+ method: string,
+ params?: Record<string, unknown>,
+ ): Promise<unknown> => {
+ void params;
+ if (method === 'Runtime.evaluate' || method === 'Runtime.callFunctionOn') {
+ return { result: { value: initialReturn } };
+ }
+ return {};
+ });
const wc = {
getURL: () => '',
getTitle: () => '',
isDestroyed: () => false,
executeJavaScript: vi.fn(async () => initialReturn),
+ debugger: {
+ isAttached: vi.fn(() => attached),
+ attach: vi.fn(() => {
+ attached = true;
+ }),
+ detach: vi.fn(() => {
+ attached = false;
+ }),
+ sendCommand,
+ },
} as unknown as Electron.WebContents & {
executeJavaScript: ReturnType<typeof vi.fn>;
+ debugger: { sendCommand: ReturnType<typeof vi.fn> };
};
const registry = fakeRegistry(
[{ sessionId: 's1', tabId: 't1', webContentsId: 101 }],
@@ -414,11 +442,11 @@ describe('RsbWebviewBackend — act:evaluate', () => {
bridge: { getHostWebContents: () => null, logger: logger() },
logger: logger(),
});
- return { backend, wc };
+ return { backend, wc, sendCommand };
}
it('runs the fn in the guest and returns its result + as variable name', async () => {
- const { backend, wc } = buildEvalEnv({ posts: [1, 2, 3] });
+ const { backend, sendCommand } = buildEvalEnv({ posts: [1, 2, 3] });
const res = await backend.call({
action: 'act',
targetId: 't1',
@@ -431,11 +459,11 @@ describe('RsbWebviewBackend — act:evaluate', () => {
// The wrapper mirrors the vendored runtime's evaluator: eval("(" + JSON.stringified-fn + ")")
// → call it → wrap in Promise.resolve. The injected fn text is a JS string
// LITERAL, so multi-statement payloads can't escape the IIFE.
- expect(wc.executeJavaScript).toHaveBeenCalledTimes(1);
- const callArg = (wc.executeJavaScript as ReturnType<typeof vi.fn>).mock.calls[0][0];
+ expect(sendCommand).toHaveBeenCalledWith('Runtime.evaluate', expect.anything());
+ const callArg = sendCommand.mock.calls.find(([method]) => method === 'Runtime.evaluate')?.[1]
+ ?.expression as string;
expect(callArg).toContain('eval("(" + "() => ({ posts: [1, 2, 3] })" + ")")');
- expect(callArg).toContain('did not produce a function');
- expect((wc.executeJavaScript as ReturnType<typeof vi.fn>).mock.calls[0][1]).toBe(false);
+ expect(callArg).toContain('evaluate source did not produce a function');
expect(res.ok).toBe(true);
expect(res.data).toMatchObject({
tabId: 't1',
@@ -446,7 +474,7 @@ describe('RsbWebviewBackend — act:evaluate', () => {
});
it('escapes embedded quotes/backslashes in fn so multi-stmt payload cannot escape IIFE', async () => {
- const { backend, wc } = buildEvalEnv(null);
+ const { backend, sendCommand } = buildEvalEnv(null);
// Adversarial payload: try to close the string + run a second statement.
const adversarial = '() => {}; window.__pwned = 1; (() => null';
await backend.call({
@@ -454,7 +482,8 @@ describe('RsbWebviewBackend — act:evaluate', () => {
targetId: 't1',
request: { kind: 'evaluate', fn: adversarial },
} as never);
- const callArg = (wc.executeJavaScript as ReturnType<typeof vi.fn>).mock.calls[0][0] as string;
+ const callArg = sendCommand.mock.calls.find(([method]) => method === 'Runtime.evaluate')?.[1]
+ ?.expression as string;
// The whole payload is a JSON.stringified literal — `"` inside got escaped,
// and the literal sits inside `eval("(" + LITERAL + ")")` so any "statement
// separator" the attacker tries (a quote + `;`) stays inside the literal.
@@ -464,22 +493,43 @@ describe('RsbWebviewBackend — act:evaluate', () => {
expect(callArg.indexOf('window.__pwned')).toBeGreaterThan(callArg.indexOf(JSON.stringify(adversarial).slice(0, 10)));
});
- it('non-evaluate act kinds are rejected with a Phase 4 message', async () => {
- const { backend } = buildEvalEnv(null);
+ it('non-evaluate act kinds route to the CDP automation helper', async () => {
+ const { backend, wc } = buildEvalEnv(null);
+ wc.executeJavaScript.mockResolvedValue({ ok: true });
+ const sendCommand = vi.fn(async () => {
+ return {};
+ });
+ Object.assign(wc, {
+ debugger: {
+ isAttached: vi.fn(() => true),
+ attach: vi.fn(),
+ detach: vi.fn(),
+ sendCommand,
+ on: vi.fn(),
+ removeListener: vi.fn(),
+ },
+ });
const res = await backend.call({
action: 'act',
targetId: 't1',
- request: { kind: 'click', ref: 'r-1' },
+ request: { kind: 'clickCoords', x: 10, y: 20 },
} as never);
- expect(res.ok).toBe(false);
- expect(res.message).toMatch(/click not yet supported/);
+ expect(res.ok).toBe(true);
+ expect(sendCommand).not.toHaveBeenCalledWith(
+ 'Input.dispatchMouseEvent',
+ expect.anything(),
+ );
+ expect(wc.executeJavaScript).toHaveBeenCalledTimes(2);
+ expect(wc.executeJavaScript.mock.calls[0][0]).toContain(
+ '"method":"Input.dispatchMouseEvent","params":{"type":"mousePressed","x":10,"y":20',
+ );
});
it('executeJavaScript throw propagates as actionFailed', async () => {
- const { backend, wc } = buildEvalEnv(null);
- (wc.executeJavaScript as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
- new Error('SyntaxError'),
- );
+ const { backend, sendCommand } = buildEvalEnv(null);
+ sendCommand.mockResolvedValueOnce({
+ exceptionDetails: { exception: { description: 'SyntaxError' } },
+ } as never);
const res = await backend.call({
action: 'act',
targetId: 't1',
@@ -490,6 +540,70 @@ describe('RsbWebviewBackend — act:evaluate', () => {
});
});
+describe('RsbWebviewBackend — snapshot automation', () => {
+ it('returns refs from the active tab and pins for the complete CDP action', async () => {
+ const wc = fakeWc();
+ let attached = false;
+ Object.assign(wc, {
+ debugger: {
+ isAttached: vi.fn(() => attached),
+ attach: vi.fn(() => {
+ attached = true;
+ }),
+ detach: vi.fn(() => {
+ attached = false;
+ }),
+ sendCommand: vi.fn(async (method: string) => {
+ if (method === 'Accessibility.enable') return {};
+ if (method === 'Accessibility.getFullAXTree') {
+ return {
+ nodes: [
+ {
+ nodeId: 'button',
+ role: { value: 'button' },
+ name: { value: 'Continue' },
+ backendDOMNodeId: 7,
+ childIds: [],
+ },
+ ],
+ };
+ }
+ throw new Error(`unexpected command: ${method}`);
+ }),
+ },
+ });
+ const registry = fakeRegistry(
+ [{ sessionId: 's1', tabId: 't1', webContentsId: 101 }],
+ new Map([['t1', wc]]),
+ );
+ const backend = new RsbWebviewBackend({
+ registry,
+ getActiveSessionId: () => 's1',
+ bridge: { getHostWebContents: () => null, logger: logger() },
+ logger: logger(),
+ });
+
+ const res = await backend.call({
+ action: 'snapshot',
+ targetId: 't1',
+ interactive: true,
+ });
+
+ expect(res.ok).toBe(true);
+ expect(res.data).toMatchObject({
+ targetId: 't1',
+ snapshot: '- button "Continue" [ref=e1]',
+ refs: {
+ e1: { role: 'button', name: 'Continue', backendDOMNodeId: 7 },
+ },
+ });
+ expect(registry.pinHistory).toEqual([
+ { op: 'pin', tabId: 't1' },
+ { op: 'unpin', tabId: 't1' },
+ ]);
+ });
+});
+
describe('RsbWebviewBackend — cross-session isolation (P2-1)', () => {
// Reproduces the race: agent holds a tabId from session A. User switches to
// session B. Without `resolveTabInActiveSession` the backend would happily
@@ -625,6 +739,51 @@ describe('RsbWebviewBackend — per-action automation pin', () => {
]);
});
+ it.each([
+ { label: 'request timeout', timeoutMs: 25, elapsedMs: 25 },
+ { label: 'bounded default', timeoutMs: undefined, elapsedMs: 60_000 },
+ ])(
+ 'navigate uses the $label, stops a stalled load, and lets dispose finish',
+ async ({ timeoutMs, elapsedMs }) => {
+ vi.useFakeTimers();
+ let finishLoad = () => {};
+ const wc = fakeWc();
+ wc.loadURLMock.mockImplementationOnce(
+ () => new Promise<void>((resolve) => {
+ finishLoad = resolve;
+ }),
+ );
+ const stop = vi.fn();
+ Object.assign(wc, { stop });
+ const { backend, registry } = buildBackend(wc);
+
+ try {
+ const navigating = backend.call({
+ action: 'navigate',
+ targetId: 't1',
+ url: 'https://stalled.test',
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
+ } as never);
+ const disposing = backend.dispose();
+
+ await vi.advanceTimersByTimeAsync(elapsedMs);
+ const result = await navigating;
+ await disposing;
+
+ expect(result.ok).toBe(false);
+ expect(result.message).toBe(`navigation timed out after ${elapsedMs}ms`);
+ expect(stop).toHaveBeenCalledTimes(1);
+ expect(registry.pinHistory).toEqual([
+ { op: 'pin', tabId: 't1' },
+ { op: 'unpin', tabId: 't1' },
+ ]);
+ } finally {
+ finishLoad();
+ vi.useRealTimers();
+ }
+ },
+ );
+
it('unpins even when wc operation throws (action failure path)', async () => {
const wc = {
getURL: () => '',
@@ -671,6 +830,27 @@ describe('RsbWebviewBackend — per-action automation pin', () => {
}
});
+ it('rejects conflicting top-level and nested act targets', async () => {
+ const wc = fakeWc();
+ const { backend, registry } = buildBackend(wc);
+
+ const result = await backend.call({
+ action: 'act',
+ targetId: 't1',
+ request: {
+ kind: 'click',
+ targetId: 't2',
+ selector: '#submit',
+ },
+ } as never);
+
+ expect(result).toMatchObject({
+ ok: false,
+ message: expect.stringContaining('targetId mismatch'),
+ });
+ expect(registry.pinHistory).toEqual([]);
+ });
+
it('non-tab-scoped actions (tabs / status / profiles / doctor) do not touch pin', async () => {
const wc = fakeWc();
const { backend, registry } = buildBackend(wc);
@@ -790,6 +970,37 @@ describe('RsbWebviewBackend — MCP session id injection', () => {
});
});
+ it('targetless direct actions select a tab from the MCP-injected session', async () => {
+ const agentWc = fakeWc();
+ const uiWc = fakeWc();
+ const registry = fakeRegistry(
+ [
+ { sessionId: 'agent-A', tabId: 'agent-tab', webContentsId: 101 },
+ { sessionId: 'ui-focus-B', tabId: 'ui-tab', webContentsId: 102 },
+ ],
+ new Map([
+ ['agent-tab', agentWc],
+ ['ui-tab', uiWc],
+ ]),
+ );
+ const backend = new RsbWebviewBackend({
+ registry,
+ getActiveSessionId: () => 'ui-focus-B',
+ bridge: { getHostWebContents: () => null, logger: logger() },
+ logger: logger(),
+ });
+
+ const res = await backend.call({
+ action: 'navigate',
+ url: 'https://agent.example',
+ __mcpSessionId: 'agent-A',
+ } as never);
+
+ expect(res.ok).toBe(true);
+ expect(agentWc.loadURLMock).toHaveBeenCalledWith('https://agent.example');
+ expect(uiWc.loadURLMock).not.toHaveBeenCalled();
+ });
+
it('empty / non-string __mcpSessionId falls back to getActiveSessionId', async () => {
const wc = fakeWc();
const registry = fakeRegistry(
@@ -823,15 +1034,720 @@ describe('RsbWebviewBackend — MCP session id injection', () => {
});
});
+describe('RsbWebviewBackend — uploads and page dialogs', () => {
+ function buildPageEnv(options?: {
+ uploadRoot?: string;
+ resourceUrl?: string;
+ humanVerification?: boolean;
+ onDialogHandled?: () => void;
+ pageEnableError?: Error;
+ }) {
+ let attached = false;
+ const listeners = new Map<string, Set<(...args: unknown[]) => void>>();
+ const sessionListeners = new Map<string, Set<(...args: unknown[]) => void>>();
+ const sendCommand = vi.fn(async (method: string) => {
+ if (method === 'Network.enable') return {};
+ if (method === 'Page.enable') {
+ if (options?.pageEnableError) throw options.pageEnableError;
+ return {};
+ }
+ if (method === 'Accessibility.enable') return {};
+ if (method === 'Accessibility.getFullAXTree') return { nodes: [] };
+ if (method === 'Runtime.evaluate') {
+ if (options?.humanVerification) {
+ return {
+ result: {
+ value: {
+ resources: [],
+ barrier: {
+ kind: 'human-verification',
+ evidence: ['page contains a verification control'],
+ },
+ },
+ },
+ };
+ }
+ return options?.resourceUrl
+ ? {
+ result: {
+ value: {
+ resources: [{ kind: 'download', url: options.resourceUrl }],
+ },
+ },
+ }
+ : { result: { objectId: 'file-input' } };
+ }
+ if (method === 'DOM.describeNode') return { node: { backendNodeId: 11 } };
+ if (method === 'Runtime.callFunctionOn') {
+ return { result: { value: { ok: true, multiple: true } } };
+ }
+ if (method === 'DOM.setFileInputFiles') return {};
+ if (method === 'Page.handleJavaScriptDialog') {
+ options?.onDialogHandled?.();
+ return {};
+ }
+ throw new Error(`unexpected command: ${method}`);
+ });
+ const wc = fakeWc();
+ const session = {
+ on: (event: string, listener: (...args: unknown[]) => void) => {
+ const group = sessionListeners.get(event) ?? new Set();
+ group.add(listener);
+ sessionListeners.set(event, group);
+ },
+ removeListener: (event: string, listener: (...args: unknown[]) => void) => {
+ sessionListeners.get(event)?.delete(listener);
+ },
+ };
+ const downloadURL = vi.fn((url: string) => {
+ let doneListener: ((...args: unknown[]) => void) | undefined;
+ const item = {
+ getFilename: () => 'page-resource.bin',
+ getURL: () => url,
+ getMimeType: () => 'application/octet-stream',
+ getTotalBytes: () => 4,
+ getReceivedBytes: () => 4,
+ setSavePath: (filePath: string) => writeFileSync(filePath, 'data'),
+ cancel: vi.fn(),
+ on: vi.fn(),
+ once: (event: string, listener: (...args: unknown[]) => void) => {
+ if (event === 'done') doneListener = listener;
+ },
+ };
+ for (const listener of sessionListeners.get('will-download') ?? []) {
+ listener({}, item, wc);
+ }
+ setTimeout(() => doneListener?.({}, 'completed'), 0);
+ });
+ Object.assign(wc, {
+ once: vi.fn(),
+ session,
+ downloadURL,
+ debugger: {
+ isAttached: () => attached,
+ attach: vi.fn(() => {
+ attached = true;
+ }),
+ detach: vi.fn(() => {
+ attached = false;
+ }),
+ sendCommand,
+ on: (event: string, listener: (...args: unknown[]) => void) => {
+ const group = listeners.get(event) ?? new Set();
+ group.add(listener);
+ listeners.set(event, group);
+ },
+ removeListener: (event: string, listener: (...args: unknown[]) => void) => {
+ listeners.get(event)?.delete(listener);
+ },
+ },
+ });
+ const registry = fakeRegistry(
+ [{ sessionId: 's1', tabId: 't1', webContentsId: 101 }],
+ new Map([['t1', wc]]),
+ );
+ const backendLogger = logger();
+ const backend = new RsbWebviewBackend({
+ registry,
+ getActiveSessionId: () => 's1',
+ artifactRoot: options?.uploadRoot ? () => options.uploadRoot! : undefined,
+ resolveUploadRoots: options?.uploadRoot
+ ? async () => [options.uploadRoot!]
+ : undefined,
+ bridge: { getHostWebContents: () => null, logger: logger() },
+ logger: backendLogger,
+ });
+ const emit = (method: string, params: Record<string, unknown>) => {
+ for (const listener of listeners.get('message') ?? []) {
+ listener({}, method, params);
+ }
+ };
+ return { backend, emit, sendCommand, downloadURL, wc, backendLogger, registry };
+ }
+
+ it('validates upload paths before assigning files to the page input', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-browser-backend-upload-'));
+ try {
+ const file = path.join(root, 'notes.txt');
+ await fs.writeFile(file, 'notes');
+ const env = buildPageEnv({ uploadRoot: root });
+
+ const res = await env.backend.call({
+ action: 'upload',
+ targetId: 't1',
+ paths: [file],
+ query: { label: 'Attachments' },
+ });
+
+ expect(res.ok).toBe(true);
+ expect(res.data).toMatchObject({ tabId: 't1', uploadedFiles: 1 });
+ expect(env.sendCommand).toHaveBeenCalledWith('DOM.setFileInputFiles', {
+ files: [await fs.realpath(file)],
+ objectId: 'file-input',
+ });
+ await env.backend.dispose();
+ } finally {
+ await fs.rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it('returns a dialog barrier from snapshot and handles the exact pending dialog', async () => {
+ const env = buildPageEnv();
+ await env.backend.call({ action: 'snapshot', targetId: 't1' });
+ env.emit('Page.javascriptDialogOpening', {
+ type: 'confirm',
+ message: 'Delete this item?',
+ });
+
+ const snapshot = await env.backend.call({ action: 'snapshot', targetId: 't1' });
+ expect(snapshot.ok).toBe(true);
+ expect(snapshot.data).toMatchObject({
+ targetId: 't1',
+ barrier: {
+ kind: 'page-dialog',
+ dialog: { type: 'confirm', message: 'Delete this item?' },
+ },
+ });
+ const dialogId = (snapshot.data as {
+ barrier: { dialog: { id: string } };
+ }).barrier.dialog.id;
+
+ const handled = await env.backend.call({
+ action: 'dialog',
+ targetId: 't1',
+ dialogId,
+ accept: false,
+ });
+ expect(handled.ok).toBe(true);
+ expect(env.sendCommand).toHaveBeenCalledWith(
+ 'Page.handleJavaScriptDialog',
+ { accept: false },
+ );
+ await env.backend.dispose();
+ });
+
+ it('returns a dialog barrier when a page action is blocked by the dialog', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-browser-dialog-action-'));
+ let finishAction = () => {};
+ const env = buildPageEnv({
+ uploadRoot: root,
+ onDialogHandled: () => finishAction(),
+ });
+ const automation = (env.backend as unknown as {
+ automation: {
+ act: (
+ tabId: string,
+ wc: WebContents,
+ request: Record<string, unknown>,
+ ) => Promise<Record<string, unknown>>;
+ };
+ }).automation;
+ const actionFinished = vi.fn();
+ const actSpy = vi.spyOn(automation, 'act').mockImplementation(
+ () => new Promise((resolve) => {
+ finishAction = () => {
+ actionFinished();
+ resolve({ tabId: 't1', kind: 'click' });
+ };
+ }),
+ );
+
+ try {
+ const action = env.backend.call({
+ action: 'act',
+ targetId: 't1',
+ request: { kind: 'click', targetId: 't1', ref: 'button-1' },
+ });
+ await vi.waitFor(() => expect(actSpy).toHaveBeenCalledTimes(1));
+ env.emit('Page.javascriptDialogOpening', {
+ type: 'confirm',
+ message: 'Continue?',
+ });
+
+ const blocked = await action;
+ expect(blocked.ok).toBe(true);
+ expect(blocked.data).toMatchObject({
+ tabId: 't1',
+ kind: 'click',
+ barrier: {
+ kind: 'page-dialog',
+ dialog: { type: 'confirm', message: 'Continue?' },
+ },
+ });
+ const dialogId = (blocked.data as {
+ barrier: { dialog: { id: string } };
+ }).barrier.dialog.id;
+
+ const handled = await env.backend.call({
+ action: 'dialog',
+ targetId: 't1',
+ dialogId,
+ accept: true,
+ });
+ expect(handled.ok).toBe(true);
+ await vi.waitFor(() => expect(actionFinished).toHaveBeenCalledTimes(1));
+ } finally {
+ await env.backend.dispose();
+ await fs.rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it('blocks direct actions after a human-verification snapshot barrier', async () => {
+ const env = buildPageEnv({ humanVerification: true });
+ const snapshot = await env.backend.call({ action: 'snapshot', targetId: 't1' });
+ expect(snapshot.data).toMatchObject({
+ barrier: { kind: 'human-verification' },
+ });
+
+ const action = await env.backend.call({
+ action: 'act',
+ targetId: 't1',
+ request: { kind: 'clickCoords', x: 10, y: 10 },
+ });
+ expect(action.data).toMatchObject({
+ barrier: { kind: 'human-verification' },
+ });
+ expect(env.sendCommand).not.toHaveBeenCalledWith(
+ 'Input.dispatchMouseEvent',
+ expect.anything(),
+ );
+ await env.backend.dispose();
+ });
+
+ it('continues a page action when dialog observation is unavailable', async () => {
+ const env = buildPageEnv({
+ pageEnableError: new Error('another debugger client owns the page'),
+ });
+ const automation = (env.backend as unknown as {
+ automation: {
+ act: (
+ tabId: string,
+ wc: WebContents,
+ request: Record<string, unknown>,
+ ) => Promise<Record<string, unknown>>;
+ };
+ }).automation;
+ vi.spyOn(automation, 'act').mockResolvedValue({
+ tabId: 't1',
+ kind: 'click',
+ });
+
+ try {
+ const result = await env.backend.call({
+ action: 'act',
+ targetId: 't1',
+ request: { kind: 'click', targetId: 't1', ref: 'button-1' },
+ });
+
+ expect(result.ok).toBe(true);
+ expect(result.data).toMatchObject({ tabId: 't1', kind: 'click' });
+ expect(env.backendLogger.warn).toHaveBeenCalledWith(
+ 'RSB page dialog observation unavailable',
+ expect.objectContaining({ tabId: 't1' }),
+ );
+ } finally {
+ await env.backend.dispose();
+ }
+ });
+
+ it('keeps the host interactive after an auto-closed dialog and arms a retry', async () => {
+ const env = buildPageEnv();
+ const automation = (env.backend as unknown as {
+ automation: {
+ act: (
+ tabId: string,
+ wc: WebContents,
+ request: Record<string, unknown>,
+ ) => Promise<Record<string, unknown>>;
+ };
+ }).automation;
+ let releaseAction = () => {};
+ const actSpy = vi.spyOn(automation, 'act').mockImplementation(
+ () => {
+ env.emit('Page.javascriptDialogOpening', {
+ type: 'confirm',
+ message: 'Continue?',
+ });
+ env.emit('Page.javascriptDialogClosed', {
+ result: false,
+ userInput: '',
+ });
+ return new Promise((resolve) => {
+ releaseAction = () => resolve({ tabId: 't1', kind: 'click' });
+ });
+ },
+ );
+
+ try {
+ const action = env.backend.call({
+ action: 'act',
+ targetId: 't1',
+ request: { kind: 'click', targetId: 't1', ref: 'button-1' },
+ });
+ await vi.waitFor(() => expect(actSpy).toHaveBeenCalledTimes(1));
+ const blocked = await action;
+ expect(blocked.data).toMatchObject({
+ barrier: {
+ kind: 'page-dialog',
+ dialog: { type: 'confirm', message: 'Continue?' },
+ },
+ });
+ expect(env.registry.pinHistory).toEqual([{ op: 'pin', tabId: 't1' }]);
+ const dialogId = (blocked.data as {
+ barrier: { dialog: { id: string } };
+ }).barrier.dialog.id;
+
+ const armed = await env.backend.call({
+ action: 'dialog',
+ targetId: 't1',
+ dialogId,
+ accept: true,
+ });
+ expect(armed.data).toMatchObject({
+ tabId: 't1',
+ armed: true,
+ retryRequired: true,
+ });
+ releaseAction();
+ await vi.waitFor(() => {
+ expect(env.registry.pinHistory).toEqual([
+ { op: 'pin', tabId: 't1' },
+ { op: 'pin', tabId: 't1' },
+ { op: 'unpin', tabId: 't1' },
+ { op: 'unpin', tabId: 't1' },
+ ]);
+ });
+ } finally {
+ releaseAction();
+ await env.backend.dispose();
+ }
+ });
+
+ it('prepares the next confirmation when no previous dialog record remains', async () => {
+ const env = buildPageEnv();
+ await env.backend.call({ action: 'snapshot', targetId: 't1' });
+
+ const dialogs = (env.backend as unknown as {
+ dialogs: {
+ respond: (...args: unknown[]) => Promise<never>;
+ };
+ }).dialogs;
+ vi.spyOn(dialogs, 'respond').mockRejectedValueOnce(
+ new Error('no page dialog is pending'),
+ );
+
+ try {
+ const armed = await env.backend.call({
+ action: 'dialog',
+ targetId: 't1',
+ accept: true,
+ });
+ expect(armed.ok).toBe(true);
+ expect(armed.data).toMatchObject({
+ tabId: 't1',
+ armed: true,
+ retryRequired: true,
+ });
+
+ env.emit('Page.javascriptDialogOpening', {
+ type: 'confirm',
+ message: 'Continue?',
+ });
+ await vi.waitFor(() => {
+ expect(env.sendCommand).toHaveBeenCalledWith(
+ 'Page.handleJavaScriptDialog',
+ { accept: true },
+ );
+ });
+ } finally {
+ await env.backend.dispose();
+ }
+ });
+
+ it.each([
+ {
+ dialogType: 'alert',
+ expected: {
+ dialogs: [{
+ type: 'alert',
+ message: 'Notice',
+ closedBy: 'auto',
+ handled: true,
+ }],
+ },
+ },
+ {
+ dialogType: 'confirm',
+ expected: {
+ barrier: {
+ kind: 'page-dialog',
+ dialog: {
+ type: 'confirm',
+ message: 'Notice',
+ closedBy: 'auto',
+ },
+ },
+ },
+ },
+ ])(
+ 'classifies an auto-closed $dialogType even when the action finishes immediately',
+ async ({ dialogType, expected }) => {
+ const env = buildPageEnv();
+ const automation = (env.backend as unknown as {
+ automation: {
+ act: (
+ tabId: string,
+ wc: WebContents,
+ request: Record<string, unknown>,
+ ) => Promise<Record<string, unknown>>;
+ };
+ }).automation;
+ vi.spyOn(automation, 'act').mockImplementation(async () => {
+ env.emit('Page.javascriptDialogOpening', {
+ type: dialogType,
+ message: 'Notice',
+ });
+ env.emit('Page.javascriptDialogClosed', {
+ result: false,
+ userInput: '',
+ });
+ return { tabId: 't1', kind: 'click' };
+ });
+
+ try {
+ const result = await env.backend.call({
+ action: 'act',
+ targetId: 't1',
+ request: { kind: 'click', targetId: 't1', ref: 'button-1' },
+ });
+ expect(result.ok).toBe(true);
+ expect(result.data).toMatchObject(expected);
+ } finally {
+ await env.backend.dispose();
+ }
+ },
+ );
+
+ it('saves only a resource listed by the latest page snapshot', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-browser-resource-'));
+ try {
+ const resourceUrl = 'https://cdn.example.test/archive.bin';
+ const env = buildPageEnv({ uploadRoot: root, resourceUrl });
+ const snapshot = await env.backend.call({
+ action: 'snapshot',
+ targetId: 't1',
+ urls: true,
+ });
+ expect(snapshot.data).toMatchObject({
+ resources: [{ kind: 'download', url: resourceUrl }],
+ });
+
+ const saved = await env.backend.call({
+ action: 'act',
+ targetId: 't1',
+ request: { kind: 'saveResource', url: resourceUrl, timeoutMs: 1000 },
+ });
+
+ expect(saved.ok).toBe(true);
+ expect(saved.data).toMatchObject({
+ kind: 'saveResource',
+ downloads: [
+ {
+ fileName: 'page-resource.bin',
+ state: 'completed',
+ },
+ ],
+ });
+ expect(env.downloadURL).toHaveBeenCalledWith(resourceUrl);
+ const artifactPath = (saved.data as {
+ downloads: Array<{ path: string }>;
+ }).downloads[0].path;
+ await expect(fs.readFile(artifactPath, 'utf8')).resolves.toBe('data');
+ await env.backend.dispose();
+ } finally {
+ await fs.rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it('captures downloads triggered by submit-enabled typing', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-browser-submit-download-'));
+ try {
+ const env = buildPageEnv({ uploadRoot: root });
+ const automation = (env.backend as unknown as {
+ automation: {
+ act: (
+ tabId: string,
+ wc: WebContents,
+ request: Record<string, unknown>,
+ ) => Promise<Record<string, unknown>>;
+ };
+ }).automation;
+ vi.spyOn(automation, 'act').mockImplementation(async () => {
+ env.downloadURL('https://example.test/submit-download');
+ return { tabId: 't1', kind: 'type', textLength: 1 };
+ });
+
+ const result = await env.backend.call({
+ action: 'act',
+ targetId: 't1',
+ request: {
+ kind: 'type',
+ targetId: 't1',
+ ref: 'input-1',
+ text: 'x',
+ submit: true,
+ },
+ } as never);
+
+ expect(result.ok).toBe(true);
+ expect(result.data).toMatchObject({
+ kind: 'type',
+ downloads: [{ state: 'completed' }],
+ });
+ await env.backend.dispose();
+ } finally {
+ await fs.rm(root, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('RsbWebviewBackend — network actions', () => {
+ function buildNetworkEnv() {
+ let attached = false;
+ const listeners = new Map<string, Set<(...args: unknown[]) => void>>();
+ const sendCommand = vi.fn(async (method: string) => {
+ if (method === 'Network.enable') return {};
+ if (method === 'Network.getResponseBody') {
+ return { body: '{"items":[1,2,3]}', base64Encoded: false };
+ }
+ throw new Error(`unexpected command: ${method}`);
+ });
+ const wc = fakeWc();
+ Object.assign(wc, {
+ once: vi.fn(),
+ debugger: {
+ isAttached: () => attached,
+ attach: vi.fn(() => {
+ attached = true;
+ }),
+ detach: vi.fn(() => {
+ attached = false;
+ }),
+ sendCommand,
+ on: (event: string, listener: (...args: unknown[]) => void) => {
+ const group = listeners.get(event) ?? new Set();
+ group.add(listener);
+ listeners.set(event, group);
+ },
+ removeListener: (event: string, listener: (...args: unknown[]) => void) => {
+ listeners.get(event)?.delete(listener);
+ },
+ },
+ });
+ const registry = fakeRegistry(
+ [{ sessionId: 's1', tabId: 't1', webContentsId: 101 }],
+ new Map([['t1', wc]]),
+ );
+ const backend = new RsbWebviewBackend({
+ registry,
+ getActiveSessionId: () => 's1',
+ bridge: { getHostWebContents: () => null, logger: logger() },
+ logger: logger(),
+ });
+ const emitNetwork = (method: string, params: Record<string, unknown>) => {
+ for (const listener of listeners.get('message') ?? []) {
+ listener({}, method, params);
+ }
+ };
+ return { backend, emitNetwork, sendCommand };
+ }
+
+ it('dispatches request history through the selected tab', async () => {
+ const env = buildNetworkEnv();
+ await env.backend.call({ action: 'requests', targetId: 't1' } as never);
+ env.emitNetwork('Network.requestWillBeSent', {
+ requestId: 'r1',
+ type: 'Fetch',
+ request: { method: 'GET', url: 'https://example.test/api/items' },
+ });
+ env.emitNetwork('Network.responseReceived', {
+ requestId: 'r1',
+ response: { url: 'https://example.test/api/items', status: 200 },
+ });
+ env.emitNetwork('Network.loadingFinished', { requestId: 'r1' });
+
+ const res = await env.backend.call({
+ action: 'requests',
+ targetId: 't1',
+ filter: '/api/',
+ } as never);
+
+ expect(res.ok).toBe(true);
+ expect(res.data).toMatchObject({
+ tabId: 't1',
+ requests: [
+ {
+ id: 'r1',
+ method: 'GET',
+ url: 'https://example.test/api/items',
+ status: 200,
+ ok: true,
+ },
+ ],
+ });
+ });
+
+ it('returns the body of the next completed matching response', async () => {
+ const env = buildNetworkEnv();
+ await env.backend.call({ action: 'requests', targetId: 't1' } as never);
+ const pending = env.backend.call({
+ action: 'responseBody',
+ targetId: 't1',
+ url: '/api/items',
+ maxChars: 8,
+ } as never);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ env.emitNetwork('Network.requestWillBeSent', {
+ requestId: 'r2',
+ type: 'XHR',
+ request: { method: 'GET', url: 'https://example.test/api/items' },
+ });
+ env.emitNetwork('Network.responseReceived', {
+ requestId: 'r2',
+ response: {
+ url: 'https://example.test/api/items',
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ },
+ });
+ env.emitNetwork('Network.loadingFinished', { requestId: 'r2' });
+
+ const res = await pending;
+
+ expect(res.ok).toBe(true);
+ expect(res.data).toMatchObject({
+ tabId: 't1',
+ response: {
+ url: 'https://example.test/api/items',
+ body: '{"items"',
+ truncated: true,
+ },
+ });
+ expect(env.sendCommand).toHaveBeenCalledWith('Network.getResponseBody', {
+ requestId: 'r2',
+ });
+ });
+});
+
describe('RsbWebviewBackend — unsupported actions', () => {
- it('snapshot returns BROWSER_RUNTIME_ACTION_FAILED with explanation', async () => {
+ it('unknown actions return BROWSER_RUNTIME_ACTION_FAILED with explanation', async () => {
const backend = new RsbWebviewBackend({
registry: fakeRegistry([], new Map()),
getActiveSessionId: () => 's1',
bridge: { getHostWebContents: () => null, logger: logger() },
logger: logger(),
});
- const res = await backend.call({ action: 'snapshot' } as never);
+ const res = await backend.call({ action: 'trace' } as never);
expect(res.ok).toBe(false);
expect(res.errorCode).toBe('BROWSER_RUNTIME_ACTION_FAILED');
expect(res.message).toMatch(/not yet supported/);
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-dialogs.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-dialogs.test.ts
new file mode 100644
index 0000000000..02a0e209f8
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-dialogs.test.ts
@@ -0,0 +1,240 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { WebContents } from 'electron';
+
+import { RsbWebviewDialogs } from '../rsb-webview-dialogs.js';
+
+function dialogHarness() {
+ let attached = false;
+ const listeners = new Map<string, Set<(...args: unknown[]) => void>>();
+ const sendCommand = vi.fn(async (method: string) => {
+ if (method === 'Page.enable' || method === 'Page.handleJavaScriptDialog') return {};
+ throw new Error(`unexpected command: ${method}`);
+ });
+ const electronDebugger = {
+ isAttached: () => attached,
+ attach: vi.fn(() => {
+ attached = true;
+ }),
+ detach: vi.fn(() => {
+ attached = false;
+ }),
+ sendCommand,
+ on: (event: string, listener: (...args: unknown[]) => void) => {
+ const group = listeners.get(event) ?? new Set();
+ group.add(listener);
+ listeners.set(event, group);
+ },
+ removeListener: (event: string, listener: (...args: unknown[]) => void) => {
+ listeners.get(event)?.delete(listener);
+ },
+ };
+ const wc = {
+ debugger: electronDebugger,
+ once: vi.fn(),
+ } as unknown as WebContents;
+ const emit = (method: string, params: Record<string, unknown>) => {
+ for (const listener of listeners.get('message') ?? []) {
+ listener({}, method, params);
+ }
+ };
+ return { wc, emit, electronDebugger, sendCommand };
+}
+
+describe('RsbWebviewDialogs', () => {
+ it('reports and accepts a pending prompt', async () => {
+ const harness = dialogHarness();
+ const dialogs = new RsbWebviewDialogs({ warn: vi.fn() });
+ await dialogs.observe(harness.wc);
+ harness.emit('Page.javascriptDialogOpening', {
+ type: 'prompt',
+ message: 'Enter a name',
+ defaultPrompt: 'Cindy',
+ });
+
+ const pending = dialogs.pending(harness.wc);
+ expect(pending).toMatchObject({
+ type: 'prompt',
+ message: 'Enter a name',
+ defaultValue: 'Cindy',
+ });
+
+ await expect(
+ dialogs.respond(harness.wc, {
+ dialogId: pending?.id,
+ accept: true,
+ promptText: 'New name',
+ }),
+ ).resolves.toMatchObject({
+ id: pending?.id,
+ accepted: true,
+ });
+ expect(harness.sendCommand).toHaveBeenCalledWith('Page.handleJavaScriptDialog', {
+ accept: true,
+ promptText: 'New name',
+ });
+ harness.emit('Page.javascriptDialogClosed', {
+ result: true,
+ userInput: 'New name',
+ });
+ expect(dialogs.pending(harness.wc)).toBeUndefined();
+ });
+
+ it('rejects a stale id without responding to a different dialog', async () => {
+ const harness = dialogHarness();
+ const dialogs = new RsbWebviewDialogs({ warn: vi.fn() });
+ await dialogs.observe(harness.wc);
+ harness.emit('Page.javascriptDialogOpening', {
+ type: 'confirm',
+ message: 'Continue?',
+ });
+
+ await expect(
+ dialogs.respond(harness.wc, {
+ dialogId: 'stale-dialog',
+ accept: false,
+ timeoutMs: 50,
+ }),
+ ).rejects.toThrow('is no longer pending');
+ expect(harness.sendCommand).not.toHaveBeenCalledWith(
+ 'Page.handleJavaScriptDialog',
+ expect.anything(),
+ );
+ });
+
+ it('resolves a one-shot opening watcher and allows cancellation', async () => {
+ const harness = dialogHarness();
+ const dialogs = new RsbWebviewDialogs({ warn: vi.fn() });
+ await dialogs.observe(harness.wc);
+
+ const opening = dialogs.watchOpening(harness.wc);
+ harness.emit('Page.javascriptDialogOpening', {
+ type: 'alert',
+ message: 'Saved',
+ });
+ await expect(opening.opened).resolves.toMatchObject({
+ type: 'alert',
+ message: 'Saved',
+ });
+
+ const cancelled = dialogs.watchOpening(harness.wc);
+ cancelled.cancel();
+ harness.emit('Page.javascriptDialogClosed', {});
+ expect(dialogs.pending(harness.wc)).toBeUndefined();
+ });
+
+ it('records auto-closed dialogs and arms the next response', async () => {
+ const harness = dialogHarness();
+ const dialogs = new RsbWebviewDialogs({ warn: vi.fn() });
+ await dialogs.observe(harness.wc);
+ harness.emit('Page.javascriptDialogOpening', {
+ type: 'confirm',
+ message: 'Continue?',
+ });
+ harness.emit('Page.javascriptDialogClosed', {
+ result: false,
+ userInput: '',
+ });
+ const first = dialogs.recent(harness.wc);
+ expect(first).toMatchObject({
+ type: 'confirm',
+ message: 'Continue?',
+ closedBy: 'auto',
+ });
+
+ const deferred = await dialogs.respond(harness.wc, {
+ dialogId: first?.id,
+ accept: true,
+ });
+ expect(deferred).toMatchObject({
+ id: first?.id,
+ deferred: true,
+ });
+
+ const armed = dialogs.armNext(harness.wc, { accept: true });
+ harness.emit('Page.javascriptDialogOpening', {
+ type: 'confirm',
+ message: 'Continue again?',
+ });
+ await expect(armed.response).resolves.toMatchObject({
+ type: 'confirm',
+ message: 'Continue again?',
+ closedBy: 'armed',
+ });
+ expect(harness.sendCommand).toHaveBeenCalledWith('Page.handleJavaScriptDialog', {
+ accept: true,
+ });
+ });
+
+ it('does not let an undirected response consume a stale recent dialog', async () => {
+ const harness = dialogHarness();
+ const dialogs = new RsbWebviewDialogs({ warn: vi.fn() });
+ await dialogs.observe(harness.wc);
+ harness.emit('Page.javascriptDialogOpening', {
+ type: 'confirm',
+ message: 'Old dialog',
+ });
+ harness.emit('Page.javascriptDialogClosed', {
+ result: false,
+ userInput: '',
+ });
+
+ await expect(
+ dialogs.respond(harness.wc, {
+ accept: true,
+ timeoutMs: 20,
+ }),
+ ).rejects.toThrow('no page dialog is pending');
+
+ const armed = dialogs.armNext(harness.wc, { accept: true });
+ harness.emit('Page.javascriptDialogOpening', {
+ type: 'confirm',
+ message: 'Fresh dialog',
+ });
+ await expect(armed.response).resolves.toMatchObject({
+ message: 'Fresh dialog',
+ closedBy: 'armed',
+ });
+ });
+
+ it('keeps a prepared response active beyond the regular action timeout', async () => {
+ vi.useFakeTimers();
+ try {
+ const harness = dialogHarness();
+ const dialogs = new RsbWebviewDialogs({ warn: vi.fn() });
+ await dialogs.observe(harness.wc);
+
+ const armed = dialogs.armNext(harness.wc, { accept: true });
+ await vi.advanceTimersByTimeAsync(60_001);
+ harness.emit('Page.javascriptDialogOpening', {
+ type: 'confirm',
+ message: 'Continue later?',
+ });
+
+ await expect(armed.response).resolves.toMatchObject({
+ type: 'confirm',
+ message: 'Continue later?',
+ closedBy: 'armed',
+ });
+ expect(harness.sendCommand).toHaveBeenCalledWith('Page.handleJavaScriptDialog', {
+ accept: true,
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('detaches only debugger sessions it owns', async () => {
+ const owned = dialogHarness();
+ const ownedDialogs = new RsbWebviewDialogs({ warn: vi.fn() });
+ await ownedDialogs.observe(owned.wc);
+ ownedDialogs.dispose();
+ expect(owned.electronDebugger.detach).toHaveBeenCalledTimes(1);
+
+ const shared = dialogHarness();
+ shared.electronDebugger.attach();
+ const sharedDialogs = new RsbWebviewDialogs({ warn: vi.fn() });
+ await sharedDialogs.observe(shared.wc);
+ sharedDialogs.dispose();
+ expect(shared.electronDebugger.detach).toHaveBeenCalledTimes(0);
+ });
+});
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-network.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-network.test.ts
new file mode 100644
index 0000000000..cb1a218b38
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-network.test.ts
@@ -0,0 +1,202 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { WebContents } from 'electron';
+
+import { RsbWebviewNetwork } from '../rsb-webview-network.js';
+
+function networkHarness() {
+ let attached = false;
+ const listeners = new Map<string, Set<(...args: unknown[]) => void>>();
+ const sendCommand = vi.fn(async (method: string) => {
+ if (method === 'Network.enable') return {};
+ if (method === 'Network.getResponseBody') {
+ return { body: '{"ok":true}', base64Encoded: false };
+ }
+ throw new Error(`unexpected command: ${method}`);
+ });
+ const electronDebugger = {
+ isAttached: () => attached,
+ attach: vi.fn(() => {
+ attached = true;
+ }),
+ detach: vi.fn(() => {
+ attached = false;
+ }),
+ sendCommand,
+ on: (event: string, listener: (...args: unknown[]) => void) => {
+ const group = listeners.get(event) ?? new Set();
+ group.add(listener);
+ listeners.set(event, group);
+ },
+ removeListener: (event: string, listener: (...args: unknown[]) => void) => {
+ listeners.get(event)?.delete(listener);
+ },
+ };
+ const wc = {
+ debugger: electronDebugger,
+ once: vi.fn(),
+ } as unknown as WebContents;
+ const emit = (event: string, ...args: unknown[]) => {
+ for (const listener of listeners.get(event) ?? []) listener({}, ...args);
+ };
+ return { wc, emit, electronDebugger, sendCommand };
+}
+
+describe('RsbWebviewNetwork', () => {
+ it('buffers request outcomes and returns a bounded response body', async () => {
+ const harness = networkHarness();
+ const network = new RsbWebviewNetwork({ warn: vi.fn() });
+ await network.observe(harness.wc);
+
+ const pendingBody = network.readResponseBody(harness.wc, {
+ url: '/api/items',
+ maxChars: 5,
+ });
+ await Promise.resolve();
+ harness.emit('message', 'Network.requestWillBeSent', {
+ requestId: 'request-1',
+ type: 'XHR',
+ request: { method: 'POST', url: 'https://example.test/api/items' },
+ });
+ harness.emit('message', 'Network.responseReceived', {
+ requestId: 'request-1',
+ response: {
+ url: 'https://example.test/api/items',
+ status: 201,
+ headers: {
+ 'content-type': 'application/json',
+ 'set-cookie': 'secret=hidden',
+ },
+ },
+ });
+ harness.emit('message', 'Network.loadingFinished', { requestId: 'request-1' });
+
+ expect(network.readRequests(harness.wc)).toEqual([
+ expect.objectContaining({
+ id: 'request-1',
+ method: 'POST',
+ resourceType: 'xhr',
+ status: 201,
+ ok: true,
+ }),
+ ]);
+ await expect(pendingBody).resolves.toEqual({
+ url: 'https://example.test/api/items',
+ status: 201,
+ headers: { 'content-type': 'application/json' },
+ body: '{"ok"',
+ truncated: true,
+ });
+ });
+
+ it('clears buffered metadata without leaking sensitive request headers', async () => {
+ const harness = networkHarness();
+ const network = new RsbWebviewNetwork({ warn: vi.fn() });
+ await network.observe(harness.wc);
+ harness.emit('message', 'Network.requestWillBeSent', {
+ requestId: 'request-2',
+ type: 'Fetch',
+ request: {
+ method: 'GET',
+ url: 'https://example.test/private',
+ headers: { authorization: 'Bearer secret' },
+ },
+ });
+
+ expect(network.readRequests(harness.wc, { filter: '/private', clear: true })).toHaveLength(1);
+ expect(network.readRequests(harness.wc)).toEqual([]);
+ expect(JSON.stringify(network.diagnostics())).not.toContain('secret');
+ });
+
+ it('waits for a new matching response instead of reusing response history', async () => {
+ const harness = networkHarness();
+ const network = new RsbWebviewNetwork({ warn: vi.fn() });
+ await network.observe(harness.wc);
+ harness.emit('message', 'Network.requestWillBeSent', {
+ requestId: 'request-old',
+ type: 'XHR',
+ request: { method: 'GET', url: 'https://example.test/api/state' },
+ });
+ harness.emit('message', 'Network.responseReceived', {
+ requestId: 'request-old',
+ response: { url: 'https://example.test/api/state', status: 200 },
+ });
+ harness.emit('message', 'Network.loadingFinished', { requestId: 'request-old' });
+
+ const pendingBody = network.readResponseBody(harness.wc, {
+ url: '/api/state',
+ timeoutMs: 1_000,
+ });
+ await Promise.resolve();
+ expect(harness.sendCommand).not.toHaveBeenCalledWith(
+ 'Network.getResponseBody',
+ { requestId: 'request-old' },
+ );
+ harness.emit('message', 'Network.requestWillBeSent', {
+ requestId: 'request-new',
+ type: 'XHR',
+ request: { method: 'GET', url: 'https://example.test/api/state' },
+ });
+ harness.emit('message', 'Network.responseReceived', {
+ requestId: 'request-new',
+ response: { url: 'https://example.test/api/state', status: 200 },
+ });
+ harness.emit('message', 'Network.loadingFinished', { requestId: 'request-new' });
+
+ await expect(pendingBody).resolves.toMatchObject({
+ url: 'https://example.test/api/state',
+ body: '{"ok":true}',
+ });
+ expect(harness.sendCommand).toHaveBeenCalledWith(
+ 'Network.getResponseBody',
+ { requestId: 'request-new' },
+ );
+ });
+
+ it('removes URL credentials from request and response output', async () => {
+ const harness = networkHarness();
+ const network = new RsbWebviewNetwork({ warn: vi.fn() });
+ await network.observe(harness.wc);
+ const pendingBody = network.readResponseBody(harness.wc, {
+ url: '/private',
+ timeoutMs: 1_000,
+ });
+ await Promise.resolve();
+ harness.emit('message', 'Network.requestWillBeSent', {
+ requestId: 'request-secret',
+ type: 'XHR',
+ request: {
+ method: 'GET',
+ url: 'https://user:[email protected]/private',
+ },
+ });
+ harness.emit('message', 'Network.responseReceived', {
+ requestId: 'request-secret',
+ response: {
+ url: 'https://user:[email protected]/private',
+ status: 200,
+ },
+ });
+ harness.emit('message', 'Network.loadingFinished', { requestId: 'request-secret' });
+
+ expect(network.readRequests(harness.wc)[0].url).toBe('https://example.test/private');
+ await expect(pendingBody).resolves.toMatchObject({
+ url: 'https://example.test/private',
+ });
+ });
+
+ it('waits for an actual quiet network window', async () => {
+ const harness = networkHarness();
+ const network = new RsbWebviewNetwork({ warn: vi.fn() });
+ await network.observe(harness.wc);
+
+ harness.emit('message', 'Network.requestWillBeSent', {
+ requestId: 'request-idle',
+ type: 'Fetch',
+ request: { method: 'GET', url: 'https://example.test/data' },
+ });
+ const pending = network.waitForIdle(harness.wc, { timeoutMs: 2_000, idleMs: 50 });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ harness.emit('message', 'Network.loadingFinished', { requestId: 'request-idle' });
+ await expect(pending).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-upload-policy.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-upload-policy.test.ts
new file mode 100644
index 0000000000..bc2b78340d
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-upload-policy.test.ts
@@ -0,0 +1,59 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { resolveUploadFiles } from '../rsb-webview-upload-policy.js';
+
+let tempRoot = '';
+let allowedRoot = '';
+let outsideRoot = '';
+
+beforeEach(async () => {
+ tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-browser-upload-test-'));
+ allowedRoot = path.join(tempRoot, 'workspace');
+ outsideRoot = path.join(tempRoot, 'outside');
+ await fs.mkdir(allowedRoot);
+ await fs.mkdir(outsideRoot);
+});
+
+afterEach(async () => {
+ await fs.rm(tempRoot, { recursive: true, force: true });
+});
+
+describe('resolveUploadFiles', () => {
+ it('accepts ordinary files inside an allowed root', async () => {
+ const file = path.join(allowedRoot, 'report.txt');
+ await fs.writeFile(file, 'hello');
+
+ await expect(resolveUploadFiles([file], [allowedRoot])).resolves.toEqual([
+ await fs.realpath(file),
+ ]);
+ });
+
+ it('rejects files outside the session roots and sensitive names', async () => {
+ const outside = path.join(outsideRoot, 'outside.txt');
+ const secret = path.join(allowedRoot, '.env.local');
+ await fs.writeFile(outside, 'outside');
+ await fs.writeFile(secret, 'TOKEN=not-real');
+
+ await expect(resolveUploadFiles([outside], [allowedRoot])).rejects.toThrow(
+ 'inside the current session directory',
+ );
+ await expect(resolveUploadFiles([secret], [allowedRoot])).rejects.toThrow(
+ 'blocked for sensitive file',
+ );
+ });
+
+ it('resolves links before checking containment', async () => {
+ const outside = path.join(outsideRoot, 'linked.txt');
+ const linkDir = path.join(allowedRoot, 'linked-outside');
+ await fs.writeFile(outside, 'outside');
+ await fs.symlink(outsideRoot, linkDir, 'junction');
+
+ await expect(
+ resolveUploadFiles([path.join(linkDir, 'linked.txt')], [allowedRoot]),
+ ).rejects.toThrow('inside the current session directory');
+ });
+});
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-artifacts.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-artifacts.ts
new file mode 100644
index 0000000000..673a11f3cb
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-artifacts.ts
@@ -0,0 +1,510 @@
+import fs from 'node:fs';
+import path from 'node:path';
+
+import type { WebContents } from 'electron';
+
+interface ArtifactLogger {
+ warn(message: string, ...args: unknown[]): void;
+}
+
+interface DownloadItemLike {
+ getFilename(): string;
+ getURL(): string;
+ getMimeType(): string;
+ getTotalBytes(): number;
+ getReceivedBytes(): number;
+ setSavePath(filePath: string): void;
+ cancel(): void;
+ on(event: string, listener: (...args: unknown[]) => void): void;
+ once(event: string, listener: (...args: unknown[]) => void): void;
+}
+
+interface SessionLike {
+ on(event: string, listener: (...args: unknown[]) => void): void;
+ removeListener(event: string, listener: (...args: unknown[]) => void): void;
+}
+
+export interface BrowserArtifact {
+ id: string;
+ fileName: string;
+ path?: string;
+ url?: string;
+ mimeType?: string;
+ bytes?: number;
+ state: 'completed' | 'cancelled' | 'interrupted';
+ startedAt: string;
+ finishedAt: string;
+}
+
+interface PendingDownload {
+ item: DownloadItemLike;
+ done: Promise<BrowserArtifact>;
+ filePath?: string;
+ knownTotalBytes?: number;
+ limitReason?: string;
+ reservationReleased?: boolean;
+}
+
+interface ArtifactCapture {
+ id: string;
+ sessionId: string;
+ webContents: WebContents;
+ directory: string;
+ accepting: boolean;
+ pending: PendingDownload[];
+ usedNames: Set<string>;
+ reservedBytes: number;
+}
+
+// A click can schedule a download after the event handler returns (for
+// example, a page may first fetch a signed URL). Keep this wait bounded while
+// allowing normal deferred download starts to be observed.
+const DOWNLOAD_GRACE_MS = 2_000;
+const DEFAULT_DOWNLOAD_TIMEOUT_MS = 60_000;
+const MAX_DOWNLOAD_TIMEOUT_MS = 5 * 60_000;
+const MAX_DOWNLOADS_PER_CAPTURE = 8;
+const MAX_DOWNLOAD_BYTES_PER_FILE = 32 * 1024 * 1024;
+const MAX_DOWNLOAD_BYTES_PER_CAPTURE = 64 * 1024 * 1024;
+const MAX_RECENT_ARTIFACTS = 100;
+const MAX_RETAINED_ARTIFACT_BYTES = 256 * 1024 * 1024;
+
+let captureSequence = 0;
+let artifactSequence = 0;
+
+function safeSegment(value: string): string {
+ const cleaned = value.replace(/[^A-Za-z0-9_-]+/g, '_').replace(/^_+|_+$/g, '');
+ return (cleaned || 'session').slice(0, 64);
+}
+
+function processArtifactRoot(rootDir: string): string {
+ return path.join(rootDir, `process-${process.pid}`);
+}
+
+export function artifactSessionRoot(rootDir: string, sessionId: string): string {
+ return path.join(processArtifactRoot(rootDir), safeSegment(sessionId));
+}
+
+async function reclaimStaleProcessRoots(rootDir: string): Promise<void> {
+ let entries: fs.Dirent[];
+ try {
+ entries = await fs.promises.readdir(rootDir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ await Promise.all(entries.map(async (entry) => {
+ if (!entry.isDirectory()) return;
+ const match = /^process-(\d+)$/.exec(entry.name);
+ if (!match) return;
+ const pid = Number(match[1]);
+ if (!Number.isSafeInteger(pid) || pid === process.pid) return;
+ try {
+ process.kill(pid, 0);
+ return;
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'EPERM') return;
+ }
+ await fs.promises.rm(path.join(rootDir, entry.name), { recursive: true, force: true });
+ }));
+}
+
+function safeFileName(raw: string): string {
+ const base = raw.split(/[\\/]/).pop() ?? '';
+ let cleaned = base
+ // eslint-disable-next-line no-control-regex -- control characters are invalid in filenames
+ .replace(/[\u0000-\u001f<>:"|?*]/g, '')
+ .replace(/^\.+/, '')
+ .replace(/[. ]+$/, '')
+ .trim();
+ if (!cleaned || cleaned === '..') cleaned = 'download';
+ if (cleaned.length > 160) cleaned = cleaned.slice(-160);
+ if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i.test(cleaned)) {
+ cleaned = `_${cleaned}`;
+ }
+ return cleaned;
+}
+
+function uniqueName(base: string, used: Set<string>): string {
+ const extension = path.extname(base);
+ const stem = base.slice(0, base.length - extension.length);
+ let candidate = base;
+ for (let index = 2; used.has(candidate.toLowerCase()); index += 1) {
+ candidate = `${stem}-${index}${extension}`;
+ }
+ used.add(candidate.toLowerCase());
+ return candidate;
+}
+
+function sessionFor(wc: WebContents): SessionLike {
+ const session = (wc as unknown as { session?: SessionLike }).session;
+ if (!session) throw new Error('webContents session is unavailable');
+ return session;
+}
+
+function boundedTimeout(value: unknown): number {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
+ ? Math.min(MAX_DOWNLOAD_TIMEOUT_MS, Math.floor(value))
+ : DEFAULT_DOWNLOAD_TIMEOUT_MS;
+}
+
+function displayUrl(value: string): string | undefined {
+ try {
+ const parsed = new URL(value);
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return undefined;
+ parsed.username = '';
+ parsed.password = '';
+ return parsed.href;
+ } catch {
+ return undefined;
+ }
+}
+
+function wait(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+/**
+ * Captures downloads only while an agent-owned browser action is in flight.
+ * Each action gets an isolated directory with bounded count and byte quotas.
+ * Failed, cancelled, evicted, and disposed files are removed; completed files
+ * remain available for later tool steps until the retention budget is reached.
+ */
+export class RsbWebviewArtifacts {
+ private readonly sessionListeners = new Map<SessionLike, (...args: unknown[]) => void>();
+ private readonly captures = new Map<WebContents, ArtifactCapture>();
+ private readonly recent: BrowserArtifact[] = [];
+ private readonly artifactSessions = new Map<string, string>();
+ private readonly preparedRoots = new Set<string>();
+ private retainedBytes = 0;
+
+ constructor(
+ private readonly rootDir: () => string,
+ private readonly logger: ArtifactLogger,
+ private readonly downloadGraceMs = DOWNLOAD_GRACE_MS,
+ ) {}
+
+ async capture<T>(
+ wc: WebContents,
+ context: { sessionId: string; timeoutMs?: number },
+ action: () => Promise<T>,
+ ): Promise<{ value: T; downloads: BrowserArtifact[] }> {
+ if (this.captures.has(wc)) {
+ throw new Error('another download-aware action is already running for this tab');
+ }
+ const session = sessionFor(wc);
+ this.observeSession(session);
+ const rootDir = this.rootDir();
+ if (!this.preparedRoots.has(rootDir)) {
+ await fs.promises.mkdir(rootDir, { recursive: true });
+ await reclaimStaleProcessRoots(rootDir);
+ this.preparedRoots.add(rootDir);
+ }
+ const parent = artifactSessionRoot(rootDir, context.sessionId);
+ await fs.promises.mkdir(parent, { recursive: true });
+ captureSequence += 1;
+ const directory = await fs.promises.mkdtemp(
+ path.join(parent, `${Date.now().toString(36)}-${captureSequence.toString(36)}-`),
+ );
+ const capture: ArtifactCapture = {
+ id: `${Date.now().toString(36)}-${captureSequence.toString(36)}`,
+ sessionId: context.sessionId,
+ webContents: wc,
+ directory,
+ accepting: true,
+ pending: [],
+ usedNames: new Set(),
+ reservedBytes: 0,
+ };
+ this.captures.set(wc, capture);
+
+ let value: T;
+ try {
+ value = await action();
+ await wait(this.downloadGraceMs);
+ } catch (err) {
+ capture.accepting = false;
+ this.captures.delete(wc);
+ for (const pending of capture.pending) pending.item.cancel();
+ await this.removeDirectory(directory);
+ throw err;
+ }
+ capture.accepting = false;
+ this.captures.delete(wc);
+
+ if (capture.pending.length === 0) {
+ await this.removeDirectory(directory);
+ return { value, downloads: [] };
+ }
+
+ const timeoutMs = boundedTimeout(context.timeoutMs);
+ const completion = Promise.all(capture.pending.map((entry) => entry.done));
+ let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
+ const timeout = new Promise<BrowserArtifact[]>((_resolve, reject) => {
+ timeoutHandle = setTimeout(() => {
+ for (const pending of capture.pending) pending.item.cancel();
+ reject(new Error(`download did not finish within ${timeoutMs}ms`));
+ }, timeoutMs);
+ });
+ let downloads: BrowserArtifact[];
+ try {
+ downloads = await Promise.race([completion, timeout]);
+ } catch (err) {
+ await this.removeDirectory(directory);
+ throw err;
+ } finally {
+ if (timeoutHandle) clearTimeout(timeoutHandle);
+ }
+ for (const artifact of downloads) {
+ if (artifact.state === 'completed' && artifact.path && artifact.bytes === undefined) {
+ artifact.bytes = await this.fileSize(artifact.path);
+ }
+ this.recent.push(artifact);
+ this.artifactSessions.set(artifact.id, context.sessionId);
+ if (artifact.path && artifact.bytes) this.retainedBytes += artifact.bytes;
+ }
+ await this.trimRecent();
+ if (!downloads.some((artifact) => artifact.state === 'completed')) {
+ await this.removeDirectory(directory);
+ }
+ return { value, downloads };
+ }
+
+ diagnostics(sessionId?: string): { activeCaptures: number; recentArtifacts: BrowserArtifact[] } {
+ return {
+ activeCaptures: [...this.captures.values()]
+ .filter((capture) => !sessionId || capture.sessionId === sessionId)
+ .length,
+ recentArtifacts: this.recent
+ .filter((artifact) => !sessionId || this.artifactSessions.get(artifact.id) === sessionId)
+ .slice(-20)
+ .map((artifact) => ({ ...artifact })),
+ };
+ }
+
+ async dispose(): Promise<void> {
+ for (const [session, listener] of this.sessionListeners) {
+ session.removeListener('will-download', listener);
+ }
+ this.sessionListeners.clear();
+ const active = [...this.captures.values()];
+ this.captures.clear();
+ await Promise.all(active.map(async (capture) => {
+ capture.accepting = false;
+ for (const pending of capture.pending) pending.item.cancel();
+ await this.removeDirectory(capture.directory);
+ }));
+ const retained = this.recent.splice(0);
+ this.artifactSessions.clear();
+ this.retainedBytes = 0;
+ await Promise.all(retained.map((artifact) => (
+ artifact.path ? this.removeArtifactFile(artifact.path) : Promise.resolve()
+ )));
+ }
+
+ private observeSession(session: SessionLike): void {
+ if (this.sessionListeners.has(session)) return;
+ const listener = (...args: unknown[]) => {
+ const item = args[1] as DownloadItemLike | undefined;
+ const wc = args[2] as WebContents | undefined;
+ if (!item || !wc) return;
+ const capture = this.captures.get(wc);
+ if (!capture?.accepting) return;
+ this.trackDownload(capture, item);
+ };
+ session.on('will-download', listener);
+ this.sessionListeners.set(session, listener);
+ }
+
+ private trackDownload(capture: ArtifactCapture, item: DownloadItemLike): void {
+ artifactSequence += 1;
+ const id = `artifact-${Date.now().toString(36)}-${artifactSequence.toString(36)}`;
+ const fileName = uniqueName(safeFileName(item.getFilename()), capture.usedNames);
+ const filePath = path.join(capture.directory, fileName);
+ const startedAt = new Date().toISOString();
+ const totalBytes = this.positiveBytes(item.getTotalBytes());
+ let finishDownload: (artifact: BrowserArtifact) => void = () => undefined;
+ const done = new Promise<BrowserArtifact>((resolve) => {
+ finishDownload = resolve;
+ });
+ const pending: PendingDownload = {
+ item,
+ ...(totalBytes ? { knownTotalBytes: totalBytes } : {}),
+ done,
+ };
+ item.once('done', (_event: unknown, rawState: unknown) => {
+ const receivedBytes = this.positiveBytes(item.getReceivedBytes());
+ const observedBytes = Math.max(totalBytes ?? 0, receivedBytes ?? 0);
+ const exceededFileQuota = observedBytes > MAX_DOWNLOAD_BYTES_PER_FILE;
+ const exceededCaptureQuota = this.receivedBytes(capture) > MAX_DOWNLOAD_BYTES_PER_CAPTURE;
+ const state = pending.limitReason || exceededFileQuota || exceededCaptureQuota
+ ? 'cancelled'
+ : rawState === 'completed'
+ ? 'completed'
+ : rawState === 'cancelled'
+ ? 'cancelled'
+ : 'interrupted';
+ if (state !== 'completed') this.releaseReservation(capture, pending);
+ if (state !== 'completed' && pending.filePath) {
+ try {
+ fs.rmSync(pending.filePath, { force: true });
+ } catch (err) {
+ this.logger.warn('failed to remove incomplete browser artifact', {
+ artifactId: id,
+ err,
+ });
+ }
+ }
+ const url = displayUrl(item.getURL());
+ finishDownload({
+ id,
+ fileName,
+ ...(state === 'completed' && pending.filePath ? { path: pending.filePath } : {}),
+ ...(url ? { url } : {}),
+ ...(item.getMimeType() ? { mimeType: item.getMimeType() } : {}),
+ ...(observedBytes > 0 ? { bytes: observedBytes } : {}),
+ state,
+ startedAt,
+ finishedAt: new Date().toISOString(),
+ });
+ });
+
+ const quotaReason = this.quotaReason(capture, totalBytes);
+ if (quotaReason) {
+ this.cancelForQuota(pending, quotaReason);
+ if (capture.pending.length < MAX_DOWNLOADS_PER_CAPTURE) {
+ capture.pending.push(pending);
+ }
+ return;
+ }
+
+ capture.pending.push(pending);
+ if (totalBytes) capture.reservedBytes += totalBytes;
+ pending.filePath = filePath;
+ item.setSavePath(filePath);
+ item.on('updated', () => {
+ if (pending.limitReason) return;
+ const receivedBytes = this.positiveBytes(item.getReceivedBytes());
+ if (
+ (receivedBytes && receivedBytes > MAX_DOWNLOAD_BYTES_PER_FILE)
+ || this.receivedBytes(capture) > MAX_DOWNLOAD_BYTES_PER_CAPTURE
+ ) {
+ this.cancelForQuota(
+ pending,
+ receivedBytes && receivedBytes > MAX_DOWNLOAD_BYTES_PER_FILE
+ ? 'single download exceeds the size limit'
+ : 'capture exceeds the total download limit',
+ );
+ }
+ });
+ }
+
+ private quotaReason(capture: ArtifactCapture, totalBytes: number | undefined): string | undefined {
+ if (capture.pending.length >= MAX_DOWNLOADS_PER_CAPTURE) {
+ return 'capture exceeds the download count limit';
+ }
+ if (totalBytes && totalBytes > MAX_DOWNLOAD_BYTES_PER_FILE) {
+ return 'single download exceeds the size limit';
+ }
+ if (
+ totalBytes
+ && capture.reservedBytes + totalBytes > MAX_DOWNLOAD_BYTES_PER_CAPTURE
+ ) {
+ return 'capture exceeds the total download limit';
+ }
+ return undefined;
+ }
+
+ private cancelForQuota(pending: PendingDownload, reason: string): void {
+ pending.limitReason = reason;
+ this.logger.warn('browser download cancelled by quota', {
+ reason,
+ fileName: pending.item.getFilename(),
+ });
+ pending.item.cancel();
+ }
+
+ private receivedBytes(capture: ArtifactCapture): number {
+ return capture.reservedBytes + capture.pending.reduce((sum, pending) => {
+ if (pending.limitReason) return sum;
+ const received = this.positiveBytes(pending.item.getReceivedBytes()) ?? 0;
+ if (pending.knownTotalBytes) {
+ return sum + Math.max(0, received - pending.knownTotalBytes);
+ }
+ return sum + received;
+ }, 0);
+ }
+
+ private releaseReservation(capture: ArtifactCapture, pending: PendingDownload): void {
+ if (!pending.knownTotalBytes || pending.reservationReleased) return;
+ pending.reservationReleased = true;
+ capture.reservedBytes = Math.max(0, capture.reservedBytes - pending.knownTotalBytes);
+ }
+
+ private positiveBytes(value: number): number | undefined {
+ return Number.isFinite(value) && value > 0 ? value : undefined;
+ }
+
+ private async fileSize(filePath: string): Promise<number | undefined> {
+ try {
+ const stat = await fs.promises.stat(filePath);
+ return stat.isFile() ? stat.size : undefined;
+ } catch {
+ return undefined;
+ }
+ }
+
+ private async trimRecent(): Promise<void> {
+ const evicted: BrowserArtifact[] = [];
+ while (
+ this.recent.length > MAX_RECENT_ARTIFACTS
+ || this.retainedBytes > MAX_RETAINED_ARTIFACT_BYTES
+ ) {
+ const artifact = this.recent.shift();
+ if (!artifact) break;
+ evicted.push(artifact);
+ this.artifactSessions.delete(artifact.id);
+ if (artifact.path && artifact.bytes) this.retainedBytes -= artifact.bytes;
+ }
+ await Promise.all(evicted.map((artifact) => (
+ artifact.path ? this.removeArtifactFile(artifact.path) : Promise.resolve()
+ )));
+ }
+
+ private async removeArtifactFile(filePath: string): Promise<void> {
+ try {
+ await fs.promises.rm(filePath, { force: true });
+ } catch (err) {
+ this.logger.warn('failed to remove retained browser artifact', {
+ filePath,
+ err,
+ });
+ return;
+ }
+ try {
+ await fs.promises.rmdir(path.dirname(filePath));
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code !== 'ENOENT' && code !== 'ENOTEMPTY') {
+ this.logger.warn('failed to remove empty browser artifact directory', { err });
+ }
+ return;
+ }
+ try {
+ // Capture directories live below a session directory. Reclaim that
+ // parent too once the last retained file for the session is gone.
+ await fs.promises.rmdir(path.dirname(path.dirname(filePath)));
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code !== 'ENOENT' && code !== 'ENOTEMPTY') {
+ this.logger.warn('failed to remove empty browser artifact session directory', { err });
+ }
+ }
+ }
+
+ private async removeDirectory(directory: string): Promise<void> {
+ try {
+ await fs.promises.rm(directory, { recursive: true, force: true });
+ } catch (err) {
+ this.logger.warn('failed to clean browser artifact directory', { err });
+ }
+ }
+}
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-automation.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-automation.ts
new file mode 100644
index 0000000000..7e1c35eb16
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-automation.ts
@@ -0,0 +1,2319 @@
+import type {
+ BrowserActRequest,
+ BrowserControlRequest,
+ BrowserElementQuery,
+} from '@cindy/browser-control-runtime';
+import type { WebContents } from 'electron';
+
+interface AutomationLogger {
+ warn(message: string, ...args: unknown[]): void;
+}
+
+interface DebuggerTransport {
+ isAttached(): boolean;
+ attach(protocolVersion?: string): void;
+ detach(): void;
+ sendCommand(method: string, commandParams?: Record<string, unknown>): Promise<unknown>;
+}
+
+interface AxValue {
+ value?: unknown;
+}
+
+interface RawAxNode {
+ nodeId?: string;
+ ignored?: boolean;
+ role?: AxValue;
+ name?: AxValue;
+ value?: AxValue;
+ childIds?: string[];
+ backendDOMNodeId?: number;
+}
+
+interface SnapshotRef {
+ role: string;
+ name?: string;
+ value?: string;
+ backendDOMNodeId: number;
+}
+
+interface SnapshotTreeNode extends SnapshotRef {
+ nodeId: string;
+ children: number[];
+ depth: number;
+ ref?: string;
+ url?: string;
+}
+
+interface ResolvedNode {
+ objectId: string;
+ backendDOMNodeId?: number;
+}
+
+export interface RsbSnapshotResult {
+ format: 'ai' | 'aria';
+ targetId: string;
+ url: string;
+ snapshot?: string;
+ refs?: Record<string, SnapshotRef>;
+ resources?: Array<{
+ kind: string;
+ url: string;
+ label?: string;
+ }>;
+ barrier?: {
+ kind: 'human-verification';
+ evidence: string[];
+ };
+ nodes?: Array<{
+ ref?: string;
+ role: string;
+ name?: string;
+ value?: string;
+ backendDOMNodeId: number;
+ }>;
+ stats: {
+ lines: number;
+ chars: number;
+ refs: number;
+ interactive: number;
+ };
+}
+
+export interface RsbActResult {
+ tabId: string;
+ kind: BrowserActRequest['kind'];
+ [key: string]: unknown;
+}
+
+export interface HumanVerificationBarrier {
+ kind: 'human-verification';
+ evidence: string[];
+}
+
+interface PageInspection {
+ resources: Array<{ kind: string; url: string; label?: string }>;
+ barrier?: HumanVerificationBarrier;
+}
+
+const INTERACTIVE_ROLES = new Set([
+ 'alertdialog',
+ 'button',
+ 'checkbox',
+ 'combobox',
+ 'gridcell',
+ 'link',
+ 'listbox',
+ 'menuitem',
+ 'menuitemcheckbox',
+ 'menuitemradio',
+ 'option',
+ 'radio',
+ 'searchbox',
+ 'slider',
+ 'spinbutton',
+ 'switch',
+ 'tab',
+ 'textbox',
+ 'treeitem',
+]);
+
+const STRUCTURAL_ROLES = new Set([
+ 'generic',
+ 'group',
+ 'list',
+ 'none',
+ 'presentation',
+ 'rootwebarea',
+]);
+
+const DEFAULT_WAIT_TIMEOUT_MS = 10_000;
+const MAX_WAIT_TIMEOUT_MS = 60_000;
+const MAX_SNAPSHOT_REFS = 2_000;
+const EFFICIENT_SNAPSHOT_MAX_CHARS = 8_000;
+const EFFICIENT_SNAPSHOT_DEPTH = 6;
+
+function axText(value: AxValue | undefined): string {
+ const raw = value?.value;
+ if (raw === undefined || raw === null) return '';
+ return typeof raw === 'string' ? raw : String(raw);
+}
+
+function finiteNonNegative(value: unknown, field: string): number {
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
+ throw new Error(`${field} requires a non-negative finite number`);
+ }
+ return value;
+}
+
+function positiveInt(value: unknown, fallback: number, max: number): number {
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
+ return fallback;
+ }
+ return Math.min(max, Math.max(1, Math.floor(value)));
+}
+
+function escapeSnapshotText(value: string): string {
+ return value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replace(/\s+/g, ' ').trim();
+}
+
+function delay(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function getDebugger(wc: WebContents): DebuggerTransport {
+ const candidate = (wc as unknown as { debugger?: DebuggerTransport }).debugger;
+ if (!candidate) {
+ throw new Error('webContents debugger is unavailable');
+ }
+ return candidate;
+}
+
+async function withDebugger<T>(
+ wc: WebContents,
+ body: (send: DebuggerTransport['sendCommand']) => Promise<T>,
+): Promise<T> {
+ const transport = getDebugger(wc);
+ const alreadyAttached = transport.isAttached();
+ if (!alreadyAttached) {
+ transport.attach('1.3');
+ }
+ try {
+ return await body(transport.sendCommand.bind(transport));
+ } finally {
+ if (!alreadyAttached && transport.isAttached()) {
+ transport.detach();
+ }
+ }
+}
+
+function buildSnapshotTree(nodes: RawAxNode[]): { tree: SnapshotTreeNode[]; roots: number[] } {
+ const tree: SnapshotTreeNode[] = [];
+ const byId = new Map<string, number>();
+ for (const raw of nodes) {
+ const nodeId = raw.nodeId;
+ const backendDOMNodeId = raw.backendDOMNodeId;
+ if (
+ raw.ignored === true ||
+ typeof nodeId !== 'string' ||
+ nodeId === '' ||
+ typeof backendDOMNodeId !== 'number' ||
+ backendDOMNodeId <= 0
+ ) {
+ continue;
+ }
+ byId.set(nodeId, tree.length);
+ tree.push({
+ nodeId,
+ role: axText(raw.role).toLowerCase() || 'unknown',
+ name: axText(raw.name) || undefined,
+ value: axText(raw.value) || undefined,
+ backendDOMNodeId,
+ children: [],
+ depth: 0,
+ });
+ }
+
+ const rawById = new Map(
+ nodes
+ .filter((node): node is RawAxNode & { nodeId: string } => typeof node.nodeId === 'string')
+ .map((node) => [node.nodeId, node]),
+ );
+ const childIndexes = new Set<number>();
+ const visibleChildren = (rawId: string, seen = new Set<string>()): number[] => {
+ if (seen.has(rawId)) return [];
+ seen.add(rawId);
+ const raw = rawById.get(rawId);
+ const result: number[] = [];
+ for (const childId of raw?.childIds ?? []) {
+ const childIndex = byId.get(childId);
+ if (childIndex !== undefined) {
+ result.push(childIndex);
+ } else {
+ result.push(...visibleChildren(childId, new Set(seen)));
+ }
+ }
+ return result;
+ };
+ for (let index = 0; index < tree.length; index += 1) {
+ tree[index].children = visibleChildren(tree[index].nodeId);
+ for (const childIndex of tree[index].children) childIndexes.add(childIndex);
+ }
+
+ const roots = tree.map((_node, index) => index).filter((index) => !childIndexes.has(index));
+ const stack = (roots.length > 0 ? roots : tree.length > 0 ? [0] : []).map((index) => ({
+ index,
+ depth: 0,
+ }));
+ while (stack.length > 0) {
+ const current = stack.pop();
+ if (!current) break;
+ const node = tree[current.index];
+ node.depth = current.depth;
+ for (const child of node.children.toReversed()) {
+ stack.push({ index: child, depth: current.depth + 1 });
+ }
+ }
+ return { tree, roots };
+}
+
+function shouldReference(node: SnapshotTreeNode): boolean {
+ if (INTERACTIVE_ROLES.has(node.role)) return true;
+ return Boolean(node.name) && !STRUCTURAL_ROLES.has(node.role);
+}
+
+function shouldRender(node: SnapshotTreeNode, req: BrowserControlRequest): boolean {
+ if (typeof req.depth === 'number' && node.depth > req.depth) return false;
+ if (req.interactive === true) return INTERACTIVE_ROLES.has(node.role);
+ if (req.compact === true && STRUCTURAL_ROLES.has(node.role) && !node.name && !node.ref) {
+ return false;
+ }
+ return true;
+}
+
+function renderSnapshotTree(
+ tree: SnapshotTreeNode[],
+ roots: number[],
+ req: BrowserControlRequest,
+): string[] {
+ const lines: string[] = [];
+ const visit = (index: number): void => {
+ const node = tree[index];
+ if (!node) return;
+ if (shouldRender(node, req)) {
+ const name = node.name ? ` "${escapeSnapshotText(node.name)}"` : '';
+ const ref = node.ref ? ` [ref=${node.ref}]` : '';
+ const value = node.value ? ` value="${escapeSnapshotText(node.value)}"` : '';
+ const url = node.url ? ` [url=${node.url}]` : '';
+ lines.push(`${' '.repeat(node.depth)}- ${node.role}${name}${ref}${value}${url}`);
+ }
+ for (const child of node.children) visit(child);
+ };
+ for (const root of roots) visit(root);
+ return lines;
+}
+
+function truncateSnapshotLines(lines: string[], maxChars: number | undefined): string[] {
+ // The shared browser contract uses zero as the explicit "no limit" value.
+ if (maxChars === undefined || maxChars === 0) return lines;
+ if (maxChars <= 0) return [];
+ const out: string[] = [];
+ let used = 0;
+ for (const line of lines) {
+ const added = line.length + (out.length > 0 ? 1 : 0);
+ if (used + added > maxChars) break;
+ out.push(line);
+ used += added;
+ }
+ return out;
+}
+
+function visibleRefs(
+ refs: Record<string, SnapshotRef>,
+ lines: string[],
+): Record<string, SnapshotRef> {
+ const rendered = lines.join('\n');
+ return Object.fromEntries(
+ Object.entries(refs).filter(([ref]) => rendered.includes(`[ref=${ref}]`)),
+ );
+}
+
+async function resolveHref(
+ send: DebuggerTransport['sendCommand'],
+ backendDOMNodeId: number,
+): Promise<string | undefined> {
+ const resolved = (await send('DOM.resolveNode', { backendNodeId: backendDOMNodeId })) as {
+ object?: { objectId?: string };
+ };
+ const objectId = resolved.object?.objectId;
+ if (!objectId) return undefined;
+ try {
+ const result = (await send('Runtime.callFunctionOn', {
+ objectId,
+ functionDeclaration: 'function() { return typeof this.href === "string" ? this.href : ""; }',
+ returnByValue: true,
+ })) as { result?: { value?: unknown } };
+ return typeof result.result?.value === 'string' && result.result.value !== ''
+ ? result.result.value
+ : undefined;
+ } finally {
+ await releaseObject(send, objectId);
+ }
+}
+
+async function releaseObject(
+ send: DebuggerTransport['sendCommand'],
+ objectId: string | undefined,
+): Promise<void> {
+ if (!objectId) return;
+ await send('Runtime.releaseObject', { objectId }).catch(() => undefined);
+}
+
+async function inspectPage(
+ send: DebuggerTransport['sendCommand'],
+ includeResources: boolean,
+): Promise<PageInspection> {
+ const evaluated = (await send('Runtime.evaluate', {
+ expression: `(() => {
+ const normalize = (value) => String(value ?? "").replace(/\\s+/g, " ").trim();
+ const pageText = normalize(document.body?.innerText || "").slice(0, 6000);
+ const title = normalize(document.title);
+ const evidence = [];
+ const titleMatch = /(verify you are human|checking your browser|just a moment|unusual traffic|captcha|人机验证|安全验证|访问验证)/i.test(title);
+ if (titleMatch) {
+ evidence.push("page title indicates manual verification");
+ }
+ const challengeSelector = [
+ '[data-sitekey]',
+ 'iframe[src*="captcha" i]',
+ 'iframe[src*="challenge" i]',
+ '[id*="captcha" i]',
+ '[class*="captcha" i]',
+ ].join(",");
+ const verificationControl = [...document.querySelectorAll(challengeSelector)].find((element) => {
+ const rect = element.getBoundingClientRect();
+ const style = getComputedStyle(element);
+ return rect.width >= 20 && rect.height >= 20 && style.visibility !== "hidden" && style.display !== "none";
+ });
+ if (verificationControl) {
+ evidence.push("page contains a verification control");
+ }
+ const textMatch = /(verify you are human|checking your browser|unusual traffic|complete the security check|i['’]?m not a robot|人机验证|安全验证|访问验证)/i.test(pageText);
+ if (textMatch) {
+ evidence.push("page text asks for a manual check");
+ }
+ const verificationBlocked = titleMatch || Boolean(verificationControl && textMatch);
+
+ const resources = [];
+ if (${JSON.stringify(includeResources)}) {
+ const seen = new Set();
+ const add = (kind, raw, label) => {
+ if (resources.length >= 200) return;
+ let url;
+ try {
+ url = new URL(String(raw || ""), document.baseURI);
+ } catch {
+ return;
+ }
+ if (!["http:", "https:"].includes(url.protocol)) return;
+ const href = url.href;
+ if (seen.has(href)) return;
+ seen.add(href);
+ const item = { kind, url: href };
+ const text = normalize(label);
+ if (text) item.label = text.slice(0, 200);
+ resources.push(item);
+ };
+ document.querySelectorAll('img[src],video[src],audio[src],source[src],a[download][href],link[rel~="stylesheet"][href],link[rel~="icon"][href],link[rel="manifest"][href]').forEach((element) => {
+ const tag = element.tagName.toLowerCase();
+ const rel = normalize(element.getAttribute("rel")).toLowerCase();
+ const kind = tag === "img"
+ ? "image"
+ : tag === "video" || tag === "source" && element.parentElement?.tagName.toLowerCase() === "video"
+ ? "video"
+ : tag === "audio" || tag === "source" && element.parentElement?.tagName.toLowerCase() === "audio"
+ ? "audio"
+ : tag === "a"
+ ? "download"
+ : rel.includes("stylesheet")
+ ? "stylesheet"
+ : "link";
+ add(kind, element.getAttribute("src") || element.getAttribute("href"), element.getAttribute("alt") || element.getAttribute("download") || element.getAttribute("title"));
+ });
+ }
+ return {
+ resources,
+ ...(verificationBlocked ? { barrier: { kind: "human-verification", evidence: [...new Set(evidence)] } } : {}),
+ };
+ })()`,
+ awaitPromise: true,
+ returnByValue: true,
+ })) as { result?: { value?: unknown }; exceptionDetails?: { text?: string } };
+ if (evaluated.exceptionDetails) {
+ throw new Error(evaluated.exceptionDetails.text ?? 'page inspection failed');
+ }
+ const value = evaluated.result?.value;
+ if (!value || typeof value !== 'object') return { resources: [] };
+ const raw = value as {
+ resources?: unknown;
+ barrier?: { kind?: unknown; evidence?: unknown };
+ };
+ const resources: PageInspection['resources'] = [];
+ if (Array.isArray(raw.resources)) {
+ for (const entry of raw.resources.slice(0, 200)) {
+ if (!entry || typeof entry !== 'object') continue;
+ const item = entry as { kind?: unknown; url?: unknown; label?: unknown };
+ if (typeof item.kind !== 'string' || typeof item.url !== 'string') continue;
+ if (item.url.length > 4096) continue;
+ try {
+ const parsed = new URL(item.url);
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') continue;
+ if (parsed.username || parsed.password) continue;
+ } catch {
+ continue;
+ }
+ resources.push({
+ kind: item.kind.slice(0, 32),
+ url: item.url,
+ ...(typeof item.label === 'string' && item.label !== ''
+ ? { label: item.label.slice(0, 200) }
+ : {}),
+ });
+ }
+ }
+ const evidence = Array.isArray(raw.barrier?.evidence)
+ ? raw.barrier.evidence.filter((item): item is string => typeof item === 'string').slice(0, 8)
+ : [];
+ return {
+ resources,
+ ...(evidence.length > 0 ? { barrier: { kind: 'human-verification', evidence } } : {}),
+ };
+}
+
+async function resolveSelector(
+ send: DebuggerTransport['sendCommand'],
+ selector: string,
+ timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
+ options?: { allowHidden?: boolean },
+): Promise<ResolvedNode> {
+ return resolveElementQuery(send, { css: selector }, timeoutMs, options);
+}
+
+async function resolveFrameRoot(
+ send: DebuggerTransport['sendCommand'],
+ selector: string,
+ timeoutMs?: number,
+): Promise<{ frameId: string; nodeId?: number }> {
+ const frame = await resolveSelector(send, selector, timeoutMs);
+ try {
+ const described = (await send('DOM.describeNode', {
+ backendNodeId: frame.backendDOMNodeId,
+ depth: 1,
+ })) as {
+ node?: {
+ frameId?: string;
+ contentDocument?: { frameId?: string; nodeId?: number };
+ };
+ };
+ const frameId = described.node?.contentDocument?.frameId ?? described.node?.frameId;
+ if (!frameId) throw new Error(`frame selector did not resolve to an iframe: ${selector}`);
+ return {
+ frameId,
+ ...(described.node?.contentDocument?.nodeId
+ ? { nodeId: described.node.contentDocument.nodeId }
+ : {}),
+ };
+ } finally {
+ await releaseObject(send, frame.objectId);
+ }
+}
+
+async function resolveSelectorInFrame(
+ send: DebuggerTransport['sendCommand'],
+ frameNodeId: number,
+ selector: string,
+): Promise<ResolvedNode> {
+ const queried = (await send('DOM.querySelector', {
+ nodeId: frameNodeId,
+ selector,
+ })) as { nodeId?: number };
+ if (!queried.nodeId) throw new Error(`selector not found in frame: ${selector}`);
+ const described = (await send('DOM.describeNode', {
+ nodeId: queried.nodeId,
+ })) as { node?: { backendNodeId?: number } };
+ if (!described.node?.backendNodeId) {
+ throw new Error(`selector could not be resolved in frame: ${selector}`);
+ }
+ return {
+ objectId: '',
+ backendDOMNodeId: described.node.backendNodeId,
+ };
+}
+
+async function resolveElementQuery(
+ send: DebuggerTransport['sendCommand'],
+ query: BrowserElementQuery,
+ timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
+ options?: { allowHidden?: boolean },
+): Promise<ResolvedNode> {
+ if (query.index !== undefined && (!Number.isInteger(query.index) || query.index < 0)) {
+ throw new Error('element query index must be a non-negative integer');
+ }
+ const hasLookupField = [
+ query.css,
+ query.role,
+ query.name,
+ query.text,
+ query.label,
+ query.placeholder,
+ query.testId,
+ ].some((value) => typeof value === 'string' && value !== '');
+ if (!hasLookupField) {
+ throw new Error('element query requires at least one field');
+ }
+ const boundedTimeout = positiveInt(timeoutMs, DEFAULT_WAIT_TIMEOUT_MS, MAX_WAIT_TIMEOUT_MS);
+ const allowHidden = options?.allowHidden === true;
+ const evaluated = (await send('Runtime.evaluate', {
+ expression: `(() => {
+ const query = ${JSON.stringify(query)};
+ const deadline = Date.now() + ${boundedTimeout};
+ const normalize = (value) => String(value ?? "").replace(/\\s+/g, " ").trim();
+ const equals = (actual, expected) => {
+ const left = normalize(actual);
+ const right = normalize(expected);
+ return query.exact === true ? left === right : left.toLowerCase().includes(right.toLowerCase());
+ };
+ const implicitRole = (element) => {
+ const explicit = element.getAttribute("role");
+ if (explicit) return explicit.toLowerCase();
+ const tag = element.tagName.toLowerCase();
+ if (tag === "article") return "article";
+ if (tag === "aside") return "complementary";
+ if (tag === "header") return element.closest("article,aside,main,nav,section") ? "generic" : "banner";
+ if (tag === "footer") return element.closest("article,aside,main,nav,section") ? "generic" : "contentinfo";
+ if (tag === "form") return "form";
+ if (tag === "h1" || tag === "h2" || tag === "h3" || tag === "h4" || tag === "h5" || tag === "h6") return "heading";
+ if (tag === "img") return element.getAttribute("alt") === "" ? "presentation" : "img";
+ if (tag === "main") return "main";
+ if (tag === "nav") return "navigation";
+ if (tag === "section") return element.getAttribute("aria-label") ? "region" : "generic";
+ if (tag === "table") return "table";
+ if (tag === "tr") return "row";
+ if (tag === "td" || tag === "th") return element.tagName === "TH" ? "columnheader" : "cell";
+ if (tag === "li") return "listitem";
+ if (tag === "ul" || tag === "ol") return "list";
+ if (tag === "output") return "status";
+ if (tag === "button") return "button";
+ if (tag === "a" && element.hasAttribute("href")) return "link";
+ if (tag === "select") return element.multiple ? "listbox" : "combobox";
+ if (tag === "textarea") return "textbox";
+ if (tag === "option") return "option";
+ if (tag === "input") {
+ const type = String(element.type || "text").toLowerCase();
+ if (["button", "submit", "reset", "image"].includes(type)) return "button";
+ if (type === "checkbox") return "checkbox";
+ if (type === "radio") return "radio";
+ if (type === "range") return "slider";
+ if (type === "number") return "spinbutton";
+ if (type === "search") return "searchbox";
+ if (!["hidden", "file"].includes(type)) return "textbox";
+ }
+ return "";
+ };
+ const labelText = (element) => {
+ if (element.labels?.length) {
+ return Array.from(element.labels).map((label) => label.textContent || "").join(" ");
+ }
+ const id = element.getAttribute("id");
+ if (id) {
+ const escaped = globalThis.CSS?.escape ? CSS.escape(id) : id.replace(/["\\\\]/g, "\\\\$&");
+ const label = document.querySelector('label[for="' + escaped + '"]');
+ if (label) return label.textContent || "";
+ }
+ return element.closest("label")?.textContent || "";
+ };
+ const accessibleName = (element) => {
+ const labelledBy = element.getAttribute("aria-labelledby");
+ if (labelledBy) {
+ const text = labelledBy.split(/\\s+/).map((id) => document.getElementById(id)?.textContent || "").join(" ");
+ if (normalize(text)) return text;
+ }
+ return element.getAttribute("aria-label")
+ || labelText(element)
+ || element.getAttribute("alt")
+ || element.getAttribute("title")
+ || (element instanceof HTMLInputElement ? element.value : "")
+ || element.textContent
+ || "";
+ };
+ const visible = (element) => {
+ if (!element.isConnected) return false;
+ if (${JSON.stringify(allowHidden)} && element instanceof HTMLInputElement && element.type === "file") {
+ return !element.disabled && element.getAttribute("aria-disabled") !== "true";
+ }
+ const style = getComputedStyle(element);
+ if (style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse") return false;
+ const rect = element.getBoundingClientRect();
+ return rect.width > 0 && rect.height > 0;
+ };
+ const matches = (element) => {
+ if (query.role && implicitRole(element) !== String(query.role).toLowerCase()) return false;
+ if (query.name && !equals(accessibleName(element), query.name)) return false;
+ if (query.text && !equals(element.textContent, query.text)) return false;
+ if (query.label && !equals(labelText(element), query.label)) return false;
+ if (query.placeholder && !equals(element.getAttribute("placeholder"), query.placeholder)) return false;
+ if (query.testId && element.getAttribute("data-testid") !== query.testId) return false;
+ return visible(element);
+ };
+ return new Promise((resolve, reject) => {
+ const poll = () => {
+ let candidates;
+ try {
+ candidates = Array.from(document.querySelectorAll(query.css || "*")).filter(matches);
+ const hasNarrowingField = Boolean(
+ query.css || query.role || query.name || query.label || query.placeholder || query.testId
+ );
+ if (query.text && !hasNarrowingField) {
+ candidates = candidates.filter((element) => (
+ !Array.from(element.children).some((child) => (
+ visible(child) && equals(child.textContent, query.text)
+ ))
+ ));
+ }
+ } catch (error) {
+ reject(error);
+ return;
+ }
+ const index = Number.isInteger(query.index) ? query.index : null;
+ if (index !== null && candidates[index]) {
+ resolve(candidates[index]);
+ return;
+ }
+ if (index === null && candidates.length === 1) {
+ resolve(candidates[0]);
+ return;
+ }
+ if (index === null && candidates.length > 1) {
+ reject(new Error("element query matched " + candidates.length + " elements; provide index"));
+ return;
+ }
+ if (Date.now() >= deadline) {
+ reject(new Error("element query timed out"));
+ return;
+ }
+ setTimeout(poll, 100);
+ };
+ poll();
+ });
+ })()`,
+ awaitPromise: true,
+ returnByValue: false,
+ timeout: boundedTimeout + 1_000,
+ })) as {
+ result?: { objectId?: string; subtype?: string };
+ exceptionDetails?: {
+ text?: string;
+ exception?: { description?: string; value?: unknown };
+ };
+ };
+ if (evaluated.exceptionDetails) {
+ const details = evaluated.exceptionDetails;
+ const message =
+ details.exception?.description ??
+ (typeof details.exception?.value === 'string' ? details.exception.value : undefined) ??
+ details.text ??
+ 'element query failed';
+ throw new Error(message);
+ }
+ const objectId = evaluated.result?.objectId;
+ if (!objectId || evaluated.result?.subtype === 'null') {
+ throw new Error('element query did not resolve to an element');
+ }
+ const described = (await send('DOM.describeNode', { objectId })) as {
+ node?: { backendNodeId?: number };
+ };
+ return { objectId, backendDOMNodeId: described.node?.backendNodeId };
+}
+
+async function resolveRef(
+ send: DebuggerTransport['sendCommand'],
+ target: SnapshotRef,
+): Promise<ResolvedNode> {
+ const resolved = (await send('DOM.resolveNode', {
+ backendNodeId: target.backendDOMNodeId,
+ })) as { object?: { objectId?: string } };
+ const objectId = resolved.object?.objectId;
+ if (!objectId) {
+ throw new Error('snapshot ref is stale; take a new snapshot');
+ }
+ return { objectId, backendDOMNodeId: target.backendDOMNodeId };
+}
+
+async function callOnNode<T>(
+ send: DebuggerTransport['sendCommand'],
+ objectId: string,
+ functionDeclaration: string,
+ args?: unknown[],
+): Promise<T> {
+ const result = (await send('Runtime.callFunctionOn', {
+ objectId,
+ functionDeclaration,
+ arguments: args?.map((value) => ({ value })),
+ returnByValue: true,
+ awaitPromise: true,
+ userGesture: true,
+ })) as {
+ result?: { value?: unknown };
+ exceptionDetails?: { text?: string; exception?: { description?: string } };
+ };
+ if (result.exceptionDetails) {
+ throw new Error(
+ result.exceptionDetails.exception?.description ??
+ result.exceptionDetails.text ??
+ 'page script failed',
+ );
+ }
+ return result.result?.value as T;
+}
+
+async function withReleasedNode<T>(
+ send: DebuggerTransport['sendCommand'],
+ resolve: () => Promise<ResolvedNode>,
+ body: (node: ResolvedNode) => Promise<T>,
+): Promise<T> {
+ const node = await resolve();
+ try {
+ return await body(node);
+ } finally {
+ await releaseObject(send, node.objectId);
+ }
+}
+
+async function fillNode(
+ send: DebuggerTransport['sendCommand'],
+ target: ResolvedNode,
+ value: unknown,
+ declaredType?: string,
+): Promise<void> {
+ await callOnNode(
+ send,
+ target.objectId,
+ `function(value, declaredType) {
+ const type = String(declaredType || (
+ this instanceof HTMLInputElement ? this.type : ""
+ )).toLowerCase();
+ if (type === "checkbox" || type === "radio") {
+ if (!(this instanceof HTMLInputElement)) {
+ throw new Error("checkbox/radio fill target is not an input");
+ }
+ const checked = value === true || value === 1 || value === "1" || value === "true";
+ if (this.checked !== checked) {
+ const setter = Object.getOwnPropertyDescriptor(
+ HTMLInputElement.prototype,
+ "checked",
+ )?.set;
+ if (setter) setter.call(this, checked);
+ else this.checked = checked;
+ this.dispatchEvent(new Event("input", { bubbles: true }));
+ this.dispatchEvent(new Event("change", { bubbles: true }));
+ }
+ return;
+ }
+ const text = value === undefined || value === null ? "" : String(value);
+ if (this instanceof HTMLSelectElement) {
+ const selected = Array.from(this.options).find((option) => (
+ option.value === text || option.label === text
+ ));
+ if (!selected) throw new Error("select option not found");
+ this.value = selected.value;
+ } else if (this instanceof HTMLInputElement || this instanceof HTMLTextAreaElement) {
+ const setter = Object.getOwnPropertyDescriptor(
+ Object.getPrototypeOf(this),
+ "value",
+ )?.set;
+ if (setter) setter.call(this, text);
+ else this.value = text;
+ } else if (this instanceof HTMLElement && this.isContentEditable) {
+ this.textContent = text;
+ } else {
+ throw new Error("fill target is not editable");
+ }
+ this.dispatchEvent(new Event("input", { bubbles: true }));
+ this.dispatchEvent(new Event("change", { bubbles: true }));
+ }`,
+ [value, declaredType],
+ );
+}
+
+async function focusNode(
+ send: DebuggerTransport['sendCommand'],
+ node: ResolvedNode,
+ requireEditable = false,
+): Promise<void> {
+ const result = await callOnNode<{ ok: boolean; reason?: string }>(
+ send,
+ node.objectId,
+ `function(requireEditable) {
+ if (!(this instanceof HTMLElement) && !(this instanceof SVGElement)) {
+ return { ok: false, reason: "target is not an element" };
+ }
+ if ("disabled" in this && this.disabled) {
+ return { ok: false, reason: "target is disabled" };
+ }
+ if (requireEditable && "readOnly" in this && this.readOnly) {
+ return { ok: false, reason: "target is read-only" };
+ }
+ if (requireEditable) {
+ const textInput = this instanceof HTMLInputElement
+ && [
+ "date", "datetime-local", "email", "month", "number", "password",
+ "search", "tel", "text", "time", "url", "week",
+ ].includes(this.type);
+ const editable = textInput
+ || this instanceof HTMLTextAreaElement
+ || (this instanceof HTMLElement && this.isContentEditable);
+ if (!editable) return { ok: false, reason: "target is not editable" };
+ }
+ this.scrollIntoView({ block: "center", inline: "center" });
+ if (typeof this.focus === "function") this.focus();
+ return { ok: true };
+ }`,
+ [requireEditable],
+ );
+ if (!result?.ok) throw new Error(result?.reason ?? 'unable to focus target');
+}
+
+async function selectEditableContents(
+ send: DebuggerTransport['sendCommand'],
+ node: ResolvedNode,
+): Promise<void> {
+ await callOnNode(
+ send,
+ node.objectId,
+ `function() {
+ if (this instanceof HTMLInputElement || this instanceof HTMLTextAreaElement) {
+ this.select();
+ return;
+ }
+ if (this instanceof HTMLElement && this.isContentEditable) {
+ const selection = this.ownerDocument.defaultView?.getSelection();
+ const range = this.ownerDocument.createRange();
+ range.selectNodeContents(this);
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+ }
+ }`,
+ );
+}
+
+async function waitForActionable(
+ send: DebuggerTransport['sendCommand'],
+ node: ResolvedNode,
+ options: { editable?: boolean; timeoutMs?: number } = {},
+): Promise<void> {
+ const timeoutMs = positiveInt(options.timeoutMs, DEFAULT_WAIT_TIMEOUT_MS, MAX_WAIT_TIMEOUT_MS);
+ const result = await callOnNode<{ ok: boolean; reason?: string }>(
+ send,
+ node.objectId,
+ `function(options) {
+ const deadline = Date.now() + options.timeoutMs;
+ const inspect = () => {
+ if (!(this instanceof Element) || !this.isConnected) return "target is detached";
+ const style = getComputedStyle(this);
+ const rect = this.getBoundingClientRect();
+ if (
+ style.display === "none"
+ || style.visibility === "hidden"
+ || style.visibility === "collapse"
+ || rect.width <= 0
+ || rect.height <= 0
+ ) return "target is not visible";
+ if (("disabled" in this && this.disabled) || this.getAttribute("aria-disabled") === "true") {
+ return "target is disabled";
+ }
+ if (options.editable) {
+ if ("readOnly" in this && this.readOnly) return "target is read-only";
+ const textInput = this instanceof HTMLInputElement
+ && [
+ "date", "datetime-local", "email", "month", "number", "password",
+ "search", "tel", "text", "time", "url", "week",
+ ].includes(this.type);
+ const editable = textInput
+ || this instanceof HTMLTextAreaElement
+ || (this instanceof HTMLElement && this.isContentEditable);
+ if (!editable) return "target is not editable";
+ }
+ return "";
+ };
+ return new Promise((resolve) => {
+ const poll = () => {
+ const reason = inspect();
+ if (!reason) {
+ this.scrollIntoView({ block: "center", inline: "center" });
+ resolve({ ok: true });
+ return;
+ }
+ if (Date.now() >= deadline) {
+ resolve({ ok: false, reason });
+ return;
+ }
+ setTimeout(poll, 100);
+ };
+ poll();
+ });
+ }`,
+ [{ editable: options.editable === true, timeoutMs }],
+ );
+ if (!result?.ok) throw new Error(result?.reason ?? 'target is not actionable');
+}
+
+let actionTicketSequence = 0;
+
+async function stampActionTarget(
+ send: DebuggerTransport['sendCommand'],
+ node: ResolvedNode,
+): Promise<string> {
+ actionTicketSequence += 1;
+ const ticket = `rsb-${Date.now().toString(36)}-${actionTicketSequence.toString(36)}`;
+ await callOnNode(
+ send,
+ node.objectId,
+ `function(ticket) {
+ Reflect.set(this, Symbol.for("cindy.rsb.action-target"), ticket);
+ return true;
+ }`,
+ [ticket],
+ );
+ return ticket;
+}
+
+async function centerOfNode(
+ send: DebuggerTransport['sendCommand'],
+ node: ResolvedNode,
+ options: { focus?: boolean } = {},
+): Promise<{ x: number; y: number }> {
+ if (options.focus !== false) await focusNode(send, node);
+ const box = (await send('DOM.getBoxModel', {
+ ...(node.backendDOMNodeId
+ ? { backendNodeId: node.backendDOMNodeId }
+ : { objectId: node.objectId }),
+ })) as { model?: { content?: number[]; border?: number[] } };
+ const quad = box.model?.content ?? box.model?.border;
+ if (!quad || quad.length < 8) throw new Error('target has no visible box');
+ const xs = [quad[0], quad[2], quad[4], quad[6]];
+ const ys = [quad[1], quad[3], quad[5], quad[7]];
+ return {
+ x: (Math.min(...xs) + Math.max(...xs)) / 2,
+ y: (Math.min(...ys) + Math.max(...ys)) / 2,
+ };
+}
+
+function mouseButton(value: unknown): 'left' | 'right' | 'middle' {
+ if (value === undefined || value === 'left') return 'left';
+ if (value === 'right' || value === 'middle') return value;
+ throw new Error('button must be left, right, or middle');
+}
+
+function modifierMask(modifiers: unknown): number {
+ if (!Array.isArray(modifiers)) return 0;
+ let mask = 0;
+ for (const raw of modifiers) {
+ if (typeof raw !== 'string') continue;
+ switch (raw.toLowerCase()) {
+ case 'alt':
+ mask |= 1;
+ break;
+ case 'control':
+ case 'ctrl':
+ mask |= 2;
+ break;
+ case 'meta':
+ case 'command':
+ case 'cmd':
+ mask |= 4;
+ break;
+ case 'controlormeta':
+ mask |= process.platform === 'darwin' ? 4 : 2;
+ break;
+ case 'shift':
+ mask |= 8;
+ break;
+ }
+ }
+ return mask;
+}
+
+type TranslatedInputMethod =
+ 'Input.dispatchKeyEvent' | 'Input.dispatchMouseEvent' | 'Input.insertText';
+
+interface TranslatedInputCommand {
+ method: TranslatedInputMethod;
+ params: Record<string, unknown>;
+ targetTicket?: string;
+}
+
+interface TranslatedInputResult {
+ ok: boolean;
+ error?: string;
+}
+
+type InputDispatcher = (
+ method: TranslatedInputMethod,
+ params: Record<string, unknown>,
+ targetTicket?: string,
+) => Promise<void>;
+
+type NativeKeyDispatcher = (
+ type: 'keyDown' | 'keyUp',
+ keyCode: string,
+ modifiers: string[],
+) => Promise<void>;
+
+/**
+ * Runs inside the guest page, not in Electron Main.
+ *
+ * An embedded guest and Cindy's composer can disagree about which renderer
+ * owns native input focus. Dispatching equivalent DOM events inside the guest
+ * keeps browser actions scoped to the tab that supplied the element reference.
+ * Keep this function self-contained so `toString()` can safely serialize it.
+ */
+function translateInputCommand(command: TranslatedInputCommand): TranslatedInputResult {
+ const params = command.params;
+ const numberParam = (value: unknown, name: string): number => {
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
+ throw new Error(`${name} must be a finite number`);
+ }
+ return value;
+ };
+ const stringParam = (value: unknown, name: string): string => {
+ if (typeof value !== 'string') throw new Error(`${name} must be a string`);
+ return value;
+ };
+ const eventWindow = (element: Element): Window & typeof globalThis =>
+ element.ownerDocument.defaultView ?? window;
+ const modifiers = (
+ mask: number,
+ ): Pick<KeyboardEventInit, 'altKey' | 'ctrlKey' | 'metaKey' | 'shiftKey'> => {
+ const enabled = (value: number): boolean => Math.floor(mask / value) % 2 === 1;
+ return {
+ altKey: enabled(1),
+ ctrlKey: enabled(2),
+ metaKey: enabled(4),
+ shiftKey: enabled(8),
+ };
+ };
+ const mouseButton = (button: unknown): number => {
+ switch (button) {
+ case undefined:
+ case 'none':
+ case 'left':
+ return 0;
+ case 'middle':
+ return 1;
+ case 'right':
+ return 2;
+ case 'back':
+ return 3;
+ case 'forward':
+ return 4;
+ default:
+ throw new Error(`unsupported mouse button: ${String(button)}`);
+ }
+ };
+ const carriesTicket = (element: Element | null): boolean => {
+ if (!command.targetTicket) return true;
+ let current = element;
+ while (current) {
+ const currentWindow = current.ownerDocument.defaultView ?? window;
+ const symbol = currentWindow.Symbol.for('cindy.rsb.action-target');
+ if (Reflect.get(current, symbol) === command.targetTicket) return true;
+ const root = current.getRootNode();
+ current =
+ current.parentElement ?? (root instanceof currentWindow.ShadowRoot ? root.host : null);
+ }
+ return false;
+ };
+ const requireTicket = (element: Element | null): void => {
+ if (!carriesTicket(element)) {
+ throw new Error('page changed the action target before input was dispatched');
+ }
+ };
+ const pointTarget = (
+ root: Document | ShadowRoot,
+ x: number,
+ y: number,
+ ): { target: Element; x: number; y: number } | null => {
+ const rootWindow =
+ ('defaultView' in root ? root.defaultView : root.ownerDocument.defaultView) ?? window;
+ const target = root.elementFromPoint(x, y);
+ if (!(target instanceof rootWindow.Element)) return null;
+ if (target.shadowRoot) {
+ const nested = target.shadowRoot.elementFromPoint(x, y);
+ if (nested instanceof rootWindow.Element) return { target: nested, x, y };
+ }
+ if (target instanceof rootWindow.HTMLIFrameElement) {
+ try {
+ const frameDocument = target.contentDocument;
+ if (frameDocument) {
+ const bounds = target.getBoundingClientRect();
+ return pointTarget(frameDocument, x - bounds.left, y - bounds.top) ?? { target, x, y };
+ }
+ } catch {
+ throw new Error('cross-origin iframe input is not supported');
+ }
+ }
+ return { target, x, y };
+ };
+ const dispatchMouse = (target: Element, type: string, init: MouseEventInit): boolean =>
+ target.dispatchEvent(new (eventWindow(target).MouseEvent)(type, init));
+ const mouseInit = (target: Element, x: number, y: number): MouseEventInit => ({
+ ...modifiers(Number(params.modifiers ?? 0)),
+ bubbles: true,
+ button: mouseButton(params.button),
+ buttons: Number(params.buttons ?? 0),
+ cancelable: true,
+ clientX: x,
+ clientY: y,
+ composed: true,
+ detail: Number(params.clickCount ?? 0),
+ screenX: x,
+ screenY: y,
+ view: eventWindow(target),
+ });
+ const isFocusable = (element: Element): element is HTMLElement => {
+ if (!(element instanceof eventWindow(element).HTMLElement)) return false;
+ if (element.isContentEditable || element.tabIndex >= 0) return true;
+ if (element.tagName === 'A') return element.hasAttribute('href');
+ return ['BUTTON', 'INPUT', 'SELECT', 'TEXTAREA'].includes(element.tagName);
+ };
+ const focusMouseTarget = (target: Element): void => {
+ let focusTarget: HTMLElement | null = null;
+ if (target instanceof eventWindow(target).HTMLLabelElement && target.control) {
+ focusTarget = target.control;
+ } else {
+ for (let current: Element | null = target; current; current = current.parentElement) {
+ if (isFocusable(current)) {
+ focusTarget = current;
+ break;
+ }
+ }
+ }
+ if (!focusTarget) return;
+ try {
+ focusTarget.focus({ preventScroll: true });
+ } catch {
+ focusTarget.focus();
+ }
+ };
+ const stateRoot = globalThis as typeof globalThis & {
+ __cindyRsbInputTranslationState?: {
+ mousePress?: { button: unknown; moved: boolean; x: number; y: number } | null;
+ };
+ };
+ const state = (stateRoot.__cindyRsbInputTranslationState ??= {});
+ const translateMouse = (): void => {
+ const type = stringParam(params.type, 'type');
+ const screenX = numberParam(params.x, 'x');
+ const screenY = numberParam(params.y, 'y');
+ const resolved = pointTarget(document, screenX, screenY);
+ if (!resolved) throw new Error(`no element found at point ${screenX},${screenY}`);
+ const { target, x, y } = resolved;
+ requireTicket(target);
+ const init = mouseInit(target, x, y);
+ if (type === 'mouseMoved') {
+ if (Number(params.buttons ?? 0) !== 0 && state.mousePress) {
+ state.mousePress.moved = true;
+ }
+ dispatchMouse(target, 'pointermove', init);
+ dispatchMouse(target, 'mousemove', init);
+ return;
+ }
+ if (type === 'mousePressed') {
+ state.mousePress = {
+ button: params.button ?? 'left',
+ moved: false,
+ x: screenX,
+ y: screenY,
+ };
+ const pointerAllowed = dispatchMouse(target, 'pointerdown', init);
+ const mouseAllowed = dispatchMouse(target, 'mousedown', init);
+ if (pointerAllowed && mouseAllowed) focusMouseTarget(target);
+ return;
+ }
+ if (type === 'mouseReleased') {
+ dispatchMouse(target, 'pointerup', init);
+ dispatchMouse(target, 'mouseup', init);
+ const pressed = state.mousePress;
+ state.mousePress = null;
+ if (
+ !pressed ||
+ pressed.moved ||
+ pressed.button !== (params.button ?? 'left') ||
+ Math.abs(pressed.x - screenX) > 1 ||
+ Math.abs(pressed.y - screenY) > 1
+ ) {
+ return;
+ }
+ if (params.button === 'right') {
+ dispatchMouse(target, 'contextmenu', init);
+ return;
+ }
+ if (params.button === 'middle') {
+ dispatchMouse(target, 'auxclick', init);
+ return;
+ }
+ dispatchMouse(target, 'click', init);
+ if (Number(params.clickCount ?? 0) >= 2) {
+ dispatchMouse(target, 'dblclick', init);
+ }
+ return;
+ }
+ throw new Error(`unsupported mouse event type: ${type}`);
+ };
+ const deepestActiveElement = (root: Document | ShadowRoot): Element | null => {
+ const active = root.activeElement;
+ if (!active) return null;
+ if (active instanceof eventWindow(active).HTMLIFrameElement) {
+ try {
+ const frameDocument = active.contentDocument;
+ if (frameDocument) return deepestActiveElement(frameDocument) ?? active;
+ } catch {
+ throw new Error('cross-origin iframe input is not supported');
+ }
+ }
+ return active.shadowRoot ? (deepestActiveElement(active.shadowRoot) ?? active) : active;
+ };
+ const isDirectTextControl = (
+ element: Element,
+ ): element is HTMLInputElement | HTMLTextAreaElement => {
+ const view = eventWindow(element);
+ if (element instanceof view.HTMLTextAreaElement) return true;
+ return (
+ element instanceof view.HTMLInputElement &&
+ ['password', 'search', 'tel', 'text', 'url'].includes(element.type)
+ );
+ };
+ const isStructuredValueControl = (element: Element): element is HTMLInputElement =>
+ element instanceof eventWindow(element).HTMLInputElement &&
+ ['date', 'datetime-local', 'month', 'time', 'week'].includes(element.type);
+ const isValueTextControl = (element: Element): element is HTMLInputElement =>
+ element instanceof eventWindow(element).HTMLInputElement &&
+ (['email', 'number'].includes(element.type) || isStructuredValueControl(element));
+ const isContentEditable = (element: Element): element is HTMLElement =>
+ element instanceof eventWindow(element).HTMLElement && element.isContentEditable;
+ const editableElement = (): Element | null => {
+ const active = deepestActiveElement(document);
+ return active &&
+ (isDirectTextControl(active) || isValueTextControl(active) || isContentEditable(active))
+ ? active
+ : null;
+ };
+ const createInputEvent = (element: Element, type: string, init: InputEventInit): Event => {
+ const view = eventWindow(element);
+ return typeof view.InputEvent === 'function'
+ ? new view.InputEvent(type, init)
+ : new view.Event(type, {
+ bubbles: init.bubbles,
+ cancelable: init.cancelable,
+ composed: init.composed,
+ });
+ };
+ const insertText = (element: Element | null, text: string, inputType = 'insertText'): void => {
+ if (!element) throw new Error('no editable element is focused');
+ const beforeInput = createInputEvent(element, 'beforeinput', {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ data: text,
+ inputType,
+ });
+ if (!element.dispatchEvent(beforeInput)) return;
+ if (isDirectTextControl(element)) {
+ const start = element.selectionStart ?? element.value.length;
+ const end = element.selectionEnd ?? element.value.length;
+ element.setRangeText(text, start, end, 'end');
+ } else if (isStructuredValueControl(element)) {
+ element.value = text;
+ } else if (isValueTextControl(element)) {
+ if (element.ownerDocument.execCommand?.('insertText', false, text)) return;
+ element.value += text;
+ } else if (isContentEditable(element)) {
+ const selection = eventWindow(element).getSelection();
+ let range = selection?.rangeCount ? selection.getRangeAt(0) : null;
+ if (!range || !element.contains(range.commonAncestorContainer)) {
+ range = element.ownerDocument.createRange();
+ range.selectNodeContents(element);
+ range.collapse(false);
+ }
+ range.deleteContents();
+ const node = element.ownerDocument.createTextNode(text);
+ range.insertNode(node);
+ range.setStartAfter(node);
+ range.collapse(true);
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+ } else {
+ throw new Error('focused element is not editable');
+ }
+ element.dispatchEvent(
+ createInputEvent(element, 'input', {
+ bubbles: true,
+ cancelable: false,
+ composed: true,
+ data: text,
+ inputType,
+ }),
+ );
+ };
+ const deleteText = (element: Element | null, direction: 'backward' | 'forward'): void => {
+ if (!element) return;
+ const inputType = direction === 'forward' ? 'deleteContentForward' : 'deleteContentBackward';
+ const beforeInput = createInputEvent(element, 'beforeinput', {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ data: null,
+ inputType,
+ });
+ if (!element.dispatchEvent(beforeInput)) return;
+ if (isDirectTextControl(element)) {
+ const value = element.value;
+ let start = element.selectionStart ?? value.length;
+ let end = element.selectionEnd ?? value.length;
+ if (start === end) {
+ if (direction === 'forward') end = Math.min(value.length, end + 1);
+ else start = Math.max(0, start - 1);
+ }
+ element.setRangeText('', start, end, 'end');
+ } else if (isValueTextControl(element)) {
+ if (element.ownerDocument.execCommand?.(direction === 'forward' ? 'forwardDelete' : 'delete'))
+ return;
+ if (direction === 'backward') element.value = element.value.slice(0, -1);
+ } else {
+ return;
+ }
+ element.dispatchEvent(
+ createInputEvent(element, 'input', {
+ bubbles: true,
+ cancelable: false,
+ composed: true,
+ data: null,
+ inputType,
+ }),
+ );
+ };
+ const keyCode = (key: string): number => {
+ const known: Record<string, number> = {
+ Backspace: 8,
+ Tab: 9,
+ Enter: 13,
+ Escape: 27,
+ ArrowLeft: 37,
+ ArrowUp: 38,
+ ArrowRight: 39,
+ ArrowDown: 40,
+ Delete: 46,
+ };
+ return known[key] ?? (key.length === 1 ? (key.toUpperCase().codePointAt(0) ?? 0) : 0);
+ };
+ const translateKey = (): void => {
+ const type = stringParam(params.type, 'type');
+ const key = stringParam(params.key, 'key');
+ const target = deepestActiveElement(document) ?? document.body ?? document.documentElement;
+ requireTicket(target);
+ if (type === 'validate') return;
+ const code = keyCode(key);
+ const init: KeyboardEventInit & { keyCode: number; which: number } = {
+ ...modifiers(Number(params.modifiers ?? 0)),
+ bubbles: true,
+ cancelable: true,
+ code: typeof params.code === 'string' ? params.code : '',
+ composed: true,
+ key,
+ keyCode: code,
+ which: code,
+ };
+ const makeKeyboardEvent = (eventType: string): KeyboardEvent => {
+ const event = new (eventWindow(target).KeyboardEvent)(eventType, init);
+ for (const [name, value] of [
+ ['keyCode', code],
+ ['which', code],
+ ['charCode', eventType === 'keypress' ? code : 0],
+ ] as const) {
+ try {
+ Object.defineProperty(event, name, { get: () => value });
+ } catch {
+ // Older Chromium builds may expose these properties as non-configurable.
+ }
+ }
+ return event;
+ };
+ if (type === 'keyUp') {
+ target.dispatchEvent(makeKeyboardEvent('keyup'));
+ return;
+ }
+ if (type !== 'keyDown' && type !== 'rawKeyDown' && type !== 'char') {
+ throw new Error(`unsupported key event type: ${type}`);
+ }
+ if (type !== 'char' && !target.dispatchEvent(makeKeyboardEvent('keydown'))) return;
+ const text = typeof params.text === 'string' ? params.text : '';
+ if (text) {
+ if (target.dispatchEvent(makeKeyboardEvent('keypress'))) {
+ insertText(editableElement(), text);
+ }
+ return;
+ }
+ const activeEditable = editableElement();
+ if (key === 'Backspace') deleteText(activeEditable, 'backward');
+ else if (key === 'Delete') deleteText(activeEditable, 'forward');
+ else if (key === 'Enter') {
+ if (
+ activeEditable &&
+ (activeEditable instanceof eventWindow(activeEditable).HTMLTextAreaElement ||
+ isContentEditable(activeEditable))
+ ) {
+ insertText(activeEditable, '\n', 'insertLineBreak');
+ } else if (
+ activeEditable &&
+ activeEditable instanceof eventWindow(activeEditable).HTMLInputElement
+ ) {
+ activeEditable.form?.requestSubmit();
+ }
+ }
+ };
+ try {
+ switch (command.method) {
+ case 'Input.dispatchMouseEvent':
+ translateMouse();
+ break;
+ case 'Input.dispatchKeyEvent':
+ translateKey();
+ break;
+ case 'Input.insertText':
+ {
+ const target = editableElement();
+ requireTicket(target);
+ insertText(target, stringParam(params.text, 'text'));
+ }
+ break;
+ }
+ return { ok: true };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+async function dispatchTranslatedInput(
+ wc: WebContents,
+ method: TranslatedInputMethod,
+ params: Record<string, unknown>,
+ targetTicket?: string,
+): Promise<void> {
+ const source = `(${translateInputCommand.toString()})(${JSON.stringify({
+ method,
+ params,
+ ...(targetTicket ? { targetTicket } : {}),
+ } satisfies TranslatedInputCommand)});`;
+ const userGesture = method === 'Input.dispatchMouseEvent' && params.type === 'mouseReleased';
+ const result = (await wc.executeJavaScript(source, userGesture)) as TranslatedInputResult;
+ if (result?.ok !== true) {
+ throw new Error(result?.error ?? `failed to translate ${method}`);
+ }
+}
+
+function nativeKeyCode(key: string): string | undefined {
+ const known: Record<string, string> = {
+ Backspace: 'BACKSPACE',
+ Tab: 'TAB',
+ Escape: 'ESCAPE',
+ ArrowLeft: 'LEFT',
+ ArrowUp: 'UP',
+ ArrowRight: 'RIGHT',
+ ArrowDown: 'DOWN',
+ Delete: 'DELETE',
+ Enter: 'ENTER',
+ Home: 'HOME',
+ End: 'END',
+ PageUp: 'PAGEUP',
+ PageDown: 'PAGEDOWN',
+ Insert: 'INSERT',
+ };
+ return known[key];
+}
+
+function nativeModifiers(mask: number): string[] {
+ return [
+ ...(mask & 1 ? ['alt'] : []),
+ ...(mask & 2 ? ['control'] : []),
+ ...(mask & 4 ? ['meta'] : []),
+ ...(mask & 8 ? ['shift'] : []),
+ ];
+}
+
+async function dispatchClick(
+ dispatchInput: InputDispatcher,
+ x: number,
+ y: number,
+ request: BrowserActRequest,
+ targetTicket?: string,
+): Promise<void> {
+ const button = mouseButton(request.button);
+ const clickCount = request.doubleClick === true ? 2 : 1;
+ const modifiers = modifierMask(request.modifiers);
+ for (let count = 1; count <= clickCount; count += 1) {
+ await dispatchInput(
+ 'Input.dispatchMouseEvent',
+ {
+ type: 'mousePressed',
+ x,
+ y,
+ button,
+ clickCount: count,
+ modifiers,
+ },
+ targetTicket,
+ );
+ if (typeof request.delayMs === 'number' && request.delayMs > 0) {
+ await delay(Math.min(request.delayMs, 5_000));
+ }
+ await dispatchInput(
+ 'Input.dispatchMouseEvent',
+ {
+ type: 'mouseReleased',
+ x,
+ y,
+ button,
+ clickCount: count,
+ modifiers,
+ },
+ targetTicket,
+ );
+ }
+}
+
+function parseKey(raw: string): { key: string; modifiers: number } {
+ const parts = raw
+ .split('+')
+ .map((part) => part.trim())
+ .filter(Boolean);
+ const key = parts.pop();
+ if (!key) throw new Error('key required');
+ return { key, modifiers: modifierMask(parts) };
+}
+
+async function dispatchKey(
+ dispatchInput: InputDispatcher,
+ rawKey: string,
+ targetTicket?: string,
+ nativeDispatch?: NativeKeyDispatcher,
+ delayMs?: number,
+): Promise<void> {
+ const { key, modifiers } = parseKey(rawKey);
+ const keyCode =
+ nativeKeyCode(key) ?? (modifiers !== 0 && key.length === 1 ? key.toUpperCase() : undefined);
+ // Printable unmodified characters and Enter retain the page-side path,
+ // which emits the input/change events expected by web applications. Native
+ // dispatch is reserved for navigation/editing keys whose browser defaults
+ // cannot be reproduced by synthetic KeyboardEvents.
+ if (nativeDispatch && keyCode) {
+ const modifierNames = nativeModifiers(modifiers);
+ await dispatchInput('Input.dispatchKeyEvent', { type: 'validate' }, targetTicket);
+ await nativeDispatch('keyDown', keyCode, modifierNames);
+ if (delayMs && delayMs > 0) await delay(Math.min(delayMs, 5_000));
+ await nativeDispatch('keyUp', keyCode, modifierNames);
+ return;
+ }
+ const text = key.length === 1 && modifiers === 0 ? key : undefined;
+ await dispatchInput(
+ 'Input.dispatchKeyEvent',
+ {
+ type: 'keyDown',
+ key,
+ ...(text ? { text } : {}),
+ modifiers,
+ },
+ targetTicket,
+ );
+ if (delayMs && delayMs > 0) await delay(Math.min(delayMs, 5_000));
+ await dispatchInput(
+ 'Input.dispatchKeyEvent',
+ {
+ type: 'keyUp',
+ key,
+ modifiers,
+ },
+ targetTicket,
+ );
+}
+
+export class RsbWebviewAutomation {
+ private readonly refsByTab = new Map<string, Map<string, SnapshotRef>>();
+ private readonly resourcesByTab = new Map<string, Set<string>>();
+ private readonly barriersByTab = new Map<string, HumanVerificationBarrier>();
+
+ constructor(private readonly logger: AutomationLogger) {}
+
+ forgetTab(tabId: string): void {
+ this.refsByTab.delete(tabId);
+ this.resourcesByTab.delete(tabId);
+ this.barriersByTab.delete(tabId);
+ }
+
+ getHumanVerificationBarrier(tabId: string): HumanVerificationBarrier | undefined {
+ const barrier = this.barriersByTab.get(tabId);
+ return barrier ? { kind: barrier.kind, evidence: [...barrier.evidence] } : undefined;
+ }
+
+ async snapshot(
+ tabId: string,
+ wc: WebContents,
+ req: BrowserControlRequest,
+ ): Promise<RsbSnapshotResult> {
+ if (req.labels === true) {
+ throw new Error('snapshot labels are unavailable in the embedded browser backend');
+ }
+ const snapshotReq =
+ req.mode === 'efficient'
+ ? {
+ ...req,
+ interactive: req.interactive ?? true,
+ compact: req.compact ?? true,
+ depth: req.depth ?? EFFICIENT_SNAPSHOT_DEPTH,
+ maxChars: req.maxChars ?? EFFICIENT_SNAPSHOT_MAX_CHARS,
+ }
+ : req;
+ return withDebugger(wc, async (send) => {
+ let inspection: PageInspection = { resources: [] };
+ try {
+ inspection = await inspectPage(send, snapshotReq.urls === true);
+ } catch (err) {
+ this.logger.warn('failed to inspect page state', { tabId, err });
+ }
+ this.resourcesByTab.delete(tabId);
+ if (inspection.resources.length > 0) {
+ this.resourcesByTab.set(
+ tabId,
+ new Set(inspection.resources.map((resource) => resource.url)),
+ );
+ }
+ if (inspection.barrier) {
+ this.refsByTab.set(tabId, new Map());
+ this.barriersByTab.set(tabId, inspection.barrier);
+ return {
+ format: snapshotReq.snapshotFormat ?? 'ai',
+ targetId: tabId,
+ url: wc.getURL(),
+ ...(inspection.resources.length > 0 ? { resources: inspection.resources } : {}),
+ barrier: inspection.barrier,
+ stats: { lines: 0, chars: 0, refs: 0, interactive: 0 },
+ };
+ }
+ this.barriersByTab.delete(tabId);
+ await send('Accessibility.enable');
+ let response: { nodes?: RawAxNode[] };
+ const frame =
+ typeof snapshotReq.frame === 'string' && snapshotReq.frame !== ''
+ ? await resolveFrameRoot(send, snapshotReq.frame, snapshotReq.timeoutMs)
+ : undefined;
+ if (typeof snapshotReq.selector === 'string' && snapshotReq.selector !== '') {
+ const selected = frame?.nodeId
+ ? await resolveSelectorInFrame(send, frame.nodeId, snapshotReq.selector)
+ : frame
+ ? undefined
+ : await resolveSelector(send, snapshotReq.selector, snapshotReq.timeoutMs);
+ if (!selected) {
+ throw new Error('frame document is unavailable for selector-scoped snapshot');
+ }
+ try {
+ response = (await send('Accessibility.getPartialAXTree', {
+ backendNodeId: selected.backendDOMNodeId,
+ fetchRelatives: true,
+ })) as { nodes?: RawAxNode[] };
+ } finally {
+ await releaseObject(send, selected.objectId);
+ }
+ } else {
+ response = (await send(
+ 'Accessibility.getFullAXTree',
+ frame ? { frameId: frame.frameId } : undefined,
+ )) as { nodes?: RawAxNode[] };
+ }
+
+ const { tree, roots } = buildSnapshotTree(
+ Array.isArray(response.nodes) ? response.nodes : [],
+ );
+ const refs: Record<string, SnapshotRef> = {};
+ let refNumber = 1;
+ const refOrder = tree
+ .map((_node, index) => index)
+ .toSorted(
+ (left, right) =>
+ Number(INTERACTIVE_ROLES.has(tree[right].role)) -
+ Number(INTERACTIVE_ROLES.has(tree[left].role)),
+ );
+ for (const index of refOrder) {
+ const node = tree[index];
+ if (!shouldReference(node) || refNumber > MAX_SNAPSHOT_REFS) continue;
+ const ref = `e${refNumber}`;
+ refNumber += 1;
+ node.ref = ref;
+ refs[ref] = {
+ role: node.role,
+ ...(node.name ? { name: node.name } : {}),
+ ...(node.value ? { value: node.value } : {}),
+ backendDOMNodeId: node.backendDOMNodeId,
+ };
+ }
+
+ if (snapshotReq.urls === true) {
+ await Promise.all(
+ tree
+ .filter((node) => node.role === 'link' && node.ref)
+ .map(async (node) => {
+ try {
+ node.url = await resolveHref(send, node.backendDOMNodeId);
+ } catch (err) {
+ this.logger.warn('failed to resolve snapshot link URL', { tabId, err });
+ }
+ }),
+ );
+ }
+
+ const rawLines = renderSnapshotTree(tree, roots, snapshotReq);
+ const lines = truncateSnapshotLines(rawLines, snapshotReq.maxChars);
+ const visible = visibleRefs(refs, lines);
+ this.refsByTab.set(tabId, new Map(Object.entries(visible)));
+ const snapshot = lines.join('\n');
+ const format = snapshotReq.snapshotFormat ?? 'ai';
+ const stats = {
+ lines: lines.length,
+ chars: snapshot.length,
+ refs: Object.keys(visible).length,
+ interactive: Object.values(visible).filter((ref) => INTERACTIVE_ROLES.has(ref.role)).length,
+ };
+ if (format === 'aria') {
+ const limit = positiveInt(req.limit, tree.length || 1, tree.length || 1);
+ return {
+ format,
+ targetId: tabId,
+ url: wc.getURL(),
+ ...(inspection.resources.length > 0 ? { resources: inspection.resources } : {}),
+ nodes: tree.slice(0, limit).map((node) => ({
+ ...(node.ref && visible[node.ref] ? { ref: node.ref } : {}),
+ role: node.role,
+ ...(node.name ? { name: node.name } : {}),
+ ...(node.value ? { value: node.value } : {}),
+ backendDOMNodeId: node.backendDOMNodeId,
+ })),
+ stats,
+ };
+ }
+ return {
+ format,
+ targetId: tabId,
+ url: wc.getURL(),
+ ...(inspection.resources.length > 0 ? { resources: inspection.resources } : {}),
+ snapshot,
+ refs: visible,
+ stats,
+ };
+ });
+ }
+
+ assertResource(tabId: string, url: string): void {
+ if (!this.resourcesByTab.get(tabId)?.has(url)) {
+ throw new Error('resource is not present in the latest page resource list');
+ }
+ }
+
+ async evaluate(
+ tabId: string,
+ wc: WebContents,
+ request: Pick<BrowserActRequest, 'fn' | 'ref' | 'timeoutMs'>,
+ ): Promise<unknown> {
+ if (typeof request.fn !== 'string' || request.fn === '') {
+ throw new Error('evaluate.fn (JS expression source) required');
+ }
+ const timeoutMs = positiveInt(request.timeoutMs, DEFAULT_WAIT_TIMEOUT_MS, MAX_WAIT_TIMEOUT_MS);
+ return withDebugger(wc, async (send) => {
+ let response: {
+ result?: { value?: unknown };
+ exceptionDetails?: { text?: string; exception?: { description?: string } };
+ };
+ if (request.ref) {
+ const snapshotRef = this.refsByTab.get(tabId)?.get(request.ref);
+ if (!snapshotRef) {
+ throw new Error(`unknown or stale snapshot ref: ${request.ref}; take a new snapshot`);
+ }
+ const target = await resolveRef(send, snapshotRef);
+ try {
+ response = (await send('Runtime.callFunctionOn', {
+ objectId: target.objectId,
+ functionDeclaration: `function(fnSource) {
+ var candidate = eval("(" + fnSource + ")");
+ if (typeof candidate !== "function") {
+ throw new Error("evaluate source did not produce a function");
+ }
+ return Promise.resolve(candidate(this));
+ }`,
+ arguments: [{ value: request.fn }],
+ awaitPromise: true,
+ returnByValue: true,
+ timeout: timeoutMs,
+ })) as typeof response;
+ } finally {
+ await releaseObject(send, target.objectId);
+ }
+ } else {
+ response = (await send('Runtime.evaluate', {
+ expression: `(() => {
+ var candidate = eval("(" + ${JSON.stringify(request.fn)} + ")");
+ if (typeof candidate !== "function") {
+ throw new Error("evaluate source did not produce a function");
+ }
+ return Promise.resolve(candidate());
+ })()`,
+ awaitPromise: true,
+ returnByValue: true,
+ timeout: timeoutMs,
+ })) as typeof response;
+ }
+ if (response.exceptionDetails) {
+ throw new Error(
+ response.exceptionDetails.exception?.description ??
+ response.exceptionDetails.text ??
+ 'evaluate failed',
+ );
+ }
+ return response.result?.value;
+ });
+ }
+
+ async setFiles(
+ tabId: string,
+ wc: WebContents,
+ req: Pick<
+ BrowserControlRequest,
+ 'paths' | 'ref' | 'inputRef' | 'element' | 'query' | 'timeoutMs'
+ >,
+ ): Promise<{ tabId: string; uploadedFiles: number }> {
+ return withDebugger(wc, async (send) => {
+ let target: ResolvedNode;
+ if (req.query && typeof req.query === 'object') {
+ target = await resolveElementQuery(send, req.query, req.timeoutMs, { allowHidden: true });
+ } else if (typeof req.element === 'string' && req.element !== '') {
+ target = await resolveSelector(send, req.element, req.timeoutMs, { allowHidden: true });
+ } else {
+ const ref = req.inputRef ?? req.ref;
+ if (typeof ref !== 'string' || ref === '') {
+ throw new Error('upload requires inputRef, ref, element, or query');
+ }
+ const snapshotRef = this.refsByTab.get(tabId)?.get(ref);
+ if (!snapshotRef) {
+ throw new Error(`unknown or stale snapshot ref: ${ref}; take a new snapshot`);
+ }
+ target = await resolveRef(send, snapshotRef);
+ }
+
+ try {
+ const readiness = await callOnNode<{
+ ok: boolean;
+ reason?: string;
+ multiple?: boolean;
+ }>(
+ send,
+ target.objectId,
+ `function() {
+ if (!(this instanceof HTMLInputElement) || this.type !== "file") {
+ return { ok: false, reason: "upload target is not a file input" };
+ }
+ if (!this.isConnected) return { ok: false, reason: "upload target is detached" };
+ if (this.disabled || this.getAttribute("aria-disabled") === "true") {
+ return { ok: false, reason: "upload target is disabled" };
+ }
+ return { ok: true, multiple: this.multiple };
+ }`,
+ );
+ if (!readiness?.ok) {
+ throw new Error(readiness?.reason ?? 'upload target is not ready');
+ }
+ const paths = req.paths ?? [];
+ if (paths.length > 1 && readiness.multiple !== true) {
+ throw new Error('upload target accepts only one file');
+ }
+ await send('DOM.setFileInputFiles', {
+ files: paths,
+ objectId: target.objectId,
+ });
+ return {
+ tabId,
+ uploadedFiles: paths.length,
+ };
+ } finally {
+ await releaseObject(send, target.objectId);
+ }
+ });
+ }
+
+ async act(
+ tabId: string,
+ wc: WebContents,
+ request: BrowserActRequest,
+ options?: {
+ nativeKeyDispatch?: NativeKeyDispatcher;
+ waitForNetworkIdle?: (timeoutMs: number) => Promise<void>;
+ },
+ ): Promise<RsbActResult> {
+ return withDebugger(wc, async (send) => {
+ const dispatchInput: InputDispatcher = async (method, params, targetTicket) => {
+ await dispatchTranslatedInput(wc, method, params, targetTicket);
+ };
+ const resolveTarget = async (
+ ref = request.ref,
+ selector = request.selector,
+ query = request.query,
+ ): Promise<ResolvedNode> => {
+ if (query && typeof query === 'object') {
+ return resolveElementQuery(send, query, request.timeoutMs);
+ }
+ if (typeof selector === 'string' && selector !== '') {
+ return resolveSelector(send, selector, request.timeoutMs);
+ }
+ if (typeof ref !== 'string' || ref === '') {
+ throw new Error(`${request.kind} requires ref, selector, or query`);
+ }
+ const target = this.refsByTab.get(tabId)?.get(ref);
+ if (!target) throw new Error(`unknown or stale snapshot ref: ${ref}; take a new snapshot`);
+ return resolveRef(send, target);
+ };
+
+ switch (request.kind) {
+ case 'saveResource':
+ throw new Error('saveResource must be handled by the browser artifact manager');
+ case 'click': {
+ return withReleasedNode(send, resolveTarget, async (target) => {
+ await waitForActionable(send, target, { timeoutMs: request.timeoutMs });
+ const ticket = await stampActionTarget(send, target);
+ const point = await centerOfNode(send, target);
+ await dispatchClick(dispatchInput, point.x, point.y, request, ticket);
+ return { tabId, kind: request.kind, ...point };
+ });
+ }
+ case 'clickCoords': {
+ const x = finiteNonNegative(request.x, 'clickCoords.x');
+ const y = finiteNonNegative(request.y, 'clickCoords.y');
+ await dispatchClick(dispatchInput, x, y, request);
+ return { tabId, kind: request.kind, x, y };
+ }
+ case 'fill': {
+ if (Array.isArray(request.fields) && request.fields.length > 0) {
+ let filled = 0;
+ for (const rawField of request.fields) {
+ if (!rawField || typeof rawField !== 'object') {
+ throw new Error('fill.fields entries must be objects');
+ }
+ const field = rawField as Record<string, unknown>;
+ if (typeof field.ref !== 'string' || field.ref === '') {
+ throw new Error('fill.fields[].ref required');
+ }
+ const fieldRef = field.ref;
+ await withReleasedNode(
+ send,
+ () => resolveTarget(fieldRef, undefined, undefined),
+ async (target) => {
+ await waitForActionable(send, target, { timeoutMs: request.timeoutMs });
+ await fillNode(
+ send,
+ target,
+ field.value,
+ typeof field.type === 'string' ? field.type : undefined,
+ );
+ },
+ );
+ filled += 1;
+ }
+ return { tabId, kind: request.kind, filled };
+ }
+ // Keep the single-target form accepted by existing embedded-backend
+ // callers while also honoring the shared multi-field contract above.
+ return withReleasedNode(send, resolveTarget, async (target) => {
+ await waitForActionable(send, target, {
+ editable: true,
+ timeoutMs: request.timeoutMs,
+ });
+ await focusNode(send, target, true);
+ if (typeof request.text !== 'string') throw new Error('fill.text required');
+ await fillNode(send, target, request.text);
+ if (request.submit === true) {
+ const ticket = await stampActionTarget(send, target);
+ await dispatchKey(dispatchInput, 'Enter', ticket);
+ }
+ return { tabId, kind: request.kind, textLength: request.text.length };
+ });
+ }
+ case 'type': {
+ return withReleasedNode(send, resolveTarget, async (target) => {
+ await waitForActionable(send, target, {
+ editable: true,
+ timeoutMs: request.timeoutMs,
+ });
+ await focusNode(send, target, true);
+ const ticket = await stampActionTarget(send, target);
+ if (typeof request.text !== 'string') throw new Error('type.text required');
+ const structured = await callOnNode<boolean>(
+ send,
+ target.objectId,
+ `function() {
+ return this instanceof HTMLInputElement
+ && ["date", "datetime-local", "month", "time", "week"].includes(this.type);
+ }`,
+ );
+ if (structured) {
+ await fillNode(send, target, request.text);
+ } else if (request.slowly === true) {
+ const perCharacterDelay = Math.min(request.delayMs ?? 50, 1_000);
+ for (const character of Array.from(request.text)) {
+ await dispatchInput('Input.insertText', { text: character }, ticket);
+ if (perCharacterDelay > 0) await delay(perCharacterDelay);
+ }
+ } else {
+ await selectEditableContents(send, target);
+ await dispatchInput('Input.insertText', { text: request.text }, ticket);
+ }
+ if (request.submit === true) await dispatchKey(dispatchInput, 'Enter', ticket);
+ return { tabId, kind: request.kind, textLength: request.text.length };
+ });
+ }
+ case 'press': {
+ let ticket: string | undefined;
+ if (request.ref || request.selector || request.query) {
+ return withReleasedNode(send, resolveTarget, async (target) => {
+ await waitForActionable(send, target, { timeoutMs: request.timeoutMs });
+ await focusNode(send, target);
+ const targetTicket = await stampActionTarget(send, target);
+ if (typeof request.key !== 'string' || request.key === '') {
+ throw new Error('press.key required');
+ }
+ await dispatchKey(
+ dispatchInput,
+ request.key,
+ targetTicket,
+ options?.nativeKeyDispatch,
+ request.delayMs,
+ );
+ return { tabId, kind: request.kind, key: request.key };
+ });
+ }
+ if (typeof request.key !== 'string' || request.key === '') {
+ throw new Error('press.key required');
+ }
+ await dispatchKey(
+ dispatchInput,
+ request.key,
+ ticket,
+ options?.nativeKeyDispatch,
+ request.delayMs,
+ );
+ return { tabId, kind: request.kind, key: request.key };
+ }
+ case 'hover': {
+ return withReleasedNode(send, resolveTarget, async (target) => {
+ await waitForActionable(send, target, { timeoutMs: request.timeoutMs });
+ const ticket = await stampActionTarget(send, target);
+ const point = await centerOfNode(send, target, { focus: false });
+ await dispatchInput(
+ 'Input.dispatchMouseEvent',
+ {
+ type: 'mouseMoved',
+ x: point.x,
+ y: point.y,
+ modifiers: modifierMask(request.modifiers),
+ },
+ ticket,
+ );
+ return { tabId, kind: request.kind, ...point };
+ });
+ }
+ case 'drag': {
+ let startTarget: ResolvedNode | undefined;
+ let endTarget: ResolvedNode | undefined;
+ try {
+ const resolvedStart = await resolveTarget(request.startRef, undefined);
+ startTarget = resolvedStart;
+ const resolvedEnd = await resolveTarget(request.endRef, undefined);
+ endTarget = resolvedEnd;
+ const start = await centerOfNode(send, resolvedStart);
+ const end = await centerOfNode(send, resolvedEnd);
+ await send('Input.dispatchMouseEvent', {
+ type: 'mouseMoved',
+ x: start.x,
+ y: start.y,
+ });
+ await send('Input.dispatchMouseEvent', {
+ type: 'mousePressed',
+ x: start.x,
+ y: start.y,
+ button: 'left',
+ clickCount: 1,
+ });
+ for (let step = 1; step <= 8; step += 1) {
+ const ratio = step / 8;
+ await send('Input.dispatchMouseEvent', {
+ type: 'mouseMoved',
+ x: start.x + (end.x - start.x) * ratio,
+ y: start.y + (end.y - start.y) * ratio,
+ button: 'left',
+ buttons: 1,
+ });
+ }
+ await send('Input.dispatchMouseEvent', {
+ type: 'mouseReleased',
+ x: end.x,
+ y: end.y,
+ button: 'left',
+ clickCount: 1,
+ });
+ return { tabId, kind: request.kind, start, end };
+ } finally {
+ await releaseObject(send, startTarget?.objectId);
+ await releaseObject(send, endTarget?.objectId);
+ }
+ }
+ case 'select': {
+ return withReleasedNode(send, resolveTarget, async (target) => {
+ await waitForActionable(send, target, { timeoutMs: request.timeoutMs });
+ const values = Array.isArray(request.values)
+ ? request.values.filter((value): value is string => typeof value === 'string')
+ : [];
+ if (values.length === 0) throw new Error('select.values required');
+ const selected = await callOnNode<string[]>(
+ send,
+ target.objectId,
+ `function(values) {
+ if (!(this instanceof HTMLSelectElement)) throw new Error("target is not a select element");
+ if (values.length > 1 && !this.multiple) {
+ throw new Error("target select does not accept multiple values");
+ }
+ const missing = values.filter((value) => (
+ !Array.from(this.options).some((option) => (
+ option.value === value || option.label === value
+ ))
+ ));
+ if (missing.length > 0) {
+ throw new Error("select options not found: " + missing.join(", "));
+ }
+ for (const option of this.options) {
+ option.selected = values.includes(option.value) || values.includes(option.label);
+ }
+ this.dispatchEvent(new Event("input", { bubbles: true }));
+ this.dispatchEvent(new Event("change", { bubbles: true }));
+ return Array.from(this.selectedOptions, option => option.value);
+ }`,
+ [values],
+ );
+ return { tabId, kind: request.kind, values: selected };
+ });
+ }
+ case 'resize': {
+ if (request.width === undefined && request.height === undefined) {
+ await send('Emulation.clearDeviceMetricsOverride');
+ return { tabId, kind: request.kind, reset: true };
+ }
+ const width = positiveInt(request.width, 0, 16_384);
+ const height = positiveInt(request.height, 0, 16_384);
+ if (width <= 0 || height <= 0) throw new Error('resize width and height required');
+ await send('Emulation.setDeviceMetricsOverride', {
+ width,
+ height,
+ deviceScaleFactor: 1,
+ mobile: false,
+ });
+ return { tabId, kind: request.kind, width, height };
+ }
+ case 'wait': {
+ const waitDeadline =
+ Date.now() +
+ positiveInt(request.timeoutMs, DEFAULT_WAIT_TIMEOUT_MS, MAX_WAIT_TIMEOUT_MS);
+ const timeMs = Math.min(
+ typeof request.timeMs === 'number' && request.timeMs >= 0 ? request.timeMs : 0,
+ MAX_WAIT_TIMEOUT_MS,
+ );
+ if (timeMs > 0) await delay(timeMs);
+ const timeoutMs = positiveInt(
+ request.timeoutMs,
+ DEFAULT_WAIT_TIMEOUT_MS,
+ MAX_WAIT_TIMEOUT_MS,
+ );
+ const hasCondition = Boolean(
+ request.selector ||
+ request.url ||
+ request.loadState ||
+ request.text ||
+ request.textGone ||
+ request.fn,
+ );
+ if (hasCondition) {
+ const params = {
+ selector: request.selector,
+ url: request.url,
+ loadState: request.loadState,
+ text: request.text,
+ textGone: request.textGone,
+ fn: request.fn,
+ timeoutMs,
+ };
+ const result = (await send('Runtime.evaluate', {
+ expression: `(() => {
+ const params = ${JSON.stringify(params)};
+ const deadline = Date.now() + params.timeoutMs;
+ let predicate;
+ if (params.fn) {
+ predicate = eval("(" + params.fn + ")");
+ if (typeof predicate !== "function") throw new Error("wait.fn did not produce a function");
+ }
+ const matches = async () => {
+ if (params.selector) {
+ const element = document.querySelector(params.selector);
+ if (!element) return false;
+ const style = getComputedStyle(element);
+ const rect = element.getBoundingClientRect();
+ if (
+ style.display === "none"
+ || style.visibility === "hidden"
+ || style.visibility === "collapse"
+ || rect.width <= 0
+ || rect.height <= 0
+ ) return false;
+ }
+ if (params.url && location.href !== params.url && !location.href.includes(params.url)) return false;
+ if (params.text && !(document.body?.innerText || "").includes(params.text)) return false;
+ if (params.textGone && (document.body?.innerText || "").includes(params.textGone)) return false;
+ if (params.loadState === "load" && document.readyState !== "complete") return false;
+ if (params.loadState === "domcontentloaded" && document.readyState === "loading") return false;
+ if (params.loadState === "networkidle" && document.readyState !== "complete") return false;
+ if (predicate && !await Promise.resolve(predicate())) return false;
+ return true;
+ };
+ return new Promise((resolve, reject) => {
+ const poll = async () => {
+ try {
+ if (await matches()) return resolve({ url: location.href, readyState: document.readyState });
+ if (Date.now() >= deadline) return reject(new Error("wait timed out"));
+ setTimeout(poll, 100);
+ } catch (error) {
+ reject(error);
+ }
+ };
+ void poll();
+ });
+ })()`,
+ awaitPromise: true,
+ returnByValue: true,
+ timeout: timeoutMs + 1_000,
+ })) as {
+ result?: { value?: unknown };
+ exceptionDetails?: { exception?: { description?: string }; text?: string };
+ };
+ if (result.exceptionDetails) {
+ throw new Error(
+ result.exceptionDetails.exception?.description ??
+ result.exceptionDetails.text ??
+ 'wait failed',
+ );
+ }
+ if (request.loadState === 'networkidle') {
+ const remainingMs = waitDeadline - Date.now();
+ if (remainingMs <= 0) throw new Error('wait timed out');
+ await options?.waitForNetworkIdle?.(remainingMs);
+ }
+ return { tabId, kind: request.kind, waitedMs: timeMs, state: result.result?.value };
+ }
+ return { tabId, kind: request.kind, waitedMs: timeMs };
+ }
+ case 'evaluate':
+ case 'close':
+ throw new Error(`${request.kind} is handled by the backend`);
+ }
+ });
+ }
+}
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-backend.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-backend.ts
index e5096f6d8c..a157afac12 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-backend.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-backend.ts
@@ -5,15 +5,14 @@
* either:
* - Electron native API on the guest `WebContents` (navigate / screenshot /
* pdf / console)
+ * - a bounded CDP session on the guest `WebContents` (snapshot / act)
* - the renderer's RSB store via the request/response bridge (open /
* focus / close)
* - the `TabRegistry` for status / tabs / profiles / doctor
*
- * Scope (Phase 3): low-complexity actions only. Phase 4 layers CDP-driven
- * snapshot / act / extract / requests / responseBody / upload on top. Actions
- * not implemented in this phase respond with `BROWSER_RUNTIME_ACTION_FAILED`
- * + a clear message ("action 'X' not yet supported in rsb-webview backend")
- * so the MCP layer still surfaces a structured error.
+ * Actions outside the sidebar browser's current capability set respond with
+ * `BROWSER_RUNTIME_ACTION_FAILED` + a clear explanation, so the MCP layer still
+ * surfaces a structured error.
*
* Why this lives in main: the `WebContents` handles + CDP debugger access are
* main-only; the backend has no business in the renderer. The renderer owns
@@ -21,9 +20,11 @@
*/
import type {
+ BrowserActRequest,
BrowserControlRequest,
BrowserControlResult,
} from '@cindy/browser-control-runtime';
+import { isPublicHttpResourceUrl } from '@cindy/browser-control-runtime';
import type { WebContents } from 'electron';
import type { TabRegistry } from '../../rsb-browser-bridge/registry.js';
@@ -34,12 +35,24 @@ import type {
BackendResult,
BrowserBackend,
} from './types.js';
+import { RsbWebviewAutomation } from './rsb-webview-automation.js';
+import { artifactSessionRoot, RsbWebviewArtifacts } from './rsb-webview-artifacts.js';
+import { RsbWebviewDialogs } from './rsb-webview-dialogs.js';
+import { RsbWebviewNetwork } from './rsb-webview-network.js';
+import { resolveUploadFiles } from './rsb-webview-upload-policy.js';
interface BackendLogger {
info(message: string, ...args: unknown[]): void;
warn(message: string, ...args: unknown[]): void;
}
+interface BrowserActivity {
+ action: BrowserControlRequest['action'];
+ finishedAt: string;
+ ok: boolean;
+ targetId?: string;
+}
+
export interface RsbWebviewBackendOptions {
registry: TabRegistry;
/**
@@ -60,6 +73,8 @@ export interface RsbWebviewBackendOptions {
/** Bridge config — same shape `registerTabOpResultHandler` uses. */
bridge: RendererBridgeOptions;
logger: BackendLogger;
+ artifactRoot?: () => string;
+ resolveUploadRoots?: (sessionId: string) => Promise<string[]>;
/**
* Timing overrides for the detached-window tab re-registration wait (tests
* only — production uses the defaults below).
@@ -79,6 +94,7 @@ export interface RsbWebviewBackendOptions {
*/
const TAB_REATTACH_TOTAL_MS = 5000;
const TAB_REATTACH_POLL_MS = 250;
+const DEFAULT_NAVIGATION_TIMEOUT_MS = 60_000;
/**
* Standard error payload for an action we can't service. Keeps the shape
@@ -125,10 +141,60 @@ function safeTabMeta(wc: WebContents): { url: string; title: string } {
return { url, title };
}
+function mayStartDownload(request: BrowserActRequest): boolean {
+ return request.kind === 'click'
+ || request.kind === 'clickCoords'
+ || request.kind === 'press'
+ || request.kind === 'select'
+ || (
+ (request.kind === 'type' || request.kind === 'fill')
+ && request.submit === true
+ );
+}
+
+async function loadUrlWithTimeout(
+ wc: WebContents,
+ url: string,
+ timeoutMs: number,
+): Promise<void> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await Promise.race([
+ wc.loadURL(url),
+ new Promise<never>((_resolve, reject) => {
+ timer = setTimeout(() => {
+ try {
+ wc.stop();
+ } catch {
+ // The guest may already be gone; the timeout must still settle.
+ }
+ reject(new Error(`navigation timed out after ${timeoutMs}ms`));
+ }, timeoutMs);
+ }),
+ ]);
+ } finally {
+ if (timer !== undefined) clearTimeout(timer);
+ }
+}
+
export class RsbWebviewBackend implements BrowserBackend {
readonly kind = 'rsb-webview' as const;
+ private readonly automation: RsbWebviewAutomation;
+ private readonly artifacts?: RsbWebviewArtifacts;
+ private readonly dialogs: RsbWebviewDialogs;
+ private readonly network: RsbWebviewNetwork;
+ private readonly activity: BrowserActivity[] = [];
+ private readonly activeCalls = new Set<Promise<BackendResult>>();
+ private disposing = false;
- constructor(private readonly opts: RsbWebviewBackendOptions) {}
+ constructor(private readonly opts: RsbWebviewBackendOptions) {
+ this.automation = new RsbWebviewAutomation(opts.logger);
+ this.artifacts = opts.artifactRoot
+ ? new RsbWebviewArtifacts(opts.artifactRoot, opts.logger)
+ : undefined;
+ this.dialogs = new RsbWebviewDialogs(opts.logger);
+ this.network = new RsbWebviewNetwork(opts.logger);
+ }
/**
* Read the agent session id from an MCP-injected request, or fall back to
@@ -142,24 +208,41 @@ export class RsbWebviewBackend implements BrowserBackend {
}
async call(request: BackendRequest): Promise<BackendResult> {
+ if (this.disposing) return actionFailed(request.action, 'browser backend is disposing');
+ const operation = (async (): Promise<BackendResult> => {
+ try {
+ const result = await this.dispatch(request);
+ this.recordActivity(request, result.ok);
+ return result;
+ } catch (err) {
+ this.opts.logger.warn('rsb-webview backend.call threw', {
+ action: request.action,
+ err,
+ });
+ const result = actionFailed(
+ request.action,
+ err instanceof Error ? err.message : String(err),
+ );
+ this.recordActivity(request, false);
+ return result;
+ }
+ })();
+ this.activeCalls.add(operation);
try {
- return await this.dispatch(request);
- } catch (err) {
- this.opts.logger.warn('rsb-webview backend.call threw', {
- action: request.action,
- err,
- });
- return actionFailed(
- request.action,
- err instanceof Error ? err.message : String(err),
- );
+ return await operation;
+ } finally {
+ this.activeCalls.delete(operation);
}
}
async dispose(): Promise<void> {
- // Nothing to tear down. Switching away from this backend doesn't kill
- // any tabs — the user's RSB stays as-is. Pin set decays naturally as
- // automation steps finish (in Phase 3 there are no pins).
+ this.disposing = true;
+ await Promise.allSettled([...this.activeCalls]);
+ // Switching backends never closes the user's tabs. Only the listeners and
+ // debugger attachments owned by this backend are released.
+ await this.artifacts?.dispose();
+ this.dialogs.dispose();
+ this.network.dispose();
}
// ── dispatch ──────────────────────────────────────────────────────────────
@@ -186,6 +269,8 @@ export class RsbWebviewBackend implements BrowserBackend {
return this.handleClose(request);
case 'navigate':
return this.handleNavigate(request);
+ case 'snapshot':
+ return this.handleSnapshot(request);
case 'screenshot':
return this.handleScreenshot(request);
case 'pdf':
@@ -194,11 +279,15 @@ export class RsbWebviewBackend implements BrowserBackend {
return this.handleConsole(request);
case 'act':
return this.handleAct(request);
+ case 'upload':
+ return this.handleUpload(request);
+ case 'dialog':
+ return this.handleDialog(request);
+ case 'requests':
+ return this.handleRequests(request);
+ case 'responseBody':
+ return this.handleResponseBody(request);
default:
- // Snapshot / extract / requests / responseBody / upload / dialog —
- // Phase 4 CDP territory. `act` supports `evaluate` only in this phase
- // (handled above); `act:click` / `act:type` / etc. require CDP Input
- // domain and ARIA snapshot infrastructure that lands in a follow-up.
return actionFailed(
request.action,
`action '${request.action}' not yet supported in rsb-webview backend`,
@@ -226,6 +315,10 @@ export class RsbWebviewBackend implements BrowserBackend {
activeSessionId: sessionId,
totalRegisteredTabs: this.opts.registry.listAll().length,
pinnedTabs: this.opts.registry.listPinned(),
+ dialogs: this.dialogs.diagnostics(),
+ ...(this.artifacts ? { artifacts: this.artifacts.diagnostics(sessionId ?? undefined) } : {}),
+ network: this.network.diagnostics(),
+ recentActivity: this.activity.slice(-20),
});
}
@@ -280,6 +373,7 @@ export class RsbWebviewBackend implements BrowserBackend {
if (!result.ok) {
return actionFailed(req.action, result.error);
}
+ if (result.tabId) void this.observeOpenedTab(result.tabId);
return actionOk(req.action, {
targetId: result.tabId,
tabId: result.tabId,
@@ -313,6 +407,7 @@ export class RsbWebviewBackend implements BrowserBackend {
this.opts.bridge,
);
if (!result.ok) return actionFailed(req.action, result.error);
+ this.automation.forgetTab(tabId);
return actionOk(req.action, { tabId });
}
@@ -326,11 +421,39 @@ export class RsbWebviewBackend implements BrowserBackend {
const resolved = await this.resolveTabForDirectAction(req, tabId);
if (!resolved.ok) return resolved.result;
return this.withTabPin(tabId, async () => {
- await resolved.wc.loadURL(url);
+ this.automation.forgetTab(tabId);
+ await this.tryObservePageSignals(resolved.wc, tabId);
+ await loadUrlWithTimeout(
+ resolved.wc,
+ url,
+ req.timeoutMs ?? DEFAULT_NAVIGATION_TIMEOUT_MS,
+ );
return actionOk(req.action, { tabId, url });
});
}
+ private async handleSnapshot(req: BackendRequest): Promise<BackendResult> {
+ const tabId = await this.resolveDirectActionTarget(req);
+ if (!tabId) return actionFailed(req.action, 'targetId required');
+ const resolved = await this.resolveTabForDirectAction(req, tabId);
+ if (!resolved.ok) return resolved.result;
+ return this.withTabPin(tabId, async () => {
+ await this.tryObservePageSignals(resolved.wc, tabId);
+ const dialog = this.dialogs.pending(resolved.wc);
+ if (dialog) {
+ return actionOk(req.action, {
+ format: req.snapshotFormat ?? 'ai',
+ targetId: tabId,
+ url: resolved.wc.getURL(),
+ barrier: { kind: 'page-dialog', dialog },
+ stats: { lines: 0, chars: 0, refs: 0, interactive: 0 },
+ });
+ }
+ const data = await this.automation.snapshot(tabId, resolved.wc, req);
+ return actionOk(req.action, data);
+ });
+ }
+
private async handleScreenshot(req: BackendRequest): Promise<BackendResult> {
const tabId = await this.resolveDirectActionTarget(req);
if (!tabId) return actionFailed(req.action, 'targetId required');
@@ -366,78 +489,215 @@ export class RsbWebviewBackend implements BrowserBackend {
});
}
- /**
- * Phase 4 lite — `act:evaluate` only. The CDP-driven act variants
- * (click / type / press / hover / drag / select / fill / wait / clickCoords /
- * resize) need an ARIA snapshot + Input domain subsystem that ships in a
- * dedicated follow-up. evaluate is dispatch-cheap because it maps straight
- * to `webContents.executeJavaScript` — included here so recipes that rely
- * on evaluate (the majority of L1 / L2 site recipes) work today.
- */
private async handleAct(req: BackendRequest): Promise<BackendResult> {
- const tabId = await this.resolveDirectActionTarget(req);
- if (!tabId) return actionFailed(req.action, 'targetId required');
- const resolved = await this.resolveTabForDirectAction(req, tabId);
- if (!resolved.ok) return resolved.result;
- const wc = resolved.wc;
-
- const inner = (req as { request?: { kind?: string; fn?: string; as?: string } }).request;
+ const inner = (req as { request?: BrowserActRequest & { as?: string } }).request;
if (!inner || typeof inner !== 'object') {
return actionFailed(req.action, 'request body required');
}
- if (inner.kind !== 'evaluate') {
- return actionFailed(
- req.action,
- `act:${String(inner.kind)} not yet supported in rsb-webview backend (Phase 4)`,
- );
+ if (
+ typeof req.targetId === 'string'
+ && typeof inner.targetId === 'string'
+ && req.targetId !== inner.targetId
+ ) {
+ return actionFailed(req.action, 'targetId mismatch between act request and nested request');
+ }
+ const automationRequest = inner.timeoutMs === undefined && req.timeoutMs !== undefined
+ ? { ...inner, timeoutMs: req.timeoutMs }
+ : inner;
+ const requestWithInnerTarget = {
+ ...req,
+ ...(typeof req.targetId === 'string'
+ ? {}
+ : typeof inner.targetId === 'string'
+ ? { targetId: inner.targetId }
+ : {}),
+ } as BackendRequest;
+ if (inner.kind === 'close') {
+ const result = await this.handleClose(requestWithInnerTarget);
+ if (!result.ok || !result.data || typeof result.data !== 'object') return result;
+ return {
+ ...result,
+ data: { ...(result.data as Record<string, unknown>), kind: 'close' },
+ };
}
- if (typeof inner.fn !== 'string' || inner.fn === '') {
- return actionFailed(req.action, 'evaluate.fn (JS expression source) required');
+
+ const tabId = await this.resolveDirectActionTarget(requestWithInnerTarget);
+ if (!tabId) return actionFailed(req.action, 'targetId required');
+ const resolved = await this.resolveTabForDirectAction(requestWithInnerTarget, tabId);
+ if (!resolved.ok) return resolved.result;
+ const wc = resolved.wc;
+ const humanVerification = this.automation.getHumanVerificationBarrier(tabId);
+ if (humanVerification) {
+ return actionOk(req.action, {
+ tabId,
+ kind: inner.kind,
+ barrier: humanVerification,
+ });
}
- // Safety / parity model:
- //
- // The vendored runtime's `act:evaluate` builds an in-page evaluator that
- // does literally `eval("(" + fnSource + ")")` then calls the resulting
- // function (see pw-tools-core.interactions.ts:1107-1131). The attack
- // surface of "agent-provided JS runs in the guest page" is the SAME there
- // — both forms are arbitrary JS in same-origin context. We mirror that
- // pattern verbatim instead of a naive `(${fn})()` concat so:
- // (a) the architectural threat model is identical, not "subtly different
- // in a way only this code knows";
- // (b) we get the same "did not produce a function" guard for free;
- // (c) `JSON.stringify` ensures fn text is a JS string literal — no IIFE
- // escape via `})(); window.x=...;((`-style payloads.
- // The caller's `fn` is still arbitrary JS that runs in the page; that's the
- // designed capability (recipe authors do same-origin fetch / DOM scraping
- // / page mutations through it). The guard only stops "smuggle multiple
- // statements past the IIFE wrapper".
- const wrapped = `(() => {
- var candidate = eval("(" + ${JSON.stringify(inner.fn)} + ")");
- if (typeof candidate !== "function") {
- throw new Error("evaluate source did not produce a function");
+ if (inner.kind === 'saveResource') {
+ if (!this.artifacts) return actionFailed(req.action, 'managed downloads are unavailable');
+ if (typeof inner.url !== 'string' || !isPublicHttpResourceUrl(inner.url)) {
+ return actionFailed(req.action, 'saveResource.url must be an http(s) URL from snapshot(urls:true)');
}
- var result = candidate();
- return Promise.resolve(result);
- })()`;
- return this.withTabPin(tabId, async () => {
- let value: unknown;
- try {
- value = await wc.executeJavaScript(wrapped, /* userGesture */ false);
- } catch (err) {
- return actionFailed(
- req.action,
- err instanceof Error ? err.message : String(err),
+ this.automation.assertResource(tabId, inner.url);
+ const sessionId = this.resolveSessionId(requestWithInnerTarget);
+ if (!sessionId) return actionFailed(req.action, 'no active RSB session');
+ return this.withTabPin(tabId, async () => {
+ await this.tryObservePageSignals(wc, tabId);
+ const captured = await this.artifacts!.capture(
+ wc,
+ { sessionId, timeoutMs: inner.timeoutMs ?? req.timeoutMs },
+ async () => {
+ wc.downloadURL(inner.url!);
+ return undefined;
+ },
);
+ if (!captured.downloads.some((artifact) => artifact.state === 'completed')) {
+ return actionFailed(req.action, 'resource download did not complete');
+ }
+ return actionOk(req.action, {
+ tabId,
+ kind: inner.kind,
+ url: inner.url,
+ downloads: captured.downloads,
+ });
+ });
+ }
+
+ if (inner.kind === 'evaluate') {
+ if (typeof inner.fn !== 'string' || inner.fn === '') {
+ return actionFailed(req.action, 'evaluate.fn (JS expression source) required');
+ }
+ return this.withTabPin(tabId, async () => {
+ await this.tryObservePageSignals(wc, tabId);
+ let value: unknown;
+ try {
+ value = await this.automation.evaluate(tabId, wc, automationRequest);
+ } catch (err) {
+ return actionFailed(
+ req.action,
+ err instanceof Error ? err.message : String(err),
+ );
+ }
+ return actionOk(req.action, {
+ tabId,
+ kind: 'evaluate',
+ ...(typeof inner.as === 'string' ? { as: inner.as } : {}),
+ result: value,
+ });
+ });
+ }
+
+ return this.withTabPin(tabId, async (retainTabPin) => {
+ await this.tryObserveNetwork(wc, tabId);
+ const opening = await this.tryWatchPageDialog(wc, tabId);
+ const pendingDialog = opening ? this.dialogs.pending(wc) : undefined;
+ if (pendingDialog) {
+ opening?.cancel();
+ return actionOk(req.action, {
+ tabId,
+ kind: inner.kind,
+ barrier: { kind: 'page-dialog', dialog: pendingDialog },
+ });
}
+
+ const actionStartedAt = Date.now();
+ const runAction = async () => {
+ const dialogBeforeStart = opening ? this.dialogs.pending(wc) : undefined;
+ if (dialogBeforeStart) {
+ opening?.cancel();
+ return {
+ tabId,
+ kind: inner.kind,
+ barrier: { kind: 'page-dialog', dialog: dialogBeforeStart },
+ };
+ }
+ const actionPromise = this.automation.act(tabId, wc, automationRequest, {
+ nativeKeyDispatch: async (type, keyCode, modifiers) => {
+ const sendInputEvent = (wc as unknown as {
+ sendInputEvent?: (event: {
+ type: 'keyDown' | 'keyUp';
+ keyCode: string;
+ modifiers?: string[];
+ }) => void;
+ }).sendInputEvent;
+ if (!sendInputEvent) throw new Error('native keyboard input is unavailable');
+ sendInputEvent({ type, keyCode, modifiers });
+ },
+ waitForNetworkIdle: (timeoutMs) => this.network.waitForIdle(wc, { timeoutMs }),
+ });
+ if (!opening) return actionPromise;
+ const outcome = await Promise.race([
+ actionPromise.then((value) => ({ type: 'action' as const, value })),
+ opening.opened.then((dialog) => ({ type: 'dialog' as const, dialog })),
+ ]);
+ if (outcome.type === 'action') {
+ opening.cancel();
+ const closedDialog = this.dialogs.recent(
+ wc,
+ undefined,
+ actionStartedAt,
+ );
+ if (closedDialog && closedDialog.type !== 'alert') {
+ return {
+ tabId,
+ kind: inner.kind,
+ barrier: { kind: 'page-dialog', dialog: closedDialog },
+ };
+ }
+ if (closedDialog) {
+ return {
+ ...outcome.value,
+ dialogs: [{ ...closedDialog, handled: true }],
+ };
+ }
+ return outcome.value;
+ }
+ if (outcome.dialog.type === 'alert') {
+ const value = await actionPromise;
+ const closedDialog = this.dialogs.recent(wc, outcome.dialog.id);
+ return {
+ ...value,
+ dialogs: [{
+ ...(closedDialog ?? outcome.dialog),
+ handled: true,
+ }],
+ };
+ }
+ void actionPromise.catch((err) => {
+ this.opts.logger.warn('browser action failed after a page dialog opened', {
+ tabId,
+ actionKind: inner.kind,
+ err,
+ });
+ });
+ retainTabPin();
+ void actionPromise.then(
+ () => this.opts.registry.unpin(tabId),
+ () => this.opts.registry.unpin(tabId),
+ );
+ return {
+ tabId,
+ kind: inner.kind,
+ barrier: { kind: 'page-dialog', dialog: outcome.dialog },
+ };
+ };
+
+ const captured = this.artifacts
+ && mayStartDownload(inner)
+ ? await this.artifacts.capture(
+ wc,
+ {
+ sessionId: this.resolveSessionId(requestWithInnerTarget) ?? 'rsb',
+ timeoutMs: inner.timeoutMs ?? req.timeoutMs,
+ },
+ runAction,
+ )
+ : { value: await runAction(), downloads: [] };
return actionOk(req.action, {
- tabId,
- kind: 'evaluate',
- // `as` is an output-variable name the recipe-runner uses to alias the
- // returned value. Surfaced verbatim so the runner's substitution
- // ({{var}}) works without an extra translation step.
- ...(typeof inner.as === 'string' ? { as: inner.as } : {}),
- result: value,
+ ...captured.value,
+ ...(captured.downloads.length > 0 ? { downloads: captured.downloads } : {}),
});
});
}
@@ -459,8 +719,223 @@ export class RsbWebviewBackend implements BrowserBackend {
});
}
+ private async handleUpload(req: BackendRequest): Promise<BackendResult> {
+ const sessionId = this.resolveSessionId(req);
+ if (!sessionId) return actionFailed(req.action, 'no active RSB session');
+ const tabId = await this.resolveDirectActionTarget(req);
+ if (!tabId) return actionFailed(req.action, 'targetId required');
+ const resolved = await this.resolveTabForDirectAction(req, tabId);
+ if (!resolved.ok) return resolved.result;
+ return this.withTabPin(tabId, async () => {
+ const roots = [
+ ...(this.opts.artifactRoot
+ ? [artifactSessionRoot(this.opts.artifactRoot(), sessionId)]
+ : []),
+ ...(this.opts.resolveUploadRoots
+ ? await this.opts.resolveUploadRoots(sessionId)
+ : []),
+ ];
+ const paths = await resolveUploadFiles(req.paths, roots);
+ await this.tryObservePageSignals(resolved.wc, tabId);
+ const data = await this.automation.setFiles(tabId, resolved.wc, {
+ ...req,
+ paths,
+ });
+ return actionOk(req.action, data);
+ });
+ }
+
+ private async handleDialog(req: BackendRequest): Promise<BackendResult> {
+ const tabId = await this.resolveDirectActionTarget(req);
+ if (!tabId) return actionFailed(req.action, 'targetId required');
+ const resolved = await this.resolveTabForDirectAction(req, tabId);
+ if (!resolved.ok) return resolved.result;
+ return this.withTabPin(tabId, async () => {
+ let dialog;
+ try {
+ dialog = await this.dialogs.respond(resolved.wc, {
+ dialogId: req.dialogId,
+ accept: req.accept,
+ promptText: req.promptText,
+ timeoutMs: req.timeoutMs,
+ });
+ } catch (err) {
+ if (
+ !(err instanceof Error)
+ || err.message !== 'no page dialog is pending'
+ || req.accept !== true
+ ) {
+ throw err;
+ }
+ const armed = this.dialogs.armNext(resolved.wc, {
+ accept: true,
+ promptText: req.promptText,
+ timeoutMs: req.timeoutMs,
+ });
+ void armed.response.catch((responseErr) => {
+ this.opts.logger.warn('prepared page dialog response expired', {
+ tabId,
+ err: responseErr,
+ });
+ });
+ return actionOk(req.action, {
+ tabId,
+ armed: true,
+ retryRequired: true,
+ });
+ }
+ if (dialog.deferred) {
+ if (
+ dialog.closedBy === 'armed'
+ || dialog.type === 'alert'
+ || req.accept !== true
+ ) {
+ return actionOk(req.action, {
+ tabId,
+ dialog,
+ handled: true,
+ });
+ }
+ const armed = this.dialogs.armNext(resolved.wc, {
+ accept: true,
+ promptText: req.promptText,
+ timeoutMs: req.timeoutMs,
+ });
+ void armed.response.catch((err) => {
+ this.opts.logger.warn('prepared page dialog response expired', {
+ tabId,
+ err,
+ });
+ });
+ return actionOk(req.action, {
+ tabId,
+ dialog,
+ armed: true,
+ retryRequired: true,
+ });
+ }
+ return actionOk(req.action, { tabId, dialog });
+ });
+ }
+
+ private async handleRequests(req: BackendRequest): Promise<BackendResult> {
+ const tabId = await this.resolveDirectActionTarget(req);
+ if (!tabId) return actionFailed(req.action, 'targetId required');
+ const resolved = await this.resolveTabForDirectAction(req, tabId);
+ if (!resolved.ok) return resolved.result;
+ return this.withTabPin(tabId, async () => {
+ await this.network.observe(resolved.wc);
+ const requests = this.network.readRequests(resolved.wc, {
+ filter: typeof req.filter === 'string' ? req.filter : undefined,
+ clear: req.clear === true,
+ });
+ return actionOk(req.action, { tabId, requests });
+ });
+ }
+
+ private async handleResponseBody(req: BackendRequest): Promise<BackendResult> {
+ const tabId = await this.resolveDirectActionTarget(req);
+ if (!tabId) return actionFailed(req.action, 'targetId required');
+ if (typeof req.url !== 'string' || req.url.trim() === '') {
+ return actionFailed(req.action, 'responseBody.url required');
+ }
+ const resolved = await this.resolveTabForDirectAction(req, tabId);
+ if (!resolved.ok) return resolved.result;
+ return this.withTabPin(tabId, async () => {
+ const response = await this.network.readResponseBody(resolved.wc, {
+ url: req.url!,
+ maxChars: req.maxChars,
+ timeoutMs: req.timeoutMs,
+ });
+ return actionOk(req.action, { tabId, response });
+ });
+ }
+
// ── helpers ───────────────────────────────────────────────────────────────
+ private recordActivity(req: BackendRequest, ok: boolean): void {
+ const directTarget = (req as { targetId?: unknown }).targetId;
+ const nestedTarget = (req as { request?: { targetId?: unknown } }).request?.targetId;
+ const targetId = typeof directTarget === 'string' && directTarget !== ''
+ ? directTarget
+ : typeof nestedTarget === 'string' && nestedTarget !== ''
+ ? nestedTarget
+ : undefined;
+ this.activity.push({
+ action: req.action,
+ finishedAt: new Date().toISOString(),
+ ok,
+ ...(targetId ? { targetId } : {}),
+ });
+ if (this.activity.length > 200) {
+ this.activity.splice(0, this.activity.length - 200);
+ }
+ }
+
+ private async tryWatchPageDialog(
+ wc: WebContents,
+ tabId: string,
+ ): Promise<ReturnType<RsbWebviewDialogs['watchOpening']> | undefined> {
+ try {
+ await this.dialogs.observe(wc);
+ return this.dialogs.watchOpening(wc);
+ } catch (err) {
+ // Dialog capture enriches an action but should not make the action fail
+ // when another debugger client owns the guest or Page.enable is refused.
+ this.opts.logger.warn('RSB page dialog observation unavailable', { tabId, err });
+ return undefined;
+ }
+ }
+
+ private async tryObserveNetwork(wc: WebContents, tabId: string): Promise<void> {
+ try {
+ await this.network.observe(wc);
+ } catch (err) {
+ // Network capture enriches normal browsing actions but must not prevent
+ // the underlying page action when DevTools owns the debugger.
+ this.opts.logger.warn('RSB network observation unavailable', { tabId, err });
+ }
+ }
+
+ private async tryObservePageSignals(wc: WebContents, tabId: string): Promise<void> {
+ await this.tryObserveNetwork(wc, tabId);
+ try {
+ await this.dialogs.observe(wc);
+ } catch (err) {
+ this.opts.logger.warn('RSB page dialog observation unavailable', { tabId, err });
+ }
+ }
+
+ /**
+ * Arm Network.enable as soon as the renderer reports a newly-created tab.
+ * `open` starts navigation in the renderer, so waiting until a later
+ * `requests` call would lose the document's initial requests.
+ */
+ private async observeOpenedTab(tabId: string): Promise<void> {
+ try {
+ const deadline = Date.now() + 2_000;
+ for (;;) {
+ const wc = this.opts.registry.getWebContentsByTabId(tabId);
+ if (wc) {
+ await this.tryObservePageSignals(wc, tabId);
+ return;
+ }
+ if (Date.now() >= deadline) {
+ this.opts.logger.warn('new browser tab was not reported before network capture arm', {
+ tabId,
+ });
+ return;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ } catch (err) {
+ this.opts.logger.warn('failed to arm network capture for new browser tab', {
+ tabId,
+ err,
+ });
+ }
+ }
+
/**
* Per-action automation pin. Wraps an action body so the targeted tab is
* pinned (LRU eviction skips it, see browserWebviewPool.evictLRU + the
@@ -486,12 +961,18 @@ export class RsbWebviewBackend implements BrowserBackend {
* acceptable until real concurrent use-cases emerge, then upgrade to
* refcount.
*/
- private async withTabPin<T>(tabId: string, body: () => Promise<T>): Promise<T> {
+ private async withTabPin<T>(
+ tabId: string,
+ body: (retainTabPin: () => void) => Promise<T>,
+ ): Promise<T> {
this.opts.registry.pin(tabId);
+ let retained = false;
try {
- return await body();
+ return await body(() => {
+ retained = true;
+ });
} finally {
- this.opts.registry.unpin(tabId);
+ if (!retained) this.opts.registry.unpin(tabId);
}
}
@@ -510,7 +991,7 @@ export class RsbWebviewBackend implements BrowserBackend {
private extractTargetId(req: BackendRequest): string | null {
const v = (req as { targetId?: unknown }).targetId;
if (typeof v === 'string' && v !== '') return v;
- const sessionId = this.opts.getActiveSessionId();
+ const sessionId = this.resolveSessionId(req);
if (!sessionId) return null;
const records = this.opts.registry.listBySession(sessionId);
// Last reported wins — RsbBrowserBridge replaces a tab's record on every
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-dialogs.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-dialogs.ts
new file mode 100644
index 0000000000..a2040aeca1
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-dialogs.ts
@@ -0,0 +1,392 @@
+import type { WebContents } from 'electron';
+
+interface DialogLogger {
+ warn(message: string, ...args: unknown[]): void;
+}
+
+interface ElectronDebugger {
+ isAttached(): boolean;
+ attach(protocolVersion?: string): void;
+ detach(): void;
+ sendCommand(method: string, commandParams?: Record<string, unknown>): Promise<unknown>;
+ on(event: string, listener: (...args: unknown[]) => void): void;
+ removeListener(event: string, listener: (...args: unknown[]) => void): void;
+}
+
+export interface BrowserPageDialog {
+ id: string;
+ type: string;
+ message: string;
+ defaultValue?: string;
+ openedAt: string;
+ closedBy?: 'agent' | 'armed' | 'auto';
+}
+
+interface PreparedResponse {
+ accept: boolean;
+ promptText?: string;
+ resolve(dialog: BrowserPageDialog): void;
+ reject(error: Error): void;
+ timer: ReturnType<typeof setTimeout>;
+}
+
+interface DialogState {
+ debugger: ElectronDebugger;
+ ownedAttachment: boolean;
+ enabled: boolean;
+ pending?: BrowserPageDialog;
+ recent?: BrowserPageDialog;
+ prepared?: PreparedResponse;
+ handledIds: Map<string, 'agent' | 'armed'>;
+ openingWaiters: Set<{
+ resolve(dialog: BrowserPageDialog): void;
+ reject(error: Error): void;
+ }>;
+ messageHandler: (...args: unknown[]) => void;
+ detachHandler: (...args: unknown[]) => void;
+ destroyedHandler: (...args: unknown[]) => void;
+}
+
+const DEFAULT_WAIT_MS = 10_000;
+const MAX_WAIT_MS = 60_000;
+const DEFAULT_ARM_WAIT_MS = 120_000;
+const MAX_ARM_WAIT_MS = 300_000;
+const MAX_DIALOG_TEXT = 16_000;
+const MAX_PROMPT_TEXT = 32_000;
+
+let dialogSequence = 0;
+
+function text(value: unknown): string {
+ return typeof value === 'string' ? value : '';
+}
+
+function boundedText(value: unknown, max = MAX_DIALOG_TEXT): string {
+ return text(value).slice(0, max);
+}
+
+function boundedWait(value: unknown): number {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
+ ? Math.min(MAX_WAIT_MS, Math.floor(value))
+ : DEFAULT_WAIT_MS;
+}
+
+function boundedArmWait(value: unknown): number {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
+ ? Math.min(MAX_ARM_WAIT_MS, Math.floor(value))
+ : DEFAULT_ARM_WAIT_MS;
+}
+
+function debuggerFor(wc: WebContents): ElectronDebugger {
+ const candidate = (wc as unknown as { debugger?: ElectronDebugger }).debugger;
+ if (!candidate) throw new Error('webContents debugger is unavailable');
+ return candidate;
+}
+
+/**
+ * Tracks JavaScript modal prompts for each embedded page and responds through
+ * the page debugger. The monitor releases only attachments it created.
+ */
+export class RsbWebviewDialogs {
+ private readonly states = new Map<WebContents, DialogState>();
+
+ constructor(private readonly logger: DialogLogger) {}
+
+ async observe(wc: WebContents): Promise<void> {
+ let state = this.states.get(wc);
+ if (!state) {
+ state = this.createState(wc);
+ this.states.set(wc, state);
+ }
+ if (state.enabled && state.debugger.isAttached()) return;
+ if (!state.debugger.isAttached()) {
+ state.debugger.attach('1.3');
+ state.ownedAttachment = true;
+ }
+ await state.debugger.sendCommand('Page.enable');
+ state.enabled = true;
+ }
+
+ pending(wc: WebContents): BrowserPageDialog | undefined {
+ const dialog = this.states.get(wc)?.pending;
+ return dialog ? { ...dialog } : undefined;
+ }
+
+ recent(wc: WebContents, dialogId?: string, openedAfter?: number): BrowserPageDialog | undefined {
+ const dialog = this.states.get(wc)?.recent;
+ if (!dialog || (dialogId && dialog.id !== dialogId)) return undefined;
+ if (openedAfter !== undefined && Date.parse(dialog.openedAt) < openedAfter) {
+ return undefined;
+ }
+ return { ...dialog };
+ }
+
+ watchOpening(wc: WebContents): {
+ opened: Promise<BrowserPageDialog>;
+ cancel(): void;
+ } {
+ const state = this.states.get(wc);
+ if (!state?.enabled) {
+ throw new Error('page dialog monitor is not active');
+ }
+ if (state.pending) {
+ return {
+ opened: Promise.resolve({ ...state.pending }),
+ cancel: () => {},
+ };
+ }
+ let active = true;
+ let waiter!: {
+ resolve(dialog: BrowserPageDialog): void;
+ reject(error: Error): void;
+ };
+ const opened = new Promise<BrowserPageDialog>((resolve, reject) => {
+ waiter = { resolve, reject };
+ state.openingWaiters.add(waiter);
+ });
+ return {
+ opened,
+ cancel: () => {
+ if (!active) return;
+ active = false;
+ state.openingWaiters.delete(waiter);
+ },
+ };
+ }
+
+ async respond(
+ wc: WebContents,
+ options: {
+ dialogId?: string;
+ accept?: boolean;
+ promptText?: string;
+ timeoutMs?: number;
+ },
+ ): Promise<BrowserPageDialog & { accepted: boolean; deferred: boolean }> {
+ if (options.dialogId && options.dialogId.length > 256) {
+ throw new Error('dialogId is too long');
+ }
+ if (typeof options.promptText === 'string' && options.promptText.length > MAX_PROMPT_TEXT) {
+ throw new Error(`promptText exceeds ${MAX_PROMPT_TEXT} characters`);
+ }
+ await this.observe(wc);
+ const state = this.states.get(wc);
+ if (!state) throw new Error('page dialog monitor unavailable');
+ const deadline = Date.now() + boundedWait(options.timeoutMs);
+ let dialog: BrowserPageDialog | undefined;
+ for (;;) {
+ const current = state.pending;
+ if (current && (!options.dialogId || current.id === options.dialogId)) {
+ dialog = current;
+ break;
+ }
+ if (current && options.dialogId && current.id !== options.dialogId) {
+ throw new Error(`dialog ${options.dialogId} is no longer pending`);
+ }
+ const recent = state.recent;
+ // An undirected response must wait for a fresh dialog. A recent dialog
+ // is only meaningful when the caller explicitly targets its id; using a
+ // stale recent record here would prevent arm-next from observing the
+ // next dialog.
+ if (recent && options.dialogId && recent.id === options.dialogId) {
+ return {
+ ...recent,
+ accepted: options.accept === true,
+ deferred: true,
+ };
+ }
+ if (recent && options.dialogId && recent.id !== options.dialogId) {
+ throw new Error(`dialog ${options.dialogId} is no longer pending`);
+ }
+ if (Date.now() >= deadline) throw new Error('no page dialog is pending');
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+
+ const accepted = options.accept === true;
+ state.handledIds.set(dialog.id, 'agent');
+ try {
+ await state.debugger.sendCommand('Page.handleJavaScriptDialog', {
+ accept: accepted,
+ ...(accepted && typeof options.promptText === 'string'
+ ? { promptText: options.promptText }
+ : {}),
+ });
+ } catch (err) {
+ state.handledIds.delete(dialog.id);
+ throw err;
+ }
+ // Keep the pending record until Page.javascriptDialogClosed arrives. The
+ // close event is the authoritative signal that Chromium finished handling
+ // the modal and also records the recent outcome for action coordination.
+ return { ...dialog, accepted, deferred: false };
+ }
+
+ armNext(
+ wc: WebContents,
+ options: {
+ accept: boolean;
+ promptText?: string;
+ timeoutMs?: number;
+ },
+ ): { response: Promise<BrowserPageDialog>; cancel(): void } {
+ const state = this.states.get(wc);
+ if (!state?.enabled) {
+ throw new Error('page dialog monitor is not active');
+ }
+ if (state.prepared) {
+ clearTimeout(state.prepared.timer);
+ state.prepared.reject(new Error('page dialog response was replaced'));
+ state.prepared = undefined;
+ }
+ let active = true;
+ let prepared!: PreparedResponse;
+ const response = new Promise<BrowserPageDialog>((resolve, reject) => {
+ const timeout = boundedArmWait(options.timeoutMs);
+ const timer = setTimeout(() => {
+ if (!active || state.prepared !== prepared) return;
+ active = false;
+ state.prepared = undefined;
+ reject(new Error('armed page dialog response expired'));
+ }, timeout);
+ prepared = {
+ accept: options.accept === true,
+ ...(typeof options.promptText === 'string' ? { promptText: options.promptText } : {}),
+ resolve,
+ reject,
+ timer,
+ };
+ state.prepared = prepared;
+ });
+ return {
+ response,
+ cancel: () => {
+ if (!active || state.prepared !== prepared) return;
+ active = false;
+ clearTimeout(prepared.timer);
+ state.prepared = undefined;
+ },
+ };
+ }
+
+ diagnostics(): { observedTabs: number; pendingDialogs: number } {
+ let pendingDialogs = 0;
+ for (const state of this.states.values()) {
+ if (state.pending) pendingDialogs += 1;
+ }
+ return { observedTabs: this.states.size, pendingDialogs };
+ }
+
+ dispose(): void {
+ for (const wc of [...this.states.keys()]) this.release(wc);
+ }
+
+ private createState(wc: WebContents): DialogState {
+ const electronDebugger = debuggerFor(wc);
+ const state: DialogState = {
+ debugger: electronDebugger,
+ ownedAttachment: false,
+ enabled: false,
+ openingWaiters: new Set(),
+ handledIds: new Map(),
+ messageHandler: () => {},
+ detachHandler: () => {},
+ destroyedHandler: () => {},
+ };
+ state.messageHandler = (...args: unknown[]) => {
+ try {
+ const method = text(args[1]);
+ const params =
+ args[2] && typeof args[2] === 'object' ? (args[2] as Record<string, unknown>) : {};
+ if (method === 'Page.javascriptDialogOpening') {
+ dialogSequence += 1;
+ const dialog: BrowserPageDialog = {
+ id: `page-dialog-${Date.now().toString(36)}-${dialogSequence.toString(36)}`,
+ type: boundedText(params.type, 64) || 'alert',
+ message: boundedText(params.message),
+ ...(boundedText(params.defaultPrompt)
+ ? { defaultValue: boundedText(params.defaultPrompt) }
+ : {}),
+ openedAt: new Date().toISOString(),
+ };
+ state.pending = dialog;
+ for (const waiter of state.openingWaiters) {
+ waiter.resolve({ ...dialog });
+ }
+ state.openingWaiters.clear();
+ const prepared = state.prepared;
+ if (prepared) {
+ state.prepared = undefined;
+ clearTimeout(prepared.timer);
+ state.handledIds.set(dialog.id, 'armed');
+ void state.debugger
+ .sendCommand('Page.handleJavaScriptDialog', {
+ accept: prepared.accept,
+ ...(prepared.accept && typeof prepared.promptText === 'string'
+ ? { promptText: prepared.promptText }
+ : {}),
+ })
+ .then(
+ () => prepared.resolve({ ...dialog, closedBy: 'armed' }),
+ (err) => prepared.reject(err instanceof Error ? err : new Error(String(err))),
+ );
+ }
+ } else if (method === 'Page.javascriptDialogClosed') {
+ const dialog = state.pending;
+ if (dialog) {
+ const closedBy = state.handledIds.get(dialog.id) ?? 'auto';
+ state.handledIds.delete(dialog.id);
+ state.recent = { ...dialog, closedBy };
+ }
+ state.pending = undefined;
+ }
+ } catch (err) {
+ this.logger.warn('RSB page dialog event handler failed', err);
+ }
+ };
+ state.detachHandler = () => {
+ state.enabled = false;
+ state.ownedAttachment = false;
+ };
+ state.destroyedHandler = () => this.release(wc);
+ electronDebugger.on('message', state.messageHandler);
+ electronDebugger.on('detach', state.detachHandler);
+ (
+ wc as unknown as {
+ once?: (event: string, listener: (...args: unknown[]) => void) => void;
+ }
+ ).once?.('destroyed', state.destroyedHandler);
+ return state;
+ }
+
+ private release(wc: WebContents): void {
+ const state = this.states.get(wc);
+ if (!state) return;
+ this.states.delete(wc);
+ try {
+ state.debugger.removeListener('message', state.messageHandler);
+ state.debugger.removeListener('detach', state.detachHandler);
+ (
+ wc as unknown as {
+ removeListener?: (event: string, listener: (...args: unknown[]) => void) => void;
+ }
+ ).removeListener?.('destroyed', state.destroyedHandler);
+ } catch {
+ // The guest may already be destroyed.
+ }
+ if (state.prepared) {
+ clearTimeout(state.prepared.timer);
+ state.prepared.reject(new Error('page dialog monitor was released'));
+ state.prepared = undefined;
+ }
+ for (const waiter of state.openingWaiters) {
+ waiter.reject(new Error('page dialog monitor was released'));
+ }
+ state.openingWaiters.clear();
+ if (state.ownedAttachment) {
+ try {
+ if (state.debugger.isAttached()) state.debugger.detach();
+ } catch {
+ // Detach is best effort during teardown.
+ }
+ }
+ }
+}
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-network.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-network.ts
new file mode 100644
index 0000000000..bb5109ad9d
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-network.ts
@@ -0,0 +1,366 @@
+import type { WebContents } from 'electron';
+
+interface NetworkLogger {
+ warn(message: string, ...args: unknown[]): void;
+}
+
+interface ElectronDebugger {
+ isAttached(): boolean;
+ attach(protocolVersion?: string): void;
+ detach(): void;
+ sendCommand(method: string, commandParams?: Record<string, unknown>): Promise<unknown>;
+ on(event: string, listener: (...args: unknown[]) => void): void;
+ removeListener(event: string, listener: (...args: unknown[]) => void): void;
+}
+
+interface RequestRecord {
+ id: string;
+ timestamp: string;
+ method: string;
+ url: string;
+ resourceType: string;
+ status?: number;
+ ok?: boolean;
+ failureText?: string;
+}
+
+interface ResponseRecord {
+ requestId: string;
+ url: string;
+ status?: number;
+ headers?: Record<string, string>;
+ finished: boolean;
+}
+
+interface MonitorState {
+ debugger: ElectronDebugger;
+ ownedAttachment: boolean;
+ enabled: boolean;
+ requests: RequestRecord[];
+ byRequestId: Map<string, RequestRecord>;
+ responses: Map<string, ResponseRecord>;
+ inFlight: Set<string>;
+ lastActivityAt: number;
+ messageHandler: (...args: unknown[]) => void;
+ detachHandler: (...args: unknown[]) => void;
+ destroyedHandler: (...args: unknown[]) => void;
+}
+
+const MAX_REQUESTS = 500;
+const DEFAULT_BODY_CHARS = 200_000;
+const MAX_BODY_CHARS = 1_000_000;
+const DEFAULT_BODY_WAIT_MS = 20_000;
+const MAX_BODY_WAIT_MS = 60_000;
+const DEFAULT_IDLE_WINDOW_MS = 500;
+const SENSITIVE_HEADERS = new Set([
+ 'authorization',
+ 'cookie',
+ 'proxy-authorization',
+ 'set-cookie',
+]);
+
+function boundedPositive(value: unknown, fallback: number, max: number): number {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
+ ? Math.min(max, Math.max(1, Math.floor(value)))
+ : fallback;
+}
+
+function text(value: unknown): string {
+ return typeof value === 'string' ? value : '';
+}
+
+function number(value: unknown): number | undefined {
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
+}
+
+function safeHeaders(value: unknown): Record<string, string> | undefined {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
+ const out: Record<string, string> = {};
+ for (const [name, raw] of Object.entries(value)) {
+ if (SENSITIVE_HEADERS.has(name.toLowerCase())) continue;
+ if (typeof raw === 'string' || typeof raw === 'number' || typeof raw === 'boolean') {
+ out[name] = String(raw);
+ }
+ }
+ return Object.keys(out).length > 0 ? out : undefined;
+}
+
+function safeUrl(value: string): string {
+ try {
+ const parsed = new URL(value);
+ parsed.username = '';
+ parsed.password = '';
+ return parsed.href;
+ } catch {
+ return value;
+ }
+}
+
+function urlMatches(pattern: string, url: string): boolean {
+ if (!pattern.includes('*')) return url.includes(pattern);
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replaceAll('*', '.*');
+ return new RegExp(`^${escaped}$`, 'i').test(url);
+}
+
+function debuggerFor(wc: WebContents): ElectronDebugger {
+ const candidate = (wc as unknown as { debugger?: ElectronDebugger }).debugger;
+ if (!candidate) throw new Error('webContents debugger is unavailable');
+ return candidate;
+}
+
+/**
+ * Keeps a bounded request history for each live RSB guest. The monitor owns a
+ * debugger attachment only when it created one and releases that attachment
+ * when the guest or backend is disposed.
+ */
+export class RsbWebviewNetwork {
+ private readonly states = new Map<WebContents, MonitorState>();
+
+ constructor(private readonly logger: NetworkLogger) {}
+
+ async observe(wc: WebContents): Promise<void> {
+ let state = this.states.get(wc);
+ if (!state) {
+ state = this.createState(wc);
+ this.states.set(wc, state);
+ }
+ if (state.enabled && state.debugger.isAttached()) return;
+ if (!state.debugger.isAttached()) {
+ state.debugger.attach('1.3');
+ state.ownedAttachment = true;
+ }
+ await state.debugger.sendCommand('Network.enable', {
+ maxTotalBufferSize: 16 * 1024 * 1024,
+ maxResourceBufferSize: 4 * 1024 * 1024,
+ maxPostDataSize: 256 * 1024,
+ });
+ state.enabled = true;
+ }
+
+ readRequests(
+ wc: WebContents,
+ options: { filter?: string; clear?: boolean } = {},
+ ): RequestRecord[] {
+ const state = this.states.get(wc);
+ if (!state) return [];
+ const filter = options.filter?.trim();
+ const result = state.requests
+ .filter((entry) => !filter || entry.url.includes(filter))
+ .map((entry) => ({ ...entry }));
+ if (options.clear === true) {
+ state.requests = [];
+ state.byRequestId.clear();
+ state.responses.clear();
+ }
+ return result;
+ }
+
+ async readResponseBody(
+ wc: WebContents,
+ options: { url: string; maxChars?: number; timeoutMs?: number },
+ ): Promise<{
+ url: string;
+ status?: number;
+ headers?: Record<string, string>;
+ body: string;
+ truncated?: boolean;
+ }> {
+ const pattern = options.url.trim();
+ if (!pattern) throw new Error('responseBody.url required');
+ await this.observe(wc);
+ const state = this.states.get(wc);
+ if (!state) throw new Error('network monitor unavailable');
+ const timeoutMs = boundedPositive(options.timeoutMs, DEFAULT_BODY_WAIT_MS, MAX_BODY_WAIT_MS);
+ const maxChars = boundedPositive(options.maxChars, DEFAULT_BODY_CHARS, MAX_BODY_CHARS);
+ const deadline = Date.now() + timeoutMs;
+ const existingResponseIds = new Set(state.responses.keys());
+
+ for (;;) {
+ const response = [...state.responses.values()]
+ .reverse()
+ .find((entry) => (
+ !existingResponseIds.has(entry.requestId)
+ && entry.finished
+ && urlMatches(pattern, entry.url)
+ ));
+ if (response) {
+ const raw = await state.debugger.sendCommand('Network.getResponseBody', {
+ requestId: response.requestId,
+ }) as { body?: unknown; base64Encoded?: unknown };
+ const encoded = text(raw.body);
+ const body = raw.base64Encoded === true
+ ? Buffer.from(encoded, 'base64').toString('utf8')
+ : encoded;
+ return {
+ url: response.url,
+ ...(response.status !== undefined ? { status: response.status } : {}),
+ ...(response.headers ? { headers: response.headers } : {}),
+ body: body.length > maxChars ? body.slice(0, maxChars) : body,
+ ...(body.length > maxChars ? { truncated: true } : {}),
+ };
+ }
+ if (Date.now() >= deadline) {
+ throw new Error(`response not found for URL pattern: ${pattern}`);
+ }
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ }
+
+ async waitForIdle(
+ wc: WebContents,
+ options: { timeoutMs?: number; idleMs?: number } = {},
+ ): Promise<void> {
+ await this.observe(wc);
+ const state = this.states.get(wc);
+ if (!state) throw new Error('network monitor unavailable');
+ const timeoutMs = boundedPositive(options.timeoutMs, DEFAULT_BODY_WAIT_MS, MAX_BODY_WAIT_MS);
+ const idleMs = boundedPositive(options.idleMs, DEFAULT_IDLE_WINDOW_MS, MAX_BODY_WAIT_MS);
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ const now = Date.now();
+ if (state.inFlight.size === 0 && now - state.lastActivityAt >= idleMs) return;
+ if (now >= deadline) throw new Error('network did not become idle before timeout');
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ }
+
+ diagnostics(): { observedTabs: number; bufferedRequests: number } {
+ let bufferedRequests = 0;
+ for (const state of this.states.values()) bufferedRequests += state.requests.length;
+ return { observedTabs: this.states.size, bufferedRequests };
+ }
+
+ dispose(): void {
+ for (const wc of [...this.states.keys()]) this.release(wc);
+ }
+
+ private createState(wc: WebContents): MonitorState {
+ const electronDebugger = debuggerFor(wc);
+ const state: MonitorState = {
+ debugger: electronDebugger,
+ ownedAttachment: false,
+ enabled: false,
+ requests: [],
+ byRequestId: new Map(),
+ responses: new Map(),
+ inFlight: new Set(),
+ lastActivityAt: Date.now(),
+ messageHandler: () => {},
+ detachHandler: () => {},
+ destroyedHandler: () => {},
+ };
+ state.messageHandler = (...args: unknown[]) => {
+ try {
+ const method = text(args[1]);
+ const params = args[2] && typeof args[2] === 'object'
+ ? args[2] as Record<string, unknown>
+ : {};
+ this.consumeMessage(state, method, params);
+ } catch (err) {
+ this.logger.warn('RSB network event handler failed', err);
+ }
+ };
+ state.detachHandler = () => {
+ state.enabled = false;
+ state.ownedAttachment = false;
+ };
+ state.destroyedHandler = () => this.release(wc);
+ electronDebugger.on('message', state.messageHandler);
+ electronDebugger.on('detach', state.detachHandler);
+ (wc as unknown as {
+ once?: (event: string, listener: (...args: unknown[]) => void) => void;
+ }).once?.('destroyed', state.destroyedHandler);
+ return state;
+ }
+
+ private consumeMessage(
+ state: MonitorState,
+ method: string,
+ params: Record<string, unknown>,
+ ): void {
+ const requestId = text(params.requestId);
+ if (!requestId) return;
+ if (method === 'Network.requestWillBeSent') {
+ const request = params.request && typeof params.request === 'object'
+ ? params.request as Record<string, unknown>
+ : {};
+ const record: RequestRecord = {
+ id: requestId,
+ timestamp: new Date().toISOString(),
+ method: text(request.method) || 'GET',
+ url: safeUrl(text(request.url)),
+ resourceType: text(params.type).toLowerCase() || 'other',
+ };
+ state.requests.push(record);
+ state.byRequestId.set(requestId, record);
+ state.inFlight.add(requestId);
+ state.lastActivityAt = Date.now();
+ if (state.requests.length > MAX_REQUESTS) {
+ const removed = state.requests.splice(0, state.requests.length - MAX_REQUESTS);
+ for (const item of removed) {
+ state.byRequestId.delete(item.id);
+ state.responses.delete(item.id);
+ }
+ }
+ return;
+ }
+ if (method === 'Network.responseReceived') {
+ const response = params.response && typeof params.response === 'object'
+ ? params.response as Record<string, unknown>
+ : {};
+ const status = number(response.status);
+ const request = state.byRequestId.get(requestId);
+ if (request) {
+ request.status = status;
+ request.ok = status !== undefined ? status >= 200 && status < 400 : undefined;
+ }
+ state.responses.set(requestId, {
+ requestId,
+ url: safeUrl(text(response.url) || request?.url || ''),
+ status,
+ headers: safeHeaders(response.headers),
+ finished: false,
+ });
+ state.lastActivityAt = Date.now();
+ return;
+ }
+ if (method === 'Network.loadingFinished') {
+ const response = state.responses.get(requestId);
+ if (response) response.finished = true;
+ state.inFlight.delete(requestId);
+ state.lastActivityAt = Date.now();
+ return;
+ }
+ if (method === 'Network.loadingFailed') {
+ const request = state.byRequestId.get(requestId);
+ if (request) {
+ request.ok = false;
+ request.failureText = text(params.errorText) || 'request failed';
+ }
+ state.inFlight.delete(requestId);
+ state.lastActivityAt = Date.now();
+ }
+ }
+
+ private release(wc: WebContents): void {
+ const state = this.states.get(wc);
+ if (!state) return;
+ this.states.delete(wc);
+ try {
+ state.debugger.removeListener('message', state.messageHandler);
+ state.debugger.removeListener('detach', state.detachHandler);
+ (wc as unknown as {
+ removeListener?: (event: string, listener: (...args: unknown[]) => void) => void;
+ }).removeListener?.('destroyed', state.destroyedHandler);
+ } catch {
+ // The guest may already be destroyed.
+ }
+ if (state.ownedAttachment) {
+ try {
+ if (state.debugger.isAttached()) state.debugger.detach();
+ } catch {
+ // Detach is best effort during teardown.
+ }
+ }
+ }
+}
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-upload-policy.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-upload-policy.ts
new file mode 100644
index 0000000000..e15234eca7
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-upload-policy.ts
@@ -0,0 +1,101 @@
+import fs from 'node:fs/promises';
+import path from 'node:path';
+
+const MAX_FILE_COUNT = 20;
+const MAX_FILE_BYTES = 100 * 1024 * 1024;
+const MAX_TOTAL_BYTES = 500 * 1024 * 1024;
+
+const BLOCKED_FILE_NAMES = new Set([
+ '.env',
+ '.npmrc',
+ '.netrc',
+ '.pypirc',
+ 'id_dsa',
+ 'id_ecdsa',
+ 'id_ed25519',
+ 'id_rsa',
+]);
+
+function isInside(parent: string, child: string): boolean {
+ const fold = (value: string) =>
+ process.platform === 'win32' ? value.toLowerCase() : value;
+ const relative = path.relative(fold(parent), fold(child));
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
+}
+
+function isBlockedFile(filePath: string): boolean {
+ const name = path.basename(filePath).toLowerCase();
+ const sensitiveDirectory = filePath
+ .split(/[\\/]+/)
+ .some((segment) => ['.git', '.ssh'].includes(segment.toLowerCase()));
+ return BLOCKED_FILE_NAMES.has(name)
+ || name.startsWith('.env.')
+ || name.endsWith('.key')
+ || sensitiveDirectory;
+}
+
+/**
+ * Resolves upload candidates to their filesystem identity and confines every
+ * file to a host-provided root. Realpath checks prevent a workdir symlink or
+ * junction from granting access to a file outside that workdir.
+ */
+export async function resolveUploadFiles(
+ candidates: unknown,
+ allowedRoots: string[],
+): Promise<string[]> {
+ if (!Array.isArray(candidates) || candidates.length === 0) {
+ throw new Error('paths must contain at least one file');
+ }
+ if (candidates.length > MAX_FILE_COUNT) {
+ throw new Error(`paths accepts at most ${MAX_FILE_COUNT} files`);
+ }
+
+ const roots: string[] = [];
+ for (const root of allowedRoots) {
+ if (!path.isAbsolute(root)) continue;
+ try {
+ const resolved = await fs.realpath(root);
+ const stat = await fs.stat(resolved);
+ if (stat.isDirectory()) roots.push(resolved);
+ } catch {
+ // A missing optional root grants nothing.
+ }
+ }
+ if (roots.length === 0) {
+ throw new Error('upload is unavailable without a local session directory');
+ }
+
+ const files: string[] = [];
+ let totalBytes = 0;
+ for (const candidate of candidates) {
+ if (typeof candidate !== 'string' || !path.isAbsolute(candidate)) {
+ throw new Error('every upload path must be an absolute local file path');
+ }
+ let resolved: string;
+ let stat;
+ try {
+ resolved = await fs.realpath(candidate);
+ stat = await fs.stat(resolved);
+ } catch {
+ throw new Error(`upload file does not exist: ${path.basename(candidate) || 'unnamed'}`);
+ }
+ if (!stat.isFile()) {
+ throw new Error(`upload path is not a regular file: ${path.basename(resolved)}`);
+ }
+ if (!roots.some((root) => isInside(root, resolved))) {
+ throw new Error('upload files must stay inside the current session directory');
+ }
+ if (isBlockedFile(resolved)) {
+ throw new Error(`upload blocked for sensitive file: ${path.basename(resolved)}`);
+ }
+ if (stat.size > MAX_FILE_BYTES) {
+ throw new Error(`upload file exceeds ${MAX_FILE_BYTES} bytes: ${path.basename(resolved)}`);
+ }
+ totalBytes += stat.size;
+ if (totalBytes > MAX_TOTAL_BYTES) {
+ throw new Error(`upload batch exceeds ${MAX_TOTAL_BYTES} bytes`);
+ }
+ files.push(resolved);
+ }
+ return files;
+}
diff --git a/apps/desktop/src/main/mcp-integrations/browser.ts b/apps/desktop/src/main/mcp-integrations/browser.ts
index c53afbac77..3887b83aa3 100644
--- a/apps/desktop/src/main/mcp-integrations/browser.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser.ts
@@ -8,7 +8,7 @@
import './browser-runtime-env.js';
import fs from 'node:fs';
import nodePath from 'node:path';
-import { ipcMain } from 'electron';
+import { app, ipcMain } from 'electron';
import {
createBrowserControlRuntime,
type BrowserControlRuntime,
@@ -182,6 +182,16 @@ const vendoredRuntime = trackBrowserRuntimeUsage(
const externalBackend = new ExternalChromeBackend(vendoredRuntime, logger);
+type SessionUploadRootResolver = (sessionId: string) => Promise<string[]>;
+
+let resolveSessionUploadRoots: SessionUploadRootResolver = async () => [];
+
+export function setBrowserSessionUploadRootResolver(
+ resolver: SessionUploadRootResolver,
+): void {
+ resolveSessionUploadRoots = resolver;
+}
+
/**
* RSB-webview backend instance (Phase 3+). Lazily constructed because the
* TabRegistry singleton must be available — which it is right after this
@@ -190,6 +200,8 @@ const externalBackend = new ExternalChromeBackend(vendoredRuntime, logger);
const rsbBackend = new RsbWebviewBackend({
registry: getRsbBrowserBridge(),
getActiveSessionId: () => getActiveRsbSessionId(),
+ artifactRoot: () => nodePath.join(app.getPath('temp'), 'cindy-browser-artifacts'),
+ resolveUploadRoots: (sessionId) => resolveSessionUploadRoots(sessionId),
bridge: {
// Lazy main-window lookup. Phase 2 uses the same pattern; once the host
// window is available the dispatch lands cleanly, before that the request
@@ -317,6 +329,8 @@ export async function setActiveBrowserBackendKind(kind: BackendKind): Promise<vo
*/
export function getBrowserMcpDeps(): {
getRuntime(): BrowserControlRuntime;
+ supportsResourceDownloads(): boolean;
+ supportsSemanticQueries(): boolean;
logger: typeof logger;
getUserRecipes(): Promise<UserRecipesResult>;
saveUserRecipe(input: Parameters<typeof writeUserRecipe>[0]): Promise<WriteUserRecipeResult>;
@@ -331,6 +345,8 @@ export function getBrowserMcpDeps(): {
// the backend split. Swapping the active backend (Phase 5) is invisible from
// @cindy/mcps' perspective.
getRuntime: () => router,
+ supportsResourceDownloads: () => router.kind === 'rsb-webview',
+ supportsSemanticQueries: () => router.kind === 'rsb-webview',
logger,
};
}
diff --git a/apps/desktop/src/main/webview-security.ts b/apps/desktop/src/main/webview-security.ts
index 8da89c9dea..2d2d40dc4a 100644
--- a/apps/desktop/src/main/webview-security.ts
+++ b/apps/desktop/src/main/webview-security.ts
@@ -107,6 +107,10 @@ export function applyWebviewHardening(
webPreferences.allowRunningInsecureContent = false;
webPreferences.webviewTag = false;
webPreferences.plugins = false;
+ // Keep Chromium dialogs enabled so Page.javascriptDialogOpening reaches the
+ // controlled debugger observer. The backend turns them into structured
+ // barriers instead of letting them silently bypass the automation contract.
+ webPreferences.disableDialogs = false;
// Codex 自定义字段(Electron 标准 WebPreferences 不认这个 key,Electron 会
// 忽略;但 Codex 在 IPC 层 / fork 的 Electron 可能消费它)。我们一并设上保持
// 字面 1:1,即便 Electron 标准侧 no-op 也无害。
diff --git a/packages/browser-control-runtime/src/index.ts b/packages/browser-control-runtime/src/index.ts
index c83538bc39..f2302d7bb7 100644
--- a/packages/browser-control-runtime/src/index.ts
+++ b/packages/browser-control-runtime/src/index.ts
@@ -8,6 +8,7 @@ export type {
BrowserControlRuntime,
BrowserControlRuntimeFactoryOptions,
BrowserControlTarget,
+ BrowserElementQuery,
BrowserImageType,
BrowserSnapshotFormat,
BrowserSnapshotMode,
@@ -23,6 +24,7 @@ export {
// default profile between managed and real-Chrome takeover) WITHOUT recreating
// the runtime — config reads hot-reload per request inside the dispatcher.
export { setBrowserRuntimeConfig as setBrowserControlRuntimeConfig } from './shim/runtime-config-snapshot.js';
+export { isPublicHttpResourceUrl } from './resource-url-policy.js';
// Re-export the effective-config type under a neutral name so host code stays
// free of the vendored type's product-specific identifier.
export type {
diff --git a/packages/browser-control-runtime/src/resource-url-policy.ts b/packages/browser-control-runtime/src/resource-url-policy.ts
new file mode 100644
index 0000000000..af7b04ee7e
--- /dev/null
+++ b/packages/browser-control-runtime/src/resource-url-policy.ts
@@ -0,0 +1,19 @@
+import { isBlockedHostnameOrIp } from './_generated/leaf/src/infra/net/ssrf.js';
+
+/**
+ * Resource downloads are host-side writes and must not become a local-network
+ * fetch primitive for page content.
+ */
+export function isPublicHttpResourceUrl(value: string): boolean {
+ try {
+ const parsed = new URL(value);
+ return (
+ (parsed.protocol === 'http:' || parsed.protocol === 'https:')
+ && !parsed.username
+ && !parsed.password
+ && !isBlockedHostnameOrIp(parsed.hostname)
+ );
+ } catch {
+ return false;
+ }
+}
diff --git a/packages/browser-control-runtime/src/runtime.ts b/packages/browser-control-runtime/src/runtime.ts
index ed84bcdaf1..dc6f3d7612 100644
--- a/packages/browser-control-runtime/src/runtime.ts
+++ b/packages/browser-control-runtime/src/runtime.ts
@@ -152,6 +152,7 @@ export function planDispatch(req: BrowserControlRequest): DispatchPlan {
ref: req.ref,
inputRef: req.inputRef,
element: req.element,
+ query: req.query,
targetId: req.targetId,
timeoutMs: req.timeoutMs,
},
diff --git a/packages/browser-control-runtime/src/types.ts b/packages/browser-control-runtime/src/types.ts
index a775345a2f..9ee6dcd29e 100644
--- a/packages/browser-control-runtime/src/types.ts
+++ b/packages/browser-control-runtime/src/types.ts
@@ -41,6 +41,7 @@ export type BrowserActKind =
| 'resize'
| 'wait'
| 'evaluate'
+ | 'saveResource'
| 'close';
export type BrowserControlTarget = 'sandbox' | 'host' | 'node';
@@ -49,10 +50,27 @@ export type BrowserSnapshotMode = 'efficient';
export type BrowserSnapshotRefs = 'role' | 'aria';
export type BrowserImageType = 'png' | 'jpeg';
+/**
+ * Backend-neutral element lookup. A query may combine multiple semantic
+ * fields; every populated field must match the same element.
+ */
+export interface BrowserElementQuery {
+ css?: string;
+ role?: string;
+ name?: string;
+ text?: string;
+ label?: string;
+ placeholder?: string;
+ testId?: string;
+ exact?: boolean;
+ index?: number;
+}
+
export interface BrowserActRequest {
kind: BrowserActKind;
targetId?: string;
ref?: string;
+ query?: BrowserElementQuery;
doubleClick?: boolean;
button?: string;
modifiers?: string[];
@@ -106,6 +124,7 @@ export interface BrowserControlRequest {
level?: string;
paths?: string[];
inputRef?: string;
+ query?: BrowserElementQuery;
timeoutMs?: number;
dialogId?: string;
accept?: boolean;
diff --git a/packages/lizi-mcps/src/browser/browserMcpServer.test.ts b/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
index c39de3a2c4..e3739a9b13 100644
--- a/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
+++ b/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
@@ -123,6 +123,163 @@ describe('createBrowserMcpServer', () => {
await h.cleanup();
});
+ it('passes through a page resource and rejects unsafe resource URLs', async () => {
+ const h = await makeHarness();
+ await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'browser',
+ args: {
+ action: 'act',
+ targetId: 't1',
+ request: {
+ kind: 'saveResource',
+ url: 'https://cdn.example.test/archive.zip',
+ },
+ },
+ },
+ });
+ expect(h.calls).toEqual([
+ {
+ action: 'act',
+ targetId: 't1',
+ request: {
+ kind: 'saveResource',
+ url: 'https://cdn.example.test/archive.zip',
+ },
+ },
+ ]);
+
+ const blocked = await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'browser',
+ args: {
+ action: 'act',
+ targetId: 't1',
+ request: { kind: 'saveResource', url: 'file:///tmp/secret' },
+ },
+ },
+ });
+ expect(h.calls).toHaveLength(1);
+ const parsed = JSON.parse(
+ (blocked.content as Array<{ text: string }>)[0].text,
+ ) as { ok: boolean; message?: string };
+ expect(parsed.ok).toBe(false);
+ expect(parsed.message).toMatch(/http\(s\)/);
+
+ const credentialed = await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'browser',
+ args: {
+ action: 'act',
+ targetId: 't1',
+ request: {
+ kind: 'saveResource',
+ url: 'https://user:[email protected]/archive.zip',
+ },
+ },
+ },
+ });
+ expect(h.calls).toHaveLength(1);
+ const credentialedResult = JSON.parse(
+ (credentialed.content as Array<{ text: string }>)[0].text,
+ ) as { ok: boolean };
+ expect(credentialedResult.ok).toBe(false);
+ await h.cleanup();
+ });
+
+ it('re-evaluates resource download support when the backend changes', async () => {
+ let downloadsSupported = true;
+ const h = await makeHarness({
+ supportsResourceDownloads: () => downloadsSupported,
+ });
+ const request = {
+ name: 'browser',
+ args: {
+ action: 'act',
+ targetId: 't1',
+ request: {
+ kind: 'saveResource',
+ url: 'https://cdn.example.test/archive.zip',
+ },
+ },
+ };
+
+ await h.client.callTool({ name: 'call_tool', arguments: request });
+ expect(h.calls).toHaveLength(1);
+
+ downloadsSupported = false;
+ const blocked = await h.client.callTool({ name: 'call_tool', arguments: request });
+ expect(h.calls).toHaveLength(1);
+ expect(JSON.parse((blocked.content as Array<{ text: string }>)[0].text)).toMatchObject({
+ ok: false,
+ errorCode: 'INVALID_ARGS',
+ });
+
+ downloadsSupported = true;
+ await h.client.callTool({ name: 'call_tool', arguments: request });
+ expect(h.calls).toHaveLength(2);
+ await h.cleanup();
+ });
+
+ it('rejects semantic queries when the active backend does not support them', async () => {
+ let semanticQueriesSupported = true;
+ const h = await makeHarness({
+ supportsSemanticQueries: () => semanticQueriesSupported,
+ });
+ const request = {
+ name: 'browser',
+ args: {
+ action: 'act',
+ targetId: 't1',
+ request: {
+ kind: 'click',
+ query: { role: 'button', name: 'Continue' },
+ },
+ },
+ };
+
+ await h.client.callTool({ name: 'call_tool', arguments: request });
+ expect(h.calls).toHaveLength(1);
+
+ semanticQueriesSupported = false;
+ const blocked = await h.client.callTool({ name: 'call_tool', arguments: request });
+ expect(h.calls).toHaveLength(1);
+ expect(JSON.parse((blocked.content as Array<{ text: string }>)[0].text)).toMatchObject({
+ ok: false,
+ errorCode: 'INVALID_ARGS',
+ });
+ await h.cleanup();
+ });
+
+ it('rejects blank element query strings before calling the runtime', async () => {
+ const h = await makeHarness();
+ for (const field of ['css', 'role', 'name', 'text', 'label', 'placeholder', 'testId']) {
+ const blocked = await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'browser',
+ args: {
+ action: 'act',
+ targetId: 't1',
+ request: {
+ kind: 'click',
+ query: { [field]: ' ' },
+ },
+ },
+ },
+ });
+ expect(JSON.parse((blocked.content as Array<{ text: string }>)[0].text)).toMatchObject({
+ ok: false,
+ errorCode: 'INVALID_ARGS',
+ });
+ }
+ expect(h.calls).toHaveLength(0);
+ await h.cleanup();
+ });
+
it('compiles extract into an act:evaluate call', async () => {
const h = await makeHarness();
await h.client.callTool({
diff --git a/packages/lizi-mcps/src/browser/tools.ts b/packages/lizi-mcps/src/browser/tools.ts
index 30cd3cc9d9..30fda29cd4 100644
--- a/packages/lizi-mcps/src/browser/tools.ts
+++ b/packages/lizi-mcps/src/browser/tools.ts
@@ -1,4 +1,8 @@
-import type { BrowserControlRequest, BrowserControlRuntime } from '@cindy/browser-control-runtime';
+import {
+ isPublicHttpResourceUrl,
+ type BrowserControlRequest,
+ type BrowserControlRuntime,
+} from '@cindy/browser-control-runtime';
import { z } from 'zod';
import type { BrowserMcpDeps } from '../types.js';
@@ -98,6 +102,7 @@ const ACT_KINDS = [
'resize',
'wait',
'evaluate',
+ 'saveResource',
'close',
] as const;
@@ -105,6 +110,54 @@ function getRuntime(deps: BrowserMcpDeps): BrowserControlRuntime {
return deps.getRuntime();
}
+function actKindSchema(deps: BrowserMcpDeps) {
+ return z.enum(ACT_KINDS).superRefine((kind, ctx) => {
+ if (kind === 'saveResource' && deps.supportsResourceDownloads?.() === false) {
+ ctx.addIssue({
+ code: 'custom',
+ message: '当前浏览器后端不支持 saveResource',
+ });
+ }
+ });
+}
+
+function elementQuerySchema(deps: BrowserMcpDeps) {
+ const nonBlankString = z.string().trim().min(1);
+ return z.object({
+ css: nonBlankString.optional(),
+ role: nonBlankString.optional(),
+ name: nonBlankString.optional(),
+ text: nonBlankString.optional(),
+ label: nonBlankString.optional(),
+ placeholder: nonBlankString.optional(),
+ testId: nonBlankString.optional(),
+ exact: z.boolean().optional(),
+ index: z.number().int().nonnegative().optional(),
+ }).superRefine((query, ctx) => {
+ const hasLookupField = [
+ query.css,
+ query.role,
+ query.name,
+ query.text,
+ query.label,
+ query.placeholder,
+ query.testId,
+ ].some((value) => typeof value === 'string' && value !== '');
+ if (!hasLookupField) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'element query requires at least one lookup field',
+ });
+ }
+ if (deps.supportsSemanticQueries?.() === false) {
+ ctx.addIssue({
+ code: 'custom',
+ message: '当前浏览器后端不支持语义元素查询',
+ });
+ }
+ });
+}
+
// Server-enforced ceiling on a single tool result (~50k tokens). A huge page /
// `extract` (multiple, no limit) / network dump would otherwise blow the
// tool-result token budget with zero truncation — `responseBody.maxChars` and
@@ -167,6 +220,8 @@ function toRuntimeRequest(args: Record<string, unknown>): BrowserControlRequest
}
export function registerBrowserTools(registry: BrowserToolRegistry, deps: BrowserMcpDeps): void {
+ const actKind = actKindSchema(deps);
+ const elementQuery = elementQuerySchema(deps);
registry.register({
name: 'browser',
category: 'browser',
@@ -202,6 +257,9 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
level: z.string().optional(),
paths: z.array(z.string()).optional(),
inputRef: z.string().optional(),
+ query: elementQuery
+ .optional()
+ .describe('action=upload 时定位文件输入框;字段语义与 act.request.query 一致'),
timeoutMs: z.number().int().positive().optional(),
dialogId: z.string().optional(),
accept: z.boolean().optional(),
@@ -227,9 +285,15 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
.describe('action=saveRecipe: 可选,一并保存的站点指南对象(site/entry/recipes/notes…)'),
request: z
.object({
- kind: z.enum(ACT_KINDS),
+ kind: actKind,
targetId: z.string().optional(),
ref: z.string().optional(),
+ query: elementQuery
+ .optional()
+ .describe(
+ '语义元素查询,可组合 role/name/text/label/placeholder/testId/css;' +
+ '默认要求唯一匹配,多项结果时用 index 明确选择。',
+ ),
doubleClick: z.boolean().optional(),
button: z.string().optional(),
modifiers: z.array(z.string()).optional(),
@@ -248,7 +312,7 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
height: z.number().int().positive().optional(),
timeMs: z.number().int().nonnegative().optional(),
selector: z.string().optional(),
- url: z.string().optional(),
+ url: z.string().optional().describe('saveResource 时使用 snapshot(urls:true) 返回的资源 URL'),
loadState: z.string().optional(),
textGone: z.string().optional(),
timeoutMs: z.number().int().positive().optional(),
@@ -284,6 +348,29 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
);
}
}
+ if (
+ args.action === 'act'
+ && args.request?.kind === 'saveResource'
+ && deps.supportsResourceDownloads?.() === false
+ ) {
+ return errorResult(
+ args.action,
+ '当前浏览器后端不支持 saveResource,请使用内嵌浏览器后端',
+ );
+ }
+ if (
+ args.action === 'act'
+ && args.request?.kind === 'saveResource'
+ && (
+ typeof args.request.url !== 'string'
+ || !isPublicHttpResourceUrl(args.request.url)
+ )
+ ) {
+ return errorResult(
+ args.action,
+ 'saveResource.url 必须是 snapshot(urls:true) 返回的 http(s) 资源地址',
+ );
+ }
// recipe: run a declarative per-site flow (composition over primitives).
// Merged L1 (bundled) + L2 (user); user version shadows builtin by id.
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index 813770934a..b3477c64a5 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -465,6 +465,10 @@ export type ControlWorkerAgent = 'claude-code' | 'codex';
/** Browser automation MCP host deps. Core browser execution is injected by host. */
export interface BrowserMcpDeps {
getRuntime(): BrowserControlRuntime;
+ /** Whether the active backend accepts managed resource downloads. */
+ supportsResourceDownloads?(): boolean;
+ /** Whether the active backend accepts semantic element queries. */
+ supportsSemanticQueries?(): boolean;
logger?: LiziMcpLogger;
/**
* Optional L2 (user-local) recipe layer. The host scans userData, parses with