diff --git a/src/browser/PlaywrightScenarioSession.test.ts b/src/browser/PlaywrightScenarioSession.test.ts index dbc170880..a9e90bce8 100644 --- a/src/browser/PlaywrightScenarioSession.test.ts +++ b/src/browser/PlaywrightScenarioSession.test.ts @@ -14,19 +14,9 @@ const mocks = vi.hoisted(() => ({ finishEvents: vi.fn(), })); -vi.mock("./PlaywrightScenarioBrowser.js", () => ({ +vi.mock("./PlaywrightScenarioBrowser.js", async (importOriginal) => ({ + ...(await importOriginal()), openPlaywrightScenarioBrowser: mocks.openBrowser, - failBrowserScenarioOperation: async ( - cleanup: () => Promise, - cause: unknown, - ) => { - try { - await cleanup(); - } catch (cleanupCause: unknown) { - throw new AggregateError([cause, cleanupCause]); - } - throw cause; - }, })); vi.mock("./PlaywrightScenarioStorage.js", () => ({ @@ -63,6 +53,7 @@ vi.mock("./PlaywrightScenarioEvents.js", () => ({ import { browserScenarioSchema } from "../domain/browserScenario.js"; import { PlaywrightScenarioSession } from "./PlaywrightScenarioSession.js"; +import { PlaywrightScenarioBrowserCleanupOwner } from "./PlaywrightScenarioBrowser.js"; const scenario = browserScenarioSchema.parse({ browser: { mode: "launch", executable_path: process.execPath }, @@ -106,25 +97,100 @@ const fixture = () => { return browserClosed; }, }; - mocks.openBrowser.mockResolvedValue({ + const opened = { page, context, browser, cleanup, profilePath: "/tmp/profile", - }); + }; + mocks.openBrowser.mockResolvedValue(opened); mocks.storage = { initialize: vi.fn(async () => undefined), settle: vi.fn(async () => undefined), close: vi.fn(async () => undefined), }; - return { cleanup, page, storage: mocks.storage }; + return { cleanup, page, context, storage: mocks.storage, opened }; }; beforeEach(() => { vi.clearAllMocks(); }); +it("finishes initialization cleanup independently of request cancellation", async () => { + const { context, opened } = fixture(); + const controller = new AbortController(); + const closeBrowser = vi.fn(async () => undefined); + const removeProfile = vi.fn(async () => undefined); + mocks.openBrowser.mockResolvedValue({ + ...opened, + cleanup: new PlaywrightScenarioBrowserCleanupOwner({ + closeBrowser, + removeProfile, + }), + }); + context.addCookies.mockImplementationOnce(async () => { + controller.abort(); + }); + const retainCleanup = vi.fn(); + + await expect( + PlaywrightScenarioSession.open( + scenario, + {}, + { + signal: controller.signal, + retainCleanup, + }, + ), + ).rejects.toMatchObject({ _tag: "AnalysisCancelledError" }); + expect(closeBrowser).toHaveBeenCalledTimes(1); + expect(removeProfile).toHaveBeenCalledTimes(1); + expect(retainCleanup).not.toHaveBeenCalled(); +}); + +it("can retry cleanup of a browser that opened after request cancellation", async () => { + const { opened } = fixture(); + const closeBrowser = vi + .fn() + .mockRejectedValueOnce(new Error("transport close failed")) + .mockResolvedValueOnce(undefined); + const removeProfile = vi.fn(async () => undefined); + const lateOpened = { + ...opened, + cleanup: new PlaywrightScenarioBrowserCleanupOwner({ + closeBrowser, + removeProfile, + }), + }; + let resolveOpening: ((value: typeof lateOpened) => void) | undefined; + const opening = new Promise((resolve) => { + resolveOpening = resolve; + }); + mocks.openBrowser.mockReturnValueOnce(opening); + const controller = new AbortController(); + const retained: (() => Promise)[] = []; + const result = PlaywrightScenarioSession.open( + scenario, + {}, + { + signal: controller.signal, + retainCleanup: (close) => retained.push(close), + }, + ); + const cancelled = expect(result).rejects.toMatchObject({ + _tag: "AnalysisCancelledError", + }); + controller.abort(); + await cancelled; + resolveOpening?.(lateOpened); + await vi.waitFor(() => expect(closeBrowser).toHaveBeenCalledTimes(1)); + expect(retained).toHaveLength(1); + await expect(retained[0]?.()).resolves.toBeUndefined(); + expect(closeBrowser).toHaveBeenCalledTimes(2); + expect(removeProfile).toHaveBeenCalledTimes(1); +}); + it("uses browser disconnect as terminal storage release after detach failure", async () => { const { cleanup, storage } = fixture(); const detachFailure = new Error("CDP detach rejected"); diff --git a/src/browser/PlaywrightScenarioSession.ts b/src/browser/PlaywrightScenarioSession.ts index da2751f7d..310aa0c16 100644 --- a/src/browser/PlaywrightScenarioSession.ts +++ b/src/browser/PlaywrightScenarioSession.ts @@ -151,9 +151,10 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort { options.signal, ); } catch (cause: unknown) { + // Resource release outlives the cancelled request, including retained retries. const lateCleanup = () => opening.then( - (lateOpened) => lateOpened.cleanup.close(undefined, options.signal), + (lateOpened) => lateOpened.cleanup.close(), () => undefined, ); options.retainCleanup?.(() => @@ -286,7 +287,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort { events === undefined ? undefined : () => events?.finish() ?? Promise.resolve(), - options.signal, ); } catch (failure: unknown) { browserFailure = { cause: failure }; diff --git a/src/domain/artifactGraph.ts b/src/domain/artifactGraph.ts index fd9ac9114..b5f21ec9b 100644 --- a/src/domain/artifactGraph.ts +++ b/src/domain/artifactGraph.ts @@ -215,6 +215,8 @@ export const artifactInventoryResultSchema = z.object({ export const artifactInventoryOutputSchema = artifactInventoryResultSchema.extend({ coverage_status: artifactInventoryCoverageSchema, + // JSON output may omit container facts, but cannot carry an undefined member. + ines: inesInventorySchema.exactOptional(), }); export type ArtifactInventoryOutput = z.infer< typeof artifactInventoryOutputSchema diff --git a/src/domain/artifactInspection.ts b/src/domain/artifactInspection.ts index 255eb853b..c67efdc3f 100644 --- a/src/domain/artifactInspection.ts +++ b/src/domain/artifactInspection.ts @@ -120,8 +120,7 @@ export const artifactInspectionOutputSchema = .array( artifactInspectionResultSchema.shape.substeps.element.safeExtend({ evidence: evidenceSchema.safeExtend({ - normalized_result: - artifactInventoryOutputSchema.and(jsonValueSchema), + normalized_result: artifactInventoryOutputSchema, }), }), ) diff --git a/src/domain/artifactInventoryOutput.test.ts b/src/domain/artifactInventoryOutput.test.ts new file mode 100644 index 000000000..dad1460cb --- /dev/null +++ b/src/domain/artifactInventoryOutput.test.ts @@ -0,0 +1,74 @@ +import { expect, it } from "vitest"; +import { + artifactInventoryOutputSchema, + artifactInventoryResultSchema, +} from "./artifactGraph.js"; +import { jsonValueSchema } from "./jsonValue.js"; + +const digest = "a".repeat(64); +const inventory = { + manifest: { + manifest_id: `agm_${digest}`, + root_artifact_id: `art_${digest}`, + root_sha256: digest, + root_format: "zip", + graph_sha256: digest, + node_count: 1, + occurrence_count: 1, + edge_count: 0, + }, + nodes: [ + { + artifact_id: `art_${digest}`, + format: "zip", + sha256: digest, + size: 22, + media_type: null, + architecture: null, + content_state: "materialized", + limitations: [], + }, + ], + occurrences: [ + { + occurrence_id: `occ_${digest}`, + artifact_id: `art_${digest}`, + parent_occurrence_id: null, + logical_path: ".", + entry_kind: "file", + artifact_kind: "container", + artifact_format: "zip", + declared_size: 22, + compressed_size: null, + executable: false, + encrypted: false, + hash_status: "verified", + source_location: null, + limitations: [], + }, + ], + edges: [], + provenance: [], + integrity_contradictions: [], + limitations: [], + coverage_status: "complete", +}; + +it("keeps absent container facts absent in JSON-safe inventory output", () => { + const output = artifactInventoryOutputSchema.parse(inventory); + expect(Object.hasOwn(output, "ines")).toBe(false); + expect(jsonValueSchema.safeParse(output).success).toBe(true); + expect( + artifactInventoryOutputSchema.safeParse({ ...inventory, ines: undefined }) + .success, + ).toBe(false); +}); + +it("keeps historical coverage omission separate from current output requirements", () => { + const { coverage_status: _coverage, ...historical } = inventory; + const imported = artifactInventoryResultSchema.parse(historical); + expect(Object.hasOwn(imported, "coverage_status")).toBe(false); + expect(artifactInventoryOutputSchema.safeParse(historical).success).toBe( + false, + ); +});