Skip to content

An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.

feat(page): trusted clicks through the debugger API

Shahriarf971312c9df0
diff --git a/lib/actions/page/trusted-click.ts b/lib/actions/page/trusted-click.ts
new file mode 100644
index 0000000..29f899b
--- /dev/null
+++ b/lib/actions/page/trusted-click.ts
@@ -0,0 +1,128 @@
+import { z } from 'zod';
+import { ActionError, defineAction } from '../core';
+import { cssPath, describeElement, resolveTarget, submitsOnClick, targetSchema } from './dom';
+
+const APPROACH_OFFSET = 120;
+
+function viewport(): { w: number; h: number } {
+ return { w: document.documentElement.clientWidth, h: document.documentElement.clientHeight };
+}
+
+function clickPoint(el: HTMLElement): { x: number; y: number } {
+ const rect = el.getBoundingClientRect();
+ const { w, h } = viewport();
+ const left = Math.max(rect.left, 0);
+ const top = Math.max(rect.top, 0);
+ const right = Math.min(rect.right, w);
+ const bottom = Math.min(rect.bottom, h);
+ if (right <= left || bottom <= top) {
+ throw new ActionError(
+ 'The element has no visible area inside the viewport — scroll it into view, then retry',
+ 'INVALID_TARGET',
+ );
+ }
+ return { x: Math.round((left + right) / 2), y: Math.round((top + bottom) / 2) };
+}
+
+function viewportPoint(point: { x: number; y: number }): { x: number; y: number } {
+ const { w, h } = viewport();
+ if (point.x < 0 || point.y < 0 || point.x >= w || point.y >= h) {
+ throw new ActionError(
+ `The point (${point.x}, ${point.y}) is outside the ${w}×${h} viewport — scroll it into view, then retry`,
+ 'INVALID_TARGET',
+ );
+ }
+ return { x: Math.round(point.x), y: Math.round(point.y) };
+}
+
+function approachPoint(to: { x: number; y: number }): { x: number; y: number } {
+ const { w, h } = viewport();
+ return {
+ x: Math.min(Math.max(to.x - APPROACH_OFFSET, 0), w - 1),
+ y: Math.min(Math.max(to.y - APPROACH_OFFSET, 0), h - 1),
+ };
+}
+
+export const trustedClick = defineAction({
+ name: 'page.trustedClick',
+ description:
+ 'Click with a real browser-level mouse event — isTrusted is true, exactly as if the user had clicked. The pointer travels to the target over a short path and dwells before pressing, so widgets that only react after genuine pointer movement (drag handles, hover menus, canvas tools, captcha checkboxes) see the sequence they wait for. Use it when page.clickElement was ignored: pages that check event.isTrusted, and the browser features only a genuine gesture unlocks — native file pickers, fullscreen, clipboard reads, popups, WebAuthn prompts. Give it either a "target" or a raw viewport "point". It attaches Chrome’s debugger for the duration, so the browser shows a “Browsentic is debugging this browser” bar while it runs, it cannot run on a tab that has DevTools open, and it is unavailable on Firefox. page.clickElement stays the default for ordinary clicks.',
+ input: z.object({
+ target: targetSchema.optional().describe('Element to click. Give this or "point", never both.'),
+ point: z
+ .object({
+ x: z.number().describe('Pixels from the left edge of the viewport'),
+ y: z.number().describe('Pixels from the top edge of the viewport'),
+ })
+ .optional()
+ .describe(
+ 'Exact viewport coordinates to click, in CSS pixels. Use this when the thing to click has no reachable element — inside a cross-origin iframe or a closed shadow root, as page.findCaptcha reports.',
+ ),
+ button: z.enum(['left', 'right', 'middle']).default('left').describe('Mouse button to press'),
+ clickCount: z
+ .number()
+ .int()
+ .min(1)
+ .max(3)
+ .default(1)
+ .describe('1 for a single click, 2 for a double click, 3 for a triple click'),
+ modifiers: z
+ .array(z.enum(['ctrl', 'shift', 'alt', 'meta']))
+ .default([])
+ .describe('Modifier keys held during the click, e.g. ["meta"] to open a link in a new tab'),
+ scrollIntoView: z.boolean().default(true).describe('Bring the element into view before clicking. Ignored with "point".'),
+ moveSteps: z
+ .number()
+ .int()
+ .min(1)
+ .max(60)
+ .default(8)
+ .describe('Pointer move events dispatched along the way in. Raise it for widgets that sample the path.'),
+ hoverMs: z
+ .number()
+ .int()
+ .min(0)
+ .max(2000)
+ .default(60)
+ .describe('Pause on the target after arriving, before pressing.'),
+ holdMs: z
+ .number()
+ .int()
+ .min(0)
+ .max(2000)
+ .default(50)
+ .describe('How long the button stays down between press and release.'),
+ }),
+ execute({ target, point, button, clickCount, modifiers, scrollIntoView, moveSteps, hoverMs, holdMs }) {
+ if (!target === !point) {
+ throw new ActionError('Give either a "target" to click or a "point" to click at — not both, not neither', 'INVALID_INPUT');
+ }
+
+ const el = target ? resolveTarget(target) : null;
+ if (el && scrollIntoView) el.scrollIntoView({ block: 'center', behavior: 'instant' });
+
+ const at = el ? clickPoint(el) : viewportPoint(point!);
+ const hit = document.elementFromPoint(at.x, at.y);
+ if (el && !(hit === el || el.contains(hit))) {
+ throw new ActionError(
+ hit
+ ? `${cssPath(hit)} covers the click point — dismiss whatever is over the element, then retry`
+ : 'Nothing is painted at the click point — scroll the element into view, then retry',
+ 'INVALID_TARGET',
+ );
+ }
+
+ return {
+ ...(el ? describeElement(el) : { over: hit ? cssPath(hit) : undefined }),
+ point: at,
+ from: approachPoint(at),
+ button,
+ clickCount,
+ modifiers,
+ moveSteps,
+ hoverMs,
+ holdMs,
+ submits: el ? submitsOnClick(el) : false,
+ };
+ },
+});
diff --git a/lib/bridge/cdp.ts b/lib/bridge/cdp.ts
new file mode 100644
index 0000000..3cc3dad
--- /dev/null
+++ b/lib/bridge/cdp.ts
@@ -0,0 +1,125 @@
+import { browser } from 'wxt/browser';
+import { failure, type ActionResult } from '@/lib/actions/protocol';
+
+export interface DebuggerSession {
+ tabId: number;
+ sessionId?: string;
+}
+
+interface AttachedTarget {
+ sessionId: string;
+ targetInfo: { url: string; type: string };
+}
+
+interface SessionDebugger {
+ attach: (target: DebuggerSession, version: string) => Promise<void>;
+ detach: (target: DebuggerSession) => Promise<void>;
+ sendCommand: (target: DebuggerSession, method: string, params?: object) => Promise<object | undefined>;
+ onEvent: {
+ addListener: (listener: (source: DebuggerSession, method: string, params?: object) => void) => void;
+ };
+}
+
+type EventListener = (source: DebuggerSession, method: string, params?: object) => void;
+
+const cdp = browser.debugger as unknown as SessionDebugger;
+
+const PROTOCOL_VERSION = '1.3';
+const INFOBAR_SETTLE_MS = 250;
+const ATTACH_SETTLE_MS = 150;
+const MAX_FRAME_DEPTH = 4;
+
+export const settle = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+const listeners = new Set<EventListener>();
+
+export function serveDebuggerEvents(): void {
+ if (import.meta.env.FIREFOX) return;
+ cdp.onEvent.addListener((source, method, params) => {
+ for (const listener of listeners) listener(source, method, params);
+ });
+}
+
+function onDebuggerEvent(listener: EventListener): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+export function send<T = unknown>(
+ session: DebuggerSession,
+ method: string,
+ params?: Record<string, unknown>,
+): Promise<T> {
+ return cdp.sendCommand(session, method, params) as Promise<T>;
+}
+
+export async function withDebugger(
+ tabId: number,
+ firefoxHint: string,
+ run: (session: DebuggerSession) => Promise<ActionResult>,
+): Promise<ActionResult> {
+ if (import.meta.env.FIREFOX) return failure('UNSUPPORTED', firefoxHint);
+
+ const session: DebuggerSession = { tabId };
+ try {
+ await cdp.attach(session, PROTOCOL_VERSION);
+ } catch (error) {
+ return failure('DEBUGGER_UNAVAILABLE', attachHint(error));
+ }
+ try {
+ await settle(INFOBAR_SETTLE_MS);
+ return await run(session);
+ } catch (error) {
+ return failure('ACTION_FAILED', error instanceof Error ? error.message : String(error));
+ } finally {
+ await send(session, 'Target.setAutoAttach', AUTO_ATTACH_OFF).catch(() => {});
+ await cdp.detach(session).catch(() => {});
+ }
+}
+
+export interface FrameSession {
+ sessionId: string;
+ url: string;
+ parent?: string;
+}
+
+const AUTO_ATTACH = {
+ autoAttach: true,
+ flatten: true,
+ waitForDebuggerOnStart: false,
+ filter: [{ type: 'iframe' }],
+};
+
+// Auto-attached child sessions outlive the root detach, and Chrome then stalls the next
+// attach on that tab instead of refusing it — a 30 s TIMEOUT rather than an error.
+const AUTO_ATTACH_OFF = { autoAttach: false, flatten: true, waitForDebuggerOnStart: false };
+
+export async function frameSessions(session: DebuggerSession): Promise<FrameSession[]> {
+ const found: FrameSession[] = [];
+ const stop = onDebuggerEvent((source, method, params) => {
+ if (method !== 'Target.attachedToTarget') return;
+ const attached = params as AttachedTarget;
+ if (attached?.targetInfo?.type !== 'iframe') return;
+ found.push({ sessionId: attached.sessionId, url: attached.targetInfo.url, parent: source.sessionId });
+ });
+
+ try {
+ let frontier = [session];
+ for (let depth = 0; depth < MAX_FRAME_DEPTH && frontier.length; depth += 1) {
+ const known = found.length;
+ for (const target of frontier) await send(target, 'Target.setAutoAttach', AUTO_ATTACH).catch(() => {});
+ await settle(ATTACH_SETTLE_MS);
+ frontier = found.slice(known).map(({ sessionId }) => ({ tabId: session.tabId, sessionId }));
+ }
+ } finally {
+ stop();
+ }
+ return found;
+}
+
+function attachHint(error: unknown): string {
+ const detail = error instanceof Error ? error.message : String(error);
+ return /already attached|another debugger/i.test(detail)
+ ? `${detail} — close DevTools for this tab, then retry.`
+ : `${detail} — Chrome’s debugger could not attach to this tab.`;
+}
diff --git a/lib/bridge/trusted-input.ts b/lib/bridge/trusted-input.ts
new file mode 100644
index 0000000..ab0ac96
--- /dev/null
+++ b/lib/bridge/trusted-input.ts
@@ -0,0 +1,76 @@
+import { invokeInTab } from '@/lib/actions/client';
+import { trustedClick } from '@/lib/actions/page/trusted-click';
+import { success, type ActionResult } from '@/lib/actions/protocol';
+import { send, settle, withDebugger, type DebuggerSession } from './cdp';
+
+const MODIFIER_BIT: Record<string, number> = { alt: 1, ctrl: 2, meta: 4, shift: 8 };
+const BUTTON_BIT: Record<string, number> = { left: 1, right: 2, middle: 4 };
+
+const MOVE_INTERVAL_MS = 12;
+const MAX_DRIFT_PX = 6;
+
+export interface Point {
+ x: number;
+ y: number;
+}
+
+export interface ClickPlan {
+ point: Point;
+ from: Point;
+ button: 'left' | 'right' | 'middle';
+ clickCount: number;
+ modifiers: string[];
+ moveSteps: number;
+ hoverMs: number;
+ holdMs: number;
+}
+
+const FIREFOX_HINT =
+ 'A trusted click needs Chrome’s debugger, which Firefox does not expose — use page.clickElement instead.';
+
+export function trustedClickInTab(tabId: number, input: unknown): Promise<ActionResult> {
+ return withDebugger(tabId, FIREFOX_HINT, async (session) => {
+ const planned = await invokeInTab(tabId, trustedClick.name, input);
+ if (!planned.ok) return planned;
+ await dispatchClick(session, planned.data as ClickPlan);
+ return success({ ...(planned.data as object), trusted: true });
+ });
+}
+
+const easeOut = (progress: number) => 1 - (1 - progress) ** 3;
+
+function pathBetween(from: Point, to: Point, steps: number): Point[] {
+ const dx = to.x - from.x;
+ const dy = to.y - from.y;
+ const span = Math.hypot(dx, dy) || 1;
+ const drift = Math.min(MAX_DRIFT_PX, span / 8);
+ return Array.from({ length: steps }, (_, index) => {
+ const progress = easeOut((index + 1) / steps);
+ const wobble = Math.sin(progress * Math.PI) * drift * (index % 2 ? -1 : 1);
+ return {
+ x: Math.round(from.x + dx * progress - (dy / span) * wobble),
+ y: Math.round(from.y + dy * progress + (dx / span) * wobble),
+ };
+ });
+}
+
+export async function dispatchClick(session: DebuggerSession, plan: ClickPlan): Promise<void> {
+ const { point, from, button, clickCount, modifiers, moveSteps, hoverMs, holdMs } = plan;
+ const held = modifiers.reduce((mask, name) => mask | (MODIFIER_BIT[name] ?? 0), 0);
+ const base = { modifiers: held, pointerType: 'mouse' };
+ const dispatch = (params: Record<string, unknown>) => send(session, 'Input.dispatchMouseEvent', params);
+ const moveTo = (at: Point) => dispatch({ ...base, ...at, type: 'mouseMoved', button: 'none', buttons: 0 });
+
+ await moveTo(from);
+ for (const at of pathBetween(from, point, moveSteps)) {
+ await settle(MOVE_INTERVAL_MS);
+ await moveTo(at);
+ }
+ await settle(hoverMs);
+
+ for (let count = 1; count <= clickCount; count += 1) {
+ await dispatch({ ...base, ...point, type: 'mousePressed', button, buttons: BUTTON_BIT[button], clickCount: count });
+ await settle(holdMs);
+ await dispatch({ ...base, ...point, type: 'mouseReleased', button, buttons: 0, clickCount: count });
+ }
+}