fix!: repair boundary contracts across CLI and MCP (#597)

* fix(comparisons)!: preserve unknowns across partial observations

Share absence and digest semantics, keep unobserved managed bodies unknown, and match unique managed type/name/signatures before structural fallback.

BREAKING CHANGE: Managed comparison metadata adds exact-signature matching and its count, and name_matching now reports exact-signature-fallback.

* fix(javascript): preserve projected result binding semantics

Share syntax-aware property reads and assigned-result resolution. Retain destructuring paths and downgrade downstream whole-result relationships instead of resolving nested or wrapped calls as aliases.

* fix(native)!: admit complete parser values and preserve typed failures

Decode Mach headers by named columns, validate complete slice keys and lipo alignment, and preserve codesign runtime flags and tagged parser errors. Rename the Ghidra test dossier fixture and connect fake-backed suites to real verification lanes.

BREAKING CHANGE: Native load-command results no longer contain the unused, always-null file_offset field.

* fix(process): preserve host identity and actionable boundary failures

Thread selected platform and environment through process and Doctor seams, stamp observed producer identity in Evidence, and retain PTY, filesystem, lease and lazy-provider failure causes. Drain cancelled lazy loads and omit exited descendants from verified lineage.

* fix(browser): preserve cleanup and document-transition evidence

Make V8 and Playwright teardown cancellation-aware, expose primary failures alongside incomplete cleanup, share frame-tree and navigation rules, and clear stale WebMCP registrations without pruning unrelated child frames.

* fix(adapters): align managed targets and typed CLI outcomes

Inspect managed PE/CLI targets independently of native provider selection, reuse successful managed selections, and keep evidence bound to the actual inspected target. Classify canonical CLI error envelopes and exhaustive setup/update/uninstall outcomes, audit registered CLI coverage, and assert platform-specific runtime results.

* docs: refresh boundary contracts and shipped roadmap behavior
This commit is contained in:
morluto
2026-10-06 00:50:38 +08:00
committed by GitHub
parent f3e6582e9e
commit 9c25dc4ed2
134 changed files with 3547 additions and 812 deletions
+28 -8
View File
@@ -28,10 +28,15 @@ export const captureFrames = (
): {
readonly items: WebPageInspection["frames"];
} => {
const root = recordValue(requiredRecord(result).frameTree);
if (root === undefined) return { items: [] };
const root = recordValue(recordValue(result)?.frameTree);
if (root === undefined) {
completeness?.exclude("frames", "invalid_protocol_value");
return { items: [] };
}
const items: WebPageInspection["frames"] = [];
for (const tree of walkFrameTrees(root)) {
for (const tree of walkFrameTrees(root, () =>
completeness?.exclude("frames", "invalid_protocol_value"),
)) {
const frame = recordValue(tree.frame);
const frameId = stringValue(frame?.id);
const sanitized = allowedSanitizedUrl(frame?.url, allowedOrigins);
@@ -71,10 +76,15 @@ export const captureResources = (
): {
readonly items: readonly CapturedResource[];
} => {
const root = recordValue(requiredRecord(result).frameTree);
if (root === undefined) return { items: [] };
const root = recordValue(recordValue(result)?.frameTree);
if (root === undefined) {
completeness?.exclude("resources", "invalid_protocol_value");
return { items: [] };
}
const items: CapturedResource[] = [];
for (const tree of walkFrameTrees(root)) {
for (const tree of walkFrameTrees(root, () =>
completeness?.exclude("resources", "invalid_protocol_value"),
)) {
for (const resource of recordsValue(tree.resources)) {
const url = allowedSanitizedUrl(resource.url, allowedOrigins);
if (url === undefined || url.origin === null) {
@@ -99,14 +109,24 @@ export const captureResources = (
return { items };
};
const walkFrameTrees = function* (
export const walkFrameTrees = function* (
root: UnknownRecord,
onMalformedChild?: () => void,
): Generator<UnknownRecord> {
const pending = [root];
while (pending.length > 0) {
const tree = pending.pop();
if (tree === undefined) return;
const children = recordsValue(tree.childFrames);
const rawChildren = tree.childFrames;
if (rawChildren !== undefined && !Array.isArray(rawChildren))
onMalformedChild?.();
const children = Array.isArray(rawChildren)
? rawChildren.flatMap((child) => {
const parsed = recordValue(child);
if (parsed === undefined) onMalformedChild?.();
return parsed === undefined ? [] : [parsed];
})
: [];
for (let index = children.length - 1; index >= 0; index -= 1) {
const child = children[index];
if (child !== undefined) pending.push(child);
+9 -1
View File
@@ -19,6 +19,7 @@ import {
firstCallFrame,
initiatorLocation,
integerOrNull,
isMainFrameNavigation,
} from "./CdpCaptureEventHelpers.js";
import type { CdpCaptureEventsState } from "./CdpCaptureEventState.js";
import type { CapturedScript } from "./CdpCaptureEventTypes.js";
@@ -365,7 +366,14 @@ export const handleFrameNavigated = (
params: UnknownRecord,
): void => {
const frame = recordValue(params.frame);
if (stringValue(frame?.id) !== state.mainFrameId) return;
if (state.mainFrameId === undefined) return;
if (
!isMainFrameNavigation(
{ method: "Page.frameNavigated", params },
state.mainFrameId,
)
)
return;
const rawUrl = stringValue(frame?.url);
const loaderId = stringValue(frame?.loaderId);
// `frameNavigated` re-fires for a document already reported (same URL and
+18
View File
@@ -6,6 +6,24 @@ import {
stringValue,
type UnknownRecord,
} from "./CdpCaptureValues.js";
import type { CdpEvent } from "./CdpConnection.js";
/** Identify a top-level navigation event from its untrusted CDP envelope. */
export const isMainFrameNavigation = (
event: CdpEvent,
mainFrameId: string,
): boolean => {
const params = recordValue(event.params);
if (params === undefined) return false;
const frameId =
event.method === "Page.frameNavigated"
? stringValue(recordValue(params.frame)?.id)
: event.method === "Page.frameRequestedNavigation" ||
event.method === "Page.navigatedWithinDocument"
? stringValue(params.frameId)
: undefined;
return frameId === mainFrameId;
};
export const firstCallFrame = (
value: UnknownRecord | undefined,
+6 -12
View File
@@ -15,8 +15,8 @@ import {
recordsValue,
requiredRecord,
stringValue,
type UnknownRecord,
} from "./CdpCaptureValues.js";
import { walkFrameTrees } from "./CdpCaptureDocuments.js";
import {
ingestElectronScriptEvent,
type ElectronScriptDraft,
@@ -233,15 +233,11 @@ const captureFrames = async (
const frameTree = recordValue(requiredRecord(result).frameTree);
if (frameTree === undefined)
throw new BrowserObservationError("inspect_web_page", "protocol_error");
const pending: Array<{
readonly tree: UnknownRecord;
readonly parent: string | null;
}> = [{ tree: frameTree, parent: null }];
const frames: ElectronPageInspection["frames"] = [];
while (pending.length > 0) {
const current = pending.shift();
if (current === undefined) break;
const frame = recordValue(current.tree.frame);
for (const tree of walkFrameTrees(frameTree, () =>
completeness.exclude("frames", "invalid_protocol_value"),
)) {
const frame = recordValue(tree.frame);
const frameId = stringValue(frame?.id);
const path = await authorizedElectronFile(stringValue(frame?.url) ?? "");
if (frameId === undefined || path === undefined) {
@@ -250,11 +246,9 @@ const captureFrames = async (
}
frames.push({
frame_id: frameId,
parent_frame_id: current.parent,
parent_frame_id: stringValue(frame?.parentId) ?? null,
file_path: path,
});
for (const child of recordsValue(current.tree.childFrames))
pending.push({ tree: child, parent: frameId });
}
return frames;
};
+10 -9
View File
@@ -20,6 +20,7 @@ import {
type UnknownRecord,
} from "./CdpCaptureValues.js";
import { mainFrameUrl } from "./CdpCaptureDocuments.js";
import { isMainFrameNavigation } from "./CdpCaptureEventHelpers.js";
interface ObservationContext {
readonly connection: CdpConnection;
@@ -158,13 +159,13 @@ class TimelineCapture {
if (params === undefined) return;
switch (event.method) {
case "Page.frameRequestedNavigation":
this.#navigationRequested(params);
this.#navigationRequested(event, params);
break;
case "Page.frameNavigated":
this.#navigationCommitted(params);
this.#navigationCommitted(event, params);
break;
case "Page.navigatedWithinDocument":
this.#sameDocument(params);
this.#sameDocument(event, params);
break;
case "Network.requestWillBeSent":
this.#redirect(params);
@@ -212,8 +213,8 @@ class TimelineCapture {
this.finalUrl = destination.scope === "approved" ? destination.url : null;
}
#navigationRequested(params: UnknownRecord): void {
if (stringValue(params.frameId) !== this.mainFrameId) return;
#navigationRequested(event: CdpEvent, params: UnknownRecord): void {
if (!isMainFrameNavigation(event, this.mainFrameId)) return;
const reason = safeDetail(params.reason);
this.#pendingReload = reason === "reload";
this.#add({
@@ -225,9 +226,9 @@ class TimelineCapture {
});
}
#navigationCommitted(params: UnknownRecord): void {
#navigationCommitted(event: CdpEvent, params: UnknownRecord): void {
const frame = recordValue(params.frame);
if (stringValue(frame?.id) !== this.mainFrameId) return;
if (!isMainFrameNavigation(event, this.mainFrameId)) return;
const rawUrl = stringValue(frame?.url);
const destination = scopedUrl(rawUrl, this.allowedOrigins);
this.#add({
@@ -246,8 +247,8 @@ class TimelineCapture {
}
}
#sameDocument(params: UnknownRecord): void {
if (stringValue(params.frameId) !== this.mainFrameId) return;
#sameDocument(event: CdpEvent, params: UnknownRecord): void {
if (!isMainFrameNavigation(event, this.mainFrameId)) return;
const rawUrl = stringValue(params.url);
const destination = scopedUrl(rawUrl, this.allowedOrigins);
this.#add({
+2 -6
View File
@@ -5,6 +5,7 @@ import type {
} from "../domain/webScreenshot.js";
import { createWebScreenshotArtifact } from "../domain/webScreenshot.js";
import { BrowserObservationError } from "../domain/errors.js";
import { isMainFrameNavigation } from "./CdpCaptureEventHelpers.js";
import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js";
import type { CdpConnection, CdpEvent } from "./CdpConnection.js";
import {
@@ -126,16 +127,11 @@ const observeScreenshotNavigation = (
origins: ReadonlySet<string>,
state: { changed: boolean; leftScope: boolean },
): void => {
if (!isMainFrameNavigation(event, mainFrameId)) return;
const params = recordValue(event.params);
if (params === undefined) return;
const frame =
event.method === "Page.frameNavigated" ? recordValue(params.frame) : params;
if (
(event.method !== "Page.frameNavigated" &&
event.method !== "Page.navigatedWithinDocument") ||
(stringValue(frame?.id) ?? stringValue(frame?.frameId)) !== mainFrameId
)
return;
state.changed = true;
if (allowedSanitizedUrl(frame?.url, origins) === undefined)
state.leftScope = true;
+135 -20
View File
@@ -19,7 +19,11 @@ import {
stringValue,
type UnknownRecord,
} from "./CdpCaptureValues.js";
import { captureFrames, mainFrameUrl } from "./CdpCaptureDocuments.js";
import {
captureFrames,
mainFrameUrl,
walkFrameTrees,
} from "./CdpCaptureDocuments.js";
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
interface DiscoveryContext {
@@ -63,18 +67,16 @@ export const discoverWebMcp = async (
undefined,
completeness,
).items;
const frameUrls = new Map(
frames.map((frame) => [
frame.frame_id,
{
url: frame.url,
origin: frame.origin,
parentFrameId: frame.parent_frame_id,
},
]),
);
const frameUrls = initialFrameScope(frameTree, frames, completeness);
const tools = new Map<string, WebMcpDiscovery["tools"]["items"][number]>();
const frameScope = { origins, frames: frameUrls, tools, completeness };
const frameScope = {
origins,
frames: frameUrls,
tools,
completeness,
transientFrames: new Set<string>(),
resolvedTransientFrames: new Set<string>(),
};
const removeListener = context.connection.onEvent((event) => {
if (event.sessionId !== context.sessionId) return;
if (ingestFrameScopeEvent(event, frameScope)) return;
@@ -84,6 +86,8 @@ export const discoverWebMcp = async (
frames: frameUrls,
tools,
completeness,
transientFrames: frameScope.transientFrames,
resolvedTransientFrames: frameScope.resolvedTransientFrames,
});
});
await context.progress?.report({
@@ -110,6 +114,8 @@ export const discoverWebMcp = async (
context.signal,
);
await assertStableAuthorizedFrame(context, initialUrl, origins);
if (frameScope.transientFrames.size > 0)
completeness.attachLimited("webmcp_tools");
return buildWebMcpResult({
context,
frameTree,
@@ -135,14 +141,46 @@ interface FrameScopeState {
readonly frames: Map<string, FrameScopeFrame>;
readonly tools: Map<string, WebMcpDiscovery["tools"]["items"][number]>;
readonly completeness: CdpCaptureCompleteness;
readonly transientFrames: Set<string>;
readonly resolvedTransientFrames: Set<string>;
}
interface FrameScopeFrame {
readonly url: string;
readonly origin: string | null;
readonly parentFrameId: string | null;
readonly loaderId?: string | undefined;
}
const initialFrameScope = (
frameTree: unknown,
frames: ReturnType<typeof captureFrames>["items"],
completeness: CdpCaptureCompleteness,
): Map<string, FrameScopeFrame> => {
const scoped = new Map<string, FrameScopeFrame>(
frames.map((frame) => [
frame.frame_id,
{
url: frame.url,
origin: frame.origin,
parentFrameId: frame.parent_frame_id,
},
]),
);
const root = recordValue(recordValue(frameTree)?.frameTree);
if (root === undefined) return scoped;
for (const tree of walkFrameTrees(root, () =>
completeness.exclude("webmcp_tools", "invalid_protocol_value"),
)) {
const frame = recordValue(tree.frame);
const frameId = stringValue(frame?.id);
const prior = frameId === undefined ? undefined : scoped.get(frameId);
if (frameId !== undefined && prior !== undefined)
scoped.set(frameId, { ...prior, loaderId: stringValue(frame?.loaderId) });
}
return scoped;
};
const ingestFrameScopeEvent = (
event: CdpEvent,
state: FrameScopeState,
@@ -153,9 +191,9 @@ const ingestFrameScopeEvent = (
case "Page.frameDetached":
return handleFrameDetached(params, state);
case "Page.frameNavigated":
return handleFrameUpdate(recordValue(params.frame), state);
return handleFrameUpdate(recordValue(params.frame), state, true);
case "Page.navigatedWithinDocument":
return handleFrameUpdate(params, state);
return handleFrameUpdate(params, state, false);
default:
return false;
}
@@ -171,36 +209,97 @@ const handleFrameDetached = (
return true;
}
removeFrame(frameId, state.frames, state.tools);
state.transientFrames.delete(frameId);
state.resolvedTransientFrames.delete(frameId);
return true;
};
const handleFrameUpdate = (
frame: UnknownRecord | undefined,
state: FrameScopeState,
documentCommitted: boolean,
): boolean => {
if (frame === undefined) {
state.completeness.exclude("webmcp_tools", "invalid_protocol_value");
return true;
}
const frameId = stringValue(frame?.id) ?? stringValue(frame?.frameId);
if (frameId === undefined) {
state.completeness.exclude("webmcp_tools", "invalid_protocol_value");
return true;
}
const url = allowedSanitizedUrl(frame?.url, state.origins);
if (url === undefined || url.origin === null) {
removeFrame(frameId, state.frames, state.tools);
state.completeness.exclude("webmcp_tools", "out_of_target_scope");
const rawUrl = stringValue(frame?.url);
// Chromium can briefly commit an inherited, empty document while replacing
// a subframe. That intermediate URL says nothing about the frame's eventual
// scope or its registered tools; wait for the next committed URL (or the
// authoritative frame-tree re-probe at the end of discovery).
if (isTransientFrameUrl(rawUrl)) {
if (documentCommitted) {
removeFrameTools(frameId, state.tools);
state.transientFrames.add(frameId);
state.resolvedTransientFrames.delete(frameId);
}
return true;
}
updateFrameScope(frame, frameId, state, documentCommitted);
return true;
};
const updateFrameScope = (
frame: UnknownRecord,
frameId: string,
state: FrameScopeState,
documentCommitted: boolean,
): void => {
const url = allowedSanitizedUrl(frame?.url, state.origins);
if (url === undefined || url.origin === null) {
removeFrameTools(frameId, state.tools);
state.frames.delete(frameId);
state.completeness.exclude("webmcp_tools", "out_of_target_scope");
return;
}
const previous = state.frames.get(frameId);
const loaderId = stringValue(frame?.loaderId);
if (hasNewDocument(documentCommitted, previous, url.url, loaderId))
removeFrameTools(frameId, state.tools);
if (documentCommitted && state.transientFrames.has(frameId))
state.resolvedTransientFrames.add(frameId);
state.frames.set(frameId, {
url: url.url,
origin: url.origin,
...(loaderId === undefined ? {} : { loaderId }),
parentFrameId:
(stringValue(frame?.parentId) ??
state.frames.get(frameId)?.parentFrameId ??
"") ||
null,
});
return true;
};
const hasNewDocument = (
documentCommitted: boolean,
previous: FrameScopeFrame | undefined,
url: string,
loaderId: string | undefined,
): boolean =>
documentCommitted &&
previous !== undefined &&
(previous.url !== url ||
(loaderId !== undefined &&
previous.loaderId !== undefined &&
previous.loaderId !== loaderId));
const removeFrameTools = (
frameId: string,
tools: Map<string, WebMcpDiscovery["tools"]["items"][number]>,
): void => {
for (const [key, tool] of tools)
if (tool.frame_id === frameId) tools.delete(key);
};
const isTransientFrameUrl = (url: string | undefined): boolean =>
url === "" || url === "about:blank" || url === "about:srcdoc";
const removeFrame = (
frameId: string,
frames: Map<string, FrameScopeFrame>,
@@ -247,10 +346,20 @@ interface WebMcpIngestOptions {
>;
readonly tools: Map<string, WebMcpDiscovery["tools"]["items"][number]>;
readonly completeness: CdpCaptureCompleteness;
readonly transientFrames: Set<string>;
readonly resolvedTransientFrames: Set<string>;
}
const ingestWebMcpEvent = (options: WebMcpIngestOptions): void => {
const { event, input, frames, tools, completeness } = options;
const {
event,
input,
frames,
tools,
completeness,
transientFrames,
resolvedTransientFrames,
} = options;
const params = recordValue(event.params);
if (params === undefined) return;
if (event.method === "WebMCP.toolsRemoved") {
@@ -265,6 +374,12 @@ const ingestWebMcpEvent = (options: WebMcpIngestOptions): void => {
}
if (event.method !== "WebMCP.toolsAdded") return;
for (const declared of recordsValue(params.tools)) {
const frameId = stringValue(declared.frameId);
if (frameId !== undefined && transientFrames.has(frameId)) {
if (!resolvedTransientFrames.has(frameId)) continue;
transientFrames.delete(frameId);
resolvedTransientFrames.delete(frameId);
}
const normalized = normalizeTool(declared, input, frames, completeness);
if (normalized === undefined) continue;
tools.set(normalized.tool_key, normalized);
@@ -1,3 +1,5 @@
// Fake-backed composition coverage; real browser verification lives in
// `npm run verify:browser`.
import { describe, expect, it } from "vitest";
import type { BrowserScenarioSessionPort } from "./BrowserScenarioSessionPort.js";
@@ -1,3 +1,5 @@
// Fixture-backed action coverage; real Electron verification lives in
// `npm run verify:electron`.
import { expect, it } from "vitest";
import {
@@ -0,0 +1,30 @@
import { expect, it } from "vitest";
import { closePlaywrightScenarioBrowser } from "./PlaywrightScenarioBrowser.js";
it("returns cancellation instead of success when an attached browser hangs on close", async () => {
const controller = new AbortController();
let closeStarted = false;
const closing = closePlaywrightScenarioBrowser(
{
browser: {
close: () => {
closeStarted = true;
return new Promise<void>(() => undefined);
},
},
context: { close: async () => undefined },
profilePath: undefined,
},
controller.signal,
);
controller.abort();
expect(closeStarted).toBe(true);
await expect(closing).rejects.toMatchObject({
_tag: "BrowserObservationError",
reason: "cleanup_failed",
cleanupIncomplete: true,
userCategory: "cancelled",
});
});
+28 -10
View File
@@ -11,6 +11,7 @@ import {
import type { BrowserScenario } from "../domain/browserScenario.js";
import { BrowserObservationError } from "../domain/errors.js";
import { withPlaywrightExecutionBoundary } from "./PlaywrightExecutionBoundary.js";
const OPERATION = "capture_browser_scenario" as const;
@@ -21,6 +22,12 @@ export interface OpenedScenarioBrowser {
readonly profilePath: string | undefined;
}
interface CloseableScenarioBrowser {
readonly context: Pick<BrowserContext, "close">;
readonly browser: Pick<Browser, "close">;
readonly profilePath: string | undefined;
}
const allowedBrowserEnvironment = (
environment: Readonly<Record<string, string | undefined>>,
): Record<string, string | undefined> => {
@@ -156,16 +163,27 @@ export const openPlaywrightScenarioBrowser = async (
}
};
export const closePlaywrightScenarioBrowser = async ({
context,
browser,
profilePath,
}: OpenedScenarioBrowser): Promise<void> => {
export const closePlaywrightScenarioBrowser = async (
{ context, browser, profilePath }: CloseableScenarioBrowser,
signal?: AbortSignal,
): Promise<void> => {
const cleanup = (async () => {
try {
// In connect mode Playwright's Browser.close disconnects its CDP client;
// it does not close the externally owned browser process.
if (profilePath === undefined) await browser.close();
else await context.close();
} finally {
if (profilePath !== undefined)
await rm(profilePath, { recursive: true, force: true, maxRetries: 3 });
}
})();
void cleanup.catch(() => undefined);
// The shared execution boundary rejects cancellation/timeouts instead of
// returning a successful capture whose browser or profile may still exist.
try {
if (profilePath === undefined) await browser.close();
else await context.close();
} finally {
if (profilePath !== undefined)
await rm(profilePath, { recursive: true, force: true, maxRetries: 3 });
await withPlaywrightExecutionBoundary(() => cleanup, 1_000, signal);
} catch (cause: unknown) {
throw new BrowserObservationError(OPERATION, "cleanup_failed", { cause });
}
};
+25 -13
View File
@@ -104,15 +104,25 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
readonly version: string;
readonly initialUrl: string;
private closed = false;
private readonly secrets: BrowserScenarioSecrets;
private readonly eventCapture: PlaywrightScenarioEvents;
private readonly signal: AbortSignal | undefined;
private constructor(
private readonly opened: OpenedScenarioBrowser,
mode: BrowserScenario["browser"]["mode"],
private readonly secrets: BrowserScenarioSecrets,
private readonly eventCapture: PlaywrightScenarioEvents,
options: {
readonly mode: BrowserScenario["browser"]["mode"];
readonly secrets: BrowserScenarioSecrets;
readonly eventCapture: PlaywrightScenarioEvents;
readonly signal?: AbortSignal;
},
) {
this.mode = mode;
this.processOwnership = mode === "launch" ? "provider-owned" : "external";
this.mode = options.mode;
this.processOwnership =
options.mode === "launch" ? "provider-owned" : "external";
this.secrets = options.secrets;
this.eventCapture = options.eventCapture;
this.signal = options.signal;
this.version = opened.browser.version();
this.initialUrl = opened.page.url();
}
@@ -139,7 +149,9 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
);
} catch (cause: unknown) {
void opening
.then((lateOpened) => closePlaywrightScenarioBrowser(lateOpened))
.then((lateOpened) =>
closePlaywrightScenarioBrowser(lateOpened, options.signal),
)
.catch(() => undefined);
throw cause;
}
@@ -154,12 +166,12 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
enabled: new Set(scenario.capture.events),
secrets,
});
const session = new PlaywrightScenarioSession(
opened,
scenario.browser.mode,
const session = new PlaywrightScenarioSession(opened, {
mode: scenario.browser.mode,
secrets,
events,
);
eventCapture: events,
...(options.signal === undefined ? {} : { signal: options.signal }),
});
await withPlaywrightExecutionBoundary(
() =>
opened.page.goto(secrets.url(scenario.start_url), {
@@ -171,7 +183,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
);
return session;
} catch (cause: unknown) {
await closePlaywrightScenarioBrowser(opened);
await closePlaywrightScenarioBrowser(opened, options.signal);
throw cause;
}
}
@@ -241,7 +253,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
? ("terminated-owned-process" as const)
: ("disconnected-external" as const);
this.closed = true;
await closePlaywrightScenarioBrowser(this.opened);
await closePlaywrightScenarioBrowser(this.opened, this.signal);
return this.mode === "launch"
? ("terminated-owned-process" as const)
: ("disconnected-external" as const);
@@ -0,0 +1,37 @@
import { expect, it } from "vitest";
import {
closeInspectorConnection,
inspectorCleanupError,
} from "./V8InspectorProvider.js";
it("returns promptly on cancellation while a V8 socket close is hung", async () => {
const controller = new AbortController();
let closeStarted = false;
const closing = closeInspectorConnection(
{
close: () => {
closeStarted = true;
return new Promise<void>(() => undefined);
},
},
controller.signal,
);
controller.abort();
expect(closeStarted).toBe(true);
await expect(closing).resolves.toBeUndefined();
});
it("maps a rejected close to incomplete cleanup and preserves the primary failure", () => {
const primary = new Error("observation failed");
const cleanup = new Error("socket close failed");
const error = inspectorCleanupError(primary, cleanup, true);
expect(error.reason).toBe("cleanup_failed");
expect(error.cleanupIncomplete).toBe(true);
expect(error.cleanupResources).toEqual(["browser_transport"]);
expect(error.cause).toBeInstanceOf(AggregateError);
if (!(error.cause instanceof AggregateError)) return;
expect(error.cause.errors).toEqual([primary, cleanup]);
});
+70 -3
View File
@@ -125,6 +125,13 @@ export class V8InspectorProvider implements JavaScriptRuntimeObservationPort {
options: ExecutionOptions = {},
): Promise<Result<JavaScriptRuntimeObservation, AnalysisError>> {
let connection: CdpConnection | undefined;
let primaryFailure: unknown;
let failed = false;
let cleanupFailure: unknown;
let cleanupFailed = false;
let outcome:
| Result<JavaScriptRuntimeObservation, AnalysisError>
| undefined;
try {
const discovery = await discoverV8Inspector(
input.inspector_endpoint,
@@ -160,15 +167,75 @@ export class V8InspectorProvider implements JavaScriptRuntimeObservationPort {
target,
state,
});
return ok(javascriptRuntimeObservationSchema.parse(result));
outcome = ok(javascriptRuntimeObservationSchema.parse(result));
} catch (cause: unknown) {
return err(providerError(cause, "observe_javascript_runtime"));
failed = true;
primaryFailure = cause;
outcome = err(providerError(cause, "observe_javascript_runtime"));
} finally {
await connection?.close();
if (connection !== undefined)
try {
await closeInspectorConnection(connection, options.signal);
} catch (cause: unknown) {
cleanupFailed = true;
cleanupFailure = cause;
}
}
if (cleanupFailed) {
return err(inspectorCleanupError(primaryFailure, cleanupFailure, failed));
}
return (
outcome ??
err(
new BrowserObservationError(
"observe_javascript_runtime",
"protocol_error",
),
)
);
}
}
export const closeInspectorConnection = async (
connection: Pick<CdpConnection, "close">,
signal?: AbortSignal,
): Promise<void> => {
const closing = connection.close();
void closing.catch(() => undefined);
// CdpConnection.close has its own one second transport bound. Do not make a
// cancelled caller wait for that fallback.
if (signal === undefined) return await closing;
let onAbort: (() => void) | undefined;
const cancelled = new Promise<void>((resolve) => {
onAbort = () => resolve();
signal.addEventListener("abort", onAbort, { once: true });
if (signal.aborted) onAbort();
});
try {
await Promise.race([closing, cancelled]);
} finally {
if (onAbort !== undefined) signal.removeEventListener("abort", onAbort);
}
};
export const inspectorCleanupError = (
primaryFailure: unknown,
cleanupFailure: unknown,
hasPrimaryFailure: boolean,
): BrowserObservationError => {
const cause = hasPrimaryFailure
? new AggregateError(
[primaryFailure, cleanupFailure],
"Inspector observation and cleanup both failed",
)
: cleanupFailure;
return new BrowserObservationError(
"observe_javascript_runtime",
"cleanup_failed",
{ cause },
);
};
const projectTarget = (target: AuthorizedV8InspectorTarget) => ({
target_id: target.id,
protocol_type: target.type,