refactor(browser): return complete scenario observations

This commit is contained in:
morluto
2026-09-29 13:02:20 +08:00
parent e8c56e0c0a
commit e80fe414b1
16 changed files with 351 additions and 459 deletions
-10
View File
@@ -6,7 +6,6 @@ import type {
BrowserScenarioEvent,
BrowserStepArtifacts,
} from "../domain/browserScenarioCapture.js";
import type { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
@@ -25,13 +24,6 @@ export interface BrowserScenarioSessionPort {
readonly dropped: number;
readonly items: readonly BrowserScenarioEvent[];
};
eventTruncationSections(): readonly (
| "events"
| "frames"
| "workers"
| "popups"
| "websockets"
)[];
perform(
action: BrowserScenarioAction,
maximumTimeoutMs: number,
@@ -39,7 +31,6 @@ export interface BrowserScenarioSessionPort {
): Promise<void>;
capture(
requested: ReadonlySet<SnapshotKind>,
budget: BrowserScenarioCaptureBudget,
maximumTimeoutMs: number,
signal?: AbortSignal,
): Promise<BrowserStepArtifacts>;
@@ -52,7 +43,6 @@ export interface BrowserScenarioSessionFactory {
scenario: BrowserScenario,
options?: {
readonly signal?: AbortSignal;
readonly budget?: BrowserScenarioCaptureBudget;
readonly deadlineAt?: number;
},
): Promise<BrowserScenarioSessionPort>;
@@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest";
import type { BrowserScenarioSessionPort } from "./BrowserScenarioSessionPort.js";
import { PlaywrightBrowserScenarioProvider } from "./PlaywrightBrowserScenarioProvider.js";
import { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import {
browserScenarioSchema,
@@ -108,13 +107,6 @@ class FakeSession implements BrowserScenarioSessionPort {
closeCalls = 0;
performCalls = 0;
captureCalls = 0;
eventTruncations: (
| "events"
| "frames"
| "workers"
| "popups"
| "websockets"
)[] = [];
onPerform: (() => void) | undefined;
private step = 0;
@@ -151,10 +143,6 @@ class FakeSession implements BrowserScenarioSessionPort {
return { retained: 0, dropped: 0, items: [] };
}
eventTruncationSections() {
return this.eventTruncations;
}
async perform(
_action: BrowserScenarioAction,
_timeout: number,
@@ -168,7 +156,8 @@ class FakeSession implements BrowserScenarioSessionPort {
capture(
requested: ReadonlySet<SnapshotKind>,
_budget: BrowserScenarioCaptureBudget,
_maximumTimeoutMs: number,
_signal?: AbortSignal,
): Promise<BrowserStepArtifacts> {
this.captureCalls += 1;
if (this.failCapture) return Promise.reject(new Error("capture failed"));
@@ -227,6 +216,19 @@ describe("PlaywrightBrowserScenarioProvider", () => {
expect(session.closeCalls).toBe(1);
});
it("returns an initial state and every step beyond the former action ceiling", async () => {
const session = new FakeSession("launch");
const provider = new PlaywrightBrowserScenarioProvider({
open: () => Promise.resolve(session),
});
const result = await provider.captureScenario(scenario({ actions: 129 }));
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.scenario.action_count).toBe(129);
expect(result.value.steps).toHaveLength(130);
expect(result.value.steps.at(-1)?.step_id).toBe("wait_128");
});
it("makes missing and truncated captures ineligible for equality", async () => {
const session = new FakeSession("launch", true);
const provider = new PlaywrightBrowserScenarioProvider({
@@ -245,24 +247,6 @@ describe("PlaywrightBrowserScenarioProvider", () => {
});
});
it("makes event limit truncation ineligible for equality", async () => {
const session = new FakeSession("launch");
session.eventTruncations = ["events", "websockets"];
const provider = new PlaywrightBrowserScenarioProvider({
open: () => Promise.resolve(session),
});
const result = await provider.captureScenario(
scenario({ events: ["websockets"] }),
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.completeness).toMatchObject({
status: "truncated",
equality_eligible: false,
truncated_sections: ["events", "websockets"],
});
});
it("records one failed step, cancels later actions, and still cleans up", async () => {
const session = new FakeSession("launch", false, true);
const provider = new PlaywrightBrowserScenarioProvider({
@@ -349,14 +333,3 @@ describe("PlaywrightBrowserScenarioProvider", () => {
expect(session.closeCalls).toBe(1);
});
});
describe("BrowserScenarioCaptureBudget", () => {
it("enforces cumulative screenshot and metadata limits", () => {
const budget = new BrowserScenarioCaptureBudget(1, 10);
expect(budget.claimScreenshot()).toBe(true);
expect(budget.claimScreenshot()).toBe(false);
expect(budget.claimMetadata(6)).toBe(true);
expect(budget.claimMetadata(5)).toBe(false);
expect(budget.claimMetadata(4)).toBe(true);
});
});
@@ -30,7 +30,6 @@ import type {
BrowserScenarioSessionFactory,
BrowserScenarioSessionPort,
} from "./BrowserScenarioSessionPort.js";
import { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";
const OPERATION = "capture_browser_scenario" as const;
let defaultFactory: Promise<BrowserScenarioSessionFactory> | undefined;
@@ -134,16 +133,13 @@ const createStep = (
const initialStep = async (input: {
readonly session: BrowserScenarioSessionPort;
readonly scenario: BrowserScenario;
readonly budget: BrowserScenarioCaptureBudget;
readonly elapsedMs: number;
readonly maximumTimeoutMs: number;
readonly signal: AbortSignal | undefined;
}): Promise<BrowserScenarioStep> => {
const { session, scenario, budget, elapsedMs, maximumTimeoutMs, signal } =
input;
const { session, scenario, elapsedMs, maximumTimeoutMs, signal } = input;
const artifacts = await session.capture(
requestedForStep(scenario, 0),
budget,
maximumTimeoutMs,
signal,
);
@@ -165,7 +161,6 @@ const initialStep = async (input: {
const executeStep = async (input: {
readonly session: BrowserScenarioSessionPort;
readonly scenario: BrowserScenario;
readonly budget: BrowserScenarioCaptureBudget;
readonly action: BrowserScenarioAction;
readonly stepIndex: number;
readonly startedAt: number;
@@ -175,7 +170,6 @@ const executeStep = async (input: {
const {
session,
scenario,
budget,
action,
stepIndex,
startedAt,
@@ -234,7 +228,7 @@ const executeStep = async (input: {
? "scenario request cancelled"
: "scenario duration limit reached",
)
: await session.capture(requested, budget, remaining, signal);
: await session.capture(requested, remaining, signal);
return createStep({
stepIndex,
stepId: action.step_id,
@@ -260,7 +254,6 @@ const globalCompleteness = (
const truncated = steps.flatMap(
({ completeness }) => completeness.truncated_sections,
);
truncated.push(...session.eventTruncationSections());
if (session.mode === "connect") missing.push("events");
return classifyBrowserScenarioCompleteness(missing, truncated);
};
@@ -273,13 +266,8 @@ const runScenario = async (
if (options.signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
const startedAt = Date.now();
const budget = new BrowserScenarioCaptureBudget(
scenario.limits.max_screenshots,
scenario.limits.max_total_metadata_bytes,
);
const session = await factory.open(scenario, {
...(options.signal === undefined ? {} : { signal: options.signal }),
budget,
deadlineAt: startedAt + scenario.limits.max_duration_ms,
});
const steps: BrowserScenarioStep[] = [];
@@ -289,7 +277,6 @@ const runScenario = async (
await initialStep({
session,
scenario,
budget,
elapsedMs: Date.now() - startedAt,
maximumTimeoutMs:
scenario.limits.max_duration_ms - (Date.now() - startedAt),
@@ -301,7 +288,6 @@ const runScenario = async (
const step = await executeStep({
session,
scenario,
budget,
action,
stepIndex: offset + 1,
startedAt,
@@ -0,0 +1,41 @@
import { expect, it } from "vitest";
import type { BrowserContext, Page } from "playwright-core";
import { browserScenarioSchema } from "../domain/browserScenario.js";
import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
import { capturePlaywrightStepArtifacts } from "./PlaywrightScenarioArtifacts.js";
const scenario = browserScenarioSchema.parse({
browser: {
mode: "launch",
executable_path: "/opt/chromium",
headless: true,
user_data: "temporary-owned",
cleanup: "close-and-delete-profile",
},
start_url: { url: "https://app.example.test/" },
allowed_origins: ["https://app.example.test"],
actions: [{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 }],
});
const secrets = BrowserScenarioSecrets.resolve(scenario, {});
if (secrets === undefined)
throw new Error("Expected resolved scenario secrets");
it("returns a complete requested text artifact beyond the former inline ceiling", async () => {
const page = {
url: () => "https://app.example.test/",
content: () => Promise.resolve("x".repeat(16 * 1_024 * 1_024 + 1)),
} as unknown as Page;
const result = await capturePlaywrightStepArtifacts({
context: {} as BrowserContext,
page,
scenario,
secrets,
requested: new Set(["dom"]),
});
expect(result.dom).toMatchObject({
state: "captured",
value: { bytes: 16 * 1_024 * 1_024 + 1 },
});
});
+25 -145
View File
@@ -11,77 +11,28 @@ import {
} from "../domain/browserScenarioCapture.js";
import type { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
const TEXT_ARTIFACT_MAX_BYTES = 1_048_576;
const historyValueSchema = z.strictObject({
length: z.number().int().min(0),
navigation_entries: z
.array(
z.strictObject({
type: z.string(),
name: z.string(),
}),
)
.max(10_000),
navigation_entries: z.array(
z.strictObject({
type: z.string(),
name: z.string(),
}),
),
});
const storageValueSchema = z.strictObject({
local_storage: z.array(z.tuple([z.string(), z.string()])).max(10_000),
session_storage: z.array(z.tuple([z.string(), z.string()])).max(10_000),
local_storage: z.array(z.tuple([z.string(), z.string()])),
session_storage: z.array(z.tuple([z.string(), z.string()])),
});
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
/** Shared retained-count budget for one scenario's screenshot artifacts. */
export class BrowserScenarioCaptureBudget {
private screenshotCount = 0;
private metadataBytes = 0;
constructor(
private readonly maximumScreenshots: number,
private readonly maximumMetadataBytes: number,
) {}
claimScreenshot(): boolean {
if (this.screenshotCount >= this.maximumScreenshots) return false;
this.screenshotCount += 1;
return true;
}
claimMetadata(bytes: number): boolean {
if (this.metadataBytes + bytes > this.maximumMetadataBytes) return false;
this.metadataBytes += bytes;
return true;
}
}
const notRequested = () => ({ state: "not_requested" as const });
const missing = (reason: string) => ({ state: "missing" as const, reason });
const truncated = (observed: number, retained: number, reason: string) => ({
state: "truncated" as const,
observed,
retained,
reason,
});
const textArtifact = (
text: string,
maximumBytes: number,
budget: BrowserScenarioCaptureBudget,
) => {
const textArtifact = (text: string) => {
const bytes = Buffer.from(text);
if (bytes.byteLength > maximumBytes)
return truncated(
bytes.byteLength,
0,
`artifact exceeds ${maximumBytes} bytes`,
);
if (!budget.claimMetadata(bytes.byteLength))
return truncated(
bytes.byteLength,
0,
"scenario metadata byte limit reached",
);
return {
state: "captured" as const,
value: {
@@ -92,23 +43,7 @@ const textArtifact = (
};
};
const metadataArtifact = <Value>(
value: Value,
budget: BrowserScenarioCaptureBudget,
) => {
const bytes = Buffer.byteLength(JSON.stringify(value));
return budget.claimMetadata(bytes)
? { state: "captured" as const, value }
: truncated(bytes, 0, "scenario metadata byte limit reached");
};
const captureScreenshot = async (
page: Page,
scenario: BrowserScenario,
budget: BrowserScenarioCaptureBudget,
) => {
if (!budget.claimScreenshot())
return truncated(1, 0, "scenario screenshot count limit reached");
const captureScreenshot = async (page: Page) => {
try {
const bytes = await page.screenshot({
type: "png",
@@ -116,8 +51,6 @@ const captureScreenshot = async (
animations: "disabled",
caret: "hide",
});
if (bytes.byteLength > scenario.limits.max_screenshot_bytes)
return truncated(bytes.byteLength, 0, "screenshot byte limit reached");
const sha256 = createHash("sha256").update(bytes).digest("hex");
return {
state: "captured" as const,
@@ -136,20 +69,10 @@ const captureScreenshot = async (
const captureDom = async (input: {
readonly page: Page;
readonly secrets: BrowserScenarioSecrets;
readonly maximumBytes: number;
readonly maximumNodes: number;
readonly budget: BrowserScenarioCaptureBudget;
}) => {
const { page, secrets, maximumBytes, maximumNodes, budget } = input;
const { page, secrets } = input;
try {
const nodes = await page.locator("*").count();
if (nodes > maximumNodes)
return truncated(nodes, 0, "DOM node limit reached");
return textArtifact(
secrets.redact(await page.content()),
Math.min(maximumBytes, TEXT_ARTIFACT_MAX_BYTES),
budget,
);
return textArtifact(secrets.redact(await page.content()));
} catch {
return missing("DOM capture failed");
}
@@ -158,21 +81,11 @@ const captureDom = async (input: {
const captureAccessibility = async (input: {
readonly page: Page;
readonly secrets: BrowserScenarioSecrets;
readonly maximumBytes: number;
readonly maximumNodes: number;
readonly budget: BrowserScenarioCaptureBudget;
}) => {
const { page, secrets, maximumBytes, maximumNodes, budget } = input;
const { page, secrets } = input;
try {
const text = await page.locator("html").ariaSnapshot();
const nodes = text.split("\n").filter((line) => line.trim() !== "").length;
if (nodes > maximumNodes)
return truncated(nodes, 0, "accessibility node limit reached");
return textArtifact(
secrets.redact(text),
Math.min(maximumBytes, TEXT_ARTIFACT_MAX_BYTES),
budget,
);
return textArtifact(secrets.redact(text));
} catch {
return missing("accessibility capture failed");
}
@@ -192,10 +105,7 @@ const navigationType = (
}
};
const captureHistory = async (
page: Page,
budget: BrowserScenarioCaptureBudget,
) => {
const captureHistory = async (page: Page) => {
try {
const raw = historyValueSchema.parse(
await page.evaluate(`(() => ({
@@ -208,12 +118,6 @@ const captureHistory = async (
)
}))()`),
);
if (raw.navigation_entries.length > 256)
return truncated(
raw.navigation_entries.length,
0,
"navigation history entry limit reached",
);
const value = {
length: raw.length,
current_url: sanitizeBrowserUrl(page.url()),
@@ -222,7 +126,7 @@ const captureHistory = async (
name: sanitizeBrowserUrl(name),
})),
};
return metadataArtifact(value, budget);
return value;
} catch {
return missing("history capture failed");
}
@@ -233,9 +137,8 @@ const captureStorage = async (input: {
readonly page: Page;
readonly scenario: BrowserScenario;
readonly secrets: BrowserScenarioSecrets;
readonly budget: BrowserScenarioCaptureBudget;
}) => {
const { context, page, scenario, secrets, budget } = input;
const { context, page, scenario, secrets } = input;
try {
const cookies = await context.cookies(scenario.allowed_origins);
const pageStorage = storageValueSchema.parse(
@@ -244,12 +147,6 @@ const captureStorage = async (input: {
session_storage: Object.entries(window.sessionStorage)
}))()`),
);
const observed =
cookies.length +
pageStorage.local_storage.length +
pageStorage.session_storage.length;
if (observed > scenario.limits.max_storage_entries)
return truncated(observed, 0, "storage entry limit reached");
const value = {
cookies: cookies.map((cookie) => ({
name: cookie.name,
@@ -269,7 +166,7 @@ const captureStorage = async (input: {
...secrets.fingerprint(value),
})),
};
return metadataArtifact(value, budget);
return value;
} catch {
return missing("storage capture failed");
}
@@ -293,9 +190,8 @@ export const capturePlaywrightStepArtifacts = async (input: {
readonly scenario: BrowserScenario;
readonly secrets: BrowserScenarioSecrets;
readonly requested: ReadonlySet<SnapshotKind>;
readonly budget: BrowserScenarioCaptureBudget;
}): Promise<BrowserStepArtifacts> => {
const { context, page, scenario, secrets, requested, budget } = input;
const { context, page, scenario, secrets, requested } = input;
const allowed = isAllowedPage(page, new Set(scenario.allowed_origins));
const denied = () => missing("current page is outside approved origins");
const state = <Value>(
@@ -310,33 +206,17 @@ export const capturePlaywrightStepArtifacts = async (input: {
? capture()
: Promise.resolve(denied());
return browserStepArtifactsSchema.parse({
screenshot: await state("screenshot", () =>
captureScreenshot(page, scenario, budget),
),
dom: await state("dom", () =>
captureDom({
page,
secrets,
maximumBytes: scenario.limits.max_total_metadata_bytes,
maximumNodes: scenario.limits.max_dom_nodes,
budget,
}),
),
screenshot: await state("screenshot", () => captureScreenshot(page)),
dom: await state("dom", () => captureDom({ page, secrets })),
accessibility: await state("accessibility", () =>
captureAccessibility({
page,
secrets,
maximumBytes: scenario.limits.max_total_metadata_bytes,
maximumNodes: scenario.limits.max_accessibility_nodes,
budget,
}),
captureAccessibility({ page, secrets }),
),
url: await state("url", async () =>
metadataArtifact(sanitizeBrowserUrl(page.url()), budget),
Promise.resolve(sanitizeBrowserUrl(page.url())),
),
history: await state("history", () => captureHistory(page, budget)),
history: await state("history", () => captureHistory(page)),
storage: await state("storage", () =>
captureStorage({ context, page, scenario, secrets, budget }),
captureStorage({ context, page, scenario, secrets }),
),
});
};
+46 -5
View File
@@ -3,7 +3,6 @@ import type { Page } from "playwright-core";
import { browserScenarioSchema } from "../domain/browserScenario.js";
import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
import { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";
import { PlaywrightScenarioEvents } from "./PlaywrightScenarioEvents.js";
describe("PlaywrightScenarioEvents", () => {
@@ -58,9 +57,7 @@ describe("PlaywrightScenarioEvents", () => {
const events = new PlaywrightScenarioEvents({
page,
enabled: new Set(["page-errors"]),
limits: scenario.limits,
secrets,
budget: new BrowserScenarioCaptureBudget(1, 1_000_000),
allowedOrigins: scenario.allowed_origins,
});
const error = new Error("m".repeat(70_000));
@@ -69,8 +66,52 @@ describe("PlaywrightScenarioEvents", () => {
expect(() => listeners.get("pageerror")?.(error)).not.toThrow();
expect(events.result().items[0]).toMatchObject({
kind: "page-error",
message: "m".repeat(65_536),
stack: "s".repeat(262_144),
message: "m".repeat(70_000),
stack: "s".repeat(300_000),
});
});
it("retains every observed event without a collection count ceiling", () => {
const listeners = new Map<string, ((value: Error) => void)[]>();
const page = {
url: () => "https://app.example.test/",
on: (name: string, listener: (value: Error) => void) => {
const registered = listeners.get(name) ?? [];
registered.push(listener);
listeners.set(name, registered);
},
} as unknown as Page;
const scenario = browserScenarioSchema.parse({
browser: {
mode: "launch",
executable_path: "/opt/chromium",
headless: true,
user_data: "temporary-owned",
cleanup: "close-and-delete-profile",
},
start_url: { url: "https://app.example.test/" },
allowed_origins: ["https://app.example.test"],
actions: [
{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 },
],
capture: { events: ["page-errors"] },
});
const secrets = BrowserScenarioSecrets.resolve(scenario, {});
if (secrets === undefined) throw new Error("Expected resolved secrets");
const events = new PlaywrightScenarioEvents({
page,
enabled: new Set(["page-errors"]),
secrets,
allowedOrigins: scenario.allowed_origins,
});
for (let index = 0; index < 2_001; index += 1)
listeners
.get("pageerror")
?.forEach((listener) => listener(new Error(`failure-${index}`)));
expect(events.result()).toMatchObject({ retained: 2_001, dropped: 0 });
expect(events.result().items.at(-1)).toMatchObject({
kind: "page-error",
message: "failure-2000",
});
});
});
+19 -104
View File
@@ -15,8 +15,6 @@ import {
type BrowserScenarioEvent,
} from "../domain/browserScenarioCapture.js";
import type { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
import type { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";
import type { BrowserScenario } from "../domain/browserScenario.js";
type EventName =
| "console"
@@ -34,61 +32,25 @@ type UnindexedEvent = BrowserScenarioEvent extends infer Event
: never
: never;
type LimitedSection = "frames" | "workers" | "popups" | "websockets";
type TruncatedSection = "events" | LimitedSection;
interface EventCaptureOptions {
readonly page: Page;
readonly enabled: ReadonlySet<EventName>;
readonly limits: Pick<
BrowserScenario["limits"],
| "max_events"
| "max_frames"
| "max_workers"
| "max_popups"
| "max_websockets"
>;
readonly secrets: BrowserScenarioSecrets;
readonly budget: BrowserScenarioCaptureBudget;
readonly allowedOrigins: readonly string[];
}
/** Bounded, arrival-ordered Playwright event capture with current-step attribution. */
/** Arrival-ordered Playwright event capture with current-step attribution. */
export class PlaywrightScenarioEvents {
private readonly items: BrowserScenarioEvent[] = [];
private readonly truncated = new Set<TruncatedSection>();
private readonly admitted = {
frames: new WeakSet<object>(),
workers: new WeakSet<object>(),
popups: new WeakSet<object>(),
websockets: new WeakSet<object>(),
};
private readonly rejected = {
frames: new WeakSet<object>(),
workers: new WeakSet<object>(),
popups: new WeakSet<object>(),
websockets: new WeakSet<object>(),
};
private readonly counts: Record<LimitedSection, number> = {
frames: 0,
workers: 0,
popups: 0,
websockets: 0,
};
private dropped = 0;
private stepIndex = 0;
private sequence = 0;
private readonly enabled: ReadonlySet<EventName>;
private readonly limits: EventCaptureOptions["limits"];
private readonly secrets: BrowserScenarioSecrets;
private readonly budget: BrowserScenarioCaptureBudget;
private readonly allowedOrigins: ReadonlySet<string>;
constructor(options: EventCaptureOptions) {
this.enabled = options.enabled;
this.limits = options.limits;
this.secrets = options.secrets;
this.budget = options.budget;
this.allowedOrigins = new Set(options.allowedOrigins);
this.observePage(options.page);
}
@@ -112,55 +74,21 @@ export class PlaywrightScenarioEvents {
} {
return {
retained: this.items.length,
dropped: this.dropped,
dropped: 0,
items: this.items,
};
}
truncationSections(): readonly TruncatedSection[] {
return [...this.truncated].sort();
}
private push(event: UnindexedEvent): void {
this.sequence += 1;
if (this.items.length >= this.limits.max_events) {
this.dropped += 1;
this.truncated.add("events");
return;
}
const parsed = browserScenarioEventSchema.parse({
...event,
sequence: this.sequence,
step_index: this.stepIndex,
});
if (!this.budget.claimMetadata(Buffer.byteLength(JSON.stringify(parsed)))) {
this.dropped += 1;
this.truncated.add("events");
return;
}
this.items.push(parsed);
}
private admit(
section: LimitedSection,
value: object,
maximum: number,
): boolean {
if (this.admitted[section].has(value)) return true;
if (this.rejected[section].has(value)) return false;
if (this.counts[section] >= maximum) {
this.rejected[section].add(value);
this.sequence += 1;
this.dropped += 1;
this.truncated.add("events");
this.truncated.add(section);
return false;
}
this.admitted[section].add(value);
this.counts[section] += 1;
return true;
}
private observePage(page: Page): void {
if (this.enabled.has("console"))
page.on("console", (message) => {
@@ -171,11 +99,11 @@ export class PlaywrightScenarioEvents {
if (this.pageInScope(page))
this.push({
kind: "page-error",
message: this.secrets.redact(error.message).slice(0, 65_536),
message: this.secrets.redact(error.message),
stack:
error.stack === undefined
? null
: this.secrets.redact(error.stack).slice(0, 262_144),
: this.secrets.redact(error.stack),
});
});
if (this.enabled.has("network")) {
@@ -234,30 +162,27 @@ export class PlaywrightScenarioEvents {
const location = message.location();
this.push({
kind: "console",
level: this.secrets.redact(message.type()).slice(0, 64),
text: this.secrets.redact(message.text()).slice(0, 65_536),
level: this.secrets.redact(message.type()),
text: this.secrets.redact(message.text()),
url: location.url === "" ? null : this.safeUrl(location.url),
});
}
private request(kind: "request" | "request-failed", request: Request): void {
const observation = {
method: this.secrets.redact(request.method()).slice(0, 32),
method: this.secrets.redact(request.method()),
url: this.safeUrl(request.url()),
resource_type: this.secrets.redact(request.resourceType()).slice(0, 64),
resource_type: this.secrets.redact(request.resourceType()),
header_names: Object.keys(request.headers())
.map((name) => this.secrets.redact(name).slice(0, 256))
.sort()
.slice(0, 256),
.map((name) => this.secrets.redact(name))
.sort(),
};
if (kind === "request-failed") {
this.push({
...observation,
kind,
status: null,
failure: this.secrets
.redact(request.failure()?.errorText ?? "unknown")
.slice(0, 1_024),
failure: this.secrets.redact(request.failure()?.errorText ?? "unknown"),
});
return;
}
@@ -273,20 +198,18 @@ export class PlaywrightScenarioEvents {
const request = response.request();
this.push({
kind: "response",
method: this.secrets.redact(request.method()).slice(0, 32),
method: this.secrets.redact(request.method()),
url: this.safeUrl(response.url()),
resource_type: this.secrets.redact(request.resourceType()).slice(0, 64),
resource_type: this.secrets.redact(request.resourceType()),
status: response.status(),
header_names: Object.keys(response.headers())
.map((name) => this.secrets.redact(name).slice(0, 256))
.sort()
.slice(0, 256),
.map((name) => this.secrets.redact(name))
.sort(),
failure: null,
});
}
private webSocket(page: Page, socket: WebSocket): void {
if (!this.admit("websockets", socket, this.limits.max_websockets)) return;
const url = this.safeUrl(socket.url());
this.push({ kind: "websocket-opened", url });
socket.on("framesent", ({ payload }) => {
@@ -320,14 +243,14 @@ export class PlaywrightScenarioEvents {
});
return;
}
const text = this.secrets.redact(payload).slice(0, 65_536);
const text = this.secrets.redact(payload);
this.push({
kind,
url,
payload_type: "text",
payload_bytes: bytes,
payload_text: text,
truncated: text.length < payload.length,
truncated: false,
});
}
@@ -335,19 +258,14 @@ export class PlaywrightScenarioEvents {
kind: "frame-attached" | "frame-detached" | "frame-navigated",
frame: Frame,
): void {
if (!this.admit("frames", frame, this.limits.max_frames)) return;
this.push({
kind,
url: frame.url() === "" ? null : this.safeUrl(frame.url()),
name:
frame.name() === ""
? null
: this.secrets.redact(frame.name()).slice(0, 1_024),
name: frame.name() === "" ? null : this.secrets.redact(frame.name()),
});
}
private worker(page: Page, worker: Worker): void {
if (!this.admit("workers", worker, this.limits.max_workers)) return;
const details = {
url: this.safeUrl(worker.url()),
name: null,
@@ -364,7 +282,6 @@ export class PlaywrightScenarioEvents {
void page.close().catch(() => undefined);
return;
}
if (!this.admit("popups", page, this.limits.max_popups)) return;
const opened = {
url: page.url() === "" ? null : this.safeUrl(page.url()),
name: null,
@@ -385,9 +302,7 @@ export class PlaywrightScenarioEvents {
private download(download: Download): void {
this.push({
kind: "download-cancelled",
suggested_filename: this.secrets
.redact(download.suggestedFilename())
.slice(0, 1_024),
suggested_filename: this.secrets.redact(download.suggestedFilename()),
url: this.safeUrl(download.url()),
});
void download.cancel().catch(() => undefined);
+4 -23
View File
@@ -21,10 +21,7 @@ import {
type OpenedScenarioBrowser,
} from "./PlaywrightScenarioBrowser.js";
import { performPlaywrightScenarioAction } from "./PlaywrightScenarioActions.js";
import {
BrowserScenarioCaptureBudget,
capturePlaywrightStepArtifacts,
} from "./PlaywrightScenarioArtifacts.js";
import { capturePlaywrightStepArtifacts } from "./PlaywrightScenarioArtifacts.js";
import { PlaywrightScenarioEvents } from "./PlaywrightScenarioEvents.js";
import { withPlaywrightExecutionBoundary } from "./PlaywrightExecutionBoundary.js";
@@ -275,7 +272,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
environment: Readonly<Record<string, string | undefined>>,
options: {
readonly signal?: AbortSignal;
readonly budget: BrowserScenarioCaptureBudget;
readonly deadlineAt: number;
},
): Promise<PlaywrightScenarioSession> {
@@ -312,9 +308,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
const events = new PlaywrightScenarioEvents({
page: opened.page,
enabled: new Set(scenario.capture.events),
limits: scenario.limits,
secrets,
budget: options.budget,
allowedOrigins: scenario.allowed_origins,
});
const session = new PlaywrightScenarioSession(
@@ -362,10 +356,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
return this.eventCapture.result();
}
eventTruncationSections() {
return this.eventCapture.truncationSections();
}
async perform(
action: BrowserScenarioAction,
maximumTimeoutMs: number,
@@ -389,7 +379,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
requested: ReadonlySet<
BrowserScenario["capture"]["after_each_step"][number]
>,
budget: BrowserScenarioCaptureBudget,
maximumTimeoutMs: number,
signal?: AbortSignal,
) {
@@ -401,7 +390,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
scenario: this.scenario,
secrets: this.secrets,
requested,
budget,
}),
maximumTimeoutMs,
signal,
@@ -421,9 +409,9 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
}
redactError(error: unknown): string {
return this.secrets
.redact(error instanceof Error ? error.message : "browser action failed")
.slice(0, 4_096);
return this.secrets.redact(
error instanceof Error ? error.message : "browser action failed",
);
}
}
@@ -441,18 +429,11 @@ export class PlaywrightScenarioSessionFactory
scenario: BrowserScenario,
options: {
readonly signal?: AbortSignal;
readonly budget?: BrowserScenarioCaptureBudget;
readonly deadlineAt?: number;
} = {},
): Promise<BrowserScenarioSessionPort> {
return PlaywrightScenarioSession.open(scenario, this.environment, {
...(options.signal === undefined ? {} : { signal: options.signal }),
budget:
options.budget ??
new BrowserScenarioCaptureBudget(
scenario.limits.max_screenshots,
scenario.limits.max_total_metadata_bytes,
),
deadlineAt:
options.deadlineAt ?? Date.now() + scenario.limits.max_duration_ms,
});