refactor(test): keep coverage at behavioral boundaries (#474)

* refactor(test): keep coverage at behavioral boundaries

* fix(ci): restore package workflow temp-root classification
This commit is contained in:
morluto
2026-08-11 18:34:32 +08:00
committed by GitHub
parent d65730c4c2
commit d4dc940bd8
117 changed files with 1519 additions and 2419 deletions
@@ -0,0 +1,56 @@
import { describe, expect, it } from "vitest";
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
describe("CdpCaptureCompleteness", () => {
it("reports attach-window limitations without claiming a complete history", () => {
const capture = new CdpCaptureCompleteness([
"network_requests",
"console_events",
]);
expect(capture.snapshot()).toMatchObject({
status: "attach_limited",
conditions: ["attach_limited"],
attach_limited_sections: ["console_events", "network_requests"],
excluded: [],
dropped_events: { total: 0 },
});
});
it("aggregates sparse exclusions and applies explicit status precedence", () => {
const capture = new CdpCaptureCompleteness(["network_requests"]);
capture.exclude("scripts", "disallowed_origin");
capture.exclude("scripts", "disallowed_origin", 2);
capture.exclude("storage_keys", "not_approved", null);
capture.drop("console_events", 4);
expect(capture.snapshot()).toMatchObject({
status: "truncated",
conditions: ["attach_limited", "policy_filtered", "truncated"],
policy_filtered_sections: ["scripts", "storage_keys"],
truncated_sections: ["console_events"],
excluded: [
{ section: "scripts", reason: "disallowed_origin", count: 3 },
{ section: "storage_keys", reason: "not_approved", count: null },
],
dropped_events: { console_events: 4, total: 4 },
});
});
it("restores initial attach limitations when reused for a new capture", () => {
const capture = new CdpCaptureCompleteness(["websocket_frames"]);
capture.drop("scripts");
capture.exclude("resources", "provider_unavailable", null);
capture.reset();
expect(capture.snapshot()).toMatchObject({
status: "attach_limited",
attach_limited_sections: ["websocket_frames"],
unavailable_sections: [],
excluded: [],
dropped_events: { total: 0 },
});
});
});
+146
View File
@@ -0,0 +1,146 @@
import { describe, expect, it } from "vitest";
import {
captureAccessibility,
captureDom,
captureFrames,
captureResources,
} from "./CdpCaptureDocuments.js";
import { inspectWebPageInputSchema } from "../domain/browserObservation.js";
const origin = "https://app.example.test";
describe("CDP document capture", () => {
it("walks deeply nested frame trees iteratively and retains a bounded prefix", () => {
let frameTree: Record<string, unknown> = {
frame: { id: "frame-0", url: `${origin}/0` },
resources: [{ url: `${origin}/0.js`, type: "Script" }],
};
for (let index = 1; index < 2_000; index += 1) {
frameTree = {
frame: {
id: `frame-${String(index)}`,
url: `${origin}/${String(index)}`,
},
resources: [{ url: `${origin}/${String(index)}.js`, type: "Script" }],
childFrames: [frameTree],
};
}
const result = { frameTree };
const frames = captureFrames(result, new Set([origin]), 3);
const resources = captureResources(result, new Set([origin]), 2);
expect(frames).toMatchObject({ total: 2_000 });
expect(frames.items).toHaveLength(3);
expect(resources).toMatchObject({ total: 2_000 });
expect(resources.items).toHaveLength(2);
});
it("rebases parent indexes when allowed DOM documents are combined", () => {
const input = inspectWebPageInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9222",
allowed_origins: [origin],
target_id: "page-1",
approved: true,
});
const snapshot = {
strings: [`${origin}/main`, `${origin}/frame`, "#document", "DIV", ""],
documents: [
{
documentURL: 0,
nodes: {
nodeType: [9, 1],
nodeName: [2, 3],
nodeValue: [4, 4],
parentIndex: [-1, 0],
attributes: [[], []],
},
},
{
documentURL: 1,
nodes: {
nodeType: [9, 1],
nodeName: [2, 3],
nodeValue: [4, 4],
parentIndex: [-1, 0],
attributes: [[], []],
},
},
],
};
const capture = captureDom(snapshot, new Set([origin]), input);
expect(capture.nodes.map((node) => node.parent_index)).toEqual([
-1, 0, -1, 2,
]);
});
it("bounds approved accessibility text by UTF-8 bytes without splitting characters", () => {
const capture = captureAccessibility(
[
{
nodes: [
{
nodeId: "node-1",
role: { value: "button" },
name: { value: "😀a" },
description: { value: "éé" },
childIds: ["missing-child"],
properties: [
{ name: "disabled", value: { value: true } },
{ name: "valuetext", value: { value: "private value" } },
],
},
],
},
],
10,
{
includeText: true,
maximumFieldBytes: 4,
maximumTotalBytes: 7,
},
);
expect(capture.nodes[0]).toMatchObject({
name: "😀",
description: "é",
states: [{ name: "disabled", value: true }],
});
expect(capture.treeIncomplete).toBe(true);
expect(capture.textCapture).toEqual({
status: "truncated",
retained_bytes: 6,
excluded_fields: 0,
truncated_fields: 2,
});
});
it("counts accessibility fields omitted without text approval", () => {
const capture = captureAccessibility(
[
{
nodes: [
{
nodeId: "node-1",
name: { value: "private name" },
description: { value: "private description" },
},
],
},
],
10,
{
includeText: false,
maximumFieldBytes: 1_024,
maximumTotalBytes: 64 * 1_024,
},
);
expect(capture.nodes[0]).toMatchObject({ name: null, description: null });
expect(capture.textCapture).toEqual({
status: "not_approved",
retained_bytes: 0,
excluded_fields: 2,
truncated_fields: 0,
});
});
});
@@ -0,0 +1,388 @@
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,
type BrowserScenario,
type BrowserScenarioAction,
} from "../domain/browserScenario.js";
import {
browserStepArtifactsSchema,
type BrowserScenarioEvent,
type BrowserStepArtifacts,
} from "../domain/browserScenarioCapture.js";
const scenario = (
options: {
readonly mode?: "launch" | "connect";
readonly captures?: readonly (
| "screenshot"
| "dom"
| "accessibility"
| "url"
| "history"
| "storage"
)[];
readonly events?: readonly (
| "console"
| "page-errors"
| "network"
| "websockets"
| "frames"
| "workers"
| "popups"
| "downloads"
)[];
readonly actions?: number;
} = {},
): BrowserScenario =>
browserScenarioSchema.parse({
schema_version: 1,
browser:
options.mode === "connect"
? {
mode: "connect",
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "page-1",
ownership: "external",
cleanup: "disconnect-only",
}
: {
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"],
environment: {
viewport: { width: 1_280, height: 720 },
locale: "en-US",
timezone: "UTC",
color_scheme: "light",
reduced_motion: "reduce",
service_workers: "block",
},
actions: Array.from({ length: options.actions ?? 1 }, (_, index) => ({
step_id: `wait_${index}`,
action: "wait_for_timeout",
duration_ms: 1,
})),
storage: {},
request_replay: { mode: "disabled" },
secrets: [],
redaction: {
secret_values: "replace-with-secret-reference",
query_parameter_names: [],
},
capture: {
after_each_step: options.captures ?? ["url"],
at_end: [],
events: options.events ?? [],
},
limits: {
max_duration_ms: 10_000,
action_timeout_ms: 1_000,
navigation_timeout_ms: 1_000,
max_events: 100,
max_frames: 10,
max_workers: 10,
max_popups: 10,
max_websockets: 10,
max_dom_nodes: 100,
max_accessibility_nodes: 100,
max_screenshots: 2,
max_screenshot_bytes: 1_024,
max_storage_entries: 10,
max_total_metadata_bytes: 16_384,
},
approved: true,
});
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
const artifactState = (
kind: SnapshotKind,
requested: ReadonlySet<SnapshotKind>,
incomplete: boolean,
) => {
if (!requested.has(kind)) return { state: "not_requested" as const };
if (kind === "url")
return {
state: "captured" as const,
value: sanitizeBrowserUrl("https://app.example.test/current"),
};
if (incomplete && kind === "screenshot")
return {
state: "truncated" as const,
observed: 2_048,
retained: 0,
reason: "fixture limit",
};
return { state: "missing" as const, reason: "fixture unavailable" };
};
class FakeSession implements BrowserScenarioSessionPort {
readonly product = "Fake Chromium";
readonly version = "1";
readonly initialUrl = "about:blank";
readonly processOwnership: "provider-owned" | "external";
closeCalls = 0;
performCalls = 0;
captureCalls = 0;
eventTruncations: (
| "events"
| "frames"
| "workers"
| "popups"
| "websockets"
)[] = [];
onPerform: (() => void) | undefined;
private step = 0;
constructor(
readonly mode: "launch" | "connect",
private readonly incomplete = false,
private readonly failAction = false,
private readonly failCapture = false,
) {
this.processOwnership = mode === "launch" ? "provider-owned" : "external";
}
currentUrl() {
return "https://app.example.test/current";
}
setStep(index: number) {
this.step = index;
}
nextEventSequence() {
return 1;
}
lastEventSequence() {
return 0;
}
events(): {
readonly retained: number;
readonly dropped: number;
readonly items: readonly BrowserScenarioEvent[];
} {
return { retained: 0, dropped: 0, items: [] };
}
eventTruncationSections() {
return this.eventTruncations;
}
async perform(
_action: BrowserScenarioAction,
_timeout: number,
signal?: AbortSignal,
) {
this.performCalls += 1;
this.onPerform?.();
if (signal?.aborted === true) throw new Error("request cancelled");
if (this.failAction) throw new Error("fixture secret action failure");
}
capture(
requested: ReadonlySet<SnapshotKind>,
_budget: BrowserScenarioCaptureBudget,
): Promise<BrowserStepArtifacts> {
this.captureCalls += 1;
if (this.failCapture) return Promise.reject(new Error("capture failed"));
return Promise.resolve(
browserStepArtifactsSchema.parse({
screenshot: artifactState("screenshot", requested, this.incomplete),
dom: artifactState("dom", requested, this.incomplete),
accessibility: artifactState(
"accessibility",
requested,
this.incomplete,
),
url: artifactState("url", requested, this.incomplete),
history: artifactState("history", requested, this.incomplete),
storage: artifactState("storage", requested, this.incomplete),
}),
);
}
close() {
this.closeCalls += 1;
return Promise.resolve(
this.mode === "launch"
? ("terminated-owned-process" as const)
: ("disconnected-external" as const),
);
}
redactError(error: unknown) {
return error instanceof Error
? error.message.replaceAll("secret", "[REDACTED]")
: "fixture failure";
}
}
describe("PlaywrightBrowserScenarioProvider", () => {
it("captures initial and action steps and closes its launched session", async () => {
const session = new FakeSession("launch");
const provider = new PlaywrightBrowserScenarioProvider({
open: () => Promise.resolve(session),
});
const result = await provider.captureScenario(scenario());
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.steps.map(({ step_index }) => step_index)).toEqual([
0, 1,
]);
expect(result.value.browser).toMatchObject({
process_ownership: "provider-owned",
cleanup: "terminated-owned-process",
});
expect(result.value.completeness).toMatchObject({
status: "complete",
equality_eligible: true,
});
expect(session.closeCalls).toBe(1);
});
it("makes missing and truncated captures ineligible for equality", async () => {
const session = new FakeSession("launch", true);
const provider = new PlaywrightBrowserScenarioProvider({
open: () => Promise.resolve(session),
});
const result = await provider.captureScenario(
scenario({ captures: ["screenshot", "dom"] }),
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.completeness).toMatchObject({
status: "truncated",
equality_eligible: false,
missing_sections: ["dom"],
truncated_sections: ["screenshot"],
});
});
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({
open: () => Promise.resolve(session),
});
const result = await provider.captureScenario(scenario({ actions: 2 }));
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.steps.map(({ status }) => status)).toEqual([
"completed",
"failed",
"cancelled",
]);
expect(result.value.steps[1]?.error).toBe(
"fixture [REDACTED] action failure",
);
expect(session.performCalls).toBe(1);
expect(session.closeCalls).toBe(1);
expect(result.value.completeness.equality_eligible).toBe(false);
});
it("disconnects external CDP sessions and marks pre-attach events missing", async () => {
const session = new FakeSession("connect");
const provider = new PlaywrightBrowserScenarioProvider({
open: () => Promise.resolve(session),
});
const result = await provider.captureScenario(
scenario({ mode: "connect" }),
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.browser).toMatchObject({
process_ownership: "external",
cleanup: "disconnected-external",
});
expect(result.value.completeness).toMatchObject({
status: "incomplete",
equality_eligible: false,
missing_sections: ["events"],
});
expect(session.closeCalls).toBe(1);
});
it("closes the session when initial capture fails", async () => {
const session = new FakeSession("launch", false, false, true);
const provider = new PlaywrightBrowserScenarioProvider({
open: () => Promise.resolve(session),
});
const result = await provider.captureScenario(scenario());
expect(result.ok).toBe(false);
expect(session.closeCalls).toBe(1);
});
it("does not open a session for an already-cancelled request", async () => {
let opens = 0;
const provider = new PlaywrightBrowserScenarioProvider({
open: () => {
opens += 1;
return Promise.resolve(new FakeSession("launch"));
},
});
const controller = new AbortController();
controller.abort();
const result = await provider.captureScenario(scenario(), {
signal: controller.signal,
});
expect(result.ok).toBe(false);
expect(opens).toBe(0);
});
it("cancels an active action and still closes the session", async () => {
const controller = new AbortController();
const session = new FakeSession("launch");
session.onPerform = () => controller.abort();
const provider = new PlaywrightBrowserScenarioProvider({
open: () => Promise.resolve(session),
});
const result = await provider.captureScenario(scenario(), {
signal: controller.signal,
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.steps[1]?.status).toBe("cancelled");
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);
});
});
@@ -0,0 +1,159 @@
import { expect, it } from "vitest";
import {
electronActiveObservationInputSchema,
electronActiveObservationResultSchema,
} from "../domain/electronActiveObservation.js";
import { createElectronActiveObservationFixtureResult } from "../domain/electronActiveObservation.fixture.js";
import { runElectronActions } from "./PlaywrightElectronActiveActions.js";
it("parses bounded window, renderer, and deep-link actions for agents", () => {
const input = electronActiveObservationInputSchema.parse({
schema_version: 1,
executable_path: "/opt/electron",
application_path: "/opt/app/main.js",
application_root: "/opt/app",
actions: [
{ step_id: "first-window", kind: "click", selector: "#run" },
{ step_id: "second-window", kind: "renderer-reload", window_index: 1 },
{ step_id: "restart", kind: "renderer-crash", window_index: 1 },
{
step_id: "deep-link",
kind: "deep-link",
delivery: "second-instance",
url: "rea-fixture://open/item",
},
],
approved: true,
});
expect(input.actions).toEqual([
{
step_id: "first-window",
kind: "click",
selector: "#run",
window_index: 0,
},
{ step_id: "second-window", kind: "renderer-reload", window_index: 1 },
{ step_id: "restart", kind: "renderer-crash", window_index: 1 },
{
step_id: "deep-link",
kind: "deep-link",
delivery: "second-instance",
url: "rea-fixture://open/item",
},
]);
});
it("rejects non-absolute deep-link values", () => {
const result = electronActiveObservationInputSchema.safeParse({
schema_version: 1,
executable_path: "/opt/electron",
application_path: "/opt/app/main.js",
application_root: "/opt/app",
actions: [
{
step_id: "bad-link",
kind: "deep-link",
delivery: "open-url",
url: "not a URL",
},
],
approved: true,
});
expect(result.success).toBe(false);
});
it("redacts action inputs from Playwright failures", async () => {
const selector = "#secret-selector";
const input = electronActiveObservationInputSchema.parse({
schema_version: 1,
executable_path: "/opt/electron",
application_path: "/opt/app/main.js",
application_root: "/opt/app",
actions: [{ step_id: "click-step", kind: "click", selector }],
approved: true,
});
const page = {
locator: () => ({
click: async () => {
throw new Error(`locator ${selector} failed with token=raw-secret`);
},
}),
};
const application = {
windows: () => [page],
};
const result = await runElectronActions(
application as never,
input,
{},
Date.now() + 1_000,
);
expect(result[0]).toMatchObject({
status: "failed",
error: "locator <redacted-input> failed with token=[REDACTED]",
});
expect(result[0]?.error).not.toContain(selector);
expect(result[0]?.error).not.toContain("raw-secret");
});
it("runs an untargeted deep-link without requiring a BrowserWindow", async () => {
const input = electronActiveObservationInputSchema.parse({
schema_version: 1,
executable_path: "/opt/electron",
application_path: "/opt/app/main.js",
application_root: "/opt/app",
actions: [
{
step_id: "open-deep-link",
kind: "deep-link",
delivery: "second-instance",
url: "rea-fixture://open/item",
},
],
approved: true,
});
const application = {
windows: () => [],
evaluate: async () => true,
};
const result = await runElectronActions(
application as never,
input,
{},
Date.now() + 1_000,
);
expect(result).toMatchObject([
{
step_id: "open-deep-link",
status: "completed",
error: null,
},
]);
});
it("rejects action outcomes that disagree with their error state", () => {
const result = createElectronActiveObservationFixtureResult("/opt/app");
const action = result.actions[0];
expect(action).toBeDefined();
if (action === undefined) return;
expect(
electronActiveObservationResultSchema.safeParse({
...result,
actions: [{ ...action, error: "unexpected failure" }],
}).success,
).toBe(false);
expect(
electronActiveObservationResultSchema.safeParse({
...result,
actions: [{ ...action, status: "failed", error: null }],
}).success,
).toBe(false);
});
@@ -0,0 +1,34 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { withPlaywrightExecutionBoundary } from "./PlaywrightExecutionBoundary.js";
import {
AnalysisCancelledError,
AnalysisTimeoutError,
} from "../domain/errors.js";
describe("withPlaywrightExecutionBoundary", () => {
afterEach(() => vi.useRealTimers());
it("rejects work that exceeds its absolute remaining duration", async () => {
vi.useFakeTimers();
const result = withPlaywrightExecutionBoundary(
() => new Promise<never>(() => undefined),
25,
);
const rejection =
expect(result).rejects.toBeInstanceOf(AnalysisTimeoutError);
await vi.advanceTimersByTimeAsync(25);
await rejection;
});
it("rejects when the caller cancels active work", async () => {
const controller = new AbortController();
const result = withPlaywrightExecutionBoundary(
() => new Promise<never>(() => undefined),
1_000,
controller.signal,
);
controller.abort();
await expect(result).rejects.toBeInstanceOf(AnalysisCancelledError);
});
});
@@ -0,0 +1,94 @@
import { describe, expect, it } from "vitest";
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", () => {
it("bounds oversized page errors before validating captured events", () => {
const listeners = new Map<string, (value: Error) => void>();
const page = {
url: () => "https://app.example.test/",
on: (name: string, listener: (value: Error) => void) => {
listeners.set(name, listener);
},
} as unknown as Page;
const scenario = browserScenarioSchema.parse({
schema_version: 1,
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"],
environment: {
viewport: { width: 1_280, height: 720 },
locale: "en-US",
timezone: "UTC",
color_scheme: "light",
reduced_motion: "reduce",
service_workers: "block",
},
actions: [
{
step_id: "wait",
action: "wait_for_timeout",
duration_ms: 1,
},
],
storage: {},
request_replay: { mode: "disabled" },
secrets: [],
redaction: {
secret_values: "replace-with-secret-reference",
query_parameter_names: [],
},
capture: {
after_each_step: [],
at_end: [],
events: ["page-errors"],
},
limits: {
max_duration_ms: 10_000,
action_timeout_ms: 1_000,
navigation_timeout_ms: 1_000,
max_events: 10,
max_frames: 10,
max_workers: 10,
max_popups: 10,
max_websockets: 10,
max_dom_nodes: 100,
max_accessibility_nodes: 100,
max_screenshots: 1,
max_screenshot_bytes: 1_024,
max_storage_entries: 10,
max_total_metadata_bytes: 1_000_000,
},
approved: true,
});
const secrets = BrowserScenarioSecrets.resolve(scenario, {});
if (secrets === undefined) throw new Error("Expected resolved secrets");
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));
error.stack = "s".repeat(300_000);
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),
});
});
});