Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions server/cmd/api/api/browser_repl_lifecycle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -804,6 +804,8 @@ func (f *fakeCDPServer) dispatch(method string, params json.RawMessage, sessionI
return map[string]any{}, nil, nil
case "Page.enable", "DOM.enable", "Runtime.enable", "Network.enable":
return map[string]any{}, nil, nil
case "Page.createIsolatedWorld":
return map[string]any{"executionContextId": 1}, nil, nil
case "Page.getFrameTree":
targetID := strings.TrimPrefix(sessionID, "session-")
f.mu.Lock()
Expand Down
10 changes: 5 additions & 5 deletions server/docs/repl.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,11 @@ The reference below is generated from `runtime/browser-repl-help.ts`; edit that
- **`gotoUrl(url)`** — Navigate the attached target and return the raw `Page.navigate` result. It does not wait for document load; synchronize explicitly with `waitForLoad()`, rendered state, or a pre-armed event.
- **`pageInfo()`** — Return `{url, title, viewport: {width, height}, scroll: {x, y}, page: {width, height}, ready_state, dialog}` for the attached target. If a JavaScript dialog freezes renderer evaluation, return the dialog and best-effort browser-level URL/title instead of document geometry.
- **`accessibilitySnapshot()`** — Return a flat `{url, title, nodes}` projection of Chromium’s computed accessibility tree. Ignored nodes and nodes without a DOM backend ID are omitted. Nodes include `backendNodeId`, role, normalized accessible name, optional value, and available `checked`, `pressed`, `selected`, `expanded`, or `disabled` state; `checked` and `pressed` may be `"mixed"`. Backend node IDs can target element helpers but become stale after navigation or DOM replacement.
- **`click(target, options?)`** — Click a CSS selector, accessibility node or `{backendNodeId}`, or finite viewport coordinates `{x, y}`. Element clicks wait for a visible, enabled, stable, unobscured target and scroll it into view; hidden duplicate selector matches are ignored and multiple visible matches are rejected. Coordinate clicks dispatch immediately. Options are `button: "left" | "right" | "middle"`, positive-integer `clickCount`, and element-only `timeoutSec` (default `10`). Resulting navigation or UI state is not awaited.
- **`typeText(text)`** — Insert text into the focused element with CDP `Input.insertText`. This is text insertion, not a sequence of physical key presses.
- **`fillInput(target, text, options?)`** — Target a selector, accessibility node, or `{backendNodeId}`; wait until visible, enabled, and editable; scroll and focus it; optionally clear it; type with physical-style key events; then dispatch `input` and `change`. Options are `clearFirst` (default `true`) and `timeoutSec` (default `10`).
- **`click(target, options?)`** — Click a CSS selector, accessibility node or `{backendNodeId}`, or finite viewport coordinates `{x, y}`. Element clicks wait for a visible, enabled, stable, unobscured target and scroll it into view; hidden duplicate selector matches are ignored and multiple visible matches are rejected. Coordinate clicks skip the wait. The pointer moves to the target along a curved path from its last position and each button is held briefly, so a click takes a fraction of a second. Options are `button: "left" | "right" | "middle"`, positive-integer `clickCount`, and element-only `timeoutSec` (default `10`). Resulting navigation or UI state is not awaited.
- **`typeText(text)`** — Type text into the focused element as physical-style key presses at a human typing pace, with longer pauses between words. Each Unicode code point is one key press, as in `pressKey`, so `\n` presses Enter.
- **`fillInput(target, text, options?)`** — Target a selector, accessibility node, or `{backendNodeId}`; wait until visible, enabled, and editable; scroll and focus it; optionally clear it; then type at a human pace as `typeText` does. Options are `clearFirst` (default `true`) and `timeoutSec` (default `10`).
- **`pressKey(key, modifiers?)`** — Send one physical-style key-down/optional-char/key-up sequence using a US keyboard layout. Named keys are case-insensitive, aliases such as `Return`, `Esc`, and `Spacebar` are normalized, and single characters preserve case. Modifiers may be the DevTools bitfield (`1=Alt`, `2=Control`, `4=Meta`, `8=Shift`), an array such as `["Control"]`, or an object such as `{ctrl: true}`. Unknown keys and modifiers throw.
- **`scroll(x, y, dy?, dx?)`** — Dispatch one wheel event at viewport coordinates. Vertical `dy` defaults to `-300`; horizontal `dx` defaults to `0`. It never retries or substitutes another scrolling mechanism when the outcome is unknown.
- **`scroll(x, y, dy?, dx?)`** — Move the pointer to viewport coordinates as `click` does, then dispatch one wheel event there. Vertical `dy` defaults to `-300`; horizontal `dx` defaults to `0`. It never retries or substitutes another scrolling mechanism when the outcome is unknown.
- **`captureScreenshot(path?, fullPage?, maxDim?)`** — Capture a PNG to a VM-local path and return the path, overwriting an existing file. The default path is `/tmp/shot.png`; `fullPage` defaults to `false`. A positive-integer `maxDim` scales pixels so neither dimension exceeds it, without enlargement. The image is not emitted automatically.
- **`listTabs(includeChrome?)`** — List page targets as `{targetId, title, url}`. Internal browser pages are included by default; pass `false` to exclude them.
- **`currentTab()`** — Return `{targetId, title, url}` for the attached tab.
Expand All @@ -125,7 +125,7 @@ The reference below is generated from `runtime/browser-repl-help.ts`; edit that
- **`waitForLoad(timeoutSec?)`** — Poll until `document.readyState === "complete"`; return `true` when loaded or `false` after `timeoutSec` (default `15`).
- **`waitForElement(target, options?)`** — Poll until a selector, accessibility node, or `{backendNodeId}` reaches `state: "attached" | "detached" | "visible" | "hidden"`; return `true` on success or `false` after `timeoutSec` (default `10`). State defaults to `"visible"`, and all selector matches are considered so a hidden duplicate cannot mask a visible match.
- **`waitForNetworkIdle(idleSec?, timeoutSec?)`** — Return `true` once no tracked requests for the attached target remain in flight for the idle interval, or `false` on timeout. Defaults to 0.5 idle seconds and a 30-second timeout.
- **`js(expressionOrFunction, options?)`** — Evaluate page code exactly once in the attached target or `options.targetId` and return its by-value result. String expressions and returned promises are awaited. Function mode supports `return`, `await`, and one explicit `options.arg` without capturing Browser REPL closures. DevTools edge values such as bigint, `NaN`, infinities, and `-0` are decoded; values without a by-value representation, such as DOM nodes, return `undefined`. Unknown options throw.
- **`js(expressionOrFunction, options?)`** — Evaluate page code exactly once in the page's own JavaScript world of the attached target or `options.targetId` and return its by-value result. Page scripts can observe this code, for example through DOM methods they wrap; the element helpers instead run in an isolated world the page cannot see, so prefer them for finding and inspecting elements. String expressions and returned promises are awaited. Function mode supports `return`, `await`, and one explicit `options.arg` without capturing Browser REPL closures. DevTools edge values such as bigint, `NaN`, infinities, and `-0` are decoded; values without a by-value representation, such as DOM nodes, return `undefined`. Unknown options throw.
- **`uploadFile(target, pathOrPaths)`** — Set a selector-, accessibility-node-, or `{backendNodeId}`-targeted file input to one VM-local path or a non-empty array of paths. Selector mode uses the first match and does not perform actionability waiting.
- **`httpGet(url, headers?, timeoutSec?)`** — Fetch a URL from the VM and return its response body as text. Supports custom headers and `timeoutSec` (default `20`); non-2xx responses throw. Its timeout covers body consumption and is clamped below the active execution deadline.

Expand Down
90 changes: 90 additions & 0 deletions server/runtime/browser-cdp-client.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import assert from 'node:assert/strict';
import test from 'node:test';

import { BrowserReplCdpClient } from './browser-cdp-client.ts';

// A client attached to `session-1` whose session commands are answered by
// `respond` and recorded, without opening a DevTools connection.
function attachedClient(respond: (method: string, params: any) => unknown) {
const client = new BrowserReplCdpClient('ws://127.0.0.1:1');
const commands: Array<{ method: string; params: any }> = [];
client.sessionId = 'session-1';
client.targetId = 'target-1';
client.ensureAttached = async () => {};
const answer = async (method: string, params?: unknown) => {
commands.push({ method, params });
return respond(method, params);
};
client.sessionCommand = answer as typeof client.sessionCommand;
client.send = ((method: string, params?: unknown) => answer(method, params)) as typeof client.send;
return { client, commands };
}

function emit(client: BrowserReplCdpClient, method: string, params: unknown, sessionId = 'session-1') {
(client as any).onEvent(method, params, sessionId);
}

function worldResponder() {
let nextContextId = 10;
return (method: string, params: any) => {
if (method === 'Page.getFrameTree') return { frameTree: { frame: { id: 'frame-1' } } };
if (method === 'Page.createIsolatedWorld') return { executionContextId: nextContextId++ };
if (method === 'Runtime.evaluate') return { result: { type: 'number', value: params.contextId } };
return {};
};
}

test('attaching enables page domains without the Runtime domain', async () => {
const { client, commands } = attachedClient(() => ({}));
await (client as any).enableDomains('session-1');
assert.deepEqual(commands.map((command) => command.method), ['Page.enable', 'DOM.enable', 'Network.enable']);
});

test('helper evaluation reuses one isolated world per document', async () => {
const { client, commands } = attachedClient(worldResponder());
assert.equal(await client.evaluateInHelperWorld('1'), 10);
assert.equal(await client.evaluateInHelperWorld('2'), 10);
const world = commands.filter((command) => command.method === 'Page.createIsolatedWorld');
assert.equal(world.length, 1);
assert.equal(world[0].params.frameId, 'frame-1');

// Same-document and child-frame navigations keep the world.
emit(client, 'Page.frameNavigated', { frame: { id: 'child', parentId: 'frame-1' } });
assert.equal(await client.evaluateInHelperWorld('3'), 10);

// A main-frame navigation replaces the document, and with it the world.
emit(client, 'Page.frameNavigated', { frame: { id: 'frame-1' } });
assert.equal(await client.evaluateInHelperWorld('4'), 11);
});

test('a new target attachment gets its own helper world', async () => {
const { client } = attachedClient(worldResponder());
assert.equal(await client.evaluateInHelperWorld('1'), 10);
client.sessionId = 'session-2';
assert.equal(await client.evaluateInHelperWorld('1'), 11);
});

test('helper evaluation recreates a world whose document went away', async () => {
const respond = worldResponder();
let failNext = false;
const { client } = attachedClient((method, params) => {
if (method === 'Runtime.evaluate' && failNext) {
failNext = false;
throw new Error('CDP Runtime.evaluate failed: Cannot find context with specified id (code -32000)');
}
return respond(method, params);
});
assert.equal(await client.evaluateInHelperWorld('1'), 10);
failNext = true;
assert.equal(await client.evaluateInHelperWorld('2'), 11);
});

test('helper evaluation does not retry other failures', async () => {
const respond = worldResponder();
const { client, commands } = attachedClient((method, params) => {
if (method === 'Runtime.evaluate') throw new Error('CDP Runtime.evaluate failed: boom (code -32000)');
return respond(method, params);
});
await assert.rejects(client.evaluateInHelperWorld('1'), /boom/);
assert.equal(commands.filter((command) => command.method === 'Runtime.evaluate').length, 1);
});
75 changes: 69 additions & 6 deletions server/runtime/browser-cdp-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ const SAFE_RETRY_METHODS = new Set([
'DOM.resolveNode',
'Network.enable',
'Page.captureScreenshot',
'Page.createIsolatedWorld',
'Page.enable',
'Page.getFrameTree',
'Page.getLayoutMetrics',
Expand All @@ -90,6 +91,14 @@ const SAFE_RETRY_METHODS = new Set([
'Target.getTargets',
]);

const HELPER_WORLD_NAME = 'browser-repl-helpers';

function isMissingContextError(err: unknown): boolean {
return /Cannot find context with specified id|Cannot find default execution context/.test(
String((err as any)?.message ?? err),
);
}

export class CdpCommandTimeoutError extends Error {
readonly cdpCommandTimeout = true;
}
Expand Down Expand Up @@ -160,6 +169,11 @@ export class BrowserReplCdpClient {
private inFlightRequests = new Set<string>();
private lastNetworkActivity = 0;

// The isolated world helper code runs in on the attached target's main
// frame. It is valid for one document and is dropped when the main frame
// navigates to another.
private helperWorld: { sessionId: string; contextId: number } | null = null;

constructor(endpoint: string) {
this.endpoint = endpoint;
}
Expand Down Expand Up @@ -317,6 +331,15 @@ export class BrowserReplCdpClient {
}
}

if (
method === 'Page.frameNavigated' &&
sessionId !== undefined &&
sessionId === this.helperWorld?.sessionId &&
!params?.frame?.parentId
) {
this.helperWorld = null;
}

if (method === 'Target.detachedFromTarget') {
if (params?.sessionId && params.sessionId === this.sessionId) {
this.sessionId = null;
Expand Down Expand Up @@ -560,7 +583,12 @@ export class BrowserReplCdpClient {

private async enableDomains(sessionId: string): Promise<boolean> {
const start = Date.now();
for (const method of ['Page.enable', 'DOM.enable', 'Runtime.enable', 'Network.enable']) {
// Runtime.enable is deliberately absent: with the Runtime domain enabled,
// Chromium previews every console argument for the client, and pages can
// observe that preview through property getters. Evaluation does not need
// it, and helper code gets its execution context from
// Page.createIsolatedWorld instead of Runtime.executionContextCreated.
for (const method of ['Page.enable', 'DOM.enable', 'Network.enable']) {
const remaining = ENABLE_DOMAINS_BUDGET_MS - (Date.now() - start);
if (remaining <= 0) {
return false;
Expand Down Expand Up @@ -733,12 +761,47 @@ export class BrowserReplCdpClient {
}
}

async evaluate<T = any>(sessionId: string, expression: string): Promise<T> {
const evalRes = await this.send<any>(
'Runtime.evaluate',
{ expression, awaitPromise: true, returnByValue: true },
sessionId,
// Returns an execution context in an isolated world on the attached
// target's main frame. The world shares the page's DOM but not its
// JavaScript globals or prototypes, so page scripts can neither observe
// helper code nor intercept the DOM methods it calls.
async helperContextId(): Promise<number> {
await this.ensureAttached();
const sessionId = this.sessionId!;
if (this.helperWorld?.sessionId === sessionId) return this.helperWorld.contextId;
const { frameTree } = await this.sessionCommand<{ frameTree: { frame: { id: string } } }>('Page.getFrameTree');
const { executionContextId } = await this.sessionCommand<{ executionContextId: number }>(
'Page.createIsolatedWorld',
{ frameId: frameTree.frame.id, worldName: HELPER_WORLD_NAME, grantUniveralAccess: false },
);
if (this.sessionId === sessionId) {
this.helperWorld = { sessionId, contextId: executionContextId };
}
return executionContextId;
}

// Runs fn with the helper world's context ID, recreating the world once if
// its document went away before the command reached it. A missing context
// means the command never ran, so the retry cannot repeat side effects.
async withHelperContext<T>(fn: (contextId: number) => Promise<T>): Promise<T> {
const contextId = await this.helperContextId();
try {
return await fn(contextId);
} catch (err) {
if (!isMissingContextError(err)) throw err;
if (this.helperWorld?.contextId === contextId) this.helperWorld = null;
return fn(await this.helperContextId());
}
}

async evaluateInHelperWorld<T = any>(expression: string): Promise<T> {
return this.withHelperContext((contextId) => this.evaluate<T>(this.sessionId!, expression, contextId));
}

async evaluate<T = any>(sessionId: string, expression: string, contextId?: number): Promise<T> {
const params: Record<string, unknown> = { expression, awaitPromise: true, returnByValue: true };
if (contextId !== undefined) params.contextId = contextId;
const evalRes = await this.send<any>('Runtime.evaluate', params, sessionId);
if (evalRes.exceptionDetails || evalRes.result?.subtype === 'error') {
const desc =
evalRes.result?.description ??
Expand Down
Loading
Loading