diff --git a/server/cmd/api/api/browser_repl_lifecycle_test.go b/server/cmd/api/api/browser_repl_lifecycle_test.go index dea13628..e00052be 100644 --- a/server/cmd/api/api/browser_repl_lifecycle_test.go +++ b/server/cmd/api/api/browser_repl_lifecycle_test.go @@ -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() diff --git a/server/docs/repl.md b/server/docs/repl.md index 81b8ec05..4f86150a 100644 --- a/server/docs/repl.md +++ b/server/docs/repl.md @@ -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. @@ -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. diff --git a/server/runtime/browser-cdp-client.test.ts b/server/runtime/browser-cdp-client.test.ts new file mode 100644 index 00000000..6f24f8b6 --- /dev/null +++ b/server/runtime/browser-cdp-client.test.ts @@ -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); +}); diff --git a/server/runtime/browser-cdp-client.ts b/server/runtime/browser-cdp-client.ts index 3e5efed9..c7729820 100644 --- a/server/runtime/browser-cdp-client.ts +++ b/server/runtime/browser-cdp-client.ts @@ -82,6 +82,7 @@ const SAFE_RETRY_METHODS = new Set([ 'DOM.resolveNode', 'Network.enable', 'Page.captureScreenshot', + 'Page.createIsolatedWorld', 'Page.enable', 'Page.getFrameTree', 'Page.getLayoutMetrics', @@ -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; } @@ -160,6 +169,11 @@ export class BrowserReplCdpClient { private inFlightRequests = new Set(); 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; } @@ -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; @@ -560,7 +583,12 @@ export class BrowserReplCdpClient { private async enableDomains(sessionId: string): Promise { 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; @@ -733,12 +761,47 @@ export class BrowserReplCdpClient { } } - async evaluate(sessionId: string, expression: string): Promise { - const evalRes = await this.send( - '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 { + 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(fn: (contextId: number) => Promise): Promise { + 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(expression: string): Promise { + return this.withHelperContext((contextId) => this.evaluate(this.sessionId!, expression, contextId)); + } + + async evaluate(sessionId: string, expression: string, contextId?: number): Promise { + const params: Record = { expression, awaitPromise: true, returnByValue: true }; + if (contextId !== undefined) params.contextId = contextId; + const evalRes = await this.send('Runtime.evaluate', params, sessionId); if (evalRes.exceptionDetails || evalRes.result?.subtype === 'error') { const desc = evalRes.result?.description ?? diff --git a/server/runtime/browser-helpers.test.ts b/server/runtime/browser-helpers.test.ts index 23261c63..662cc8f7 100644 --- a/server/runtime/browser-helpers.test.ts +++ b/server/runtime/browser-helpers.test.ts @@ -22,10 +22,10 @@ function helpersWithMatches(matches: unknown[]) { getComputedStyle: () => ({ display: 'block', visibility: 'visible', opacity: '1' }), }); // The selector resolvers use only these client members. - const client: Pick = { + const client: Pick = { sessionId: 'session', async ensureAttached() {}, - async evaluate(_sessionId: string, expression: string): Promise { + async evaluateInHelperWorld(expression: string): Promise { return vm.runInContext(expression, page) as T; }, }; @@ -60,3 +60,247 @@ test('selector fillInput reports not visible when every match is hidden', async /was not editable within 0s \(not visible\)$/, ); }); + +interface SentCommand { + method: string; + params: any; +} + +// Records the CDP commands a helper sends. Selector resolution evaluates in +// the helper world and reports a ready element at (100, 50); anything sent +// to the page's own world is recorded so tests can assert it never happens. +function recordingHelpers(clickResults: Array> = [], random?: () => number) { + const commands: SentCommand[] = []; + const mainWorldEvaluations: string[] = []; + const client = { + sessionId: 'session', + targetId: 'target', + executionDeadlineMs: null, + async ensureAttached() {}, + async evaluateInHelperWorld(expression: string) { + if (expression.includes('resolveClickTarget')) { + const result = clickResults.length > 1 ? clickResults.shift() : clickResults[0]; + commands.push({ method: 'resolveClickTarget', params: result }); + return result ?? { status: 'ready', x: 100, y: 50 }; + } + if (expression.includes('resolveFillTarget')) return { status: 'ready' }; + return undefined; + }, + async evaluate(_sessionId: string, expression: string) { + mainWorldEvaluations.push(expression); + return undefined; + }, + async sessionCommand(method: string, params?: unknown) { + commands.push({ method, params }); + if (method === 'Page.getLayoutMetrics') { + return { cssLayoutViewport: { clientWidth: 800, clientHeight: 600 } }; + } + return {}; + }, + }; + const helpers = new BrowserHelpers(client as unknown as BrowserReplCdpClient, random); + helpers.waitMs = async () => {}; + return { helpers, commands, mainWorldEvaluations }; +} + +test('click moves the pointer along a path before pressing and releasing', async () => { + const { helpers, commands } = recordingHelpers(); + await helpers.click('button'); + const mouse = commands.filter((command) => command.method === 'Input.dispatchMouseEvent'); + const moves = mouse.filter((command) => command.params.type === 'mouseMoved'); + assert.ok(moves.length >= 5, `expected a multi-step path, got ${moves.length} moves`); + assert.deepEqual( + mouse.slice(moves.length).map((command) => command.params.type), + ['mousePressed', 'mouseReleased'], + ); + assert.deepEqual(moves.at(-1)!.params, { type: 'mouseMoved', x: 100, y: 50, button: 'none', buttons: 0 }); + for (const move of moves) { + assert.ok(move.params.x >= 0 && move.params.x < 800 && move.params.y >= 0 && move.params.y < 600); + } +}); + +test('a second click on the same point does not move the pointer again', async () => { + const { helpers, commands } = recordingHelpers(); + await helpers.click({ x: 100, y: 50 }); + commands.length = 0; + await helpers.click({ x: 100, y: 50 }); + assert.deepEqual( + commands.filter((command) => command.method === 'Input.dispatchMouseEvent').map((command) => command.params.type), + ['mousePressed', 'mouseReleased'], + ); +}); + +test('fillInput types real key events and dispatches no synthetic page events', async () => { + const { helpers, commands, mainWorldEvaluations } = recordingHelpers(); + await helpers.fillInput('input', 'hi there', { clearFirst: false }); + const keyDowns = commands.filter( + (command) => command.method === 'Input.dispatchKeyEvent' && command.params.type === 'keyDown', + ); + assert.equal(keyDowns.map((command) => command.params.key).join(''), 'hi there'); + assert.deepEqual(mainWorldEvaluations, []); +}); + +test('typeText sends key events instead of inserting text', async () => { + const { helpers, commands } = recordingHelpers(); + await helpers.typeText('ok'); + assert.ok(!commands.some((command) => command.method === 'Input.insertText')); + assert.deepEqual( + commands.filter((command) => command.method === 'Input.dispatchKeyEvent').map((command) => command.params.type), + ['keyDown', 'char', 'keyUp', 'keyDown', 'char', 'keyUp'], + ); +}); + +test('click presses only once the target is under the parked pointer', async () => { + // Resolve, check at the pointer, resolve again, check again. + const { helpers, commands } = recordingHelpers([ + { status: 'ready', x: 100, y: 50 }, + { status: 'off target' }, + { status: 'ready', x: 300, y: 200 }, + { status: 'ready', x: 300, y: 200 }, + ]); + await helpers.click('button'); + const sequence = commands + .filter((command) => command.method === 'resolveClickTarget' || command.params?.type === 'mousePressed') + .map((command) => command.method === 'resolveClickTarget' ? command.params.status : 'press'); + assert.deepEqual(sequence, ['ready', 'off target', 'ready', 'ready', 'press']); + const press = commands.find((command) => command.params?.type === 'mousePressed')!; + assert.deepEqual([press.params.x, press.params.y], [300, 200]); +}); + +test('scroll rejects non-finite coordinates before moving the pointer', async () => { + const { helpers, commands } = recordingHelpers(); + await assert.rejects(helpers.scroll(Number.NaN, 10), /scroll: x and y must be finite/); + assert.deepEqual(commands, []); +}); + +// Runs fn against a fake clock where every CDP command takes ackMs and +// waitMs advances the clock instead of sleeping. Returns the keyDown times. +async function typeWithFakeClock(text: string, ackMs: number, deadlineInMs: number | null, random?: () => number) { + const realNow = Date.now; + let now = 1_000_000; + Date.now = () => now; + try { + const { helpers, commands } = recordingHelpers([], random); + const keyDowns: number[] = []; + const client = (helpers as any).client; + const send = client.sessionCommand; + client.sessionCommand = async (method: string, params?: any) => { + if (method === 'Input.dispatchKeyEvent' && params?.type === 'keyDown') keyDowns.push(now); + now += ackMs; + return send(method, params); + }; + helpers.waitMs = async (ms = 0) => { + now += ms; + }; + const start = now; + helpers.executionDeadlineMs = deadlineInMs === null ? null : start + deadlineInMs; + await helpers.typeText(text); + return { elapsed: now - start, keyDowns, commands }; + } finally { + Date.now = realNow; + } +} + +test('humanized typing fits the execution deadline including command time', async () => { + // 120 printable characters at 3 commands each take 3.6s of acknowledgements. + const { elapsed } = await typeWithFakeClock('typing '.repeat(17) + 'x', 10, 5_000); + assert.ok(elapsed <= 4_500, `typing took ${elapsed}ms within a 5s deadline`); +}); + +test('command acknowledgement time counts toward the typing cadence', async () => { + // A random source near 1 picks the slowest planned interval, 119ms. + const { keyDowns } = await typeWithFakeClock('abcdefghij', 10, null, () => 0.999); + for (let index = 1; index < keyDowns.length; index++) { + assert.equal(keyDowns[index] - keyDowns[index - 1], 119); + } +}); + +test('click gives up on a target that left the pointer once its timeout passes', async () => { + const { helpers, commands } = recordingHelpers([ + { status: 'ready', x: 100, y: 50 }, + { status: 'off target' }, + ]); + await assert.rejects( + helpers.click('button', { timeoutSec: 0 }), + /^Error: click: selector "button" was not actionable within 0s \(off target\)$/, + ); + assert.ok(!commands.some((command) => command.params?.type === 'mousePressed')); +}); + +test('default fillInput fits the execution deadline including clearing', async () => { + const realNow = Date.now; + let now = 1_000_000; + Date.now = () => now; + try { + const { helpers } = recordingHelpers(); + const client = (helpers as any).client; + const send = client.sessionCommand; + client.sessionCommand = async (method: string, params?: any) => { + now += 10; + return send(method, params); + }; + helpers.waitMs = async (ms = 0) => { + now += ms; + }; + const start = now; + helpers.executionDeadlineMs = start + 3_000; + // 75 printable characters plus four clearing commands take 2.29s of + // acknowledgements at 10ms each. + await helpers.fillInput('input', 'x'.repeat(75)); + assert.ok(now - start <= 2_500, `fillInput took ${now - start}ms within a 3s deadline`); + } finally { + Date.now = realNow; + } +}); + +test('click presses where the pointer stopped while the target is still under it', async () => { + // The target shifted on hover, so its center moved, but it is still under + // the pointer. + const { helpers, commands } = recordingHelpers([ + { status: 'ready', x: 100, y: 50 }, + { status: 'ready', x: 104, y: 50 }, + ]); + await helpers.click('button', { timeoutSec: 0 }); + assert.equal(commands.filter((command) => command.method === 'resolveClickTarget').length, 2); + const press = commands.find((command) => command.params?.type === 'mousePressed')!; + assert.deepEqual([press.params.x, press.params.y], [100, 50]); +}); + +test('the parked-pointer check hit-tests the pointer coordinates', async () => { + let checked: unknown = null; + const { helpers } = recordingHelpers(); + const client = (helpers as any).client; + client.evaluateInHelperWorld = async (expression: string) => { + const at = expression.match(/, (null|\{[^}]*\})\)$/)?.[1]; + if (at && at !== 'null') checked = JSON.parse(at); + return { status: 'ready', x: 100, y: 50 }; + }; + await helpers.click('button'); + assert.deepEqual(checked, { x: 100, y: 50 }); +}); + +test('fillInput clearing spends no time the typing would need', async () => { + const realNow = Date.now; + let now = 1_000_000; + Date.now = () => now; + try { + const { helpers } = recordingHelpers(); + const client = (helpers as any).client; + const send = client.sessionCommand; + // Clearing an empty field is acknowledged in 1ms per command; inserting + // a character takes 30ms, and its key-down and key-up 1ms each. + client.sessionCommand = async (method: string, params?: any) => { + now += params?.type === 'char' ? 30 : 1; + return send(method, params); + }; + helpers.waitMs = async (ms = 0) => { + now += ms; + }; + const start = now; + helpers.executionDeadlineMs = start + 3_000; + await helpers.fillInput('input', 'x'.repeat(75)); + assert.ok(now - start <= 2_500, `fillInput took ${now - start}ms within a 3s deadline`); + } finally { + Date.now = realNow; + } +}); diff --git a/server/runtime/browser-helpers.ts b/server/runtime/browser-helpers.ts index e1028ce2..2aa040a6 100644 --- a/server/runtime/browser-helpers.ts +++ b/server/runtime/browser-helpers.ts @@ -2,6 +2,17 @@ import { writeFileSync } from 'fs'; import sharp from 'sharp'; import { BrowserReplCdpClient, isInternalUrl, type CdpEvent } from './browser-cdp-client.ts'; import { browserReplBrowserMethodNames } from './browser-repl-help.ts'; +import { + budgetScale, + gaussianDelay, + keystrokeInterval, + mousePath, + typingSchedule, + uniformJitter, + type KeyTiming, + type Point, + type Random, +} from './humanize.ts'; import { buildFunctionCallExpression, normalizeJsOptions, @@ -18,6 +29,13 @@ const SCROLL_COMMAND_TIMEOUT_MS = 5_000; // Leave time for helper errors to beat the destructive execution deadline. const EXECUTION_DEADLINE_MARGIN_MS = 500; +// Mean delay between pointer moves along a humanized path. +const MOUSE_STEP_MS = 10; + +// Time humanized pauses leave for the input commands themselves when a cell's +// execution deadline forces the pauses to shrink. +const INPUT_COMMAND_RESERVE_MS = 1_000; + const SHADOW_HIT_TEST_SOURCE = ` const composedContains = (ancestor, node) => { for (let current = node; current;) { @@ -195,12 +213,17 @@ function normalizeKeyModifiers(modifiers?: string[] | Record): export class BrowserHelpers { private readonly client: BrowserReplCdpClient; + private readonly random: Random; + // Last pointer position dispatched to each target, where the next + // humanized move starts. + private readonly pointers = new Map(); executionDeadlineMs: number | null = null; onLog?: (message: string) => void; - constructor(client: BrowserReplCdpClient) { + constructor(client: BrowserReplCdpClient, random: Random = Math.random) { this.client = client; + this.random = random; } private waitDeadline(timeoutMs: number): { deadline: number; clamped: boolean } { @@ -324,8 +347,7 @@ export class BrowserHelpers { } return info; } - const evalRes = await this.client.sessionCommand('Runtime.evaluate', { - expression: `(() => ({ + const value = await this.client.evaluateInHelperWorld>(`(() => ({ url: location.href, title: document.title, viewport: { width: window.innerWidth, height: window.innerHeight }, @@ -335,13 +357,10 @@ export class BrowserHelpers { height: document.documentElement ? document.documentElement.scrollHeight : 0, }, ready_state: document.readyState, - }))()`, - returnByValue: true, - }); - const value = evalRes.result?.value ?? {}; + }))()`); const dialog = this.client.pendingDialog; return { - ...value, + ...(value ?? {}), dialog: dialog ? { type: dialog.type, message: dialog.message } : null, }; }; @@ -362,19 +381,37 @@ export class BrowserHelpers { } let point: ClickPoint; + // Resolves an element target to its clickable point, within one deadline + // shared by the first resolution and the check after the pointer moves. + let resolve: (() => Promise) | null = null; + // Reports 'ready' if the element target is still under the given point. + let statusAt: ((at: ClickPoint) => Promise) | null = null; + let deadline = 0; + let notActionable = ''; if (typeof target === 'string') { if (target.length === 0) throw new Error('click: selector must not be empty'); - point = await this.waitForClickablePoint( - target, - nonNegativeSeconds(options.timeoutSec, 10, 'click'), - ); + const timeoutSec = nonNegativeSeconds(options.timeoutSec, 10, 'click'); + deadline = this.waitDeadline(timeoutSec * 1000).deadline; + notActionable = `click: selector ${JSON.stringify(target)} was not actionable within ${timeoutSec}s`; + resolve = () => this.waitForClickablePoint(target, timeoutSec, deadline); + statusAt = async (at) => (await this.selectorClickProbe(target, at))?.status ?? 'not actionable'; + point = await resolve(); } else { const nodeId = backendNodeId(target, 'click'); if (nodeId !== null) { - point = await this.waitForClickableBackendNode( - nodeId, - nonNegativeSeconds(options.timeoutSec, 10, 'click'), - ); + const timeoutSec = nonNegativeSeconds(options.timeoutSec, 10, 'click'); + deadline = this.waitDeadline(timeoutSec * 1000).deadline; + notActionable = `click: backend node ${nodeId} was not actionable within ${timeoutSec}s`; + resolve = () => this.waitForClickableBackendNode(nodeId, timeoutSec, deadline); + statusAt = async (at) => { + try { + return (await this.backendClickProbe(nodeId, at))?.status ?? 'not actionable'; + } catch (error) { + if (!this.backendNodeGone(error)) throw error; + return 'not found'; + } + }; + point = await resolve(); } else { const coordinate = target as ClickPoint; if ( @@ -392,14 +429,21 @@ export class BrowserHelpers { } } - await this.client.sessionCommand('Input.dispatchMouseEvent', { - type: 'mouseMoved', - x: point.x, - y: point.y, - button: 'none', - }); + await this.moveMouseTo(point); + // The pointer's path can hover other elements on the way, which may open + // something over the target or move it. Press only while the target is + // still under the parked pointer, which is where the button is pressed; + // otherwise move to the target again, within the same deadline. + while (resolve && statusAt) { + const status = await statusAt(point); + if (status === 'ready') break; + if (Date.now() >= deadline) throw new Error(`${notActionable} (${status})`); + point = await resolve(); + await this.moveMouseTo(point); + } const buttons = button === 'left' ? 1 : button === 'right' ? 2 : 4; for (let count = 1; count <= (clickCount as number); count++) { + if (count > 1) await this.humanPause(uniformJitter(110, 30, 60, this.random)); await this.client.sessionCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: point.x, @@ -408,6 +452,7 @@ export class BrowserHelpers { buttons, clickCount: count, }); + await this.humanPause(uniformJitter(90, 30, 50, this.random)); await this.client.sessionCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: point.x, @@ -420,7 +465,10 @@ export class BrowserHelpers { }; typeText = async (text: string): Promise => { - await this.client.sessionCommand('Input.insertText', { text }); + if (typeof text !== 'string') { + throw new Error('typeText: text must be a string'); + } + await this.typeHumanized(text); }; fillInput = async ( @@ -459,21 +507,14 @@ export class BrowserHelpers { windowsVirtualKeyCode: 65, nativeVirtualKeyCode: 65, }; + // Clearing takes no pauses: nothing about it predicts how long the + // typing's key commands will take, and the typing's adaptive pauses + // cannot recover time already spent. await this.client.sessionCommand('Input.dispatchKeyEvent', { type: 'rawKeyDown', ...selectAll }); await this.client.sessionCommand('Input.dispatchKeyEvent', { type: 'keyUp', ...selectAll }); - await this.pressKey('Backspace'); - } - // pressKey accepts any single Unicode code point. Characters outside the - // US layout use CDP char events with no synthetic physical key code. - for (const char of text) { - await this.pressKey(char); + await this.keyPress('Backspace', undefined, 0); } - await this.evaluateInPage(`(() => { - const el = document.activeElement; - if (!el) return; - el.dispatchEvent(new Event('input', { bubbles: true })); - el.dispatchEvent(new Event('change', { bubbles: true })); - })()`); + await this.typeHumanized(text); }; private static readonly MODIFIER_BITS: Record = { @@ -487,6 +528,16 @@ export class BrowserHelpers { key: string, modifiers?: number | string[] | Record, ): Promise => { + await this.keyPress(key, modifiers); + }; + + // Presses one key, holding it for holdMs (by default half of a typing + // keystroke interval) between key-down and key-up. + private async keyPress( + key: string, + modifiers?: number | string[] | Record, + holdMs?: number, + ): Promise { let modifierBits = 0; if (typeof modifiers === 'number') { if (!Number.isInteger(modifiers) || modifiers < 0 || modifiers > 15) { @@ -526,6 +577,7 @@ export class BrowserHelpers { }; const shortcut = (modifierBits & (1 | 2 | 4)) !== 0; const printable = [...def.key].length === 1 && !!def.text && !shortcut; + holdMs ??= Math.floor(keystrokeInterval(this.random) / 2); await this.client.sessionCommand('Input.dispatchKeyEvent', { ...base, type: 'keyDown', @@ -538,10 +590,15 @@ export class BrowserHelpers { text: def.text, }); } + await this.humanPause(holdMs); await this.client.sessionCommand('Input.dispatchKeyEvent', { ...base, type: 'keyUp' }); - }; + } scroll = async (x: number, y: number, dy = -300, dx = 0): Promise => { + if (typeof x !== 'number' || !Number.isFinite(x) || typeof y !== 'number' || !Number.isFinite(y)) { + throw new Error('scroll: x and y must be finite viewport coordinates'); + } + await this.moveMouseTo({ x, y }); await this.client.sessionCommand( 'Input.dispatchMouseEvent', { @@ -686,11 +743,7 @@ export class BrowserHelpers { waitForLoad = async (timeoutSec = 15): Promise => { const { deadline } = this.waitDeadline(timeoutSec * 1000); while (Date.now() <= deadline) { - const res = await this.client.sessionCommand('Runtime.evaluate', { - expression: 'document.readyState', - returnByValue: true, - }); - if (res.result?.value === 'complete') return true; + if (await this.client.evaluateInHelperWorld('document.readyState') === 'complete') return true; await this.waitMs(300); } return false; @@ -715,7 +768,7 @@ export class BrowserHelpers { const timeoutSec = nonNegativeSeconds(options.timeoutSec, 10, 'waitForElement'); const { deadline } = this.waitDeadline(timeoutSec * 1000); for (;;) { - const found = typeof target === 'string' ? await this.evaluateInPage( + const found = typeof target === 'string' ? await this.client.evaluateInHelperWorld( `(function elementState(selector, state) { const elements = [...document.querySelectorAll(selector)]; const visible = (el) => { @@ -855,7 +908,9 @@ export class BrowserHelpers { functionDeclaration: string, args: unknown[] = [], ): Promise { - const resolved = await this.client.sessionCommand('DOM.resolveNode', { backendNodeId: id }); + const resolved = await this.client.withHelperContext((executionContextId) => + this.client.sessionCommand('DOM.resolveNode', { backendNodeId: id, executionContextId }), + ); const objectId = resolved.object?.objectId; if (!objectId) throw new Error(`could not resolve backend node ${id}`); try { @@ -884,14 +939,69 @@ export class BrowserHelpers { } } - private async waitForClickableBackendNode(id: number, timeoutSec: number): Promise { - const { deadline } = this.waitDeadline(timeoutSec * 1000); - let lastStatus = 'not found'; - for (;;) { - try { - const result = await this.callOnBackendNode( - id, - `async function resolveBackendClickTarget() { + // Checks a selector's click target once. Without `at`, it scrolls the + // target into view and reports its center if it is stable and unobscured; + // with `at`, it only reports whether the target is under that point. + private selectorClickProbe(selector: string, at: ClickPoint | null) { + return this.client.evaluateInHelperWorld( + `(async function resolveClickTarget(selector, at) { + const visible = (el) => { + if (!el.isConnected || el.getClientRects().length === 0) return false; + if (typeof el.checkVisibility === 'function') { + return el.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }); + } + const style = getComputedStyle(el); + return style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0'; + }; + ${SHADOW_HIT_TEST_SOURCE} + const matches = [...document.querySelectorAll(selector)]; + if (matches.length === 0) return { status: 'not found' }; + const candidates = matches.filter(visible); + if (candidates.length === 0) return { status: 'not visible' }; + if (candidates.length > 1) return { status: 'multiple', count: candidates.length }; + const el = candidates[0]; + if (el.matches(':disabled') || el.getAttribute('aria-disabled') === 'true') { + return { status: 'disabled' }; + } + if (at) { + const parked = deepElementFromPoint(at.x, at.y); + return parked && composedContains(el, parked) ? { status: 'ready', x: at.x, y: at.y } : { status: 'off target' }; + } + el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' }); + const before = el.getBoundingClientRect(); + await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); + if (!el.isConnected || !visible(el)) return { status: 'detached or hidden' }; + const after = el.getBoundingClientRect(); + const stable = + Math.abs(before.x - after.x) < 0.25 && + Math.abs(before.y - after.y) < 0.25 && + Math.abs(before.width - after.width) < 0.25 && + Math.abs(before.height - after.height) < 0.25; + if (!stable) return { status: 'moving' }; + const left = Math.max(0, after.left); + const right = Math.min(innerWidth, after.right); + const top = Math.max(0, after.top); + const bottom = Math.min(innerHeight, after.bottom); + if (right <= left || bottom <= top) return { status: 'outside viewport' }; + const x = left + (right - left) / 2; + const y = top + (bottom - top) / 2; + const hit = deepElementFromPoint(x, y); + if (!hit || !composedContains(el, hit)) { + return { + status: 'intercepted', + hit: hit ? hit.tagName.toLowerCase() : null, + }; + } + return { status: 'ready', x, y }; + })(${JSON.stringify(selector)}, ${JSON.stringify(at)})`, + ) as Promise<{ status?: string; count?: number; x?: number; y?: number }>; + } + + // The backend-node counterpart of selectorClickProbe. + private backendClickProbe(id: number, at: ClickPoint | null) { + return this.callOnBackendNode( + id, + `async function resolveBackendClickTarget(at) { const el = this; const visible = (candidate) => { if (!(candidate instanceof Element) || !candidate.isConnected || candidate.getClientRects().length === 0) return false; @@ -901,8 +1011,13 @@ export class BrowserHelpers { const style = getComputedStyle(candidate); return style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0'; }; + ${SHADOW_HIT_TEST_SOURCE} if (!visible(el)) return { status: 'not visible' }; if (el.matches(':disabled') || el.getAttribute('aria-disabled') === 'true') return { status: 'disabled' }; + if (at) { + const parked = deepElementFromPoint(at.x, at.y); + return parked && composedContains(el, parked) ? { status: 'ready', x: at.x, y: at.y } : { status: 'off target' }; + } el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' }); const before = el.getBoundingClientRect(); await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); @@ -921,14 +1036,25 @@ export class BrowserHelpers { if (right <= left || bottom <= top) return { status: 'outside viewport' }; const x = left + (right - left) / 2; const y = top + (bottom - top) / 2; - ${SHADOW_HIT_TEST_SOURCE} const hit = deepElementFromPoint(x, y); if (!hit || !composedContains(el, hit)) { return { status: 'intercepted', hit: hit ? hit.tagName.toLowerCase() : null }; } return { status: 'ready', x, y }; }`, - ) as { status?: string; x?: number; y?: number }; + [at], + ) as Promise<{ status?: string; x?: number; y?: number }>; + } + + private async waitForClickableBackendNode( + id: number, + timeoutSec: number, + deadline = this.waitDeadline(timeoutSec * 1000).deadline, + ): Promise { + let lastStatus = 'not found'; + for (;;) { + try { + const result = await this.backendClickProbe(id, null); if (result?.status === 'ready' && typeof result.x === 'number' && typeof result.y === 'number') { return { x: result.x, y: result.y }; } @@ -1018,59 +1144,14 @@ export class BrowserHelpers { } } - private async waitForClickablePoint(selector: string, timeoutSec: number): Promise { - const { deadline } = this.waitDeadline(timeoutSec * 1000); + private async waitForClickablePoint( + selector: string, + timeoutSec: number, + deadline = this.waitDeadline(timeoutSec * 1000).deadline, + ): Promise { let lastStatus = 'not found'; for (;;) { - const result = await this.evaluateInPage( - `(async function resolveClickTarget(selector) { - const visible = (el) => { - if (!el.isConnected || el.getClientRects().length === 0) return false; - if (typeof el.checkVisibility === 'function') { - return el.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }); - } - const style = getComputedStyle(el); - return style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0'; - }; - const matches = [...document.querySelectorAll(selector)]; - if (matches.length === 0) return { status: 'not found' }; - const candidates = matches.filter(visible); - if (candidates.length === 0) return { status: 'not visible' }; - if (candidates.length > 1) return { status: 'multiple', count: candidates.length }; - const el = candidates[0]; - if (el.matches(':disabled') || el.getAttribute('aria-disabled') === 'true') { - return { status: 'disabled' }; - } - el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' }); - const before = el.getBoundingClientRect(); - await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); - if (!el.isConnected || !visible(el)) return { status: 'detached or hidden' }; - const after = el.getBoundingClientRect(); - const stable = - Math.abs(before.x - after.x) < 0.25 && - Math.abs(before.y - after.y) < 0.25 && - Math.abs(before.width - after.width) < 0.25 && - Math.abs(before.height - after.height) < 0.25; - if (!stable) return { status: 'moving' }; - const left = Math.max(0, after.left); - const right = Math.min(innerWidth, after.right); - const top = Math.max(0, after.top); - const bottom = Math.min(innerHeight, after.bottom); - if (right <= left || bottom <= top) return { status: 'outside viewport' }; - const x = left + (right - left) / 2; - const y = top + (bottom - top) / 2; - ${SHADOW_HIT_TEST_SOURCE} - const hit = deepElementFromPoint(x, y); - if (!hit || !composedContains(el, hit)) { - return { - status: 'intercepted', - hit: hit ? hit.tagName.toLowerCase() : null, - }; - } - return { status: 'ready', x, y }; - })(${JSON.stringify(selector)})`, - ) as { status?: string; count?: number; x?: number; y?: number }; - + const result = await this.selectorClickProbe(selector, null); if (result?.status === 'ready' && typeof result.x === 'number' && typeof result.y === 'number') { return { x: result.x, y: result.y }; } @@ -1093,7 +1174,7 @@ export class BrowserHelpers { const { deadline } = this.waitDeadline(timeoutSec * 1000); let lastStatus = 'not found'; for (;;) { - const result = await this.evaluateInPage( + const result = await this.client.evaluateInHelperWorld( `(function resolveFillTarget(selector) { const visible = (el) => { if (!el.isConnected || el.getClientRects().length === 0) return false; @@ -1146,10 +1227,109 @@ export class BrowserHelpers { } } + // js() runs caller code in the page's own world, where the caller expects + // page globals. Built-in helpers use the client's isolated helper world. private async evaluateInPage(expression: string): Promise { await this.client.ensureAttached(); return this.client.evaluate(this.client.sessionId!, expression); } + + // Milliseconds humanized pauses may use before the cell's execution + // deadline, leaving room for the input commands themselves. + private pauseBudgetMs(): number { + const exec = this.executionDeadlineMs; + if (exec === null) return Number.POSITIVE_INFINITY; + return exec - EXECUTION_DEADLINE_MARGIN_MS - INPUT_COMMAND_RESERVE_MS - Date.now(); + } + + private async humanPause(ms: number): Promise { + const pause = Math.min(ms, Math.max(0, this.pauseBudgetMs())); + if (pause > 0) await this.waitMs(pause); + } + + // Moves the pointer to `to` along a curved, eased path from where the last + // humanized move on this target ended. The first move on a target starts + // from a random point in the viewport. + private async moveMouseTo(to: Point): Promise { + await this.client.ensureAttached(); + const targetId = this.client.targetId!; + const metrics = await this.client.sessionCommand('Page.getLayoutMetrics'); + const viewport = { + width: Math.max(1, Math.floor(metrics?.cssLayoutViewport?.clientWidth ?? to.x + 1)), + height: Math.max(1, Math.floor(metrics?.cssLayoutViewport?.clientHeight ?? to.y + 1)), + }; + const known = this.pointers.get(targetId); + const from = known ?? { + x: Math.floor(this.random() * viewport.width), + y: Math.floor(this.random() * viewport.height), + }; + const path = from.x === to.x && from.y === to.y ? [to] : mousePath(from, to, viewport, this.random); + const delays = path.map((_, index) => (index === 0 ? 0 : gaussianDelay(MOUSE_STEP_MS, 3, this.random))); + const scale = budgetScale(delays.reduce((sum, delay) => sum + delay, 0), this.pauseBudgetMs()); + // Each point has a scheduled time from the start of the move. A move + // command can take longer than a step to be acknowledged, so points whose + // successor is already due are skipped: slow acknowledgements send fewer + // events instead of stretching the movement. + const due: number[] = []; + let elapsed = 0; + for (const delay of delays) { + elapsed += Math.floor(delay * scale); + due.push(elapsed); + } + const start = Date.now(); + let last = known ?? null; + for (let index = 0; index < path.length; index++) { + const final = index === path.length - 1; + const wait = start + due[index] - Date.now(); + if (wait > 0) await this.waitMs(wait); + else if (!final && start + due[index + 1] <= Date.now()) continue; + const point = path[index]; + if (last && last.x === point.x && last.y === point.y) continue; + await this.client.sessionCommand('Input.dispatchMouseEvent', { + type: 'mouseMoved', + x: point.x, + y: point.y, + button: 'none', + buttons: 0, + }); + last = point; + this.pointers.set(targetId, point); + } + } + + // Types each code point of text as a key press at a human cadence. pressKey + // accepts any single code point; characters outside the US layout use CDP + // char events with no synthetic physical key code. + // + // Time spent waiting for key command acknowledgements counts toward the gap + // before the next key, so slow acknowledgements do not stretch the cadence. + // Before each key, the remaining pauses are scaled to fit the cell's + // deadline after the remaining keys' commands, estimated from the + // acknowledgement time measured so far. + private async typeHumanized(text: string): Promise { + const chars = [...text]; + const schedule = typingSchedule(text, this.random); + const remainingPauseMs: number[] = new Array(schedule.length + 1).fill(0); + for (let index = schedule.length - 1; index >= 0; index--) { + const key = schedule[index]; + remainingPauseMs[index] = remainingPauseMs[index + 1] + key.beforeMs + key.holdMs + key.afterMs; + } + let ackMs = 0; + for (let index = 0; index < chars.length; index++) { + const timing: KeyTiming = schedule[index]; + const expectedAckMs = index === 0 ? 0 : (ackMs / index) * (chars.length - index); + const scale = budgetScale(remainingPauseMs[index], this.pauseBudgetMs() - expectedAckMs); + const before = Math.floor(timing.beforeMs * scale); + const hold = Math.floor(timing.holdMs * scale); + if (before > 0) await this.waitMs(before); + const pressStart = Date.now(); + await this.keyPress(chars[index], undefined, hold); + const keyAckMs = Math.max(0, Date.now() - pressStart - hold); + ackMs += keyAckMs; + const after = Math.floor(timing.afterMs * scale) - keyAckMs; + if (after > 0) await this.waitMs(after); + } + } } export function buildBrowserGlobals(helpers: BrowserHelpers): Record { diff --git a/server/runtime/browser-repl-help.ts b/server/runtime/browser-repl-help.ts index f38721c7..77725ba8 100644 --- a/server/runtime/browser-repl-help.ts +++ b/server/runtime/browser-repl-help.ts @@ -70,18 +70,18 @@ export const browserReplHelpRegistry = { click: { signature: 'click(target, options?)', description: - '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.', + '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.', example: 'await click({ backendNodeId: submit.backendNodeId });', }, typeText: { signature: 'typeText(text)', description: - 'Insert text into the focused element with CDP `Input.insertText`. This is text insertion, not a sequence of physical key presses.', + '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: { signature: 'fillInput(target, text, options?)', description: - '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`).', + '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`).', example: 'await fillInput("input[name=email]", "person@example.com");', }, pressKey: { @@ -93,7 +93,7 @@ export const browserReplHelpRegistry = { scroll: { signature: 'scroll(x, y, dy?, dx?)', description: - '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.', + '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: { signature: 'captureScreenshot(path?, fullPage?, maxDim?)', @@ -158,7 +158,7 @@ export const browserReplHelpRegistry = { js: { signature: 'js(expressionOrFunction, options?)', description: - '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.', + '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.', example: 'const title = await js(() => document.title);\nconst text = await js(selector => document.querySelector(selector)?.textContent, { arg: "main" });', }, diff --git a/server/runtime/browser-repl.ts b/server/runtime/browser-repl.ts index 9c4ad8d1..05adff4a 100644 --- a/server/runtime/browser-repl.ts +++ b/server/runtime/browser-repl.ts @@ -18,6 +18,7 @@ const SOCKET_PATH = process.env.BROWSER_REPL_SOCKET || '/tmp/browser-repl.sock'; const REPL_ID = process.env.BROWSER_REPL_ID || 'unknown'; const CDP_ENDPOINT = process.env.CDP_ENDPOINT || 'ws://127.0.0.1:9222'; const CUSTOM_TOOLS_STATE_PATH = `${SOCKET_PATH}.custom-tools.json`; +const CUSTOM_TOOLS_DIRTY_PATH = `${SOCKET_PATH}.custom-tools.dirty`; // Keep the endpoint discoverable by dynamically imported browser clients even // when the image relies on the runtime's default rather than an explicit env. process.env.CDP_ENDPOINT = CDP_ENDPOINT; @@ -339,6 +340,7 @@ const customToolRegistry = new CustomWebMCPRegistry( }); }, publishCustomTools, + CUSTOM_TOOLS_DIRTY_PATH, ); publishCustomTools([]); customToolRegistry.setErrorHandler((message) => process.stderr.write(`[custom-webmcp] ${message}\n`)); diff --git a/server/runtime/custom-webmcp-page-runtime.ts b/server/runtime/custom-webmcp-page-runtime.ts index 65183572..eecd4109 100644 --- a/server/runtime/custom-webmcp-page-runtime.ts +++ b/server/runtime/custom-webmcp-page-runtime.ts @@ -114,7 +114,11 @@ export class CustomWebMCPPageRuntime { async dispose(sessionId: string, runtimeKey: string, contextId?: number): Promise { const params: Record = { - expression: `globalThis[${JSON.stringify(runtimeKey)}]?.dispose?.()`, + expression: `(() => { + const key = ${JSON.stringify(runtimeKey)}; + globalThis[key]?.dispose?.(); + delete globalThis[key]; + })()`, awaitPromise: true, }; if (contextId !== undefined) params.contextId = contextId; diff --git a/server/runtime/custom-webmcp.test.ts b/server/runtime/custom-webmcp.test.ts index e5fca7c8..32a7cd9d 100644 --- a/server/runtime/custom-webmcp.test.ts +++ b/server/runtime/custom-webmcp.test.ts @@ -1,6 +1,10 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import { matchesURLPattern } from './custom-webmcp.ts'; +import { existsSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { BrowserReplCdpClient } from './browser-cdp-client.ts'; +import { CustomWebMCPRegistry, matchesURLPattern } from './custom-webmcp.ts'; test('matches URL patterns across top-level and nested frame URLs', () => { assert.equal( @@ -34,3 +38,160 @@ test('supports wildcard schemes and host boundaries', () => { assert.equal(matchesURLPattern('https://evil.com/form?next=.example.com/path', '*://*.example.com/*'), false); assert.equal(matchesURLPattern('chrome-extension://abc/.example.com/form', '*://*.example.com/*'), false); }); + +test('an empty registry leaves open pages untouched', async () => { + const sent: string[] = []; + const client = { + async ensureConnected() {}, + async send(method: string) { + sent.push(method); + return {}; + }, + async listTargets() { + return [{ targetId: 'page-1', type: 'page', title: '', url: 'https://example.com/', attached: false }]; + }, + subscribeEvents: () => () => {}, + subscribeDisconnect: () => () => {}, + }; + const registry = new CustomWebMCPRegistry( + client as unknown as BrowserReplCdpClient, + (_signal, callback) => callback(), + () => {}, + ); + await (registry as any).reconcile(); + await registry.dispose(); + assert.deepEqual(sent, ['Target.setDiscoverTargets']); +}); + +test('a dirty marker from an earlier process sweeps pages until cleanup succeeds', async () => { + const marker = join(mkdtempSync(join(tmpdir(), 'custom-webmcp-')), 'dirty'); + writeFileSync(marker, ''); + const sent: string[] = []; + let failDispose = true; + const client = { + async ensureConnected() {}, + async send(method: string, params?: any) { + sent.push(method); + if (method === 'Target.attachToTarget') return { sessionId: 'session-1' }; + if (method === 'Page.getFrameTree') return { frameTree: { frame: { id: 'frame-1', loaderId: 'l', url: 'https://example.com/' } } }; + if (method === 'Page.createIsolatedWorld') return { executionContextId: 7 }; + if (method === 'Runtime.evaluate' && String(params?.expression).includes('delete globalThis')) { + if (failDispose) throw new Error('timed out'); + return {}; + } + if (method === 'Runtime.evaluate') return { result: { value: [] } }; + return {}; + }, + async listTargets() { + return [{ targetId: 'page-1', type: 'page', title: '', url: 'https://example.com/', attached: false }]; + }, + subscribeEvents: () => () => {}, + subscribeDisconnect: () => () => {}, + }; + const registry = new CustomWebMCPRegistry( + client as unknown as BrowserReplCdpClient, + (_signal, callback) => callback(), + () => {}, + marker, + ); + await (registry as any).reconcile(); + assert.ok(sent.includes('Target.attachToTarget')); + assert.ok(existsSync(marker), 'a failed cleanup keeps the marker'); + + sent.length = 0; + failDispose = false; + await (registry as any).reconcile(); + assert.ok(sent.includes('Target.attachToTarget'), 'the retry sweeps the page again'); + assert.ok(!existsSync(marker), 'a successful cleanup clears the marker'); + await registry.dispose(); +}); + +function recoveryClient(options: { failAttachOnce?: boolean; failWorldOnce?: boolean } = {}) { + const sent: string[] = []; + let failAttach = options.failAttachOnce ?? false; + let failWorld = options.failWorldOnce ?? false; + const client = { + async ensureConnected() {}, + async send(method: string) { + sent.push(method); + if (method === 'Target.attachToTarget') { + if (failAttach) { + failAttach = false; + throw new Error('attach failed'); + } + return { sessionId: 'session-1' }; + } + if (method === 'Page.getFrameTree') return { frameTree: { frame: { id: 'frame-1', loaderId: 'l', url: 'https://example.com/' } } }; + if (method === 'Page.createIsolatedWorld') { + if (failWorld) { + failWorld = false; + throw new Error('timed out'); + } + return { executionContextId: 7 }; + } + if (method === 'Runtime.evaluate') return { result: { value: [] } }; + return {}; + }, + async listTargets() { + return [{ targetId: 'page-1', type: 'page', title: '', url: 'https://example.com/', attached: false }]; + }, + subscribeEvents: () => () => {}, + subscribeDisconnect: () => () => {}, + }; + return { client: client as unknown as BrowserReplCdpClient, sent }; +} + +function markedRegistry(client: BrowserReplCdpClient) { + const marker = join(mkdtempSync(join(tmpdir(), 'custom-webmcp-')), 'dirty'); + writeFileSync(marker, ''); + const registry = new CustomWebMCPRegistry(client, (_signal, callback) => callback(), () => {}, marker); + return { registry, marker }; +} + +test('a recovery sweep that could not attach to a page keeps the marker', async () => { + const { client, sent } = recoveryClient({ failAttachOnce: true }); + const { registry, marker } = markedRegistry(client); + await (registry as any).reconcile(); + assert.ok(existsSync(marker), 'an unattached page keeps the marker'); + sent.length = 0; + await (registry as any).reconcile(); + assert.ok(sent.includes('Target.attachToTarget'), 'the retry attaches to the page'); + assert.ok(!existsSync(marker)); + await registry.dispose(); +}); + +test('a graceful dispose after a complete sweep clears the marker', async () => { + const { client } = recoveryClient(); + const { registry, marker } = markedRegistry(client); + await registry.add({ + namespace: 'probe', + tools: [{ + kind: 'page', + match: { url_patterns: ['https://example.com/*'] }, + tool: { name: 'title', description: 'Read the title', inputSchema: { type: 'object', properties: {} } }, + execute: () => 'title', + }], + } as any); + assert.ok(existsSync(marker)); + await registry.dispose(); + assert.ok(!existsSync(marker)); +}); + +test('a dispose before any sweep keeps a marker from an earlier process', async () => { + const { client } = recoveryClient(); + const { registry, marker } = markedRegistry(client); + await registry.dispose(); + assert.ok(existsSync(marker)); +}); + +test('a recovery sweep that could not create the isolated world keeps the marker', async () => { + const { client, sent } = recoveryClient({ failWorldOnce: true }); + const { registry, marker } = markedRegistry(client); + await (registry as any).reconcile(); + assert.ok(existsSync(marker), 'a page without its isolated world keeps the marker'); + sent.length = 0; + await (registry as any).reconcile(); + assert.ok(sent.includes('Page.createIsolatedWorld'), 'the retry creates the world'); + assert.ok(!existsSync(marker)); + await registry.dispose(); +}); diff --git a/server/runtime/custom-webmcp.ts b/server/runtime/custom-webmcp.ts index 028da74e..c8069177 100644 --- a/server/runtime/custom-webmcp.ts +++ b/server/runtime/custom-webmcp.ts @@ -1,3 +1,4 @@ +import { existsSync, rmSync, writeFileSync } from 'node:fs'; import type { BrowserReplCdpClient, CdpEvent, CdpTarget } from './browser-cdp-client'; import { CustomToolDefinitions, matchesURLPattern, normalizedURL } from './custom-webmcp-definitions.ts'; import type { AddCustomToolsInput, CustomToolDefinition, CustomToolFrameMatch, CustomToolSummary } from './custom-webmcp-definitions.ts'; @@ -71,13 +72,25 @@ export class CustomWebMCPRegistry { private readonly unsubscribeDisconnect: () => void; private onError?: (message: string) => void; private readonly client: BrowserReplCdpClient; + // Pages may hold registrations from this or an earlier REPL process until a + // cleanup pass succeeds. The marker file outlives an abrupt process death so + // the next process knows to sweep open pages; without it, an empty registry + // never attaches to pages at all. + private readonly dirtyMarkerPath?: string; + private dirty: boolean; + // Whether this connection's page records cover every open page: the last + // sweep tracked each page it tried, and the connection has not dropped. + private swept = false; constructor( client: BrowserReplCdpClient, runInvocation: (signal: AbortSignal, callback: () => Promise, fromPage: boolean) => Promise, publishDefinitions: (tools: CustomToolSummary[]) => void, + dirtyMarkerPath?: string, ) { this.client = client; + this.dirtyMarkerPath = dirtyMarkerPath; + this.dirty = dirtyMarkerPath !== undefined && existsSync(dirtyMarkerPath); this.definitions = new CustomToolDefinitions(publishDefinitions); this.pageRuntime = new CustomWebMCPPageRuntime(client, runInvocation, (sessionId, id, revision) => { const targetId = this.sessions.get(sessionId); @@ -139,19 +152,27 @@ export class CustomWebMCPRegistry { this.unsubscribeDisconnect(); if (this.reconcileTimer) clearTimeout(this.reconcileTimer); if (this.reconnectTimer) clearTimeout(this.reconnectTimer); + let settled = true; if (this.reconciliation) { - await Promise.race([ - this.reconciliation.catch(() => undefined), - new Promise((resolve) => setTimeout(resolve, 500)), + settled = await Promise.race([ + this.reconciliation.then(() => true, () => true), + new Promise((resolve) => setTimeout(() => resolve(false), 500)), ]); } this.pageRuntime.abortAll(); - await Promise.all([...this.pages.values()].map(async (page) => { - await this.pageRuntime.dispose(page.sessionId, MAIN_PAGE_RUNTIME_KEY); - if (page.contextId !== null) await this.pageRuntime.dispose(page.sessionId, PAGE_RUNTIME_KEY, page.contextId); - await this.detachPage(page); + const pageCleanup = await Promise.all([...this.pages.values()].map(async (page) => { + const mainDisposed = await this.pageRuntime.dispose(page.sessionId, MAIN_PAGE_RUNTIME_KEY); + const isolatedDisposed = page.contextId !== null && + await this.pageRuntime.dispose(page.sessionId, PAGE_RUNTIME_KEY, page.contextId); + const detached = await this.detachPage(page); + return mainDisposed && isolatedDisposed && detached; })); - await Promise.all([...this.iframeSessions.values()].map((frame) => this.detachSession(frame.sessionId))); + const frameCleanup = await Promise.all( + [...this.iframeSessions.values()].map((frame) => this.detachSession(frame.sessionId)), + ); + if (settled && this.swept && pageCleanup.every(Boolean) && frameCleanup.every(Boolean)) { + this.setDirty(false); + } this.pages.clear(); this.sessions.clear(); this.iframeSessions.clear(); @@ -192,6 +213,7 @@ export class CustomWebMCPRegistry { private handleDisconnect(): void { this.connectionGeneration++; + this.swept = false; this.emptyRegistryCleaned = false; this.pages.clear(); this.sessions.clear(); @@ -278,7 +300,11 @@ export class CustomWebMCPRegistry { } } - await Promise.all(pages.map(async (target) => { + // With no definitions and no registrations possibly left on pages, there + // is nothing to install or remove, so pages are left untouched. + if (this.definitions.size > 0) this.setDirty(true); + const reconcilable = this.dirty ? pages : []; + await Promise.all(reconcilable.map(async (target) => { try { await this.reconcilePage(target, targets); } catch (error) { @@ -298,12 +324,18 @@ export class CustomWebMCPRegistry { this.retryReconcile(); } })); + // A page whose attachment failed has no record, so cleanup cannot reach + // it; the sweep is incomplete until every page has one. + this.swept = reconcilable.every((target) => this.pages.has(target.targetId)); if (this.definitions.size === 0) { const cleanupGeneration = this.connectionGeneration; const pageCleanup = await Promise.all([...this.pages.values()].map(async (page) => { const mainDisposed = await this.pageRuntime.dispose(page.sessionId, MAIN_PAGE_RUNTIME_KEY); - const isolatedDisposed = page.contextId === null || + // Without its isolated world, a page may still hold CDP tool + // registrations from an earlier process; only disposing that world + // shows they are gone. + const isolatedDisposed = page.contextId !== null && await this.pageRuntime.dispose(page.sessionId, PAGE_RUNTIME_KEY, page.contextId); const detached = await this.detachPage(page); return mainDisposed && isolatedDisposed && detached; @@ -315,12 +347,22 @@ export class CustomWebMCPRegistry { this.sessions.clear(); this.iframeSessions.clear(); this.iframeTargetsBySession.clear(); - this.emptyRegistryCleaned = cleanupGeneration === this.connectionGeneration && + this.emptyRegistryCleaned = cleanupGeneration === this.connectionGeneration && this.swept && pageCleanup.every(Boolean) && frameCleanup.every(Boolean); - if (!this.emptyRegistryCleaned) this.retryReconcile(); + this.swept = false; + if (this.emptyRegistryCleaned) this.setDirty(false); + else this.retryReconcile(); } } + private setDirty(dirty: boolean): void { + if (this.dirty === dirty) return; + this.dirty = dirty; + if (this.dirtyMarkerPath === undefined) return; + if (dirty) writeFileSync(this.dirtyMarkerPath, '', {mode: 0o600}); + else rmSync(this.dirtyMarkerPath, {force: true}); + } + private async reconcilePage(target: CdpTarget, targets: CdpTarget[]): Promise { let page = this.pages.get(target.targetId); if (!page) { @@ -346,8 +388,9 @@ export class CustomWebMCPRegistry { }; this.pages.set(target.targetId, page); this.sessions.set(page.sessionId, target.targetId); + // Runtime.bindingCalled is delivered without Runtime.enable, which would + // make Chromium preview console arguments in a way pages can observe. await this.client.send('Page.enable', undefined, page.sessionId, RECONCILE_COMMAND_TIMEOUT_MS); - await this.client.send('Runtime.enable', undefined, page.sessionId, RECONCILE_COMMAND_TIMEOUT_MS); if (this.disposed) { this.pages.delete(target.targetId); this.sessions.delete(page.sessionId); diff --git a/server/runtime/humanize.test.ts b/server/runtime/humanize.test.ts new file mode 100644 index 00000000..cd2184b9 --- /dev/null +++ b/server/runtime/humanize.test.ts @@ -0,0 +1,81 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { + budgetScale, + gaussianDelay, + mousePath, + splitWordChunks, + typingSchedule, + uniformJitter, +} from './humanize.ts'; + +// Deterministic generator so path shape assertions are reproducible. +function seeded(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state * 1664525 + 1013904223) >>> 0; + return state / 2 ** 32; + }; +} + +test('mousePath curves from the start to exactly the target inside the viewport', () => { + for (let seed = 1; seed <= 50; seed++) { + const path = mousePath({ x: 5, y: 590 }, { x: 412.5, y: 7.25 }, { width: 800, height: 600 }, seeded(seed)); + assert.ok(path.length >= 5 && path.length <= 80, `path length ${path.length}`); + assert.deepEqual(path.at(-1), { x: 412.5, y: 7.25 }); + for (const point of path) { + assert.ok(point.x >= 0 && point.x <= 799 && point.y >= 0 && point.y <= 599, JSON.stringify(point)); + } + } +}); + +test('mousePath is not a straight line', () => { + const path = mousePath({ x: 0, y: 300 }, { x: 600, y: 300 }, { width: 800, height: 600 }, seeded(7)); + assert.ok(path.some((point) => point.y !== 300)); +}); + +test('delays stay within their documented bounds', () => { + const random = seeded(3); + for (let i = 0; i < 1000; i++) { + const gaussian = gaussianDelay(10, 3, random); + assert.ok(gaussian >= 3 && gaussian <= 30, `gaussian ${gaussian}`); + const uniform = uniformJitter(140, 60, 60, random); + assert.ok(uniform >= 80 && uniform <= 200, `uniform ${uniform}`); + } +}); + +test('splitWordChunks keeps trailing whitespace with each word', () => { + assert.deepEqual(splitWordChunks('Hello world. How are\tyou?'), ['Hello ', 'world. ', 'How ', 'are\t', 'you?']); + assert.deepEqual(splitWordChunks(' lead'), [' ', 'lead']); + assert.deepEqual(splitWordChunks(''), []); +}); + +test('typingSchedule times every code point and pauses longer between words', () => { + const text = 'Hi. café 😀'; + const schedule = typingSchedule(text, seeded(11)); + assert.equal(schedule.length, [...text].length); + assert.equal(schedule[0].beforeMs, 0); + for (const key of schedule) { + const interval = key.holdMs + key.afterMs; + assert.ok(interval >= 50 && interval <= 119, `interval ${interval}`); + } + // "c" starts the second word, after a sentence end: (80..200) * 1.5. + assert.ok(schedule[4].beforeMs >= 120 && schedule[4].beforeMs <= 300, `pause ${schedule[4].beforeMs}`); + assert.equal(schedule[5].beforeMs, 0); +}); + +test('budgetScale only ever shrinks pauses', () => { + assert.equal(budgetScale(100, Number.POSITIVE_INFINITY), 1); + assert.equal(budgetScale(100, 100), 1); + assert.equal(budgetScale(200, 50), 0.25); + assert.equal(budgetScale(200, -10), 0); +}); + +test('mousePath stays bounded for very distant targets', () => { + const started = Date.now(); + const path = mousePath({ x: 0, y: 0 }, { x: 1e12, y: 5 }, { width: 800, height: 600 }, seeded(5)); + assert.ok(path.length <= 80); + assert.deepEqual(path.at(-1), { x: 1e12, y: 5 }); + assert.ok(Date.now() - started < 1_000); +}); diff --git a/server/runtime/humanize.ts b/server/runtime/humanize.ts new file mode 100644 index 00000000..9c4ef57e --- /dev/null +++ b/server/runtime/humanize.ts @@ -0,0 +1,165 @@ +// Human-like pointer paths and typing cadence for Browser REPL input. The +// algorithms mirror the computer API's server/lib/mousetrajectory and +// server/lib/typinghumanizer so both input surfaces move the same way. + +export type Random = () => number; + +export interface Point { + x: number; + y: number; +} + +// Bezier control points are drawn from this far beyond the start/end box. +const BOUNDS_PADDING = 80; +const KNOTS_COUNT = 2; +const DISTORTION_MEAN = 1; +const DISTORTION_STDEV = 1; +const DISTORTION_FREQ = 0.5; +const PATH_LENGTH_SCALE = 20; +const MIN_POINTS = 5; +const MAX_POINTS = 80; +// Upper bound on curve samples, which otherwise grow with distance. +const MAX_CURVE_SAMPLES = 2_000; + +function normal(random: Random, mean: number, stdDev: number): number { + const u1 = Math.max(random(), 1e-10); + const u2 = random(); + return mean + stdDev * Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2); +} + +function binomial(n: number, k: number): number { + let result = 1; + for (let i = 1; i <= k; i++) result = (result * (n - k + i)) / i; + return result; +} + +function bezierPoint(controls: Point[], t: number): Point { + const n = controls.length - 1; + let x = 0; + let y = 0; + for (let i = 0; i <= n; i++) { + const weight = binomial(n, i) * t ** i * (1 - t) ** (n - i); + x += controls[i].x * weight; + y += controls[i].y * weight; + } + return { x, y }; +} + +// Returns a curved path from `from` to `to` that ends exactly at `to`. Points +// are eased so movement decelerates into the target, with small jitter along +// the way. Intermediate points are clamped to the viewport. +export function mousePath( + from: Point, + to: Point, + viewport: { width: number; height: number }, + random: Random = Math.random, +): Point[] { + const left = Math.min(from.x, to.x) - BOUNDS_PADDING; + const right = Math.max(from.x, to.x) + BOUNDS_PADDING; + const top = Math.min(from.y, to.y) - BOUNDS_PADDING; + const bottom = Math.max(from.y, to.y) + BOUNDS_PADDING; + const knots: Point[] = []; + for (let i = 0; i < KNOTS_COUNT; i++) { + knots.push({ x: left + random() * (right - left), y: top + random() * (bottom - top) }); + } + const controls = [from, ...knots, to]; + + const curveCount = Math.min( + MAX_CURVE_SAMPLES, + Math.max(Math.ceil(Math.abs(from.x - to.x)), Math.ceil(Math.abs(from.y - to.y)), 2), + ); + const curve: Point[] = []; + for (let i = 0; i < curveCount; i++) { + curve.push(bezierPoint(controls, i / (curveCount - 1))); + } + for (let i = 1; i < curve.length - 1; i++) { + if (random() < DISTORTION_FREQ) { + const delta = Math.round(normal(random, DISTORTION_MEAN, DISTORTION_STDEV)); + curve[i] = { x: curve[i].x + delta, y: curve[i].y + delta }; + } + } + + let length = 0; + for (let i = 1; i < curve.length; i++) { + length += Math.hypot(curve[i].x - curve[i - 1].x, curve[i].y - curve[i - 1].y); + } + const count = Math.min(MAX_POINTS, Math.max(MIN_POINTS, Math.floor(length ** 0.25 * PATH_LENGTH_SCALE))); + const maxX = Math.max(0, viewport.width - 1); + const maxY = Math.max(0, viewport.height - 1); + const points: Point[] = []; + for (let i = 0; i < count; i++) { + const t = i / (count - 1); + const eased = -t * (t - 2); + const index = Math.min(curve.length - 1, Math.max(0, Math.floor(eased * (curve.length - 1)))); + points.push({ + x: Math.min(maxX, Math.max(0, Math.round(curve[index].x))), + y: Math.min(maxY, Math.max(0, Math.round(curve[index].y))), + }); + } + points[points.length - 1] = { x: to.x, y: to.y }; + return points; +} + +// Gaussian delay centered on meanMs with a stddev of 40% of the mean, clamped +// to [minMs, 3 * meanMs], so step timing has natural motor variance. +export function gaussianDelay(meanMs: number, minMs: number, random: Random = Math.random): number { + const delay = Math.round(normal(random, meanMs, meanMs * 0.4)); + return Math.min(meanMs * 3, Math.max(minMs, delay)); +} + +// Uniform delay in [baseMs - jitterMs, baseMs + jitterMs], clamped to minMs. +export function uniformJitter(baseMs: number, jitterMs: number, minMs: number, random: Random = Math.random): number { + const ms = baseMs - jitterMs + Math.floor(random() * (2 * jitterMs + 1)); + return Math.max(minMs, ms); +} + +// Splits text into word-sized chunks that keep their trailing whitespace: +// "Hello world. Bye" becomes ["Hello ", "world. ", "Bye"]. +export function splitWordChunks(text: string): string[] { + return text.match(/\S*\s+|\S+$/gu) ?? []; +} + +export function isSentenceEnd(chunk: string): boolean { + return /[.!?]\s*$/u.test(chunk); +} + +export interface KeyTiming { + // Pause before the key goes down: zero within a word, longer between words. + beforeMs: number; + // Time the key is held down. + holdMs: number; + // Time after the key comes up, before the next key. + afterMs: number; +} + +// Returns the timing of each code point of `text`. Keystrokes within a word +// share an interval of 50-119 ms, split evenly between holding the key and the +// gap after it; words are separated by a longer pause, and sentences by a +// longer one still. +export function typingSchedule(text: string, random: Random = Math.random): KeyTiming[] { + const schedule: KeyTiming[] = []; + let pauseBeforeWord = 0; + for (const chunk of splitWordChunks(text)) { + const interval = keystrokeInterval(random); + const holdMs = Math.floor(interval / 2); + let first = true; + for (const _ of chunk) { + schedule.push({ beforeMs: first ? pauseBeforeWord : 0, holdMs, afterMs: interval - holdMs }); + first = false; + } + pauseBeforeWord = uniformJitter(140, 60, 60, random); + if (isSentenceEnd(chunk)) pauseBeforeWord = Math.floor((pauseBeforeWord * 3) / 2); + } + return schedule; +} + +export function keystrokeInterval(random: Random = Math.random): number { + return 50 + Math.floor(random() * 70); +} + +// Returns the factor that scales totalMs of pauses down to fit budgetMs, so a +// cell's execution deadline is not spent on cosmetic pauses. +export function budgetScale(totalMs: number, budgetMs: number): number { + if (totalMs <= budgetMs) return 1; + return Math.max(0, budgetMs) / totalMs; +}