refactor(browser): remove arbitrary capture ceilings

This commit is contained in:
morluto
2026-09-29 15:31:27 +08:00
parent 4cea84d7cb
commit 5dd3b4655e
16 changed files with 228 additions and 125 deletions
-5
View File
@@ -35,11 +35,6 @@ export const requiredRecord = (value: unknown): UnknownRecord => {
return record;
};
export const boundedText = (value: unknown, maximum = 1_024): string | null => {
const text = stringValue(value);
return text === undefined ? null : text.slice(0, maximum);
};
export const isHttpUrl = (value: string | undefined): boolean => {
if (value === undefined) return false;
try {
+1 -1
View File
@@ -17,7 +17,7 @@ export const authorizedElectronFile = async (
value: string,
roots: readonly string[],
): Promise<string | undefined> => {
if (value.length > 65_536 || /%(?:2f|5c)/iu.test(value)) return undefined;
if (/%(?:2f|5c)/iu.test(value)) return undefined;
let url: URL;
try {
url = new URL(value);
@@ -7,7 +7,7 @@ import {
import { createElectronActiveObservationFixtureResult } from "../domain/electronActiveObservation.fixture.js";
import { runElectronActions } from "./PlaywrightElectronActiveActions.js";
it("parses bounded window, renderer, and deep-link actions for agents", () => {
it("parses window, renderer, and deep-link actions for agents", () => {
const input = electronActiveObservationInputSchema.parse({
executable_path: "/opt/electron",
application_path: "/opt/app/main.js",
@@ -122,12 +122,7 @@ it("redacts action inputs from Playwright failures", async () => {
windows: () => [page],
};
const result = await runElectronActions(
application as never,
input,
{},
Date.now() + 1_000,
);
const result = await runElectronActions(application as never, input, {});
expect(result[0]).toMatchObject({
status: "failed",
@@ -154,7 +149,6 @@ it("retains complete action errors and Electron window text", async () => {
{ windows: () => [page] } as never,
input,
{},
Date.now() + 1_000,
);
const result = createElectronActiveObservationFixtureResult("/opt/app");
const longUrl = `file://${"/segment".repeat(10_000)}`;
@@ -281,12 +275,7 @@ it("runs an untargeted deep-link without requiring a BrowserWindow", async () =>
evaluate: async () => true,
};
const result = await runElectronActions(
application as never,
input,
{},
Date.now() + 1_000,
);
const result = await runElectronActions(application as never, input, {});
expect(result).toMatchObject([
{
@@ -297,6 +286,30 @@ it("runs an untargeted deep-link without requiring a BrowserWindow", async () =>
]);
});
it("honors caller-selected Electron waits beyond the former action timeout", async () => {
const input = electronActiveObservationInputSchema.parse({
executable_path: "/opt/electron",
application_path: "/opt/app/main.js",
application_root: "/opt/app",
actions: [{ step_id: "wait-long", kind: "wait", duration_ms: 60_000 }],
});
let duration = 0;
const page = {
waitForTimeout: async (value: number) => {
duration = value;
},
};
const application = {
windows: () => [page],
firstWindow: async () => page,
};
const result = await runElectronActions(application as never, input, {});
expect(result[0]).toMatchObject({ status: "completed" });
expect(duration).toBe(60_000);
});
it("rejects action outcomes that disagree with their error state", () => {
const result = createElectronActiveObservationFixtureResult("/opt/app");
const action = result.actions[0];
+28 -54
View File
@@ -10,7 +10,6 @@ import type {
} from "../domain/electronActiveObservation.js";
const OPERATION = "capture_electron_scenario" as const;
const ACTION_TIMEOUT_MS = 5_000;
const hookEventSchema = z.strictObject({
sequence: z.number().int().min(1),
@@ -108,7 +107,6 @@ export const runElectronActions = async (
application: ElectronApplication,
input: ElectronActiveObservationInput,
options: ExecutionOptions,
deadline: number,
): Promise<ElectronActions> => {
const actions: ElectronActions = [];
for (const action of input.actions) {
@@ -118,18 +116,13 @@ export const runElectronActions = async (
const windowIndex = actionWindowIndex(action);
let selectedWindow: Page | undefined;
try {
const remaining = deadline - Date.now();
if (remaining <= 0)
throw new BrowserObservationError(OPERATION, "timeout");
selectedWindow =
windowIndex === null
? undefined
: await waitForWindow({
application,
windowIndex,
timeout: ACTION_TIMEOUT_MS,
signal: options.signal,
deadline,
});
if (
(action.kind === "click" ||
@@ -143,10 +136,7 @@ export const runElectronActions = async (
application,
action,
selectedWindow,
remaining,
actionTimeoutMs: ACTION_TIMEOUT_MS,
options,
deadline,
});
actions.push({
step_id: action.step_id,
@@ -179,20 +169,14 @@ type RunActionContext = {
readonly application: ElectronApplication;
readonly action: ElectronAction;
readonly selectedWindow: Page | undefined;
readonly remaining: number;
readonly actionTimeoutMs: number;
readonly options: ExecutionOptions;
readonly deadline: number;
};
const runAction = async ({
application,
action,
selectedWindow,
remaining,
actionTimeoutMs,
options,
deadline,
}: RunActionContext): Promise<void> => {
switch (action.kind) {
case "click":
@@ -200,25 +184,21 @@ const runAction = async ({
throw new BrowserObservationError(OPERATION, "window_not_found");
await runWithExecutionLimits(
selectedWindow.locator(action.selector).click({
timeout: Math.min(actionTimeoutMs, remaining),
timeout: 0,
}),
options.signal,
deadline,
);
return;
case "wait": {
const page =
selectedWindow ??
(await application.firstWindow({
timeout: Math.min(actionTimeoutMs, remaining),
timeout: 0,
}));
await runWithExecutionLimits(
page.waitForTimeout(Math.min(action.duration_ms, remaining)),
page.waitForTimeout(action.duration_ms),
options.signal,
deadline,
);
if (action.duration_ms > remaining)
throw new BrowserObservationError(OPERATION, "timeout");
return;
}
case "renderer-reload":
@@ -226,10 +206,9 @@ const runAction = async ({
throw new BrowserObservationError(OPERATION, "window_not_found");
await runWithExecutionLimits(
selectedWindow.reload({
timeout: Math.min(actionTimeoutMs, remaining),
timeout: 0,
}),
options.signal,
deadline,
);
return;
case "renderer-crash": {
@@ -241,7 +220,6 @@ const runAction = async ({
return true;
}, action.window_index),
options.signal,
deadline,
);
if (!crashed)
throw new BrowserObservationError(OPERATION, "window_not_found");
@@ -251,7 +229,6 @@ const runAction = async ({
await runWithExecutionLimits(
emitDeepLink(application, action),
options.signal,
deadline,
);
return;
}
@@ -273,20 +250,15 @@ const actionWindowIndex = (action: ElectronAction): number | null => {
type WaitForWindowContext = {
readonly application: ElectronApplication;
readonly windowIndex: number;
readonly timeout: number;
readonly signal: AbortSignal | undefined;
readonly deadline: number;
};
const waitForWindow = async ({
application,
windowIndex,
timeout,
signal,
deadline,
}: WaitForWindowContext): Promise<Page> => {
const stopAt = Math.min(deadline, Date.now() + timeout);
while (Date.now() < stopAt) {
while (true) {
if (signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
const window = application.windows()[windowIndex];
@@ -294,10 +266,8 @@ const waitForWindow = async ({
await runWithExecutionLimits(
new Promise<void>((resolve) => setTimeout(resolve, 25)),
signal,
stopAt,
);
}
throw new BrowserObservationError(OPERATION, "window_not_found");
};
const emitDeepLink = (
@@ -430,35 +400,39 @@ export const readApplicationState = async (
};
};
/** Apply a deadline and caller cancellation to one Playwright operation. */
/** Apply an optional lifecycle deadline and caller cancellation to an operation. */
export const runWithExecutionLimits = async <Value>(
operation: Promise<Value>,
signal: AbortSignal | undefined,
deadline: number,
deadline?: number,
): Promise<Value> => {
if (signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
if (signal === undefined && deadline === undefined) return operation;
let timer: ReturnType<typeof setTimeout> | undefined;
let abortListener: (() => void) | undefined;
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new BrowserObservationError(OPERATION, "timeout")),
Math.max(1, deadline - Date.now()),
const interruptions: Promise<never>[] = [];
if (deadline !== undefined)
interruptions.push(
new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new BrowserObservationError(OPERATION, "timeout")),
Math.max(1, deadline - Date.now()),
);
}),
);
if (signal !== undefined)
interruptions.push(
new Promise<never>((_, reject) => {
abortListener = () =>
reject(new BrowserObservationError(OPERATION, "cancelled"));
signal.addEventListener("abort", abortListener, { once: true });
}),
);
});
const cancellation =
signal === undefined
? timeout
: Promise.race([
timeout,
new Promise<never>((_, reject) => {
abortListener = () =>
reject(new BrowserObservationError(OPERATION, "cancelled"));
signal.addEventListener("abort", abortListener, { once: true });
}),
]);
try {
return await Promise.race([operation, cancellation]);
return interruptions.length === 0
? await operation
: await Promise.race([operation, ...interruptions]);
} finally {
if (timer !== undefined) clearTimeout(timer);
if (abortListener !== undefined)
@@ -41,7 +41,7 @@ import {
} from "./PlaywrightElectronActiveActions.js";
const OPERATION = "capture_electron_scenario" as const;
const RUN_TIMEOUT_MS = 60_000;
const STARTUP_TIMEOUT_MS = 60_000;
/** Public identity for provider-owned Electron runtime experiments. */
export const PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY: ProviderIdentity =
@@ -165,14 +165,14 @@ export class PlaywrightElectronActiveProvider
try {
if (options.signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
const deadline = Date.now() + RUN_TIMEOUT_MS;
const startupDeadline = Date.now() + STARTUP_TIMEOUT_MS;
const paths = await canonicalPaths(input);
application = await electron.launch({
executablePath: paths.executable,
cwd: paths.root,
env: safeElectronEnvironment(runId),
args: ["-r", hookPath, paths.application, ...input.args],
timeout: Math.max(1, deadline - Date.now()),
timeout: Math.max(1, startupDeadline - Date.now()),
});
const leaderPid = application.process().pid;
if (
@@ -192,16 +192,10 @@ export class PlaywrightElectronActiveProvider
expectedCommand: paths.executable,
sweepTokenOwnedProcesses: true,
};
const actions = await runElectronActions(
application,
input,
options,
deadline,
);
const actions = await runElectronActions(application, input, options);
const state = await runWithExecutionLimits(
readApplicationState(application),
options.signal,
deadline,
);
outcome = ok(createResult(paths, input, actions, state));
} catch (cause: unknown) {
@@ -341,7 +335,7 @@ const createResult = (
},
coverage: createCoverage(hookSnapshot),
limitations: [
"IPC payloads are represented only by bounded value shapes; values are never retained, channels are capped at 1,024 characters, and argument-shape arrays at 32 entries.",
"IPC payloads are represented by value shapes; payload values are never retained.",
"IPC direction and sender/receiver identifiers are observed only where Electron exposes them at the hooked boundary.",
"The runtime timeline records lifecycle, navigation, shell, permission, popup, download, protocol, preload, native-addon, process, and IPC events; activity before hook installation is unavailable.",
"The preload and renderer process contexts are not instrumented by the main-process -r hook; preload configuration and contextBridge API-shape events are main-boundary observations, not proof of renderer-side execution.",