Skip to content

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

fix: back and forward settle on pages restored from the back-forward cache; live computer_browser and computer_wait test (LPT-934)

alexshpunt-clanker[bot]403aacb13e00
diff --git a/src/computer-tools.ts b/src/computer-tools.ts
index b197100..74117e8 100644
--- a/src/computer-tools.ts
+++ b/src/computer-tools.ts
@@ -90,7 +90,6 @@ const displayParameters = Type.Object({
height: Type.Integer({ minimum: 480, maximum: 16384, description: "New height in physical pixels." }),
}, { additionalProperties: false });
-const literals = <T extends string>(values: readonly T[], description: string) => Type.Union(values.map(value => Type.Literal(value)), { description });
/** An element of a window or page: a Playwright locator string, or locator fields that must all match. */
const targetSchema = (description: string) => Type.Union([
Type.String({ description: "A Playwright locator such as getByRole('button', { name: 'Save' }) or getByLabel('Name').nth(1)." }),
@@ -108,7 +107,7 @@ const waitParameters = Type.Object({
window: Type.String({ description: "Window address from Search, Read or a name; a browser window checks its active tab." }),
conditions: Type.Array(Type.Object({
target: Type.Optional(targetSchema("The element the check applies to; omit for aria on the whole window or page, and for url_contains and title.")),
- is: Type.Optional(literals(["exists", "absent", "visible", "hidden", "enabled", "disabled", "selected", "checked", "unchecked", "focused"] as const, "State the target is in.")),
+ is: Type.Optional(Type.Union([Type.Literal("exists"), Type.Literal("absent"), Type.Literal("visible"), Type.Literal("hidden"), Type.Literal("enabled"), Type.Literal("disabled"), Type.Literal("selected"), Type.Literal("checked"), Type.Literal("unchecked"), Type.Literal("focused")], { description: "State the target is in." })),
value: Type.Optional(Type.String({ description: "The target's value (its name if it has none, or a page element's text) equals this." })),
contains: Type.Optional(Type.String({ description: "The target's value, name or text contains this." })),
count: Type.Optional(Type.Integer({ minimum: 0, maximum: 10000, description: "Exactly this many elements match the target." })),
@@ -116,7 +115,7 @@ const waitParameters = Type.Object({
url_contains: Type.Optional(Type.String({ description: "Browser windows: the active tab's URL contains this." })),
title: Type.Optional(Type.String({ description: "Browser windows: the active tab's title equals this." })),
}, { additionalProperties: false }), { minItems: 1, maxItems: 16, description: "Every condition must hold. Each takes one check: is, value, contains, count or aria with a target, aria alone, or url_contains or title alone." }),
- mode: Type.Optional(literals(["wait", "check"] as const, "wait (default) samples until every condition holds or timeout_ms passes; check takes one sample.")),
+ mode: Type.Optional(Type.Union([Type.Literal("wait"), Type.Literal("check")], { description: "wait (default) samples until every condition holds or timeout_ms passes; check takes one sample." })),
timeout_ms: Type.Optional(Type.Integer({ minimum: 0, maximum: 60000, description: "wait: longest wait, default 5000." })),
interval_ms: Type.Optional(Type.Integer({ minimum: 50, maximum: 5000, description: "wait: time between samples, default 250." })),
stable: Type.Optional(Type.Integer({ minimum: 1, maximum: 10, description: "wait: consecutive satisfied samples required, default 1." })),
@@ -131,11 +130,10 @@ export function waitCommand(params: Static<typeof waitParameters>): Record<strin
const browserParameters = Type.Object({
window: Type.String({ description: "Window address of a browser opened with computer_open or attached to it." }),
- action: literals(["navigate", "back", "forward", "reload", "wait_load", "new_tab", "switch_tab", "close_tab", "dialog", "upload", "wait_download", "cancel_download", "evaluate"] as const,
- "What to do in the active tab: navigate to url; back, forward or reload; wait_load until the page reaches state; new_tab (optional url) becomes active; switch_tab or close_tab by tab; dialog answers the open JavaScript dialog; upload files into target; wait_download or cancel_download by download; evaluate runs expression."),
+ action: Type.Union([Type.Literal("navigate"), Type.Literal("back"), Type.Literal("forward"), Type.Literal("reload"), Type.Literal("wait_load"), Type.Literal("new_tab"), Type.Literal("switch_tab"), Type.Literal("close_tab"), Type.Literal("dialog"), Type.Literal("upload"), Type.Literal("wait_download"), Type.Literal("cancel_download"), Type.Literal("evaluate")], { description: "What to do in the active tab: navigate to url; back, forward or reload; wait_load until the page reaches state; new_tab (optional url) becomes active; switch_tab or close_tab by tab; dialog answers the open JavaScript dialog; upload files into target; wait_download or cancel_download by download; evaluate runs expression." }),
url: Type.Optional(Type.String({ description: "navigate and new_tab: an http(s) URL." })),
tab: Type.Optional(Type.String({ description: "switch_tab and close_tab: a tab id such as t2 from the snapshot's tab list; close_tab defaults to the active tab." })),
- state: Type.Optional(literals(["load", "domcontentloaded", "networkidle"] as const, "wait_load: load state to reach, default load.")),
+ state: Type.Optional(Type.Union([Type.Literal("load"), Type.Literal("domcontentloaded"), Type.Literal("networkidle")], { description: "wait_load: load state to reach, default load." })),
accept: Type.Optional(Type.Boolean({ description: "dialog: accept (true) or dismiss (false)." })),
text: Type.Optional(Type.String({ description: "dialog: the answer to an accepted prompt." })),
target: Type.Optional(targetSchema("upload: the file input, or with chooser the element that opens the file chooser; evaluate: the element passed to a function expression.")),
diff --git a/src/web-worker.ts b/src/web-worker.ts
index a87451d..7c4e161 100644
--- a/src/web-worker.ts
+++ b/src/web-worker.ts
@@ -136,6 +136,27 @@ function untilDialog<T>(tab: Tab, operation: Promise<T>): Promise<T | "dialog">
}).finally(() => tab.onDialog.delete(wake));
}
+/**
+ * Go back or forward and wait for the new document. A page restored from the back-forward cache (attached browsers
+ * keep it on) fires none of the load events Playwright waits for, though its URL changes: when the URL has changed
+ * and the traversal still has not settled 2 s later, the restore counts as done.
+ */
+async function traverse(page: Page, direction: "back" | "forward", timeout: number): Promise<{ response: Awaited<ReturnType<Page["goBack"]>>; restored: boolean }> {
+ const before = page.url();
+ const traversal = direction === "back" ? page.goBack({ waitUntil: "domcontentloaded", timeout }) : page.goForward({ waitUntil: "domcontentloaded", timeout });
+ let settled = false;
+ traversal.then(() => { settled = true; }, () => { settled = true; });
+ const end = Date.now() + timeout;
+ while (!settled && Date.now() < end) {
+ await new Promise(resolve => setTimeout(resolve, 100));
+ if (settled || page.url() === before) continue;
+ const grace = Date.now() + 2_000;
+ while (!settled && Date.now() < grace) await new Promise(resolve => setTimeout(resolve, 100));
+ if (!settled) { traversal.catch(() => undefined); return { response: null, restored: true }; }
+ }
+ return { response: await traversal, restored: false };
+}
+
function locate(page: Page, target: WebTarget): Locator {
if (target.ref) return page.getByRef(target.ref);
if (target.locator) return page.locator(target.locator);
@@ -171,7 +192,8 @@ async function open({ browser, url, profile: kind, attach: target }: WebLaunchOp
: await chromium.launchPersistentContext(directory, {
channel: browser, headless: false, chromiumSandbox: true, viewport: null, ignoreDefaultArgs: true,
args: ["--user-data-dir=" + directory, "--remote-debugging-pipe", "--no-first-run", "--no-default-browser-check",
- "--disable-sync", "--window-size=1100,800", "about:blank"],
+ // Playwright's default flags include this one: a page restored from the back-forward cache fires no load events.
+ "--disable-sync", "--disable-back-forward-cache", "--window-size=1100,800", "about:blank"],
});
trackTabs(context);
active = tabs[0] ?? adopt(await context.newPage());
@@ -443,7 +465,8 @@ async function act(action: WebAction) {
case "wait_load": return page.waitForLoadState(action.state as "load", { timeout });
case "navigate": return page.goto(action.url!, { waitUntil: "domcontentloaded", timeout });
case "back": case "forward": {
- const response = await (action.action === "back" ? page.goBack({ waitUntil: "domcontentloaded", timeout }) : page.goForward({ waitUntil: "domcontentloaded", timeout }));
+ const { response, restored } = await traverse(page, action.action, timeout);
+ if (restored) { note(`${tab.id}: ${action.action} restored ${page.url()} from the back-forward cache`); return undefined; }
if (response === null) note(`${tab.id}: ${action.action} made no new document request (no history entry or a same-document navigation)`);
return response;
}
diff --git a/test/computer-tools.test.ts b/test/computer-tools.test.ts
index 3244c53..b5ff95a 100644
--- a/test/computer-tools.test.ts
+++ b/test/computer-tools.test.ts
@@ -75,7 +75,7 @@ test("computer_browser runs a page action on the window and returns the page's n
expect(f.page).toHaveBeenLastCalledWith("act", { action: "navigate", url: "https://example.com/next" }, undefined);
// The snapshot is the window's current observation, so its refs ground the next action.
const id = result.details.observation_id!;
- expect((await f.resources.read(at(`computer:observation/${id}`), cwd)).details.status).toBe("observed");
+ expect((await f.resources.read(at(`computer:observation/${id}`), cwd))?.details.status).toBe("observed");
await expect(f.resources.browserAction(window, cwd, { action: "click", target: { ref: "e1" } })).rejects.toThrow("computer_browser runs navigate, back");
await expect(f.resources.browserAction(window, cwd, { action: "navigate", url: "file:///etc/passwd" })).rejects.toThrow("url must be HTTP(S)");
await expect(f.resources.browserAction(at("computer:machine/local"), cwd, { action: "reload" })).rejects.toThrow("computer_browser needs the window address");
diff --git a/test/live/typed-browser.live.ts b/test/live/typed-browser.live.ts
new file mode 100644
index 0000000..780c1d2
--- /dev/null
+++ b/test/live/typed-browser.live.ts
@@ -0,0 +1,46 @@
+import { afterAll, expect, test } from "vitest";
+import { requireComputerAddress } from "../../src/computer-resources.ts";
+import { waitCommand } from "../../src/computer-tools.ts";
+import { presentComputerResult } from "../../src/provider.ts";
+import { connectLive, serveFixture } from "./remote.ts";
+
+// LPT-934 step 2: computer_browser and computer_wait on a Playwright browser of the configured machine.
+const live = await connectLive();
+const fixture = await serveFixture(live.runner);
+afterAll(async () => { await live.close(); fixture.close(); });
+const page = async (window: string, command: Record<string, unknown>) => {
+ const started = Date.now();
+ const result = await live.resources.browserAction(requireComputerAddress(window), live.cwd, command);
+ const body = presentComputerResult(result);
+ console.log(`${command.action}: ${result.details.status} in ${Date.now() - started} ms`);
+ return { result, body };
+};
+const wait = async (window: string, params: Omit<Parameters<typeof waitCommand>[0], "window">) => {
+ const started = Date.now();
+ const result = await live.insert(window, waitCommand({ window, ...params }));
+ console.log(`wait ${params.mode ?? "wait"}: ${(result.details.verification as { verdict?: string } | undefined)?.verdict} in ${Date.now() - started} ms`);
+ return result.details.verification as { verdict: string; timed_out: boolean };
+};
+
+test("a browser window is navigated, tabbed, answered and checked by its address alone", async () => {
+ const opened = await live.insert(live.machine, { action: "open_browser", url: `${fixture.base}/` });
+ expect(opened.details.status, JSON.stringify(opened.content)).toBe("observed");
+ const window = `computer:window/${opened.details.window_ref}`;
+ expect((await page(window, { action: "navigate", url: `${fixture.base}/tabs` })).body).toContain("Tabs and dialogs");
+ expect(await wait(window, { mode: "check", conditions: [{ url_contains: "/tabs" }, { target: { role: "heading", name: "Tabs and dialogs" }, is: "visible" }] })).toMatchObject({ verdict: "satisfied" });
+ const evaluated = await page(window, { action: "evaluate", expression: "document.title" });
+ expect(evaluated.body).toContain('Evaluation result: "Tabs and dialogs"');
+ // A JavaScript dialog opened by page code is answered by computer_browser, and the page sees the answer.
+ await page(window, { action: "evaluate", expression: "setTimeout(() => { document.title = 'answered ' + confirm('Proceed?') }, 200); 1" });
+ await new Promise(resolve => setTimeout(resolve, 600));
+ expect((await page(window, { action: "dialog", accept: true })).result.details.status).toBe("delivered");
+ expect(await wait(window, { timeout_ms: 3000, conditions: [{ title: "answered true" }] })).toMatchObject({ verdict: "satisfied" });
+ const tab = await page(window, { action: "new_tab", url: `${fixture.base}/` });
+ expect(tab.body).toMatch(/Tab t2 \(active\)/);
+ // Closing the active tab leaves no tab active until switch_tab, so page actions refuse until then.
+ expect((await page(window, { action: "close_tab" })).body).toMatch(/Tab t1/);
+ expect((await page(window, { action: "back" })).result.details.status).toBe("refused");
+ expect((await page(window, { action: "switch_tab", tab: "t1" })).body).toMatch(/Tab t1 \(active\)/);
+ expect((await page(window, { action: "back" })).body).toContain("Fixture home");
+ expect(await wait(window, { timeout_ms: 500, conditions: [{ title: "Never" }] })).toMatchObject({ verdict: "unsatisfied", timed_out: true });
+});