Files
openbot/scripts/browser-dialogs-e2e.ts
T
NBandClaude Opus 5.5 f9265cd8bd Let the agent answer page dialogs that its action opened (#4148)
* Let the agent answer page dialogs that its action opened

When an agent input action opens a page alert or confirm, the action now
returns the dialog: an opaque id, the type, and the redacted message. The
new handle_dialog tool answers it through CDP, then closes Electron's box
with the internal -cancel-dialogs event. A run_script step stops with
status "dialog".

A person's dialog, a dialog under an external debugger, and a dialog that
is open when the turn ends stay in the native box for a person. Close and
shutdown detach the debugger and close the box, also when Electron shows
the box after the close.

scripts/browser-dialogs-e2e.ts (21 cases) runs in the CI browser job. It
fails if an Electron upgrade changes -run-dialog or -cancel-dialogs.

The agent context budget increases because of the new tool description
and schema (catalog.descriptions +123, catalog.schemas +245,
visible-tools +31).

Fixes #4015

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Close a page dialog box when its tab closes

Electron keeps its native dialog box open after the page closes, and
nobody can answer it then. The engine now cancels every box of the tab
when it is destroyed, also a box that shows after the close. A new
fixture case checks a person's dialog.

Refs #4015

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep the dialog watch attached for the whole agent action

The engine keeps its debugger attached with Page on while a dialog
watch runs. Thus it sees a dialog that a page load or a timer opens
after the input command returns. A tab queue drain ends the watch, also
after an interruption.

Other review fixes:
- A dialog that opens after the tab starts to close goes to the native
  box and does not hold the tab queue.
- releaseDialogs signals the waiters.
- handle_dialog uses Effect.timeoutOption for the next dialog.
- A handoff signals only when something changed.

The E2E fixture adds two cases: a dialog from a timer after the click,
and a dialog during a navigation.

Refs #4015

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Remove the export of the dialog type that only browser-cdp uses

Knip reports BrowserDialogType as an unused export.

Refs #4015

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:10:16 +01:00

153 lines
5.1 KiB
TypeScript

import { spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { z } from "zod";
import { withoutElectronRuntimeFlags } from "./electron-spawn-env";
class FixtureProcessTimeout extends Error {}
/** The case count of `browser-dialogs-electron.ts`. A case that stops running fails the check. */
const DIALOG_CASES = 24;
const projectRoot = dirname(dirname(fileURLToPath(import.meta.url)));
const buildRoot = await mkdtemp(join(tmpdir(), "openbot-dialogs-"));
const reportPath = join(projectRoot, ".openbot-build/browser-dialogs-e2e/report.json");
const runId = randomUUID();
let sourceSha: string | undefined;
try {
await mkdir(dirname(reportPath), { recursive: true });
// The QuickJS sandbox loads its WebAssembly file next to its own module, so it stays in
// node_modules, and the entry sits in the project to resolve it.
const entry = join(dirname(reportPath), "browser-dialogs.mjs");
await run(process.execPath, [
"build",
join(projectRoot, "scripts/browser-dialogs-electron.ts"),
"--target=node",
"--format=esm",
"--external=electron",
"--external=quickjs-emscripten-core",
"--external=@jitl/quickjs-wasmfile-release-sync",
`--outfile=${entry}`,
]);
sourceSha = (await output("git", ["rev-parse", "HEAD"])).trim();
const bunVersion = await output(process.execPath, ["--version"]);
await run(
join(projectRoot, "node_modules/.bin/electron"),
[
...(process.platform === "linux" ? ["--no-sandbox"] : []),
entry,
`--fixture-root=${buildRoot}`,
`--report-path=${reportPath}`,
`--source-sha=${sourceSha}`,
`--run-id=${runId}`,
`--harness-runtime=${process.version}`,
`--bun-version=${bunVersion.trim()}`,
],
true,
);
const report = z
.object({
status: z.literal("passed"),
cases: z.array(z.string()).min(DIALOG_CASES),
runId: z.literal(runId),
sourceSha: z.literal(sourceSha),
})
.parse(JSON.parse(await readFile(reportPath, "utf8")));
// Machine-readable summary of the completed case count.
process.stdout.write(
`${JSON.stringify({ status: report.status, cases: report.cases.length, report: reportPath })}\n`,
);
} catch (error) {
let completedCases: string[] = [];
let nativeFailure = false;
try {
const current = z
.object({ runId: z.literal(runId), status: z.string(), cases: z.array(z.string()).optional() })
.parse(JSON.parse(await readFile(reportPath, "utf8")));
completedCases = current.cases ?? [];
nativeFailure = current.status === "failed";
} catch {
// This invocation owns no valid report yet. An earlier report cannot supply its result.
}
if (error instanceof FixtureProcessTimeout) {
await writeFile(
reportPath,
`${JSON.stringify(
{
status: "timed_out",
runId,
sourceSha,
cases: completedCases,
reason: "Owned fixture exceeded its 180-second process guard.",
},
null,
2,
)}\n`,
);
} else if (!nativeFailure) {
await writeFile(
reportPath,
`${JSON.stringify(
{
status: "failed",
runId,
sourceSha,
cases: completedCases,
reason: "Fixture process completion or report verification failed.",
},
null,
2,
)}\n`,
);
}
throw error;
} finally {
await rm(buildRoot, { recursive: true, force: true });
}
async function run(command: string, args: string[], electron = false): Promise<void> {
await new Promise<void>((resolve, reject) => {
const child = spawn(command, args, {
cwd: projectRoot,
stdio: "inherit",
env: electron ? withoutElectronRuntimeFlags(process.env) : process.env,
});
let force: NodeJS.Timeout | undefined;
let timedOut = false;
const timeout = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
force = setTimeout(() => child.kill("SIGKILL"), 3_000);
}, 180_000);
child.once("error", (error) => {
clearTimeout(timeout);
clearTimeout(force);
reject(error);
});
child.once("exit", (code, signal) => {
clearTimeout(timeout);
clearTimeout(force);
if (timedOut) reject(new FixtureProcessTimeout("Browser dialog fixture timed out."));
else if (code === 0 && signal === null) resolve();
else reject(new Error(`Browser dialog fixture process failed (${code}).`));
});
});
}
async function output(command: string, args: string[]): Promise<string> {
return new Promise((resolve, reject) => {
const child = spawn(command, args, { cwd: projectRoot, stdio: ["ignore", "pipe", "inherit"] });
let text = "";
child.stdout.on("data", (chunk: Buffer) => {
text += chunk.toString("utf8");
});
child.once("error", reject);
child.once("exit", (code) =>
code === 0 ? resolve(text) : reject(new Error("Unable to read fixture source SHA.")),
);
});
}