Skip to content

Computer use for the Pi coding agent — Windows apps, browsers and desktops through native UI trees, screenshots and real input.

feat: points, drags, held keys, timelines and pen on browser pages through Playwright (LPT-927 part b)

alexshpunt-clanker[bot]963b6bb563b5
diff --git a/src/computer-resources.ts b/src/computer-resources.ts
index 8078bfb..3f554ba 100644
--- a/src/computer-resources.ts
+++ b/src/computer-resources.ts
@@ -939,8 +939,8 @@ export class ComputerResources {
/** Typed input on the active page of a browser window through Playwright; a current DOM observation gives the change list. */
private async pageInput(window: string, session: ComputerSession, plan: InputPlan, cwd: string, signal?: AbortSignal): Promise<ComputerResult> {
if (typeof plan.web === "string") throw new ComputerRequestError(plan.web);
- if (plan.point || plan.end) throw new ComputerRequestError(`${plan.label} at a point of a browser page is not available yet; give a target, or space: "window" for window pixels.`);
- const target = typeof plan.target === "string" ? refKind(plan.target) === "page" ? { ref: plan.target } : plan.target : undefined;
+ // A page timeline carries its own points and targets; other page actions take the element target.
+ const target = plan.web.action !== "timeline" && typeof plan.target === "string" ? refKind(plan.target) === "page" ? { ref: plan.target } : plan.target : undefined;
const command = { ...plan.web, ...(target !== undefined ? { target } : {}) };
let action: WebAction;
try { action = validateWebAction(command); }
diff --git a/src/computer-tools.ts b/src/computer-tools.ts
index 8c96c6b..fa9cea8 100644
--- a/src/computer-tools.ts
+++ b/src/computer-tools.ts
@@ -1,7 +1,7 @@
import { Type, type JsonValue, type Static } from "@earendil-works/pi-ai";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { Text } from "@earendil-works/pi-tui";
-import { ComputerRequestError, type ComputerResources, type InputPlan } from "./computer-resources.ts";
+import { ComputerRequestError, refKind, type ComputerResources, type InputPlan, type InputPoint } from "./computer-resources.ts";
import type { ComputerAddress } from "./computer-address.ts";
import { computerActionRenderer } from "./computer-action-renderer.ts";
import { parseComputerViews } from "./computer-views.ts";
@@ -265,6 +265,21 @@ const shared = (params: { space?: "page" | "window"; foreground?: boolean }) =>
({ ...(params.space ? { space: params.space } : {}), ...(params.foreground !== undefined ? { foreground: params.foreground } : {}) });
const timeout = (params: { timeout_ms?: number }) => params.timeout_ms !== undefined ? { timeout_ms: params.timeout_ms } : {};
const pageModifiers = (modifiers?: string[]) => modifiers?.length ? { modifiers: modifiers.map(key => PAGE_MODIFIERS[key]) } : {};
+/** A Playwright key name for a key the native tools also take, such as ctrl, return, up or f5. */
+function pageKey(key: string): string {
+ const lower = key.toLowerCase();
+ return PAGE_MODIFIERS[lower === "control" ? "ctrl" : lower] ?? PAGE_KEYS[lower] ?? (/^f\d{1,2}$/.test(lower) ? lower.toUpperCase() : key);
+}
+/** A target inside a page timeline: a page ref, or a Playwright locator string. */
+const pageTarget = (target: string) => refKind(target) === "page" ? { ref: target } : target;
+/** A move of a page timeline to a point or to the centre of a target. */
+const pageMove = (at_ms: number, to: { target?: string; point?: InputPoint }, steps?: number) =>
+ ({ at_ms, type: "move", ...(to.target !== undefined ? { target: pageTarget(to.target) } : to.point), ...(steps ? { steps } : {}) });
+/** Keys held around a page timeline's events. */
+function holding(modifiers: string[] | undefined, start: number, end: number, events: Record<string, unknown>[]) {
+ const keys = (modifiers ?? []).map(key => PAGE_MODIFIERS[key]);
+ return [...keys.map(key => ({ at_ms: start, type: "key_down", key })), ...events, ...keys.reverse().map(key => ({ at_ms: end, type: "key_up", key }))];
+}
const clickParameters = Type.Object({
window: inputWindow, target: inputTarget("The element to click"), x: coordinate("Left"), y: coordinate("Top"), space: pointSpace,
@@ -280,8 +295,12 @@ export function clickPlan(params: Static<typeof clickParameters>): InputPlan {
: button === "right" ? count === 2 ? "A right double click works on browser pages only." : { action: "right_click", ...modifiers, ...timeout(params) }
: count === 2 ? button === "middle" ? "A middle double click works on browser pages only." : { action: "double_click", ...modifiers, ...timeout(params) }
: { action: "click", ...(button === "middle" ? { button } : {}), ...modifiers, ...timeout(params) };
- return { label: "click", ...aim(params, "click", true), ...shared(params), native,
- web: { action: "click", ...(button !== "left" ? { button } : {}), ...(count > 1 ? { click_count: count } : {}), ...pageModifiers(params.modifiers), ...timeout(params) } };
+ const aimed = aim(params, "click", true);
+ // A point of a page gets the presses Playwright's mouse.click sends, numbered so the page sees double and triple clicks.
+ const presses = Array.from({ length: count }, (_, index) => [{ at_ms: 0, type: "button_down", button, click_count: index + 1 }, { at_ms: 0, type: "button_up", button, click_count: index + 1 }]).flat();
+ return { label: "click", ...aimed, ...shared(params), native,
+ web: aimed.point ? { action: "timeline", events: holding(params.modifiers, 0, 0, [pageMove(0, aimed), ...presses]) }
+ : { action: "click", ...(button !== "left" ? { button } : {}), ...(count > 1 ? { click_count: count } : {}), ...pageModifiers(params.modifiers), ...timeout(params) } };
}
const hoverParameters = Type.Object({
@@ -292,8 +311,9 @@ const hoverParameters = Type.Object({
/** What computer_hover sends; on a native window it moves the real pointer, so it runs in the foreground. */
export function hoverPlan(params: Static<typeof hoverParameters>): InputPlan {
- return { label: "hover", ...aim(params, "hover", true), ...shared(params),
- native: { action: "hover", dwell_ms: params.dwell_ms ?? 300, ...timeout(params) }, web: { action: "hover", ...timeout(params) } };
+ const aimed = aim(params, "hover", true);
+ return { label: "hover", ...aimed, ...shared(params), native: { action: "hover", dwell_ms: params.dwell_ms ?? 300, ...timeout(params) },
+ web: aimed.point ? { action: "timeline", events: [pageMove(0, aimed)] } : { action: "hover", ...timeout(params) } };
}
const endpoint = (what: string) => Type.Object({
@@ -309,13 +329,18 @@ const dragParameters = Type.Object({
modifiers: modifiersField, foreground: foregroundField,
}, { additionalProperties: false });
-/** What computer_drag sends to a native window. */
+/** What computer_drag sends: a native drag, or a page timeline that presses, moves and releases. */
export function dragPlan(params: Static<typeof dragParameters>): InputPlan {
- const end = aim(params.to, "to", true);
- return { label: "drag", ...aim(params.from, "from", true), end, ...shared(params),
+ const start = aim(params.from, "from", true), end = aim(params.to, "to", true);
+ // On a page the drag is a timeline: press at the start, move through via to the end over duration_ms, release.
+ const duration = params.duration_ms ?? 500, button = params.button ?? "left";
+ const stops = [...(params.via ?? []).map(point => ({ point })), end];
+ const steps = Math.max(1, Math.round(duration / stops.length / 16));
+ const web = { action: "timeline", events: holding(params.modifiers, 0, duration, [pageMove(0, start), { at_ms: 0, type: "button_down", button },
+ ...stops.map((stop, index) => pageMove(Math.round(duration * (index + 1) / stops.length), stop, steps)), { at_ms: duration, type: "button_up", button }]) };
+ return { label: "drag", ...start, end, ...shared(params), web,
native: { action: "drag", ...(params.duration_ms !== undefined ? { duration_ms: params.duration_ms } : {}), ...(params.button && params.button !== "left" ? { button: params.button } : {}),
- ...(params.modifiers?.length ? { modifiers: params.modifiers } : {}), ...(params.via ? { via: params.via } : {}) },
- web: "drag on browser pages is not available yet; use space: \"window\" for window pixels." };
+ ...(params.modifiers?.length ? { modifiers: params.modifiers } : {}), ...(params.via ? { via: params.via } : {}) } };
}
const scrollParameters = Type.Object({
@@ -334,7 +359,8 @@ export function scrollPlan(params: Static<typeof scrollParameters>): InputPlan {
: dx && dy ? "Scroll a native element along one axis at a time, or give a point."
: { action: "scroll", direction: dy > 0 ? "down" : dy < 0 ? "up" : dx > 0 ? "right" : "left", amount: Math.abs(dx || dy), ...timeout(params) };
return { label: "scroll", ...aimed, ...shared(params), native,
- web: { action: "scroll", ...(dx ? { delta_x: dx * 100 } : {}), ...(dy ? { delta_y: dy * 100 } : {}), ...timeout(params) } };
+ web: aimed.point ? { action: "timeline", events: [pageMove(0, aimed), { at_ms: 0, type: "wheel", ...(dx ? { dx: dx * 100 } : {}), ...(dy ? { dy: dy * 100 } : {}) }] }
+ : { action: "scroll", ...(dx ? { delta_x: dx * 100 } : {}), ...(dy ? { delta_y: dy * 100 } : {}), ...timeout(params) } };
}
const typeParameters = Type.Object({
@@ -374,9 +400,12 @@ export function pressPlan(params: Static<typeof pressParameters>): InputPlan {
if (held.some(part => !PAGE_MODIFIERS[part])) throw new ComputerRequestError("Modifiers are ctrl, shift, alt and win.");
const native = params.hold_ms !== undefined ? { action: "hold", keys: [...held, key.toLowerCase()], duration_ms: params.hold_ms }
: { action: "key", key: key.toLowerCase(), ...(held.length ? { modifiers: held } : {}) };
- const pageKey = PAGE_KEYS[key.toLowerCase()] ?? (/^f\d{1,2}$/i.test(key) ? key.toUpperCase() : key);
- return { label: "press", ...aim(params, "press", false), ...shared(params), native,
- web: params.hold_ms !== undefined ? "hold_ms on browser pages is not available yet." : { action: "press", key: [...held.map(part => PAGE_MODIFIERS[part]), pageKey].join("+") } };
+ const keys = [...held.map(part => PAGE_MODIFIERS[part]), pageKey(key)];
+ const aimed = aim(params, "press", false);
+ if (params.hold_ms !== undefined && aimed.target !== undefined) throw new ComputerRequestError("hold_ms goes to the focused element; focus it with computer_click first.");
+ return { label: "press", ...aimed, ...shared(params), native,
+ web: params.hold_ms !== undefined ? { action: "timeline", events: [...keys.map(name => ({ at_ms: 0, type: "key_down", key: name })), ...[...keys].reverse().map(name => ({ at_ms: params.hold_ms!, type: "key_up", key: name }))] }
+ : { action: "press", key: keys.join("+") } };
}
const selectParameters = Type.Object({
@@ -420,9 +449,14 @@ const timelineParameters = Type.Object({
}, { additionalProperties: false }), { minItems: 1, maxItems: 5000, description: "Timed events. Every key and button pressed must be released; anything still held is released when the call ends." }),
}, { additionalProperties: false });
-/** What computer_timeline sends to a native window, in the foreground. */
+/** What computer_timeline sends: native events in the foreground, or page events in CSS pixels through Playwright and CDP. */
export function timelinePlan(params: Static<typeof timelineParameters>): InputPlan {
- return { label: "timeline", ...shared(params), native: { action: "timeline", events: params.events }, web: "timeline on browser pages is not available yet; use space: \"window\" for window pixels." };
+ const native = params.events.find(event => event.type === "move_relative" || event.eraser || event.barrel || event.button === "x1" || event.button === "x2");
+ const web = native ? `${native.type === "move_relative" ? "move_relative" : native.eraser ? "The pen eraser" : native.barrel ? "The pen barrel button" : `Button ${native.button}`} needs native input: give space: "window" and points in pixels of the window's latest image.`
+ : { action: "timeline", events: params.events.map(({ eraser: _eraser, barrel: _barrel, ...event }) => ({ ...event,
+ ...(event.key !== undefined ? { key: pageKey(event.key) } : {}),
+ ...(event.type === "wheel" ? { ...(event.dx ? { dx: event.dx * 100 } : {}), ...(event.dy ? { dy: event.dy * 100 } : {}) } : {}) })) };
+ return { label: "timeline", ...shared(params), native: { action: "timeline", events: params.events }, web };
}
/**
* Register the typed computer_* tools that replace Insert commands one cluster at a time. They are deferred: a
diff --git a/src/web-browser.ts b/src/web-browser.ts
index 0e856e1..738c478 100644
--- a/src/web-browser.ts
+++ b/src/web-browser.ts
@@ -27,9 +27,11 @@ export interface WebSnapshotOptions {
export interface WebAction {
action: "click" | "hover" | "fill" | "type" | "press" | "check" | "uncheck" | "select" | "focus" | "scroll" | "wait" | "wait_load"
| "navigate" | "back" | "forward" | "reload" | "new_tab" | "switch_tab" | "close_tab" | "dialog"
- | "upload" | "wait_download" | "cancel_download" | "evaluate";
+ | "upload" | "wait_download" | "cancel_download" | "evaluate" | "timeline";
target?: WebTarget;
button?: "left" | "right" | "middle"; click_count?: number;
+ /** Timed mouse, keyboard, wheel and pen events at CSS points of the page, for timeline. */
+ events?: WebTimelineEvent[];
/** Keys held during a click or hover. */
modifiers?: ("Alt" | "Control" | "Meta" | "Shift")[];
text?: string; key?: string; values?: string[];
@@ -50,6 +52,81 @@ export interface WebAction {
/** JavaScript expression evaluated in the active tab, or a function called with the target element. */
expression?: string;
}
+/**
+ * One event of a page timeline, at_ms after its start. Points are CSS pixels of the page; a move can go to the centre
+ * of a target instead. Keys use Playwright names such as Control, Enter or a; wheel deltas are CSS pixels.
+ */
+export interface WebTimelineEvent {
+ at_ms: number;
+ type: "key_down" | "key_up" | "button_down" | "button_up" | "move" | "wheel" | "pen_down" | "pen_move" | "pen_up";
+ key?: string; button?: "left" | "right" | "middle";
+ /** button_down and button_up: which click of a multiple click this is, so the page sees double and triple clicks. */
+ click_count?: number;
+ x?: number; y?: number; target?: WebTarget;
+ /** move: intermediate mouse moves on the way, for a smooth path. */
+ steps?: number;
+ dx?: number; dy?: number;
+ pressure?: number; tilt_x?: number; tilt_y?: number;
+}
+/** Longest page timeline, in time and events. */
+const WEB_TIMELINE_MS = 120_000, WEB_TIMELINE_EVENTS = 5000;
+const TIMELINE_FIELDS: Record<WebTimelineEvent["type"], string[]> = {
+ key_down: ["key"], key_up: ["key"], button_down: ["button", "click_count"], button_up: ["button", "click_count"],
+ move: ["x", "y", "target", "steps"], wheel: ["dx", "dy"],
+ pen_down: ["x", "y", "pressure", "tilt_x", "tilt_y"], pen_move: ["x", "y", "pressure", "tilt_x", "tilt_y"], pen_up: ["x", "y", "pressure", "tilt_x", "tilt_y"],
+};
+/** Check a page timeline completely before any input: order, fields, points and balanced presses. */
+export function validateWebTimeline(value: unknown): WebTimelineEvent[] {
+ if (!Array.isArray(value) || value.length < 1 || value.length > WEB_TIMELINE_EVENTS) throw Error(`timeline needs 1..${WEB_TIMELINE_EVENTS} events.`);
+ const keys = new Set<string>(), buttons = new Set<string>();
+ let last = 0, pen = false;
+ const events = value.map((raw, index) => {
+ const event = record(raw, `events[${index}]`) as unknown as WebTimelineEvent;
+ const fields = TIMELINE_FIELDS[event.type];
+ if (!fields) throw Error(`events[${index}] needs a type: ${Object.keys(TIMELINE_FIELDS).join(", ")}.`);
+ only(event as unknown as Record<string, unknown>, ["at_ms", "type", ...fields], `A ${event.type} event`);
+ event.at_ms = integer(event.at_ms, last, WEB_TIMELINE_MS, "at_ms");
+ last = event.at_ms;
+ const point = (required: boolean) => {
+ if (event.target !== undefined) { event.target = validateWebTarget(event.target); if (event.x !== undefined || event.y !== undefined) throw Error("A move goes to a target or a point, not both."); return; }
+ if (event.x === undefined && event.y === undefined && !required) return;
+ for (const axis of ["x", "y"] as const) if (typeof event[axis] !== "number" || !Number.isFinite(event[axis]) || event[axis]! < 0 || event[axis]! > 100_000) throw Error(`${event.type} needs x and y in CSS pixels.`);
+ };
+ switch (event.type) {
+ case "key_down": case "key_up": {
+ const key = text(event.key, "key", 64);
+ if (event.type === "key_down" ? keys.has(key) : !keys.has(key)) throw Error(`Key ${key} is ${event.type === "key_down" ? "already down" : "not down"}.`);
+ event.type === "key_down" ? keys.add(key) : keys.delete(key);
+ break;
+ }
+ case "button_down": case "button_up": {
+ const button = event.button ?? "left";
+ if (!["left", "right", "middle"].includes(button)) throw Error("button must be left, right or middle.");
+ if (event.click_count !== undefined) event.click_count = integer(event.click_count, 1, 3, "click_count");
+ if (event.type === "button_down" ? buttons.has(button) : !buttons.has(button)) throw Error(`Button ${button} is ${event.type === "button_down" ? "already down" : "not down"}.`);
+ event.type === "button_down" ? buttons.add(button) : buttons.delete(button);
+ break;
+ }
+ case "move":
+ if (event.target === undefined) point(true); else point(false);
+ if (event.steps !== undefined) event.steps = integer(event.steps, 1, 200, "steps");
+ break;
+ case "wheel":
+ for (const axis of ["dx", "dy"] as const) if (event[axis] !== undefined && (typeof event[axis] !== "number" || !Number.isFinite(event[axis]) || Math.abs(event[axis]!) > 20_000)) throw Error(`${axis} must be CSS pixels within ±20000.`);
+ if (!event.dx && !event.dy) throw Error("wheel needs dx or dy.");
+ break;
+ default:
+ point(true);
+ if (event.pressure !== undefined && !(typeof event.pressure === "number" && event.pressure >= 0 && event.pressure <= 1)) throw Error("Pen pressure must be 0..1.");
+ for (const tilt of [event.tilt_x, event.tilt_y]) if (tilt !== undefined && !(Number.isInteger(tilt) && tilt >= -90 && tilt <= 90)) throw Error("Pen tilt must be an integer -90..90.");
+ if (event.type === "pen_down" ? pen : event.type === "pen_up" && !pen) throw Error(`The pen is ${pen ? "already" : "not"} down.`);
+ if (event.type === "pen_down") pen = true; else if (event.type === "pen_up") pen = false;
+ }
+ return event;
+ });
+ if (keys.size || buttons.size || pen) throw Error(`The timeline leaves ${[...keys, ...buttons, ...(pen ? ["the pen"] : [])].join(", ")} down; release everything it presses.`);
+ return events;
+}
/** One retained console message, uncaught page error or failed network event. `seq` increases across the browser's lifetime. */
export interface WebLogEntry {
seq: number; at: string; tab: string;
@@ -200,6 +277,7 @@ const ACTIONS: Record<WebAction["action"], { fields: readonly string[]; target:
wait_download: { fields: ["download"], target: "none" },
cancel_download: { fields: ["download"], target: "none" },
evaluate: { fields: ["expression"], target: "optional" },
+ timeline: { fields: ["events"], target: "none" },
};
const tabId = (value: unknown): string => {
if (typeof value !== "string" || !/^t\d{1,6}$/.test(value)) throw Error("tab must be a tab id such as t2 from the tab list.");
@@ -278,6 +356,7 @@ export function validateWebAction(value: unknown): WebAction {
}
}
if (name === "evaluate") action.expression = text(command.expression, "expression", 20_000);
+ if (name === "timeline") action.events = validateWebTimeline(command.events);
if ((name === "wait_download" || name === "cancel_download") && command.download !== undefined) {
if (typeof command.download !== "string" || !/^d\d{1,6}$/.test(command.download)) throw Error("download must be an id such as d1 from the download list.");
action.download = command.download;
diff --git a/src/web-worker.ts b/src/web-worker.ts
index 20a5b69..f366e64 100644
--- a/src/web-worker.ts
+++ b/src/web-worker.ts
@@ -9,7 +9,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { chromium, firefox, type Browser, type BrowserContext, type Dialog, type Download, type FrameLocator, type Locator, type Page } from "playwright-core";
import { ATTACH_APPROVAL_MS, parseBrowserCommandLine } from "./browser-command-line.ts";
-import type { WebAction, WebDownload, WebEvaluation, WebLaunchOptions, WebLogEntry, WebSnapshotOptions, WebTab, WebTarget } from "./web-browser.ts";
+import type { WebAction, WebDownload, WebEvaluation, WebLaunchOptions, WebLogEntry, WebSnapshotOptions, WebTab, WebTarget, WebTimelineEvent } from "./web-browser.ts";
import type { ConditionResult, UiCondition } from "./ui-conditions.ts";
import { ariaTreeFromYaml, matchesAriaTemplate } from "./aria-match.ts";
@@ -366,6 +366,61 @@ async function snapshot({ target, boxes, depth, log: wantLog }: WebSnapshotOptio
return { url: page.url(), title: tab.title, snapshot: text === "dialog" ? "" : text, ...(dialog ? { dialog } : {}), ...base() };
}
+/**
+ * Play a page timeline with Playwright's mouse and keyboard, and a pen through CDP: each event waits for its at_ms.
+ * Whatever is still held when it ends or fails is released, so no key, button or pen stays down.
+ */
+async function play(page: Page, events: WebTimelineEvent[], timeout: number): Promise<void> {
+ const keys = new Set<string>(), buttons = new Set<"left" | "right" | "middle">();
+ let cdp: Awaited<ReturnType<BrowserContext["newCDPSession"]>> | undefined, pen: { x: number; y: number } | undefined;
+ const started = performance.now();
+ let penDown = false;
+ const penEvent = async (type: "mousePressed" | "mouseMoved" | "mouseReleased", event: WebTimelineEvent) => {
+ if (!cdp) {
+ try { cdp = await page.context().newCDPSession(page); }
+ catch { throw new Error("Pen input needs a Chromium browser such as Chrome or Edge. Nothing more was sent."); }
+ }
+ pen = { x: event.x ?? pen?.x ?? 0, y: event.y ?? pen?.y ?? 0 };
+ // A pen in contact presses the left button with its pressure; a hovering pen moves with no button.
+ const touching = type === "mousePressed" || type === "mouseMoved" && penDown;
+ await cdp.send("Input.dispatchMouseEvent", { type, ...pen, button: type === "mouseMoved" && !penDown ? "none" : "left", buttons: touching ? 1 : 0,
+ clickCount: type === "mouseMoved" ? 0 : 1, pointerType: "pen", force: touching ? event.pressure ?? 0.5 : 0, tiltX: event.tilt_x ?? 0, tiltY: event.tilt_y ?? 0 });
+ };
+ try {
+ for (const event of events) {
+ const wait = started + event.at_ms - performance.now();
+ if (wait > 0) await new Promise(resolve => setTimeout(resolve, wait));
+ switch (event.type) {
+ case "key_down": await page.keyboard.down(event.key!); keys.add(event.key!); break;
+ case "key_up": await page.keyboard.up(event.key!); keys.delete(event.key!); break;
+ case "button_down": await page.mouse.down({ button: event.button ?? "left", clickCount: event.click_count }); buttons.add(event.button ?? "left"); break;
+ case "button_up": await page.mouse.up({ button: event.button ?? "left", clickCount: event.click_count }); buttons.delete(event.button ?? "left"); break;
+ case "move": {
+ let { x, y } = event as { x: number; y: number };
+ if (event.target) {
+ const element = locate(page, event.target);
+ await element.scrollIntoViewIfNeeded({ timeout });
+ const box = await element.boundingBox({ timeout });
+ if (!box) throw new Error("The target has no place on the page. Nothing more was sent.");
+ x = box.x + box.width / 2; y = box.y + box.height / 2;
+ }
+ await page.mouse.move(x, y, { steps: event.steps });
+ break;
+ }
+ case "wheel": await page.mouse.wheel(event.dx ?? 0, event.dy ?? 0); break;
+ case "pen_down": await penEvent("mousePressed", event); penDown = true; break;
+ case "pen_move": await penEvent("mouseMoved", event); break;
+ case "pen_up": await penEvent("mouseReleased", event); penDown = false; break;
+ }
+ }
+ } finally {
+ for (const button of buttons) await page.mouse.up({ button }).catch(() => {});
+ for (const key of [...keys].reverse()) await page.keyboard.up(key).catch(() => {});
+ if (penDown && cdp && pen) await cdp.send("Input.dispatchMouseEvent", { type: "mouseReleased", ...pen, button: "left", buttons: 0, clickCount: 1, pointerType: "pen" }).catch(() => {});
+ await cdp?.detach().catch(() => {});
+ }
+}
+
async function act(action: WebAction) {
const timeout = action.timeout_ms ?? (["navigate", "back", "forward", "reload", "new_tab", "wait_load", "wait_download", "upload", "evaluate"].includes(action.action) ? 30_000 : 5_000);
switch (action.action) {
@@ -471,6 +526,7 @@ async function act(action: WebAction) {
return response;
}
case "reload": return page.reload({ waitUntil: "domcontentloaded", timeout });
+ case "timeline": return play(page, action.events!, timeout);
case "upload": {
if (!action.chooser) return target!.setInputFiles(action.files!, { timeout });
// Intercepting the chooser keeps the native file dialog closed; the page receives the files as if picked there.
diff --git a/test/computer-tools.test.ts b/test/computer-tools.test.ts
index 45f0fb6..f169777 100644
--- a/test/computer-tools.test.ts
+++ b/test/computer-tools.test.ts
@@ -88,8 +88,9 @@ test("input tools build one plan for native windows and one for browser pages",
expect(refKind("f1e3")).toBe("page");
expect(refKind("getByRole('button', { name: 'Save' })")).toBe("locator");
expect(clickPlan({ window: w, target: "1:a" })).toEqual({ label: "click", target: "1:a", native: { action: "click" }, web: { action: "click" } });
- expect(clickPlan({ window: w, x: 10, y: 20, count: 2, modifiers: ["ctrl"] })).toEqual({ label: "click", point: { x: 10, y: 20 },
- native: { action: "double_click", modifiers: ["ctrl"] }, web: { action: "click", click_count: 2, modifiers: ["Control"] } });
+ expect(clickPlan({ window: w, x: 10, y: 20, count: 2, modifiers: ["ctrl"] })).toMatchObject({ label: "click", point: { x: 10, y: 20 },
+ native: { action: "double_click", modifiers: ["ctrl"] }, web: { action: "timeline" } });
+ expect(clickPlan({ window: w, target: "e1", count: 2, modifiers: ["ctrl"] }).web).toEqual({ action: "click", click_count: 2, modifiers: ["Control"] });
expect(clickPlan({ window: w, target: "e1", button: "right" }).native).toEqual({ action: "right_click" });
expect(clickPlan({ window: w, target: "e1", count: 3 }).native).toBe("A triple click works on browser pages only.");
expect(() => clickPlan({ window: w })).toThrow("click needs a target or a point (x and y).");
@@ -112,7 +113,15 @@ test("input tools build one plan for native windows and one for browser pages",
expect(selectPlan({ window: w, target: "1:a", checked: false })).toMatchObject({ native: { action: "uncheck" }, web: { action: "uncheck" } });
expect(selectPlan({ window: w, menu: ["File", "Save"] })).toMatchObject({ native: { action: "menu", path: ["File", "Save"] } });
expect(() => selectPlan({ window: w, target: "1:a", checked: true, values: ["a"] })).toThrow("select takes one of values, checked or menu");
- expect(timelinePlan({ window: w, events: [{ at_ms: 0, type: "key_down", key: "a" }, { at_ms: 5, type: "key_up", key: "a" }] }).native).toMatchObject({ action: "timeline" });
+ const keyed = timelinePlan({ window: w, events: [{ at_ms: 0, type: "key_down", key: "ctrl" }, { at_ms: 5, type: "wheel", dy: 2 }, { at_ms: 9, type: "key_up", key: "ctrl" }] });
+ expect(keyed.native).toMatchObject({ action: "timeline", events: [{ key: "ctrl" }, { dy: 2 }, { key: "ctrl" }] });
+ expect(keyed.web).toEqual({ action: "timeline", events: [{ at_ms: 0, type: "key_down", key: "Control" }, { at_ms: 5, type: "wheel", dy: 200 }, { at_ms: 9, type: "key_up", key: "Control" }] });
+ expect(pressPlan({ window: w, key: "shift+up", hold_ms: 300 }).web).toEqual({ action: "timeline", events: [
+ { at_ms: 0, type: "key_down", key: "Shift" }, { at_ms: 0, type: "key_down", key: "ArrowUp" }, { at_ms: 300, type: "key_up", key: "ArrowUp" }, { at_ms: 300, type: "key_up", key: "Shift" }] });
+ expect(dragPlan({ window: w, from: { target: "e2" }, to: { x: 50, y: 60 }, duration_ms: 200 }).web).toEqual({ action: "timeline", events: [
+ { at_ms: 0, type: "move", target: { ref: "e2" } }, { at_ms: 0, type: "button_down", button: "left" },
+ { at_ms: 200, type: "move", x: 50, y: 60, steps: 13 }, { at_ms: 200, type: "button_up", button: "left" }] });
+ expect(scrollPlan({ window: w, x: 4, y: 5, delta_y: 1 }).web).toEqual({ action: "timeline", events: [{ at_ms: 0, type: "move", x: 4, y: 5 }, { at_ms: 0, type: "wheel", dy: 100 }] });
});
test("typed input refuses mismatched targets before anything reaches the machine", async () => {
@@ -175,9 +184,17 @@ test("typed input on a browser window goes to Playwright with page refs and loca
expect(f.page.mock.calls.slice(-2).map(call => call[1])).toEqual([
{ action: "type", text: "Ada", target: { locator: "internal:label=\"Name\"i" } },
{ action: "press", key: "Enter", target: { locator: "internal:label=\"Name\"i" } }]);
- await expect(f.resources.input(window, cwd, clickPlan({ window: "x", x: 5, y: 5 }))).rejects.toThrow("click at a point of a browser page is not available yet");
+ // A point of a page is a timeline in CSS pixels, with the click numbered like Playwright's mouse.click.
+ await f.resources.input(window, cwd, clickPlan({ window: "x", x: 5, y: 6, count: 2, modifiers: ["ctrl"] }));
+ expect(f.page.mock.calls.at(-1)![1]).toEqual({ action: "timeline", events: [
+ { at_ms: 0, type: "key_down", key: "Control" }, { at_ms: 0, type: "move", x: 5, y: 6 },
+ { at_ms: 0, type: "button_down", button: "left", click_count: 1 }, { at_ms: 0, type: "button_up", button: "left", click_count: 1 },
+ { at_ms: 0, type: "button_down", button: "left", click_count: 2 }, { at_ms: 0, type: "button_up", button: "left", click_count: 2 },
+ { at_ms: 0, type: "key_up", key: "Control" }] });
+ await expect(f.resources.input(window, cwd, timelinePlan({ window: "x", events: [{ at_ms: 0, type: "move_relative", dx: 5, dy: 0 }] }))).rejects.toThrow("move_relative needs native input");
+ await expect(f.resources.input(window, cwd, timelinePlan({ window: "x", events: [{ at_ms: 0, type: "key_down", key: "a" }] }))).rejects.toThrow("The timeline leaves a down");
await expect(f.resources.input(window, cwd, selectPlan({ window: "x", menu: ["File"] }))).rejects.toThrow("menu works on native windows");
- expect(f.page).toHaveBeenCalledTimes(3);
+ expect(f.page).toHaveBeenCalledTimes(4);
});
/** One window (pid 10, id 7) a session can list and observe; the host decides how a close request ends. */
diff --git a/test/live/typed-input.live.ts b/test/live/typed-input.live.ts
index b877f3c..e638f66 100644
--- a/test/live/typed-input.live.ts
+++ b/test/live/typed-input.live.ts
@@ -66,6 +66,34 @@ test("one action vocabulary drives a native window by locator, ref and point", a
} finally { await deleteComputer(live.resources, window, { path: window }, live.cwd); }
});
+test("points of a browser page take clicks, wheel, drags, held keys and a pressure pen through Playwright", async () => {
+ const opened = await live.insert(live.machine, { action: "open_browser", url: `${fixture.base}/input` });
+ expect(opened.details.status, JSON.stringify(opened.content)).toBe("observed");
+ const window = `computer:window/${opened.details.window_ref}`;
+ const since = (await fixture.journal()).length;
+ try {
+ const delivered = async (plan: InputPlan) => { const { result, body } = await act(window, plan); expect(result.details.status, body).toBe("delivered"); };
+ await delivered(clickPlan({ window, x: 200, y: 200, modifiers: ["shift"] }));
+ await delivered(clickPlan({ window, x: 220, y: 200, count: 2 }));
+ // The double click asked the pad for pointer lock; leave it so later moves are ordinary.
+ await delivered(pressPlan({ window, key: "Escape" }));
+ await delivered(scrollPlan({ window, x: 300, y: 300, delta_y: 2 }));
+ await delivered(dragPlan({ window, from: { x: 100, y: 150 }, to: { x: 400, y: 260 }, via: [{ x: 250, y: 150 }], duration_ms: 300 }));
+ await delivered(pressPlan({ window, key: "w", hold_ms: 400 }));
+ await delivered(timelinePlan({ window, events: [{ at_ms: 0, type: "pen_down", x: 150, y: 400, pressure: 0.8, tilt_x: 20 }, { at_ms: 40, type: "pen_move", x: 200, y: 410, pressure: 0.8 },
+ { at_ms: 80, type: "pen_move", x: 260, y: 420, pressure: 0.8 }, { at_ms: 120, type: "pen_up", x: 260, y: 420 }] }));
+ const journal = (await fixture.journal()).slice(since);
+ console.log(journal.map(entry => JSON.stringify(entry)).join("\n"));
+ expect(journal).toContainEqual(expect.objectContaining({ type: "pointerdown", pointerType: "mouse", shift: true }));
+ expect(journal.filter(entry => entry.type === "pointerdown" && entry.pointerType === "mouse").length).toBeGreaterThanOrEqual(4);
+ expect(journal).toContainEqual(expect.objectContaining({ type: "wheel", deltaY: 200 }));
+ expect(journal).toContainEqual(expect.objectContaining({ type: "pointermove", pointerType: "mouse", buttons: 1 }));
+ const held = journal.filter(entry => entry.key === "w");
+ expect(held.map(entry => entry.type)).toEqual(["keydown", "keyup"]);
+ expect(journal).toContainEqual(expect.objectContaining({ type: "pointerdown", pointerType: "pen", pressure: 0.8, tiltX: 20 }));
+ } finally { await deleteComputer(live.resources, window, { path: window }, live.cwd); }
+});
+
test("the same vocabulary drives a browser page through Playwright by locator and page ref", async () => {
const opened = await live.insert(live.machine, { action: "open_browser", url: `${fixture.base}/wait` });
expect(opened.details.status, JSON.stringify(opened.content)).toBe("observed");
@@ -81,7 +109,7 @@ test("the same vocabulary drives a browser page through Playwright by locator an
expect((await act(window, pressPlan({ window, key: "ctrl+a" }))).result.details.status).toBe("delivered");
expect((await act(window, hoverPlan({ window, target: "getByRole('button', { name: 'Unlock later' })" }))).result.details.status).toBe("delivered");
expect((await act(window, scrollPlan({ window, delta_y: 2 }))).result.details.status).toBe("delivered");
- const refused = await live.resources.input(requireComputerAddress(window), live.cwd, timelinePlan({ window, events: [{ at_ms: 0, type: "key_down", key: "a" }, { at_ms: 10, type: "key_up", key: "a" }] })).catch((error: Error) => error.message);
- expect(String(refused)).toContain("timeline on browser pages");
+ const refused = await live.resources.input(requireComputerAddress(window), live.cwd, timelinePlan({ window, events: [{ at_ms: 0, type: "move_relative", dx: 5, dy: 0 }] })).catch((error: Error) => error.message);
+ expect(String(refused)).toContain("move_relative needs native input");
} finally { await deleteComputer(live.resources, window, { path: window }, live.cwd); }
});