refactor(tools): return complete analysis results inline
This commit is contained in:
@@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
|
||||
import { browserScenarioSchema } from "../domain/browserScenario.js";
|
||||
import { BROWSER_SCENARIO_CAPTURE_LIMITS } from "../domain/browserScenarioValues.js";
|
||||
|
||||
const secret = (secret_id: string) => ({ source: "secret", secret_id });
|
||||
const literal = (value: string) => ({
|
||||
@@ -120,7 +119,7 @@ const baseScenario = () => ({
|
||||
});
|
||||
|
||||
describe("browserScenarioSchema", () => {
|
||||
it("accepts and normalizes a bounded declared scenario", () => {
|
||||
it("accepts and normalizes a declared scenario", () => {
|
||||
const parsed = browserScenarioSchema.parse(baseScenario());
|
||||
expect(parsed.allowed_origins).toEqual([
|
||||
"https://api.example.test",
|
||||
@@ -150,10 +149,23 @@ describe("browserScenarioSchema", () => {
|
||||
"proxy-authorization",
|
||||
"set-cookie",
|
||||
]);
|
||||
expect(parsed.limits).toEqual(BROWSER_SCENARIO_CAPTURE_LIMITS);
|
||||
expect(parsed).not.toHaveProperty("limits");
|
||||
});
|
||||
|
||||
it("rejects caller supplied capture limits", () => {
|
||||
it("accepts caller selected action timeouts without a fixed ceiling", () => {
|
||||
const input = baseScenario();
|
||||
input.actions[0] = { ...input.actions[0], timeout_ms: 120_000 } as never;
|
||||
input.actions[1] = {
|
||||
step_id: "pause",
|
||||
action: "wait_for_timeout",
|
||||
duration_ms: 120_001,
|
||||
} as never;
|
||||
const actions = browserScenarioSchema.parse(input).actions;
|
||||
expect(actions[0]).toMatchObject({ timeout_ms: 120_000 });
|
||||
expect(actions[1]).toMatchObject({ duration_ms: 120_001 });
|
||||
});
|
||||
|
||||
it("does not accept the removed provider timeout configuration", () => {
|
||||
expect(
|
||||
browserScenarioSchema.safeParse({
|
||||
...baseScenario(),
|
||||
|
||||
@@ -24,14 +24,9 @@ export interface BrowserScenarioSessionPort {
|
||||
readonly dropped: number;
|
||||
readonly items: readonly BrowserScenarioEvent[];
|
||||
};
|
||||
perform(
|
||||
action: BrowserScenarioAction,
|
||||
maximumTimeoutMs: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void>;
|
||||
perform(action: BrowserScenarioAction, signal?: AbortSignal): Promise<void>;
|
||||
capture(
|
||||
requested: ReadonlySet<SnapshotKind>,
|
||||
maximumTimeoutMs: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<BrowserStepArtifacts>;
|
||||
close(): Promise<"terminated-owned-process" | "disconnected-external">;
|
||||
@@ -43,7 +38,6 @@ export interface BrowserScenarioSessionFactory {
|
||||
scenario: BrowserScenario,
|
||||
options?: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly deadlineAt?: number;
|
||||
},
|
||||
): Promise<BrowserScenarioSessionPort>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { delayWithCancellation } from "./CdpCaptureValues.js";
|
||||
|
||||
describe("cancellable browser observation delays", () => {
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("schedules durations beyond the native timer range in consecutive waits", async () => {
|
||||
vi.useFakeTimers();
|
||||
let completed = false;
|
||||
const waiting = delayWithCancellation(
|
||||
2_147_483_648,
|
||||
"observe_javascript_runtime",
|
||||
).then(() => {
|
||||
completed = true;
|
||||
});
|
||||
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
await vi.advanceTimersByTimeAsync(2_147_483_647);
|
||||
expect(completed).toBe(false);
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await waiting;
|
||||
expect(completed).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -78,19 +78,24 @@ export const delayWithCancellation = async (
|
||||
operation: BrowserObservationOperation,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
if (durationMs === 0) return;
|
||||
if (signal?.aborted === true) throw new AnalysisCancelledError(operation);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
resolve();
|
||||
}, durationMs);
|
||||
const onAbort = (): void => {
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
reject(new AnalysisCancelledError(operation));
|
||||
};
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal?.aborted === true) onAbort();
|
||||
});
|
||||
const maximumTimerDelay = 2_147_483_647;
|
||||
let remaining = durationMs;
|
||||
while (remaining > 0) {
|
||||
if (signal?.aborted === true) throw new AnalysisCancelledError(operation);
|
||||
const delay = Math.min(remaining, maximumTimerDelay);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
resolve();
|
||||
}, delay);
|
||||
const onAbort = (): void => {
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
reject(new AnalysisCancelledError(operation));
|
||||
};
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal?.aborted === true) onAbort();
|
||||
});
|
||||
remaining -= delay;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -3,7 +3,6 @@ import WebSocket, { type RawData } from "ws";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisError,
|
||||
AnalysisTimeoutError,
|
||||
BrowserObservationError,
|
||||
type BrowserObservationOperation,
|
||||
} from "../domain/errors.js";
|
||||
@@ -17,14 +16,10 @@ export interface CdpEvent {
|
||||
interface PendingCommand {
|
||||
readonly resolve: (value: unknown) => void;
|
||||
readonly reject: (error: AnalysisError) => void;
|
||||
readonly timer: ReturnType<typeof setTimeout>;
|
||||
readonly removeAbort: () => void;
|
||||
}
|
||||
|
||||
const CONNECT_TIMEOUT_MS = 5_000;
|
||||
const COMMAND_TIMEOUT_MS = 5_000;
|
||||
|
||||
/** Correlated, bounded JSON-RPC transport for one CDP target operation. */
|
||||
/** Correlated JSON-RPC transport for one CDP target operation. */
|
||||
export class CdpConnection {
|
||||
readonly #pending = new Map<number, PendingCommand>();
|
||||
readonly #listeners = new Set<(event: CdpEvent) => void>();
|
||||
@@ -50,7 +45,7 @@ export class CdpConnection {
|
||||
): Promise<CdpConnection> {
|
||||
if (signal?.aborted === true) throw new AnalysisCancelledError(operation);
|
||||
const socket = new WebSocket(url, {
|
||||
handshakeTimeout: CONNECT_TIMEOUT_MS,
|
||||
handshakeTimeout: 0,
|
||||
maxPayload: 0,
|
||||
perMessageDeflate: false,
|
||||
});
|
||||
@@ -74,7 +69,7 @@ export class CdpConnection {
|
||||
return () => this.#disconnectListeners.delete(listener);
|
||||
}
|
||||
|
||||
/** Execute one bounded command, optionally within a flat target session. */
|
||||
/** Execute one command, optionally within a flat target session. */
|
||||
async send(
|
||||
method: string,
|
||||
params: Readonly<Record<string, unknown>> = {},
|
||||
@@ -93,21 +88,14 @@ export class CdpConnection {
|
||||
const onAbort = (): void => {
|
||||
const pending = this.#pending.get(id);
|
||||
if (pending === undefined) return;
|
||||
clearTimeout(pending.timer);
|
||||
pending.removeAbort();
|
||||
this.#pending.delete(id);
|
||||
reject(new AnalysisCancelledError(this.operation));
|
||||
};
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
this.#pending.delete(id);
|
||||
reject(new AnalysisTimeoutError(this.operation, COMMAND_TIMEOUT_MS));
|
||||
}, COMMAND_TIMEOUT_MS);
|
||||
this.#pending.set(id, {
|
||||
resolve,
|
||||
reject,
|
||||
timer,
|
||||
removeAbort: () => signal?.removeEventListener("abort", onAbort),
|
||||
});
|
||||
this.socket.send(
|
||||
@@ -208,7 +196,6 @@ export class CdpConnection {
|
||||
}
|
||||
|
||||
#complete(id: number, pending: PendingCommand): void {
|
||||
clearTimeout(pending.timer);
|
||||
pending.removeAbort();
|
||||
this.#pending.delete(id);
|
||||
}
|
||||
@@ -247,11 +234,6 @@ const waitForOpen = async (
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> =>
|
||||
await new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
cleanup();
|
||||
terminateSocket(socket);
|
||||
reject(new AnalysisTimeoutError(operation, CONNECT_TIMEOUT_MS));
|
||||
}, CONNECT_TIMEOUT_MS);
|
||||
const onOpen = (): void => {
|
||||
cleanup();
|
||||
resolve();
|
||||
@@ -266,18 +248,26 @@ const waitForOpen = async (
|
||||
}),
|
||||
);
|
||||
};
|
||||
const onClose = (code: number, reason: Buffer): void => {
|
||||
onFailure(
|
||||
new Error(
|
||||
`CDP WebSocket closed before opening (${code}: ${reason.toString("utf8")})`,
|
||||
),
|
||||
);
|
||||
};
|
||||
const onAbort = (): void => {
|
||||
terminateSocket(socket);
|
||||
onFailure(new AnalysisCancelledError(operation));
|
||||
};
|
||||
const cleanup = (): void => {
|
||||
clearTimeout(timer);
|
||||
socket.off("open", onOpen);
|
||||
socket.off("error", onFailure);
|
||||
socket.off("close", onClose);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
};
|
||||
socket.once("open", onOpen);
|
||||
socket.once("error", onFailure);
|
||||
socket.once("close", onClose);
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal?.aborted === true) onAbort();
|
||||
});
|
||||
|
||||
@@ -5,14 +5,11 @@ import { z } from "zod";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisError,
|
||||
AnalysisTimeoutError,
|
||||
BrowserObservationError,
|
||||
type BrowserObservationOperation,
|
||||
} from "../domain/errors.js";
|
||||
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
||||
|
||||
const HTTP_TIMEOUT_MS = 5_000;
|
||||
|
||||
const endpointVersionSchema = z.object({
|
||||
Browser: z.string().min(1),
|
||||
"Protocol-Version": z.string().min(1),
|
||||
@@ -323,9 +320,6 @@ export const readCdpJson = async (
|
||||
);
|
||||
},
|
||||
);
|
||||
request_.setTimeout(HTTP_TIMEOUT_MS, () =>
|
||||
request_.destroy(new AnalysisTimeoutError(operation, HTTP_TIMEOUT_MS)),
|
||||
);
|
||||
request_.on("error", (cause: unknown) =>
|
||||
reject(endpointFailure(cause, operation, signal)),
|
||||
);
|
||||
|
||||
@@ -143,11 +143,7 @@ class FakeSession implements BrowserScenarioSessionPort {
|
||||
return { retained: 0, dropped: 0, items: [] };
|
||||
}
|
||||
|
||||
async perform(
|
||||
_action: BrowserScenarioAction,
|
||||
_timeout: number,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
async perform(_action: BrowserScenarioAction, signal?: AbortSignal) {
|
||||
this.performCalls += 1;
|
||||
this.onPerform?.();
|
||||
if (signal?.aborted === true) throw new Error("request cancelled");
|
||||
@@ -156,7 +152,6 @@ class FakeSession implements BrowserScenarioSessionPort {
|
||||
|
||||
capture(
|
||||
requested: ReadonlySet<SnapshotKind>,
|
||||
_maximumTimeoutMs: number,
|
||||
_signal?: AbortSignal,
|
||||
): Promise<BrowserStepArtifacts> {
|
||||
this.captureCalls += 1;
|
||||
|
||||
@@ -134,13 +134,11 @@ const initialStep = async (input: {
|
||||
readonly session: BrowserScenarioSessionPort;
|
||||
readonly scenario: BrowserScenario;
|
||||
readonly elapsedMs: number;
|
||||
readonly maximumTimeoutMs: number;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
}): Promise<BrowserScenarioStep> => {
|
||||
const { session, scenario, elapsedMs, maximumTimeoutMs, signal } = input;
|
||||
const { session, scenario, elapsedMs, signal } = input;
|
||||
const artifacts = await session.capture(
|
||||
requestedForStep(scenario, 0),
|
||||
maximumTimeoutMs,
|
||||
signal,
|
||||
);
|
||||
return createStep({
|
||||
@@ -163,19 +161,10 @@ const executeStep = async (input: {
|
||||
readonly scenario: BrowserScenario;
|
||||
readonly action: BrowserScenarioAction;
|
||||
readonly stepIndex: number;
|
||||
readonly startedAt: number;
|
||||
readonly priorFailure: boolean;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
}): Promise<BrowserScenarioStep> => {
|
||||
const {
|
||||
session,
|
||||
scenario,
|
||||
action,
|
||||
stepIndex,
|
||||
startedAt,
|
||||
priorFailure,
|
||||
signal,
|
||||
} = input;
|
||||
const { session, scenario, action, stepIndex, priorFailure, signal } = input;
|
||||
const beforeUrl = session.currentUrl();
|
||||
const eventStart = session.nextEventSequence();
|
||||
const requested = requestedForStep(scenario, stepIndex);
|
||||
@@ -208,10 +197,7 @@ const executeStep = async (input: {
|
||||
outcome = { status: "cancelled", error: "scenario request cancelled" };
|
||||
} else {
|
||||
try {
|
||||
const elapsed = Date.now() - startedAt;
|
||||
const remaining = scenario.limits.max_duration_ms - elapsed;
|
||||
if (remaining <= 0) throw new Error("Scenario duration limit reached");
|
||||
await session.perform(action, remaining, signal);
|
||||
await session.perform(action, signal);
|
||||
} catch (cause: unknown) {
|
||||
outcome = {
|
||||
status: requestCancelled() ? "cancelled" : "failed",
|
||||
@@ -219,16 +205,10 @@ const executeStep = async (input: {
|
||||
};
|
||||
}
|
||||
}
|
||||
const remaining = scenario.limits.max_duration_ms - (Date.now() - startedAt);
|
||||
const artifacts =
|
||||
outcome.status === "cancelled" || remaining <= 0
|
||||
? unavailableArtifacts(
|
||||
requested,
|
||||
outcome.status === "cancelled"
|
||||
? "scenario request cancelled"
|
||||
: "scenario duration limit reached",
|
||||
)
|
||||
: await session.capture(requested, remaining, signal);
|
||||
outcome.status === "cancelled"
|
||||
? unavailableArtifacts(requested, "scenario request cancelled")
|
||||
: await session.capture(requested, signal);
|
||||
return createStep({
|
||||
stepIndex,
|
||||
stepId: action.step_id,
|
||||
@@ -266,10 +246,10 @@ const runScenario = async (
|
||||
if (options.signal?.aborted === true)
|
||||
throw new BrowserObservationError(OPERATION, "cancelled");
|
||||
const startedAt = Date.now();
|
||||
const session = await factory.open(scenario, {
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
deadlineAt: startedAt + scenario.limits.max_duration_ms,
|
||||
});
|
||||
const session = await factory.open(
|
||||
scenario,
|
||||
options.signal === undefined ? {} : { signal: options.signal },
|
||||
);
|
||||
const steps: BrowserScenarioStep[] = [];
|
||||
let cleanup: "terminated-owned-process" | "disconnected-external" | undefined;
|
||||
try {
|
||||
@@ -278,8 +258,6 @@ const runScenario = async (
|
||||
session,
|
||||
scenario,
|
||||
elapsedMs: Date.now() - startedAt,
|
||||
maximumTimeoutMs:
|
||||
scenario.limits.max_duration_ms - (Date.now() - startedAt),
|
||||
signal: options.signal,
|
||||
}),
|
||||
);
|
||||
@@ -290,7 +268,6 @@ const runScenario = async (
|
||||
scenario,
|
||||
action,
|
||||
stepIndex: offset + 1,
|
||||
startedAt,
|
||||
priorFailure: failed,
|
||||
signal: options.signal,
|
||||
});
|
||||
|
||||
@@ -61,23 +61,46 @@ it("rejects non-absolute deep-link values", () => {
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts any argument count while validating each argument", () => {
|
||||
it("keeps long Electron arguments and deep-link URLs intact", () => {
|
||||
const longArgument = "x".repeat(5_000);
|
||||
const longUrl = `rea-fixture://open/${"item".repeat(2_000)}`;
|
||||
const longStepId = "step".repeat(100);
|
||||
const input = electronActiveObservationInputSchema.parse({
|
||||
executable_path: "/opt/electron",
|
||||
application_path: "/opt/app/main.js",
|
||||
application_root: "/opt/app",
|
||||
args: Array.from({ length: 40 }, (_, index) => `--flag-${index}`),
|
||||
args: [longArgument],
|
||||
actions: [
|
||||
{
|
||||
step_id: longStepId,
|
||||
kind: "deep-link",
|
||||
delivery: "open-url",
|
||||
url: longUrl,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(input.args).toHaveLength(40);
|
||||
expect(input.args).toEqual([longArgument]);
|
||||
expect(input.actions[0]).toMatchObject({
|
||||
step_id: longStepId,
|
||||
url: longUrl,
|
||||
});
|
||||
expect(
|
||||
electronActiveObservationInputSchema.safeParse({
|
||||
executable_path: "/opt/electron",
|
||||
application_path: "/opt/app/main.js",
|
||||
application_root: "/opt/app",
|
||||
args: ["x".repeat(4_097)],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
electronActiveObservationResultSchema.parse({
|
||||
...createElectronActiveObservationFixtureResult("/opt/app"),
|
||||
actions: [
|
||||
{
|
||||
step_id: longStepId,
|
||||
kind: "deep-link",
|
||||
window_index: null,
|
||||
target: null,
|
||||
status: "completed",
|
||||
elapsed_ms: 0,
|
||||
error: null,
|
||||
},
|
||||
],
|
||||
}).actions[0]?.step_id,
|
||||
).toBe(longStepId);
|
||||
});
|
||||
|
||||
it("redacts action inputs from Playwright failures", async () => {
|
||||
@@ -114,6 +137,131 @@ it("redacts action inputs from Playwright failures", async () => {
|
||||
expect(result[0]?.error).not.toContain("raw-secret");
|
||||
});
|
||||
|
||||
it("retains complete action errors and Electron window text", async () => {
|
||||
const longError = `locator failed ${"detail ".repeat(300)}`;
|
||||
const input = electronActiveObservationInputSchema.parse({
|
||||
executable_path: "/opt/electron",
|
||||
application_path: "/opt/app/main.js",
|
||||
application_root: "/opt/app",
|
||||
actions: [{ step_id: "click-step", kind: "click", selector: "#run" }],
|
||||
});
|
||||
const page = {
|
||||
locator: () => ({
|
||||
click: async () => Promise.reject(new Error(longError)),
|
||||
}),
|
||||
};
|
||||
const actions = await runElectronActions(
|
||||
{ windows: () => [page] } as never,
|
||||
input,
|
||||
{},
|
||||
Date.now() + 1_000,
|
||||
);
|
||||
const result = createElectronActiveObservationFixtureResult("/opt/app");
|
||||
const longUrl = `file://${"/segment".repeat(10_000)}`;
|
||||
const longTitle = "title".repeat(4_000);
|
||||
|
||||
expect(actions[0]?.error).toBe(longError);
|
||||
expect(
|
||||
electronActiveObservationResultSchema.parse({
|
||||
...result,
|
||||
windows: [{ ...result.windows[0], url: longUrl, title: longTitle }],
|
||||
actions: [
|
||||
{
|
||||
step_id: "click-step",
|
||||
kind: "click",
|
||||
window_index: 0,
|
||||
target: "window:0",
|
||||
status: "failed",
|
||||
elapsed_ms: 1,
|
||||
error: longError,
|
||||
},
|
||||
],
|
||||
}).windows[0],
|
||||
).toMatchObject({ url: longUrl, title: longTitle });
|
||||
});
|
||||
|
||||
it("accepts complete Electron input and observation strings", () => {
|
||||
const longText = "evidence-".repeat(3_000);
|
||||
const longPath = `/opt/${"directory/".repeat(2_000)}app`;
|
||||
const input = electronActiveObservationInputSchema.parse({
|
||||
executable_path: longPath,
|
||||
application_path: `${longPath}/main.js`,
|
||||
application_root: longPath,
|
||||
actions: [
|
||||
{ step_id: longText, kind: "click", selector: longText },
|
||||
{
|
||||
step_id: longText,
|
||||
kind: "deep-link",
|
||||
delivery: "open-url",
|
||||
url: `custom://${longText}`,
|
||||
},
|
||||
],
|
||||
});
|
||||
const fixture = createElectronActiveObservationFixtureResult("/opt/app");
|
||||
const event = {
|
||||
...fixture.ipc.events[0],
|
||||
correlation_id: longText,
|
||||
event: longText,
|
||||
channel: longText,
|
||||
sender: longText,
|
||||
receiver: longText,
|
||||
frame: longText,
|
||||
target: longText,
|
||||
result_shape: longText,
|
||||
process_type: longText,
|
||||
source: longText,
|
||||
artifact_path: longPath,
|
||||
};
|
||||
const result = electronActiveObservationResultSchema.parse({
|
||||
...fixture,
|
||||
application: {
|
||||
...fixture.application,
|
||||
application_path: longPath,
|
||||
electron_version: longText,
|
||||
},
|
||||
actions: [
|
||||
{
|
||||
...fixture.actions[0],
|
||||
step_id: longText,
|
||||
target: longText,
|
||||
error: longText,
|
||||
status: "failed",
|
||||
},
|
||||
],
|
||||
windows: [
|
||||
{
|
||||
...fixture.windows[0],
|
||||
window_id: longText,
|
||||
web_contents_id: longText,
|
||||
url: longText,
|
||||
title: longText,
|
||||
},
|
||||
],
|
||||
ipc: { events: [event], observed: 1 },
|
||||
timeline: {
|
||||
events: [
|
||||
{
|
||||
...event,
|
||||
kind: "navigation",
|
||||
phase: "observed",
|
||||
direction: null,
|
||||
capture_method: "event-emitter",
|
||||
},
|
||||
],
|
||||
observed: 1,
|
||||
},
|
||||
limitations: [longText],
|
||||
});
|
||||
|
||||
expect(input.actions[0]?.step_id).toBe(longText);
|
||||
expect(input.actions[0]?.kind === "click" && input.actions[0].selector).toBe(
|
||||
longText,
|
||||
);
|
||||
expect(result.ipc.events[0]?.channel).toBe(longText);
|
||||
expect(result.windows[0]?.title).toBe(longText);
|
||||
expect(result.limitations[0]).toBe(longText);
|
||||
});
|
||||
|
||||
it("runs an untargeted deep-link without requiring a BrowserWindow", async () => {
|
||||
const input = electronActiveObservationInputSchema.parse({
|
||||
executable_path: "/opt/electron",
|
||||
|
||||
@@ -14,7 +14,7 @@ const ACTION_TIMEOUT_MS = 5_000;
|
||||
|
||||
const hookEventSchema = z.strictObject({
|
||||
sequence: z.number().int().min(1),
|
||||
correlation_id: z.string().max(256).nullable(),
|
||||
correlation_id: z.string().nullable(),
|
||||
kind: z.enum([
|
||||
"main-handler-invocation",
|
||||
"main-event-invocation",
|
||||
@@ -40,10 +40,9 @@ const hookEventSchema = z.strictObject({
|
||||
"updater",
|
||||
"error",
|
||||
]),
|
||||
event: z.string().max(128).nullable(),
|
||||
event: z.string().nullable(),
|
||||
phase: z.enum(["attempted", "completed", "blocked", "failed", "observed"]),
|
||||
channel: z.string().max(1_024).nullable(),
|
||||
channel_truncated: z.boolean().default(false),
|
||||
channel: z.string().nullable(),
|
||||
direction: z
|
||||
.enum([
|
||||
"renderer-to-main",
|
||||
@@ -52,17 +51,16 @@ const hookEventSchema = z.strictObject({
|
||||
"utility-to-main",
|
||||
])
|
||||
.nullable(),
|
||||
sender: z.string().max(256).nullable(),
|
||||
receiver: z.string().max(256).nullable(),
|
||||
frame: z.string().max(256).nullable(),
|
||||
target: z.string().max(256).nullable(),
|
||||
argument_shapes: z.array(z.string().max(64)).max(32),
|
||||
argument_shapes_truncated: z.boolean().default(false),
|
||||
result_shape: z.string().max(64).nullable(),
|
||||
process_type: z.string().max(128).nullable(),
|
||||
source: z.string().max(64),
|
||||
sender: z.string().nullable(),
|
||||
receiver: z.string().nullable(),
|
||||
frame: z.string().nullable(),
|
||||
target: z.string().nullable(),
|
||||
argument_shapes: z.array(z.string()),
|
||||
result_shape: z.string().nullable(),
|
||||
process_type: z.string().nullable(),
|
||||
source: z.string(),
|
||||
capture_method: z.enum(["api-wrapper", "event-emitter", "process-hook"]),
|
||||
artifact_path: z.string().max(16_384).nullable(),
|
||||
artifact_path: z.string().nullable(),
|
||||
artifact_sha256: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{64}$/u)
|
||||
@@ -80,14 +78,14 @@ const hookSnapshotSchema = z.strictObject({
|
||||
|
||||
const metricSchema = z.strictObject({
|
||||
pid: z.number().int().min(1),
|
||||
type: z.string().min(1).max(128),
|
||||
name: z.string().max(256).nullable(),
|
||||
service_name: z.string().max(256).nullable(),
|
||||
type: z.string().min(1),
|
||||
name: z.string().nullable(),
|
||||
service_name: z.string().nullable(),
|
||||
});
|
||||
|
||||
const windowMetadataSchema = z.strictObject({
|
||||
window_id: z.string().max(256),
|
||||
web_contents_id: z.string().max(256),
|
||||
window_id: z.string(),
|
||||
web_contents_id: z.string(),
|
||||
visible: z.boolean().nullable(),
|
||||
destroyed: z.boolean(),
|
||||
});
|
||||
@@ -341,8 +339,8 @@ export const readApplicationState = async (
|
||||
pages.map(
|
||||
async (page: Page, index): Promise<ElectronPageSnapshot> => ({
|
||||
index,
|
||||
url: page.url().slice(0, 65_536),
|
||||
title: (await page.title()).slice(0, 16_384),
|
||||
url: page.url(),
|
||||
title: await page.title(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -481,5 +479,5 @@ const safeActionErrorMessage = (
|
||||
.sort((left, right) => right.length - left.length);
|
||||
for (const value of inputValues)
|
||||
message = message.split(value).join("<redacted-input>");
|
||||
return redactSensitiveText(message).slice(0, 1_024);
|
||||
return redactSensitiveText(message);
|
||||
};
|
||||
|
||||
@@ -7,19 +7,29 @@ const OPERATION = "capture_browser_scenario" as const;
|
||||
|
||||
export const withPlaywrightExecutionBoundary = <Value>(
|
||||
work: () => Promise<Value>,
|
||||
maximumTimeoutMs: number,
|
||||
timeoutMs: number | undefined,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Value> => {
|
||||
if (maximumTimeoutMs <= 0)
|
||||
return Promise.reject(
|
||||
new AnalysisTimeoutError(OPERATION, maximumTimeoutMs),
|
||||
);
|
||||
if (timeoutMs !== undefined && timeoutMs <= 0)
|
||||
return Promise.reject(new AnalysisTimeoutError(OPERATION, timeoutMs));
|
||||
if (signal?.aborted === true)
|
||||
return Promise.reject(new AnalysisCancelledError(OPERATION));
|
||||
|
||||
return new Promise<Value>((resolve, reject) => {
|
||||
let settled = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const deadline =
|
||||
timeoutMs === undefined ? undefined : Date.now() + timeoutMs;
|
||||
const scheduleTimeout = (): void => {
|
||||
if (deadline === undefined) return;
|
||||
const remaining = deadline - Date.now();
|
||||
if (remaining <= 0) {
|
||||
fail(new AnalysisTimeoutError(OPERATION, timeoutMs ?? 0));
|
||||
return;
|
||||
}
|
||||
timer = setTimeout(scheduleTimeout, Math.min(remaining, 2_147_483_647));
|
||||
timer.unref();
|
||||
};
|
||||
const cleanup = (): void => {
|
||||
if (timer !== undefined) clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
@@ -39,11 +49,7 @@ export const withPlaywrightExecutionBoundary = <Value>(
|
||||
const onAbort = (): void => {
|
||||
fail(new AnalysisCancelledError(OPERATION));
|
||||
};
|
||||
timer = setTimeout(
|
||||
() => fail(new AnalysisTimeoutError(OPERATION, maximumTimeoutMs)),
|
||||
maximumTimeoutMs,
|
||||
);
|
||||
timer.unref();
|
||||
scheduleTimeout();
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal?.aborted === true) {
|
||||
onAbort();
|
||||
|
||||
@@ -34,23 +34,19 @@ interface PerformActionInput {
|
||||
readonly page: Page;
|
||||
readonly action: BrowserScenarioAction;
|
||||
readonly secrets: BrowserScenarioSecrets;
|
||||
readonly defaultTimeoutMs: number;
|
||||
readonly maximumTimeoutMs: number;
|
||||
}
|
||||
|
||||
/** Execute one admitted declarative action with no caller-supplied code. */
|
||||
export const performPlaywrightScenarioAction = async (
|
||||
input: PerformActionInput,
|
||||
): Promise<void> => {
|
||||
const { page, action, secrets, defaultTimeoutMs, maximumTimeoutMs } = input;
|
||||
const { page, action, secrets } = input;
|
||||
const timeout = "timeout_ms" in action ? action.timeout_ms : undefined;
|
||||
const options = {
|
||||
timeout: Math.min(timeout ?? defaultTimeoutMs, maximumTimeoutMs),
|
||||
};
|
||||
const options = timeout === undefined ? {} : { timeout };
|
||||
switch (action.action) {
|
||||
case "goto":
|
||||
await page.goto(secrets.url(action.destination), {
|
||||
timeout: options.timeout,
|
||||
...options,
|
||||
waitUntil: action.wait_until,
|
||||
});
|
||||
return;
|
||||
@@ -89,8 +85,6 @@ export const performPlaywrightScenarioAction = async (
|
||||
});
|
||||
return;
|
||||
case "wait_for_timeout":
|
||||
if (action.duration_ms > maximumTimeoutMs)
|
||||
throw new Error("Scenario duration limit reached");
|
||||
await page.waitForTimeout(action.duration_ms);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -118,17 +118,11 @@ const configureAttachedEnvironment = async (
|
||||
export const openPlaywrightScenarioBrowser = async (
|
||||
scenario: BrowserScenario,
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
maximumTimeoutMs: number,
|
||||
): Promise<OpenedScenarioBrowser> => {
|
||||
if (scenario.browser.mode === "connect") {
|
||||
const browser = await chromium.connectOverCDP(
|
||||
scenario.browser.cdp_endpoint,
|
||||
{
|
||||
timeout: Math.min(
|
||||
scenario.limits.navigation_timeout_ms,
|
||||
maximumTimeoutMs,
|
||||
),
|
||||
},
|
||||
{ timeout: 0 },
|
||||
);
|
||||
try {
|
||||
const target = await findConnectedPage(
|
||||
@@ -165,7 +159,7 @@ export const openPlaywrightScenarioBrowser = async (
|
||||
handleSIGHUP: false,
|
||||
handleSIGINT: false,
|
||||
handleSIGTERM: false,
|
||||
timeout: maximumTimeoutMs,
|
||||
timeout: 0,
|
||||
});
|
||||
const browser = context.browser();
|
||||
if (browser === null) {
|
||||
|
||||
@@ -211,8 +211,8 @@ const initializePage = async (
|
||||
scenario: BrowserScenario,
|
||||
secrets: BrowserScenarioSecrets,
|
||||
): Promise<Set<Page>> => {
|
||||
context.setDefaultTimeout(scenario.limits.action_timeout_ms);
|
||||
context.setDefaultNavigationTimeout(scenario.limits.navigation_timeout_ms);
|
||||
context.setDefaultTimeout(0);
|
||||
context.setDefaultNavigationTimeout(0);
|
||||
const ownedPages = new Set([page]);
|
||||
if (scenario.browser.mode === "connect")
|
||||
await blockAttachedServiceWorkers(page);
|
||||
@@ -272,25 +272,19 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
options: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly deadlineAt: number;
|
||||
},
|
||||
): Promise<PlaywrightScenarioSession> {
|
||||
const remaining = (): number => options.deadlineAt - Date.now();
|
||||
if (options.signal?.aborted === true)
|
||||
throw new BrowserObservationError(OPERATION, "cancelled");
|
||||
const secrets = BrowserScenarioSecrets.resolve(scenario, environment);
|
||||
if (secrets === undefined)
|
||||
throw new BrowserObservationError(OPERATION, "secret_unavailable");
|
||||
const opening = openPlaywrightScenarioBrowser(
|
||||
scenario,
|
||||
environment,
|
||||
remaining(),
|
||||
);
|
||||
const opening = openPlaywrightScenarioBrowser(scenario, environment);
|
||||
let opened: OpenedScenarioBrowser;
|
||||
try {
|
||||
opened = await withPlaywrightExecutionBoundary(
|
||||
() => opening,
|
||||
remaining(),
|
||||
undefined,
|
||||
options.signal,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
@@ -302,7 +296,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
|
||||
try {
|
||||
await withPlaywrightExecutionBoundary(
|
||||
() => initializePage(opened.context, opened.page, scenario, secrets),
|
||||
remaining(),
|
||||
undefined,
|
||||
options.signal,
|
||||
);
|
||||
const events = new PlaywrightScenarioEvents({
|
||||
@@ -321,12 +315,9 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
|
||||
() =>
|
||||
opened.page.goto(secrets.url(scenario.start_url), {
|
||||
waitUntil: "load",
|
||||
timeout: Math.min(
|
||||
scenario.limits.navigation_timeout_ms,
|
||||
remaining(),
|
||||
),
|
||||
timeout: 0,
|
||||
}),
|
||||
remaining(),
|
||||
undefined,
|
||||
options.signal,
|
||||
);
|
||||
return session;
|
||||
@@ -358,7 +349,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
|
||||
|
||||
async perform(
|
||||
action: BrowserScenarioAction,
|
||||
maximumTimeoutMs: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
await withPlaywrightExecutionBoundary(
|
||||
@@ -367,10 +357,8 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
|
||||
page: this.opened.page,
|
||||
action,
|
||||
secrets: this.secrets,
|
||||
defaultTimeoutMs: this.scenario.limits.action_timeout_ms,
|
||||
maximumTimeoutMs,
|
||||
}),
|
||||
maximumTimeoutMs,
|
||||
"timeout_ms" in action ? action.timeout_ms : undefined,
|
||||
signal,
|
||||
);
|
||||
}
|
||||
@@ -379,7 +367,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
|
||||
requested: ReadonlySet<
|
||||
BrowserScenario["capture"]["after_each_step"][number]
|
||||
>,
|
||||
maximumTimeoutMs: number,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
return withPlaywrightExecutionBoundary(
|
||||
@@ -391,7 +378,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
|
||||
secrets: this.secrets,
|
||||
requested,
|
||||
}),
|
||||
maximumTimeoutMs,
|
||||
undefined,
|
||||
signal,
|
||||
);
|
||||
}
|
||||
@@ -429,13 +416,8 @@ export class PlaywrightScenarioSessionFactory
|
||||
scenario: BrowserScenario,
|
||||
options: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly deadlineAt?: number;
|
||||
} = {},
|
||||
): Promise<BrowserScenarioSessionPort> {
|
||||
return PlaywrightScenarioSession.open(scenario, this.environment, {
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
deadlineAt:
|
||||
options.deadlineAt ?? Date.now() + scenario.limits.max_duration_ms,
|
||||
});
|
||||
return PlaywrightScenarioSession.open(scenario, this.environment, options);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import type {
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import type { JavaScriptRuntimeObservationPort } from "../application/JavaScriptRuntimeObservationPort.js";
|
||||
import {
|
||||
MAX_JAVASCRIPT_RUNTIME_LOCATION_BYTES,
|
||||
javascriptRuntimeObservationSchema,
|
||||
javascriptRuntimeTargetListSchema,
|
||||
type JavaScriptRuntimeObservation,
|
||||
@@ -20,7 +19,6 @@ import {
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
boundedText,
|
||||
numberValue,
|
||||
recordValue,
|
||||
stringValue,
|
||||
@@ -273,11 +271,7 @@ const ingestScript = (
|
||||
state.scriptsObserved += 1;
|
||||
const value = recordValue(event.params);
|
||||
const rawUrl = stringValue(value?.url);
|
||||
if (
|
||||
rawUrl === undefined ||
|
||||
rawUrl === "" ||
|
||||
Buffer.byteLength(rawUrl) > MAX_JAVASCRIPT_RUNTIME_LOCATION_BYTES
|
||||
) {
|
||||
if (rawUrl === undefined || rawUrl === "") {
|
||||
state.invalidScripts += 1;
|
||||
retainEvent(state, 0);
|
||||
return;
|
||||
@@ -285,7 +279,7 @@ const ingestScript = (
|
||||
const draft: ScriptDraft = {
|
||||
rawUrl,
|
||||
executionContextKey: contextKey(value?.executionContextId),
|
||||
cdpHash: boundedText(value?.hash, 512),
|
||||
cdpHash: stringValue(value?.hash) ?? null,
|
||||
length: nonnegativeInteger(value?.length),
|
||||
isModule: value?.isModule === true,
|
||||
};
|
||||
@@ -320,7 +314,7 @@ const ingestContext = (
|
||||
}
|
||||
const origin =
|
||||
event.method === "Runtime.executionContextCreated"
|
||||
? boundedText(runtimeContext?.origin, 4_096)
|
||||
? (stringValue(runtimeContext?.origin) ?? null)
|
||||
: null;
|
||||
const draft: ContextDraft = {
|
||||
contextKey: key,
|
||||
|
||||
Reference in New Issue
Block a user