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.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(frames): step into an iframe and let every page tool, site tool and live tool follow
Shahriar7dde44882350
diff --git a/README.md b/README.mdindex f65ae7e..61f6bd1 100644--- a/README.md+++ b/README.md@@ -14,7 +14,7 @@ Hand your real, logged-in browser to the AI agent you already run. Browsentic is- **Your Real Browser, Not a Headless One**: Drives the tab in front of you, in your own profile, with your own logins and sessions- **Bring Your Own Agent**: Runs on the agent CLI you already pay for and are already signed in to — switch between Claude Code, Codex and Antigravity with one click, and pick the model each one runs-- **51 Page Capabilities**: Reading, clicking, typing, dragging, on-site search, form submission, navigation, screenshots, file upload and download, captchas, theming and accessibility, console and network diagnostics, background progress monitoring, scheduled and repeating jobs, pointing at an element, and calling the tools a WebMCP site registers for agents+- **52 Page Capabilities**: Reading, clicking, typing, dragging, on-site search, form submission, navigation, stepping into iframes, screenshots, file upload and download, captchas, theming and accessibility, console and network diagnostics, background progress monitoring, scheduled and repeating jobs, pointing at an element, and calling the tools a WebMCP site registers for agents- **Live Tools, Off By Default**: For work that repeats twenty times or needs something no tool covers, flip the **Live tool** switch and the agent may write a small script for the page — you read the code in the panel and approve it before a line of it runs- **Keep What It Wrote**: A script that worked can be kept as a tool of your own, named after the site it belongs to (`youtube.com:watch:darken-page-except-video-player`) and run later by typing `/`. The code stays in the browser; no MCP client can reach it- **Voice, Text, or Demonstration**: Dictate in the side panel, type anywhere, or record yourself doing a job once and later say "do it like last time"diff --git a/src/daemon/agent/mapping.ts b/src/daemon/agent/mapping.tsindex c7bf5d2..f3e5f84 100644--- a/src/daemon/agent/mapping.ts+++ b/src/daemon/agent/mapping.ts@@ -31,6 +31,7 @@ const READ_ONLY_ACTIONS = new Set(['page.findSearch','page.findCaptcha','page.listSiteTools',+ 'page.switchFrame','page.monitorStatus','page.timerStatus','page.readTheme',diff --git a/src/daemon/skills/browser-control.md b/src/daemon/skills/browser-control.mdindex e8edcdc..9c0b853 100644--- a/src/daemon/skills/browser-control.md+++ b/src/daemon/skills/browser-control.md@@ -130,6 +130,14 @@ The result also carries `downloadId`, and `page_attachFile { downloadId, targetExpect a confirm prompt — writing a file to someone's disk is gated the same way uploading one is. Four refusals are final and none of them is worth routing around: an executable (`DOWNLOAD_REFUSED`), anything over 100 MB (`DOWNLOAD_TOO_LARGE`), a file from a host this run was not about (`DOWNLOAD_OFF_SCOPE`), and a click that downloaded nothing (`NO_DOWNLOAD_STARTED` — it probably opened a page instead, so check where the tab landed). Say what happened and stop.-## 11. Multi-step tasks+## 11. Frames — when the thing is inside an iframe++`page_getPageInfo` sees one document at a time. Visible iframes come back under `frames` with a selector, and nothing inside them is in the snapshot: a form, a button or a piece of text that is plainly on screen but missing from the inventory is usually inside one.++`page_switchFrame { frame: { selector } }` steps into it. From then on every tool acts inside that frame as if it were the page — snapshot, click, fill, wait, `page_listSiteTools`, `page_callSiteTool`, `page_injectCode` and `page_runCode` — and each snapshot carries a `frame` block naming where you are. Call it again from inside to go deeper. `page_switchFrame {}` returns to the top document and `{ to: "parent" }` steps out one level; any navigation puts you back at the top on its own. `page_screenshot` and `page_navigate` always work on the whole tab, wherever you are.++`FRAME_UNREACHABLE` means the frame cannot run scripts, most often a sandbox without `allow-scripts`. Do not retry it: a screenshot still shows what is there, and `page_trustedClick` with a `point` still reaches it.++## 12. Multi-step tasksDo the whole task, not the first step of it. If the user says "search for X and open the first result", that is a fill, a submit, a wait, a snapshot, and a click — finish all of it, then report once at the end. Stop early only when you are blocked on something the user must decide.diff --git a/src/extension/entrypoints/background.ts b/src/extension/entrypoints/background.tsindex da7ecd6..90389c6 100644--- a/src/extension/entrypoints/background.ts+++ b/src/extension/entrypoints/background.ts@@ -5,6 +5,7 @@ import { invokeForHarness } from '@/lib/bridge/invoke';import { serveDebuggerEvents } from '@/lib/bridge/cdp';import { serveCodeToolkits } from '@/lib/bridge/code-toolkit';import { serveDiagnostics } from '@/lib/bridge/diagnostics';+import { serveFrameFocus } from '@/lib/bridge/frame-focus';import { analyzeStoredFile } from '@/lib/bridge/file-store';import { pushSkill, removeSkill, resyncSkills } from '@/lib/bridge/skill-store';import { nameStoredSession } from '@/lib/bridge/session-store';@@ -202,6 +203,7 @@ export default defineBackground(() => {});serveDiagnostics();+ serveFrameFocus();serveCodeToolkits();serveRecorder();serveMonitor();diff --git a/src/extension/entrypoints/content.ts b/src/extension/entrypoints/content.tsindex 85fe0fc..7b44fde 100644--- a/src/extension/entrypoints/content.ts+++ b/src/extension/entrypoints/content.ts@@ -1,4 +1,5 @@import { exposeActions } from '@/lib/actions/host';+import { exposeFrameProbe } from '@/lib/frames/host';import { exposeIndicator } from '@/lib/indicator/host';import { exposeMonitor } from '@/lib/monitor/watch';import { exposeRail } from '@/lib/rail/host';@@ -12,6 +13,8 @@ export default defineContentScript({if (world.__browsenticActions) return;world.__browsenticActions = true;exposeActions();+ exposeFrameProbe();+ if (window !== window.top) return;exposeRecorder();exposeMonitor();exposeIndicator();diff --git a/src/lib/actions/client.ts b/src/lib/actions/client.tsindex 3af4a88..9a96e0d 100644--- a/src/lib/actions/client.ts+++ b/src/lib/actions/client.ts@@ -1,6 +1,7 @@import { browser } from 'wxt/browser';import type { ScriptPublicPath } from 'wxt/utils/inject-script';import type { z } from 'zod';+import { focusedFrame, FRAME_GONE_HINT, TOP_FRAME } from '@/lib/bridge/frame-focus';import type { Action } from './core';import { ACTION_CHANNEL, failure, type ActionResult } from './protocol';@@ -14,17 +15,31 @@ export async function invokeInTab<I extends z.ZodType = z.ZodType, O = unknown>(tabId: number,action: Action<I, O> | string,...[input]: InputArgs<I>+): Promise<ActionResult<O>> {+ return invokeInFrame(tabId, await focusedFrame(tabId), action, ...([input] as InputArgs<I>));+}++export async function invokeInFrame<I extends z.ZodType = z.ZodType, O = unknown>(+ tabId: number,+ frameId: number,+ action: Action<I, O> | string,+ ...[input]: InputArgs<I>): Promise<ActionResult<O>> {const name = typeof action === 'string' ? action : action.name;const send = async () =>- (await browser.tabs.sendMessage(tabId, { channel: ACTION_CHANNEL, action: name, input })) as ActionResult<O>;+ (await browser.tabs.sendMessage(tabId, { channel: ACTION_CHANNEL, action: name, input }, { frameId })) as ActionResult<O>;+ const unreachable = (detail: string): ActionResult<never> =>+ failure(+ 'TAB_UNREACHABLE',+ frameId === TOP_FRAME ? `${detail} — the page may not allow content scripts` : `${detail} — ${FRAME_GONE_HINT}`,+ );try {return await send();} catch (error) {const message = error instanceof Error ? error.message : String(error);if (!message.includes(NO_RECEIVER)) return unreachable(message);- if (!(await injectContentScript(tabId))) return unreachable(message);+ if (!(await injectContentScript(tabId, frameId))) return unreachable(message);if (!RETRY_AFTER_HEAL.has(name)) {return failure('TAB_UNREACHABLE',@@ -52,13 +67,15 @@ export async function invokeInActiveTab<I extends z.ZodType = z.ZodType, O = unkconst INJECT_TIMEOUT_MS = 5_000;-export async function injectContentScript(tabId: number): Promise<boolean> {+export async function injectContentScript(tabId: number, frameId = TOP_FRAME): Promise<boolean> {const files = (browser.runtime.getManifest().content_scripts ?? []).flatMap((script) => script.js ?? [],) as ScriptPublicPath[];if (!files.length) return false;try {- await withTimeout(browser.scripting.executeScript({ target: { tabId }, files, injectImmediately: true }));+ await withTimeout(+ browser.scripting.executeScript({ target: { tabId, frameIds: [frameId] }, files, injectImmediately: true }),+ );return true;} catch {return false;@@ -71,6 +88,3 @@ function withTimeout<T>(promise: Promise<T>): Promise<T> {new Promise<never>((_, reject) => setTimeout(() => reject(new Error('injection timed out')), INJECT_TIMEOUT_MS)),]);}--const unreachable = (detail: string): ActionResult<never> =>- failure('TAB_UNREACHABLE', `${detail} — the page may not allow content scripts`);diff --git a/src/lib/actions/page/get-page-info.ts b/src/lib/actions/page/get-page-info.tsindex 8c68563..b9917f8 100644--- a/src/lib/actions/page/get-page-info.ts+++ b/src/lib/actions/page/get-page-info.ts@@ -1,6 +1,7 @@import { z } from 'zod';import { defineAction } from '../core';import { accessibleText, cssPath, describeElement, documentBounds, isExposed } from './dom';+import { isFrameElement, sandboxOf } from './switch-frame';interface Tally {links: number;@@ -43,7 +44,7 @@ const LANDMARK_ROLES = new Set([export const getPageInfo = defineAction({name: 'page.getPageInfo',description:- 'Snapshot the current page: document metadata, viewport and scroll state, a semantic layout tree with a text diagram, the heading outline, and an inventory of interactive elements — each carrying its ARIA role, its live state (disabled, checked, expanded, filled, aria-current) and the landmark region it sits in. When the site registers WebMCP tools, the result also carries a siteTools list — prefer page.callSiteTool over clicking wherever a listed tool covers the step.',+ 'Snapshot the current page: document metadata, viewport and scroll state, a semantic layout tree with a text diagram, the heading outline, and an inventory of interactive elements — each carrying its ARIA role, its live state (disabled, checked, expanded, filled, aria-current) and the landmark region it sits in. When the site registers WebMCP tools, the result also carries a siteTools list — prefer page.callSiteTool over clicking wherever a listed tool covers the step. Visible iframes come back under "frames"; nothing inside one is in this snapshot until page.switchFrame enters it, and "frame" then says which one is in focus.',input: z.object({maxPerKind: z.number()@@ -82,10 +83,29 @@ export const getPageInfo = defineAction({text: accessibleText(heading).slice(0, 120),})),interactive: inventory(found, owners, maxPerKind),+ frames: embeddedFrames(),};},});+const MAX_FRAMES = 20;++function embeddedFrames() {+ const frames = [...document.querySelectorAll('iframe,frame')]+ .filter(isFrameElement)+ .filter(isExposed)+ .slice(0, MAX_FRAMES)+ .map((frame) => ({+ selector: cssPath(frame),+ src: frame.src || undefined,+ name: frame.name || undefined,+ title: frame.title || undefined,+ sandbox: sandboxOf(frame),+ bounds: documentBounds(frame),+ }));+ return frames.length ? frames : undefined;+}+function regionRole(el: HTMLElement): string | undefined {const explicit = el.getAttribute('role');if (explicit) return LANDMARK_ROLES.has(explicit) ? explicit : undefined;diff --git a/src/lib/actions/page/switch-frame.ts b/src/lib/actions/page/switch-frame.tsnew file mode 100644index 0000000..498a9ad--- /dev/null+++ b/src/lib/actions/page/switch-frame.ts@@ -0,0 +1,65 @@+import { z } from 'zod';+import { ActionError, defineAction } from '../core';+import { cssPath, describeElement, resolveTarget, targetSchema } from './dom';++export type FrameElement = HTMLIFrameElement | HTMLFrameElement;++interface FrameRuntime {+ runtime?: { getFrameId?: (target: unknown) => number };+}++export const switchFrame = defineAction({+ name: 'page.switchFrame',+ description:+ 'Step into an <iframe> so that every later page action — reading, clicking, typing, waiting, site tools, injected code — runs inside it as if it were the page, or step back out. page.getPageInfo lists the frames the current document embeds under "frames"; pass one as "frame" to enter it, and call again from inside to go deeper. Call it with no arguments to return to the top document, or with to: "parent" to step out one level. The focus is per tab, clears when the tab navigates, and page.getPageInfo reports it under "frame" whenever it is not the top. A frame that forbids scripts (a sandbox without allow-scripts) or a browser-internal frame cannot be entered; page.screenshot and page.trustedClick by coordinates still reach those. page.screenshot and page.navigate always act on the whole tab.',+ input: z.object({+ frame: targetSchema+ .optional()+ .describe(+ 'The <iframe> or <frame> element to enter, matched inside the frame currently in focus — use a selector from the "frames" list of page.getPageInfo. Omit it to leave instead.',+ ),+ to: z+ .enum(['top', 'parent'])+ .default('top')+ .describe('Where to go when no "frame" is given: "top" returns to the main document, "parent" steps out one level.'),+ }),+ execute({ frame }) {+ if (!frame) {+ throw new ActionError('Leaving a frame is resolved by the Browsentic extension, not in the page', 'UNSUPPORTED');+ }+ const el = resolveTarget(frame);+ if (!isFrameElement(el)) {+ throw new ActionError(+ `${cssPath(el)} is a <${el.tagName.toLowerCase()}>, not an <iframe> — pick one of the frames page.getPageInfo lists`,+ 'INVALID_TARGET',+ );+ }+ return {+ frameId: frameIdOf(el),+ src: el.src || undefined,+ name: el.name || undefined,+ sandbox: sandboxOf(el),+ ...describeElement(el),+ };+ },+});++export function isFrameElement(el: Element): el is FrameElement {+ return el instanceof HTMLIFrameElement || el instanceof HTMLFrameElement;+}++export function sandboxOf(el: FrameElement): string | undefined {+ return el instanceof HTMLIFrameElement && el.hasAttribute('sandbox') ? el.sandbox.value || 'all restrictions' : undefined;+}++export function frameIdOf(target: unknown): number {+ const scope = globalThis as { browser?: FrameRuntime; chrome?: FrameRuntime };+ const id = (scope.browser?.runtime?.getFrameId ?? scope.chrome?.runtime?.getFrameId)?.(target);+ if (typeof id !== 'number' || id < 0) {+ throw new ActionError(+ 'This browser cannot identify frames from the page — entering a frame needs Chrome 116 or Firefox 96 or newer',+ 'UNSUPPORTED',+ );+ }+ return id;+}diff --git a/src/lib/actions/registry.ts b/src/lib/actions/registry.tsindex 6c80156..17b796d 100644--- a/src/lib/actions/registry.ts+++ b/src/lib/actions/registry.ts@@ -47,6 +47,7 @@ import { stopDiagnostics } from './page/stop-diagnostics';import { stopMonitor } from './page/stop-monitor';import { stopTimer } from './page/stop-timer';import { submitForm } from './page/submit-form';+import { switchFrame } from './page/switch-frame';import { switchTab } from './page/switch-tab';import { timerStatus } from './page/timer-status';import { trustedClick } from './page/trusted-click';@@ -99,6 +100,7 @@ export const actions: ReadonlyMap<string, AnyAction> = new Map(navigate,openTab,switchTab,+ switchFrame,closeTab,screenshot,listFiles,diff --git a/src/lib/bridge/code-toolkit.ts b/src/lib/bridge/code-toolkit.tsindex 8e9d425..b924148 100644--- a/src/lib/bridge/code-toolkit.ts+++ b/src/lib/bridge/code-toolkit.ts@@ -17,7 +17,8 @@ import { runCode } from '@/lib/actions/page/run-code';import { installerSource, TOOLKIT_MISSING, type ToolkitEntry } from '@/lib/actions/page/toolkit';import { failure, success, type ActionResult } from '@/lib/actions/protocol';import { scopeOf, slugFromPurpose } from '@/lib/skills/saved-tool';-import { send, withDebugger, type DebuggerSession } from './cdp';+import { send, withDebugger } from './cdp';+import { mainWorldOf, type FrameContext } from './frame-context';import { getSavedTool, scopeMatches } from './saved-tools';const TOOLKITS_KEY = 'browsentic/codeToolkits';@@ -27,6 +28,9 @@ const FIREFOX_HINT =const MAX_ERROR_LENGTH = 600;+const FRAME_CONTEXT_HINT =+ 'Chrome’s debugger found no script context for the frame in focus — call page.switchFrame with no arguments and inject from the top document, or enter the frame again once it has loaded.';+interface StoredToolkit {id: string;origin: string;@@ -243,7 +247,9 @@ export async function runToolkit(tabId: number, url: string | undefined, input:function evaluateInstaller(tabId: number, toolkit: StoredToolkit): Promise<ActionResult> {return withDebugger(tabId, FIREFOX_HINT, async (session) => {- const reply = await evaluate(session, installerSource(toolkit.id, toolkit.code));+ const context = await mainWorldOf(session);+ if (!context) return failure('FRAME_UNREACHABLE', FRAME_CONTEXT_HINT);+ const reply = await evaluate(context, installerSource(toolkit.id, toolkit.code));const thrown = reply.exceptionDetails;if (thrown) {return failure('CODE_ERROR', `The code failed while installing: ${describeThrow(thrown)}`);@@ -256,11 +262,12 @@ function evaluateInstaller(tabId: number, toolkit: StoredToolkit): Promise<Actio});}-function evaluate(session: DebuggerSession, expression: string): Promise<EvaluateReply> {+function evaluate({ session, contextId }: FrameContext, expression: string): Promise<EvaluateReply> {return send<EvaluateReply>(session, 'Runtime.evaluate', {expression,returnByValue: true,awaitPromise: true,+ ...(contextId == null ? {} : { contextId }),});}diff --git a/src/lib/bridge/frame-context.ts b/src/lib/bridge/frame-context.tsnew file mode 100644index 0000000..49d9325--- /dev/null+++ b/src/lib/bridge/frame-context.ts@@ -0,0 +1,72 @@+import { FRAME_MARK_ATTRIBUTE } from '@/lib/frames/events';+import { frameSessions, onDebuggerEvent, send, settle, type DebuggerSession } from './cdp';+import { focusedFrame, markFrame, TOP_FRAME, unmarkFrame } from './frame-focus';++export interface FrameContext {+ session: DebuggerSession;+ contextId?: number;+}++interface ContextCreated {+ context?: { id: number; auxData?: { isDefault?: boolean } };+}++interface ValueReply {+ result?: { value?: unknown };+}++const CONTEXTS_SETTLE_MS = 50;++/**+ * The main world of the frame in focus, addressed for `Runtime.evaluate`. The top frame is+ * the session itself. A child frame is found by marking its document from the isolated+ * world and reading the mark back from each candidate context: same-process frames share+ * the root session, out-of-process ones arrive as auto-attached child sessions.+ */+export async function mainWorldOf(session: DebuggerSession): Promise<FrameContext | null> {+ const frameId = await focusedFrame(session.tabId);+ if (frameId === TOP_FRAME) return { session };++ const token = crypto.randomUUID();+ if (!(await markFrame(session.tabId, frameId, token))) return null;+ try {+ const children = (await frameSessions(session)).map(({ sessionId }) => ({ tabId: session.tabId, sessionId }));+ for (const candidate of [session, ...children]) {+ for (const contextId of await defaultContexts(candidate)) {+ if ((await markIn(candidate, contextId)) === token) return { session: candidate, contextId };+ }+ }+ return null;+ } finally {+ void unmarkFrame(session.tabId, frameId);+ }+}++async function defaultContexts(session: DebuggerSession): Promise<number[]> {+ const found: number[] = [];+ const stop = onDebuggerEvent((source, method, params) => {+ if (method !== 'Runtime.executionContextCreated') return;+ if (source.tabId !== session.tabId || source.sessionId !== session.sessionId) return;+ const context = (params as ContextCreated).context;+ if (context?.auxData?.isDefault) found.push(context.id);+ });+ try {+ await send(session, 'Runtime.enable');+ await settle(CONTEXTS_SETTLE_MS);+ } catch {+ return [];+ } finally {+ stop();+ await send(session, 'Runtime.disable').catch(() => {});+ }+ return found;+}++async function markIn(session: DebuggerSession, contextId: number): Promise<unknown> {+ const reply = await send<ValueReply>(session, 'Runtime.evaluate', {+ expression: `document.documentElement.getAttribute(${JSON.stringify(FRAME_MARK_ATTRIBUTE)})`,+ returnByValue: true,+ contextId,+ }).catch(() => null);+ return reply?.result?.value;+}diff --git a/src/lib/bridge/frame-focus.ts b/src/lib/bridge/frame-focus.tsnew file mode 100644index 0000000..ae36fd5--- /dev/null+++ b/src/lib/bridge/frame-focus.ts@@ -0,0 +1,93 @@+import { browser } from 'wxt/browser';+import { FRAME_CHANNEL, type FrameDescription, type FrameOrigin, type FrameProbeBody } from '@/lib/frames/events';++export const FRAME_FOCUS_KEY = 'browsentic/frameFocus';++export const TOP_FRAME = 0;++export interface FrameStep {+ frameId: number;+ url: string;+ selector: string;+}++type FocusMap = Record<string, FrameStep[]>;++let cache: FocusMap | null = null;++async function readFocus(): Promise<FocusMap> {+ if (cache) return cache;+ const stored = await browser.storage.session.get(FRAME_FOCUS_KEY);+ cache = (stored[FRAME_FOCUS_KEY] as FocusMap | undefined) ?? {};+ return cache;+}++async function writeFocus(next: FocusMap): Promise<void> {+ cache = next;+ await browser.storage.session.set({ [FRAME_FOCUS_KEY]: next });+}++export async function framePath(tabId: number): Promise<FrameStep[]> {+ return (await readFocus())[String(tabId)] ?? [];+}++export async function focusedFrame(tabId: number): Promise<number> {+ return (await framePath(tabId)).at(-1)?.frameId ?? TOP_FRAME;+}++export async function focusedUrl(tabId: number, fallback?: string): Promise<string | undefined> {+ return (await framePath(tabId)).at(-1)?.url ?? fallback;+}++export async function setFramePath(tabId: number, path: FrameStep[]): Promise<void> {+ const { [String(tabId)]: _previous, ...rest } = await readFocus();+ await writeFocus(path.length ? { ...rest, [String(tabId)]: path } : rest);+}++export function forgetFrameFocus(tabId: number): Promise<void> {+ return setFramePath(tabId, []);+}++export function serveFrameFocus(): void {+ browser.tabs.onRemoved.addListener((tabId) => void forgetFrameFocus(tabId));+ browser.tabs.onUpdated.addListener((tabId, change) => {+ if (change.status === 'loading') void forgetFrameFocus(tabId);+ });+}++async function probe<T>(tabId: number, frameId: number, message: FrameProbeBody): Promise<T | null> {+ try {+ const reply = await browser.tabs.sendMessage(tabId, { channel: FRAME_CHANNEL, ...message }, { frameId });+ return (reply as T | undefined) ?? null;+ } catch {+ return null;+ }+}++export const describeFrame = (tabId: number, frameId: number) =>+ probe<FrameDescription>(tabId, frameId, { op: 'describe' });++export const markFrame = (tabId: number, frameId: number, token: string) =>+ probe<{ ok: true }>(tabId, frameId, { op: 'mark', token });++export const unmarkFrame = (tabId: number, frameId: number) => probe<{ ok: true }>(tabId, frameId, { op: 'unmark' });++const locateFrame = (tabId: number, parent: number, frameId: number) =>+ probe<FrameOrigin>(tabId, parent, { op: 'locate', frameId });++/** Where the focused frame's viewport origin sits in the tab's viewport, in CSS pixels. */+export async function frameOffset(tabId: number): Promise<FrameOrigin | null> {+ const path = await framePath(tabId);+ let origin: FrameOrigin = { x: 0, y: 0 };+ let parent = TOP_FRAME;+ for (const { frameId } of path) {+ const child = await locateFrame(tabId, parent, frameId);+ if (!child) return null;+ origin = { x: origin.x + child.x, y: origin.y + child.y };+ parent = frameId;+ }+ return origin;+}++export const FRAME_GONE_HINT =+ 'the frame in focus is gone or blocks scripts — call page.switchFrame with no arguments to return to the top document';diff --git a/src/lib/bridge/frames.ts b/src/lib/bridge/frames.tsnew file mode 100644index 0000000..7b4480d--- /dev/null+++ b/src/lib/bridge/frames.ts@@ -0,0 +1,64 @@+import { z } from 'zod';+import { injectContentScript, invokeInTab } from '@/lib/actions/client';+import { switchFrame } from '@/lib/actions/page/switch-frame';+import { failure, success, type ActionResult } from '@/lib/actions/protocol';+import { describeFrame, framePath, setFramePath, TOP_FRAME, type FrameStep } from './frame-focus';++interface EnteredFrame {+ frameId: number;+ selector: string;+ src?: string;+ name?: string;+ sandbox?: string;+}++export async function switchFrameInTab(tabId: number, topUrl: string | undefined, input: unknown): Promise<ActionResult> {+ const parsed = switchFrame.input.safeParse(input ?? {});+ if (!parsed.success) return failure('INVALID_INPUT', z.prettifyError(parsed.error));++ const path = await framePath(tabId);+ if (!parsed.data.frame) {+ const left = parsed.data.to === 'top' ? [] : path.slice(0, -1);+ await setFramePath(tabId, left);+ return success(focusOf(left, topUrl));+ }++ const planned = await invokeInTab(tabId, switchFrame.name, parsed.data);+ if (!planned.ok) return planned;+ const entered = planned.data as EnteredFrame;++ const reached = await reachFrame(tabId, entered.frameId);+ if (!reached) {+ return failure(+ 'FRAME_UNREACHABLE',+ `${entered.selector} cannot be entered — ${+ entered.sandbox && !entered.sandbox.includes('allow-scripts')+ ? 'its sandbox forbids scripts'+ : 'it is a browser-internal frame or has not loaded'+ }. page.screenshot still shows it and page.trustedClick with a "point" still reaches it.`,+ );+ }++ const next = [...path, { frameId: entered.frameId, url: reached.url, selector: entered.selector }];+ await setFramePath(tabId, next);+ return success({ entered: planned.data, ...focusOf(next, topUrl) });+}++async function reachFrame(tabId: number, frameId: number) {+ const described = await describeFrame(tabId, frameId);+ if (described) return described;+ if (!(await injectContentScript(tabId, frameId))) return null;+ return describeFrame(tabId, frameId);+}++export function focusOf(path: FrameStep[], topUrl: string | undefined) {+ const current = path.at(-1);+ return {+ frame: {+ depth: path.length,+ frameId: current?.frameId ?? TOP_FRAME,+ url: current?.url ?? topUrl,+ path: path.map(({ selector, url }) => ({ selector, url })),+ },+ };+}diff --git a/src/lib/bridge/invoke.ts b/src/lib/bridge/invoke.tsindex 45bfbc0..0d2eb5e 100644--- a/src/lib/bridge/invoke.ts+++ b/src/lib/bridge/invoke.ts@@ -1,6 +1,6 @@import { browser } from 'wxt/browser';import { z } from 'zod';-import { invokeInTab } from '@/lib/actions/client';+import { invokeInFrame, invokeInTab } from '@/lib/actions/client';import { ActionError } from '@/lib/actions/core';import { attachFile } from '@/lib/actions/page/attach-file';import { awaitMonitor } from '@/lib/actions/page/await-monitor';@@ -31,6 +31,7 @@ import { startTimer } from '@/lib/actions/page/start-timer';import { stopDiagnostics } from '@/lib/actions/page/stop-diagnostics';import { stopMonitor } from '@/lib/actions/page/stop-monitor';import { stopTimer } from '@/lib/actions/page/stop-timer';+import { switchFrame } from '@/lib/actions/page/switch-frame';import { switchTab } from '@/lib/actions/page/switch-tab';import { timerStatus } from '@/lib/actions/page/timer-status';import { trustedClick } from '@/lib/actions/page/trusted-click';@@ -41,6 +42,8 @@ import { findCaptchaInTab, solveCaptchaInTab } from '@/lib/bridge/captcha';import { installToolkit, runToolkit } from '@/lib/bridge/code-toolkit';import { callSiteToolInTab, listSiteToolsInTab, pageInfoWithSiteTools } from '@/lib/bridge/site-tools';import { captureFromPage } from '@/lib/bridge/downloads';+import { focusedUrl, forgetFrameFocus, TOP_FRAME } from '@/lib/bridge/frame-focus';+import { switchFrameInTab } from '@/lib/bridge/frames';import { listMeta, readBytes } from '@/lib/bridge/file-store';import {readConsoleFor,@@ -83,7 +86,8 @@ export async function invokeForHarness(async function targetOrigin(tabId?: number, runId?: string): Promise<string | undefined> {const owner = runId ? await sessionForRun(runId) : null;const tab = await resolveTab(tabId, owner);- return tab?.url ? hostOf(tab.url) : undefined;+ const url = tab?.id != null ? await focusedUrl(tab.id, tab.url) : tab?.url;+ return url ? hostOf(url) : undefined;}function hostOf(url: string): string | undefined {@@ -130,16 +134,17 @@ async function dispatch(if (action === navigate.name) return navigateTab(tab.id, input);if (action === searchSite.name) return searchTab(tab.id, input);if (action === switchTab.name) return switchSessionTab({ id: tab.id, windowId: tab.windowId }, input, owner);+ if (action === switchFrame.name) return switchFrameInTab(tab.id, tab.url, input);if (action === closeTab.name) return closeOpenTab({ id: tab.id, windowId: tab.windowId }, input);if (action === screenshot.name) return screenshotTab({ id: tab.id, windowId: tab.windowId }, input, runId);if (action === pickElement.name) return pickInTab({ id: tab.id, windowId: tab.windowId }, input);if (action === attachFile.name) return attachStoredFile(tab.id, input);if (action === captureDownload.name) return captureFromPage(tab.id, input);- if (action === injectCode.name) return installToolkit(tab.id, tab.url, input);- if (action === runCode.name) return runToolkit(tab.id, tab.url, input);- if (action === getPageInfo.name) return pageInfoWithSiteTools(tab.id, input);- if (action === listSiteTools.name) return listSiteToolsInTab(tab.id, tab.url);- if (action === callSiteTool.name) return callSiteToolInTab(tab.id, tab.url, input);+ if (action === injectCode.name) return installToolkit(tab.id, await focusedUrl(tab.id, tab.url), input);+ if (action === runCode.name) return runToolkit(tab.id, await focusedUrl(tab.id, tab.url), input);+ if (action === getPageInfo.name) return pageInfoWithSiteTools(tab.id, tab.url, input);+ if (action === listSiteTools.name) return listSiteToolsInTab(tab.id, await focusedUrl(tab.id, tab.url));+ if (action === callSiteTool.name) return callSiteToolInTab(tab.id, await focusedUrl(tab.id, tab.url), input);if (action === trustedClick.name) return trustedClickInTab(tab.id, input);if (action === dragElement.name && isTrustedDrag(input)) return dragInTab(tab.id, input);if (action === findCaptcha.name) return findCaptchaInTab(tab.id);@@ -358,7 +363,8 @@ async function attachStoredFile(tabId: number, input: unknown): Promise<ActionReconst NO_CONTENT_SCRIPT = 'Receiving end does not exist';async function navigateTab(tabId: number, input: unknown): Promise<ActionResult> {- const inPage = await invokeInTab(tabId, navigate.name, input);+ await forgetFrameFocus(tabId);+ const inPage = await invokeInFrame(tabId, TOP_FRAME, navigate.name, input);if (inPage.ok) {return success({ ...(inPage.data as object), loaded: await watchForLoad(tabId).settled });}diff --git a/src/lib/bridge/pick.ts b/src/lib/bridge/pick.tsindex 7ed3260..ba9052a 100644--- a/src/lib/bridge/pick.ts+++ b/src/lib/bridge/pick.ts@@ -1,6 +1,7 @@import { invokeInTab } from '@/lib/actions/client';import { pickElement } from '@/lib/actions/page/pick-element';import { success, type ActionResult } from '@/lib/actions/protocol';+import { describeFrame, focusedFrame, frameOffset, TOP_FRAME } from './frame-focus';import { blobToDataUrl, captureViewport } from './screenshot';export interface PickShot {@@ -33,10 +34,22 @@ export async function pickInTab(if (!picked.ok) return picked;const { capture, ...data } = picked.data as { capture?: PickCapture } & Record<string, unknown>;- const shot = capture ? await shootRegion(tab.windowId, capture).catch(() => null) : null;+ const placed = capture ? await inTabViewport(tab.id, capture) : null;+ const shot = placed ? await shootRegion(tab.windowId, placed).catch(() => null) : null;return success(shot ? { ...data, shot } : data);}+async function inTabViewport(tabId: number, capture: PickCapture): Promise<PickCapture | null> {+ if ((await focusedFrame(tabId)) === TOP_FRAME) return capture;+ const [offset, top] = await Promise.all([frameOffset(tabId), describeFrame(tabId, TOP_FRAME)]);+ if (!offset || !top) return null;+ return {+ ...capture,+ region: { ...capture.region, x: capture.region.x + offset.x, y: capture.region.y + offset.y },+ viewport: top.viewport,+ };+}+async function shootRegion(windowId: number | undefined, capture: PickCapture): Promise<PickShot | null> {const { viewport, dpr } = capture;const x = Math.max(0, capture.region.x - REGION_PADDING_CSS_PX);diff --git a/src/lib/bridge/screenshot.ts b/src/lib/bridge/screenshot.tsindex 0c0fd87..8537db5 100644--- a/src/lib/bridge/screenshot.ts+++ b/src/lib/bridge/screenshot.ts@@ -1,7 +1,8 @@import { browser } from 'wxt/browser';-import { invokeInTab } from '@/lib/actions/client';+import { invokeInFrame } from '@/lib/actions/client';import { ActionError } from '@/lib/actions/core';import { failure, success, type ActionResult } from '@/lib/actions/protocol';+import { TOP_FRAME } from './frame-focus';import { publishScreenshot } from './screenshot-preview';interface CapturePlan {@@ -26,7 +27,7 @@ export async function screenshotTab(input?: unknown,runId?: string,): Promise<ActionResult> {- const planned = await invokeInTab(tab.id, 'page.screenshot', input);+ const planned = await invokeInFrame(tab.id, TOP_FRAME, 'page.screenshot', input);if (!planned.ok) return planned;const plan = planned.data as CapturePlan;@@ -38,7 +39,7 @@ export async function screenshotTab(if (error instanceof ActionError) return failure(error.code, error.message);return failure('CAPTURE_FAILED', error instanceof Error ? error.message : String(error));} finally {- void invokeInTab(tab.id, 'page.scrollTo', {+ void invokeInFrame(tab.id, TOP_FRAME, 'page.scrollTo', {position: { x: plan.scroll.x, y: plan.scroll.y },behavior: 'instant',});@@ -88,7 +89,7 @@ async function capture(tab: { id: number; windowId?: number }, plan: CapturePlanfor (const y of ys) {for (const x of xs) {- const scrolled = await invokeInTab(tab.id, 'page.scrollTo', {+ const scrolled = await invokeInFrame(tab.id, TOP_FRAME, 'page.scrollTo', {position: { x, y },behavior: 'instant',});diff --git a/src/lib/bridge/site-tools.ts b/src/lib/bridge/site-tools.tsindex 489a77f..137a42f 100644--- a/src/lib/bridge/site-tools.ts+++ b/src/lib/bridge/site-tools.ts@@ -15,6 +15,8 @@ import { callSiteTool } from '@/lib/actions/page/call-site-tool';import { getPageInfo } from '@/lib/actions/page/get-page-info';import { failure, success, type ActionResult } from '@/lib/actions/protocol';import { originOf } from './code-toolkit';+import { focusedFrame, framePath } from './frame-focus';+import { focusOf } from './frames';const TIMEOUT_MARKER = '⟪browsentic:site-tool-timeout⟫';@@ -141,7 +143,7 @@ async function callRegisteredTool(async function inMainWorld<T>(tabId: number, func: (...args: never[]) => Promise<T>, args: unknown[]): Promise<T | null> {try {const results = await browser.scripting.executeScript({- target: { tabId },+ target: { tabId, frameIds: [await focusedFrame(tabId)] },world: 'MAIN',func: func as () => Promise<T>,args: args as [],@@ -158,10 +160,18 @@ export async function probeSiteTools(tabId: number) {return { api: read.api, count: read.tools.length, tools: read.tools };}-export async function pageInfoWithSiteTools(tabId: number, input: unknown): Promise<ActionResult> {- const [info, siteTools] = await Promise.all([invokeInTab(tabId, getPageInfo.name, input), probeSiteTools(tabId)]);- if (!info.ok || !siteTools) return info;- return success({ ...(info.data as object), siteTools });+export async function pageInfoWithSiteTools(tabId: number, topUrl: string | undefined, input: unknown): Promise<ActionResult> {+ const [info, siteTools, path] = await Promise.all([+ invokeInTab(tabId, getPageInfo.name, input),+ probeSiteTools(tabId),+ framePath(tabId),+ ]);+ if (!info.ok) return info;+ return success({+ ...(info.data as object),+ ...(siteTools ? { siteTools } : {}),+ ...(path.length ? focusOf(path, topUrl) : {}),+ });}export async function listSiteToolsInTab(tabId: number, url: string | undefined): Promise<ActionResult> {diff --git a/src/lib/bridge/trusted-input.ts b/src/lib/bridge/trusted-input.tsindex 00838f0..13716df 100644--- a/src/lib/bridge/trusted-input.ts+++ b/src/lib/bridge/trusted-input.ts@@ -2,8 +2,9 @@ import { invokeInTab } from '@/lib/actions/client';import { dragElement } from '@/lib/actions/page/drag-element';import { APPROACH_STEPS, pathBetween, type Point } from '@/lib/actions/page/pointer';import { trustedClick } from '@/lib/actions/page/trusted-click';-import { success, type ActionResult } from '@/lib/actions/protocol';+import { failure, success, type ActionResult } from '@/lib/actions/protocol';import { send, settle, withDebugger, type DebuggerSession } from './cdp';+import { FRAME_GONE_HINT, frameOffset } from './frame-focus';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 };@@ -40,7 +41,10 @@ export function trustedClickInTab(tabId: number, input: unknown): Promise<Actionreturn 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);+ const offset = await frameOffset(tabId);+ if (!offset) return failure('TAB_UNREACHABLE', `The click could not be placed — ${FRAME_GONE_HINT}`);+ const plan = planned.data as ClickPlan;+ await dispatchClick(session, { ...plan, point: shifted(plan.point, offset), from: shifted(plan.from, offset) });return success({ ...(planned.data as object), trusted: true });});}@@ -49,11 +53,21 @@ export function dragInTab(tabId: number, input: unknown): Promise<ActionResult>return withDebugger(tabId, FIREFOX_DRAG_HINT, async (session) => {const planned = await invokeInTab(tabId, dragElement.name, input);if (!planned.ok) return planned;- await dispatchDrag(session, planned.data as DragPlan);+ const offset = await frameOffset(tabId);+ if (!offset) return failure('TAB_UNREACHABLE', `The drag could not be placed — ${FRAME_GONE_HINT}`);+ const plan = planned.data as DragPlan;+ await dispatchDrag(session, {+ ...plan,+ approach: shifted(plan.approach, offset),+ grip: shifted(plan.grip, offset),+ drop: shifted(plan.drop, offset),+ });return success({ ...(planned.data as object), trusted: true });});}+const shifted = (at: Point, by: Point): Point => ({ x: at.x + by.x, y: at.y + by.y });+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);diff --git a/src/lib/frames/events.ts b/src/lib/frames/events.tsnew file mode 100644index 0000000..0fea90e--- /dev/null+++ b/src/lib/frames/events.ts@@ -0,0 +1,32 @@+export const FRAME_CHANNEL = 'browsentic/frame';++export const FRAME_MARK_ATTRIBUTE = 'data-browsentic-frame';++export type FrameProbeBody =+ | { op: 'describe' }+ | { op: 'mark'; token: string }+ | { op: 'unmark' }+ | { op: 'locate'; frameId: number };++export type FrameProbe = FrameProbeBody & { channel: typeof FRAME_CHANNEL };++export interface FrameDescription {+ url: string;+ title: string;+ top: boolean;+ viewport: { w: number; h: number };+}++export interface FrameOrigin {+ x: number;+ y: number;+}++export function isFrameProbe(message: unknown): message is FrameProbe {+ return (+ typeof message === 'object' &&+ message !== null &&+ (message as { channel?: unknown }).channel === FRAME_CHANNEL &&+ typeof (message as { op?: unknown }).op === 'string'+ );+}diff --git a/src/lib/frames/host.ts b/src/lib/frames/host.tsnew file mode 100644index 0000000..7a7d7c3--- /dev/null+++ b/src/lib/frames/host.ts@@ -0,0 +1,53 @@+import { browser } from 'wxt/browser';+import { frameIdOf, isFrameElement, type FrameElement } from '@/lib/actions/page/switch-frame';+import { FRAME_MARK_ATTRIBUTE, isFrameProbe, type FrameDescription, type FrameOrigin } from './events';++export function exposeFrameProbe(): void {+ browser.runtime.onMessage.addListener((message: unknown, _sender, sendResponse) => {+ if (!isFrameProbe(message)) return;+ switch (message.op) {+ case 'describe':+ sendResponse(describeFrame());+ return;+ case 'mark':+ document.documentElement.setAttribute(FRAME_MARK_ATTRIBUTE, message.token);+ sendResponse({ ok: true });+ return;+ case 'unmark':+ document.documentElement.removeAttribute(FRAME_MARK_ATTRIBUTE);+ sendResponse({ ok: true });+ return;+ case 'locate':+ sendResponse(locateChild(message.frameId));+ return;+ }+ });+}++function describeFrame(): FrameDescription {+ return {+ url: location.href,+ title: document.title,+ top: window === window.top,+ viewport: { w: window.innerWidth, h: window.innerHeight },+ };+}++function locateChild(frameId: number): FrameOrigin | null {+ const child = [...document.querySelectorAll('iframe,frame')].filter(isFrameElement).find((el) => hostsFrame(el, frameId));+ if (!child) return null;+ const rect = child.getBoundingClientRect();+ const style = getComputedStyle(child);+ return {+ x: rect.x + child.clientLeft + parseFloat(style.paddingLeft),+ y: rect.y + child.clientTop + parseFloat(style.paddingTop),+ };+}++function hostsFrame(el: FrameElement, frameId: number): boolean {+ try {+ return frameIdOf(el) === frameId;+ } catch {+ return false;+ }+}