The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.
JavaScript agent-skillsai-agentautomationbrowserbrowser-automationclaude-codecodexhermes-agentskillsskills-sh
add page-scoped keyboard and file input
Aute49be74216cdc
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjsindex 806fa00..2cbaf0c 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs@@ -240,6 +240,39 @@ export function pageBasicOperationsCase() {"function evaluate surfaces page exceptions");+ await first.fill("#text-input", "page keyboard");+ await first.evaluate(() => {+ const input = document.querySelector("#text-input");+ input.focus();+ input.setSelectionRange(input.value.length, input.value.length);+ });+ await first.keyboard.type(" 世界");+ assertEqual(+ await first.evaluate("document.querySelector('#text-input').value"),+ "page keyboard 世界",+ "page.keyboard.type inserts Unicode text in the addressed page"+ );+ await first.keyboard.press(process.platform === "darwin" ? "Meta+A" : "Control+A");+ await first.keyboard.type("replaced");+ assertEqual(+ await first.evaluate("document.querySelector('#text-input').value"),+ "replaced",+ "page.keyboard.press accepts platform shortcut chords"+ );+ await first.keyboard.dispatch("#text-input", "Escape", "keydown");+ assertIncludes(+ await first.evaluate("window.__fixtureState.keys.join(',')"),+ "Escape",+ "page.keyboard.dispatch targets an element in the addressed page"+ );+ await first.setInputFiles("#file-input", [uploadPath, uploadPathTwo]);+ assertEqual(+ await first.evaluate("Array.from(document.querySelector('#file-input').files).map(file => file.name).join(',')"),+ "fixture-upload.txt,fixture-upload-two.txt",+ "page.setInputFiles attaches multiple files in the addressed page"+ );+ assertEqual((await currentTab()).targetId, first.targetId, "Page keyboard and file methods keep their Page active");+const screenshotPath = join(tempDir, "page-api-first.png");assertEqual(await first.screenshot(screenshotPath, { full: false }),diff --git a/package/ego-browser/src/driver/keyboard.ts b/package/ego-browser/src/driver/keyboard.tsindex 1e5682c..0065080 100644--- a/package/ego-browser/src/driver/keyboard.ts+++ b/package/ego-browser/src/driver/keyboard.ts@@ -8,6 +8,16 @@ type FillInputOptions = {timeout?: number;};+export type KeyboardServices = {+ cdp(+ method: string,+ params?: Record<string, unknown>,+ sessionId?: string,+ timeoutMs?: number,+ ): Promise<any>;+ sleep(ms: number): Promise<void>;+};+const KEYS = {Enter: { vk: 13, key: "Enter", code: "Enter", text: "\r" },Tab: { vk: 9, key: "Tab", code: "Tab", text: "\t" },@@ -31,7 +41,21 @@ const META_MODIFIER = 4;const INPUT_EVENT_DELAY_MS = 25;const INPUT_DISPATCH_TIMEOUT_MS = 1000;-function keyDefinition(key) {+const defaultKeyboardServices: KeyboardServices = {+ async cdp(method, params = {}, sessionId, timeoutMs) {+ // Keep the legacy cdp() override path for calls without a custom timeout.+ // Timed input dispatches use browserCdp() so a stalled native request can+ // still fall back to the synthetic event probe.+ if (timeoutMs === undefined) {+ return cdp(method, params, sessionId);+ }+ const response = await browserCdp(method, params, sessionId, timeoutMs);+ return response?.result || {};+ },+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),+};++export function keyDefinition(key) {const special = KEYS[key];if (special) {return special;@@ -69,6 +93,16 @@ function editingCommandsForKey(key, modifiers) {* @returns {Promise<void>}*/export async function pressKey(key, modifiers = 0) {+ return pressKeyInPage(defaultKeyboardServices, undefined, key, modifiers);+}++/** Dispatch one key press through an explicit Page session. */+export async function pressKeyInPage(+ services: KeyboardServices,+ sessionId: string | undefined,+ key: string,+ modifiers = 0,+) {const { vk, code, text } = keyDefinition(key);const base = {key,@@ -78,22 +112,22 @@ export async function pressKey(key, modifiers = 0) {nativeVirtualKeyCode: vk,};const commands = editingCommandsForKey(key, modifiers);- const probeId = await installKeyProbe(key);+ const probeId = await installKeyProbe(services, sessionId, key);let dispatchError: unknown = null;try {- await dispatchKeyEvent({+ await dispatchKeyEvent(services, sessionId, {type: "keyDown",...base,...(text ? { text, unmodifiedText: text } : {}),...(commands ? { commands } : {}),});- await inputEventDelay();- await dispatchKeyEvent({ type: "keyUp", ...base });+ await inputEventDelay(services);+ await dispatchKeyEvent(services, sessionId, { type: "keyUp", ...base });} catch (error) {if (!isKeyDispatchTimeout(error)) throw error;dispatchError = error;}- const completed = await finishKeyProbe(probeId, {+ const completed = await finishKeyProbe(services, sessionId, probeId, {key,code,text,@@ -108,7 +142,19 @@ export async function pressKey(key, modifiers = 0) {* @returns {Promise<void>}*/export async function typeText(text) {- await cdp("Input.insertText", { text });+ await typeTextInPage(defaultKeyboardServices, undefined, text);+}++/** Insert text through an explicit Page session. */+export async function typeTextInPage(+ services: KeyboardServices,+ sessionId: string | undefined,+ text: string,+) {+ if (typeof text !== "string") {+ throw new TypeError("page.keyboard.type text must be a string");+ }+ await services.cdp("Input.insertText", { text }, sessionId);}/**@@ -189,25 +235,35 @@ export async function dispatchKey(selector, key = "Enter", event = "keypress") {);}-function inputEventDelay() {- return new Promise((resolve) => setTimeout(resolve, INPUT_EVENT_DELAY_MS));+function inputEventDelay(services: KeyboardServices) {+ return services.sleep(INPUT_EVENT_DELAY_MS);}-async function dispatchKeyEvent(params: Record<string, unknown>) {- await browserCdp(+async function dispatchKeyEvent(+ services: KeyboardServices,+ sessionId: string | undefined,+ params: Record<string, unknown>,+) {+ await services.cdp("Input.dispatchKeyEvent",params,- undefined,+ sessionId,INPUT_DISPATCH_TIMEOUT_MS,);}-async function installKeyProbe(key: string) {+async function installKeyProbe(+ services: KeyboardServices,+ sessionId: string | undefined,+ key: string,+) {if (!canProbeInputFallback()) return null;const id = `key_${Date.now()}_${Math.random().toString(16).slice(2)}`;try {- const result = await cdp("Runtime.evaluate", {- expression: `(() => {+ const result = await services.cdp(+ "Runtime.evaluate",+ {+ expression: `(() => {window.__egoBrowserInputProbes ||= {};const probe = { seen: false };probe.handler = (event) => {@@ -217,9 +273,11 @@ async function installKeyProbe(key: string) {window.__egoBrowserInputProbes[${JSON.stringify(id)}] = probe;return true;})()`,- returnByValue: true,- awaitPromise: false,- });+ returnByValue: true,+ awaitPromise: false,+ },+ sessionId,+ );return result.result?.value ? id : null;} catch {return null;@@ -227,14 +285,18 @@ async function installKeyProbe(key: string) {}async function finishKeyProbe(+ services: KeyboardServices,+ sessionId: string | undefined,id: string | null,definition: { key: string; code: string; text: string; commands?: string[] },) {if (!id) return false;- await inputEventDelay();+ await inputEventDelay(services);try {- const result = await cdp("Runtime.evaluate", {- expression: `(() => {+ const result = await services.cdp(+ "Runtime.evaluate",+ {+ expression: `(() => {const probes = window.__egoBrowserInputProbes || {};const probe = probes[${JSON.stringify(id)}];if (!probe) return { seen: false, fallback: false };@@ -319,9 +381,11 @@ async function finishKeyProbe(target.dispatchEvent(new KeyboardEvent("keyup", keyboardInit));return { seen: false, fallback: true };})()`,- returnByValue: true,- awaitPromise: false,- });+ returnByValue: true,+ awaitPromise: false,+ },+ sessionId,+ );const value = result.result?.value;return Boolean(value?.seen || value?.fallback);} catch {diff --git a/package/ego-browser/src/driver/page-input.ts b/package/ego-browser/src/driver/page-input.tsnew file mode 100644index 0000000..e334e68--- /dev/null+++ b/package/ego-browser/src/driver/page-input.ts@@ -0,0 +1,138 @@+import { isAbsolute } from "node:path";++import { resolveElementObjectId } from "../element-resolver.js";+import { type RefMap } from "../ref-map.js";+import { keyDefinition, type KeyboardServices } from "./keyboard.js";++type PageInputServices = KeyboardServices;++const MODIFIER_BITS: Record<string, number> = {+ alt: 1,+ control: 2,+ ctrl: 2,+ meta: 4,+ command: 4,+ shift: 8,+};++/** Parse Playwright-style key chords such as Meta+A or Control+Shift+P. */+export function parseKeyChord(chord: string): {+ key: string;+ modifiers: number;+} {+ if (typeof chord !== "string" || chord.trim().length === 0) {+ throw new TypeError("page.keyboard.press requires a non-empty key");+ }+ const parts = chord.split("+");+ const key = parts.pop()?.trim() || "";+ if (!key) {+ throw new TypeError(`page.keyboard.press received invalid chord: ${chord}`);+ }+ let modifiers = 0;+ for (const rawModifier of parts) {+ const modifier = rawModifier.trim().toLowerCase();+ const bit = MODIFIER_BITS[modifier];+ if (!bit) {+ throw new TypeError(+ `page.keyboard.press received unsupported modifier: ${rawModifier}`,+ );+ }+ modifiers |= bit;+ }+ return { key, modifiers };+}++/** Dispatch a synthetic DOM KeyboardEvent to one resolved element. */+export async function dispatchKeyInPage(+ services: PageInputServices,+ sessionId: string,+ refMap: RefMap,+ selector: string,+ key = "Enter",+ event = "keypress",+): Promise<void> {+ if (typeof event !== "string" || event.length === 0) {+ throw new TypeError("page.keyboard.dispatch requires an event name");+ }+ const { vk, code } = keyDefinition(key);+ const resolved = await resolveElementObjectId(+ cdpAdapter(services),+ sessionId,+ refMap,+ selector,+ );+ try {+ await services.cdp(+ "Runtime.callFunctionOn",+ {+ functionDeclaration:+ "function(keyCode,key,code,event){this.focus();this.dispatchEvent(new KeyboardEvent(event,{key,code,keyCode,which:keyCode,bubbles:true}));}",+ objectId: resolved.objectId,+ arguments: [+ { value: vk },+ { value: key },+ { value: code },+ { value: event },+ ],+ returnByValue: true,+ awaitPromise: false,+ },+ resolved.sessionId,+ );+ } finally {+ await releaseObject(services, resolved.sessionId, resolved.objectId);+ }+}++/** Set one or more local files on an input in one explicit Page session. */+export async function setInputFilesInPage(+ services: PageInputServices,+ sessionId: string,+ refMap: RefMap,+ selector: string,+ path: string | string[],+): Promise<void> {+ const files = Array.isArray(path) ? path : [path];+ if (+ files.length === 0 ||+ files.some(+ (file) =>+ typeof file !== "string" || file.length === 0 || !isAbsolute(file),+ )+ ) {+ throw new TypeError("page.setInputFiles requires absolute file paths");+ }+ const resolved = await resolveElementObjectId(+ cdpAdapter(services),+ sessionId,+ refMap,+ selector,+ );+ try {+ await services.cdp(+ "DOM.setFileInputFiles",+ { files, objectId: resolved.objectId },+ resolved.sessionId,+ );+ } finally {+ await releaseObject(services, resolved.sessionId, resolved.objectId);+ }+}++function cdpAdapter(services: PageInputServices) {+ return {+ sendRaw(method, params, sessionId) {+ return services.cdp(method, params, sessionId);+ },+ };+}++async function releaseObject(+ services: PageInputServices,+ sessionId: string,+ objectId: string,+): Promise<void> {+ await services+ .cdp("Runtime.releaseObject", { objectId }, sessionId)+ .catch(() => {});+}diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjsindex 0cc352a..b2b0879 100644--- a/package/ego-browser/src/page-model.test.mjs+++ b/package/ego-browser/src/page-model.test.mjs@@ -209,6 +209,8 @@ function createFixture(rootDir) {}if (method === "Runtime.releaseObject") return {};if (method === "Input.insertText") return {};+ if (method === "Input.dispatchKeyEvent") return {};+ if (method === "DOM.setFileInputFiles") return {};if (method === "Input.dispatchMouseEvent") {if (timeoutNextMouseDispatch) {timeoutNextMouseDispatch = false;@@ -725,6 +727,67 @@ test("Page scrollBy evaluates in the addressed page", async () => {});});+test("Page keyboard press and type use the addressed target session", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const first = await task.newPage("https://example.test/first");+ await task.newPage("https://example.test/second");++ await first.keyboard.press("Meta+A");+ await first.keyboard.type("hello 世界");++ const keyCalls = fixture.calls.filter(+ ([kind, method]) =>+ kind === "cdp" &&+ (method === "Input.dispatchKeyEvent" || method === "Input.insertText"),+ );+ assert(keyCalls.length >= 3);+ assert(keyCalls.every((call) => call[3] === `session:${first.targetId}`));+ assert(+ keyCalls.some(+ ([, method, params]) =>+ method === "Input.dispatchKeyEvent" &&+ params.type === "keyDown" &&+ params.modifiers === 4 &&+ params.commands?.includes("selectAll"),+ ),+ "Meta+A must retain the native selectAll editing command",+ );+ assert(+ keyCalls.some(+ ([, method, params]) =>+ method === "Input.insertText" && params.text === "hello 世界",+ ),+ );+ assert.equal(fixture.activeTarget(), first.targetId);+ });+});++test("Page keyboard dispatch and file input resolve inside the addressed page", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const first = await task.newPage("https://example.test/first");+ await task.newPage("https://example.test/second");++ await first.keyboard.dispatch("#editor", "Enter", "keydown");+ await first.setInputFiles("#upload", ["/tmp/one.txt", "/tmp/two.txt"]);++ const dispatchCall = fixture.calls.find(+ ([kind, method, params]) =>+ kind === "cdp" &&+ method === "Runtime.callFunctionOn" &&+ params.functionDeclaration.includes("KeyboardEvent"),+ );+ assert.equal(dispatchCall[3], `session:${first.targetId}`);+ const uploadCall = fixture.calls.find(+ ([kind, method]) => kind === "cdp" && method === "DOM.setFileInputFiles",+ );+ assert.deepEqual(uploadCall[2].files, ["/tmp/one.txt", "/tmp/two.txt"]);+ assert.equal(uploadCall[3], `session:${first.targetId}`);+ assert.equal(fixture.activeTarget(), first.targetId);+ });+});+test("Page actions resolve snapshot refs inside the addressed page", async () => {await withFixture(async (fixture) => {const task = taskForRound(fixture, "round-a");diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.tsindex 94eef3c..8c22e33 100644--- a/package/ego-browser/src/page-model.ts+++ b/package/ego-browser/src/page-model.ts@@ -29,6 +29,12 @@ import {type PageMouseButtonOptions,type PageMouseClickOptions,} from "./driver/page-actions.js";+import {+ dispatchKeyInPage,+ parseKeyChord,+ setInputFilesInPage,+} from "./driver/page-input.js";+import { pressKeyInPage, typeTextInPage } from "./driver/keyboard.js";import { assertNoEgoError } from "./ego-errors.js";import {withPage as defaultWithPage,@@ -187,6 +193,15 @@ type MouseActionRunner = (operation: (services: PageModelServices, sessionId: string) => Promise<void>,) => Promise<PageActionReceipt>;+type KeyboardSelectorRunner = (+ selector: string,+ operation: (+ services: PageModelServices,+ sessionId: string,+ refMap: RefMap,+ ) => Promise<void>,+) => Promise<PageActionReceipt>;+/** Page-scoped mouse state and CDP Input primitives. */export class PageMouse {readonly #run: MouseActionRunner;@@ -263,6 +278,40 @@ export class PageMouse {}}+/** Page-scoped keyboard input and low-level event dispatch. */+export class PageKeyboard {+ readonly #run: MouseActionRunner;+ readonly #runForSelector: KeyboardSelectorRunner;++ constructor(run: MouseActionRunner, runForSelector: KeyboardSelectorRunner) {+ this.#run = run;+ this.#runForSelector = runForSelector;+ }++ async press(chord: string): Promise<PageActionReceipt> {+ const { key, modifiers } = parseKeyChord(chord);+ return this.#run((services, sessionId) =>+ pressKeyInPage(services, sessionId, key, modifiers),+ );+ }++ async type(text: string): Promise<PageActionReceipt> {+ return this.#run((services, sessionId) =>+ typeTextInPage(services, sessionId, text),+ );+ }++ async dispatch(+ selector: string,+ key = "Enter",+ event = "keypress",+ ): Promise<PageActionReceipt> {+ return this.#runForSelector(selector, (services, sessionId, refMap) =>+ dispatchKeyInPage(services, sessionId, refMap, selector, key, event),+ );+ }+}+export class PageBudgetError extends Error {readonly code = "EGO_PAGE_BUDGET_REACHED";readonly spaceId: number;@@ -549,6 +598,7 @@ export class Page {readonly label: string;readonly spaceId: number;readonly mouse: PageMouse;+ readonly keyboard: PageKeyboard;readonly #services: PageModelServices;#targetId?: string;#openedBy?: PageOrigin;@@ -568,6 +618,14 @@ export class Page {this.mouse = new PageMouse((operation) =>this.#runRawAction((sessionId) => operation(this.#services, sessionId)),);+ this.keyboard = new PageKeyboard(+ (operation) =>+ this.#runRawAction((sessionId) => operation(this.#services, sessionId)),+ (selector, operation) =>+ this.#runAction(selector, (sessionId, refMap) =>+ operation(this.#services, sessionId, refMap),+ ),+ );}get targetId(): string | undefined {@@ -745,6 +803,15 @@ export class Page {);}+ async setInputFiles(+ selector: string,+ path: string | string[],+ ): Promise<PageActionReceipt> {+ return this.#runAction(selector, (sessionId, refMap) =>+ setInputFilesInPage(this.#services, sessionId, refMap, selector, path),+ );+ }+async scrollBy(deltaY: number,options: { deltaX?: number; behavior?: ScrollBehavior } = {},