Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(browser): confirm service-worker cancellation cleanup (#4010)
Ysopwnable2a2a33ad9215
diff --git a/scripts/lib/browser-scenario-storage-e2e.mjs b/scripts/lib/browser-scenario-storage-e2e.mjsindex 97829e5c2..6e1a5911a 100644--- a/scripts/lib/browser-scenario-storage-e2e.mjs+++ b/scripts/lib/browser-scenario-storage-e2e.mjs@@ -626,6 +626,7 @@ const verifyCancelledStorage = async (const pending = provider.captureScenario(cancelledScenario, {signal: controller.signal,});+ let failure;try {await waitForNewDocument(observer,@@ -645,19 +646,23 @@ const verifyCancelledStorage = async (});controller.abort(new Error("cancel storage seed scenario"));const result = await pending;- assert.ok(- !result.ok ||+ if (result.ok)+ assert.ok(result.value.steps.some(({ status }) => status === "cancelled"),- "Cancellation unexpectedly completed every scenario step",- );+ "Cancellation unexpectedly completed every scenario step",+ );+ else assert.equal(result.error._tag, "AnalysisCancelledError");const targets = await (await fetch(`${endpoint}/json/list`)).json();assert.ok(targets.some(({ id }) => id === targetId),"Cancelled connect-mode storage cleanup closed the external target",);+ } catch (cause) {+ failure = cause;+ throw cause;} finally {- controller.abort();- await provider.close();+ controller.abort(new Error("cancel failed storage verification"));+ await closeVerifierResources([() => provider.close()], failure);}};diff --git a/src/browser/CdpConnection.ts b/src/browser/CdpConnection.tsindex 57319c1d1..78511fb8f 100644--- a/src/browser/CdpConnection.ts+++ b/src/browser/CdpConnection.ts@@ -254,10 +254,20 @@ export class CdpConnection {if (pending === undefined) return;const hasResult = "result" in message;const hasError = "error" in message;+ // Chromium cannot route a rejection through a flat session after that+ // session disappears. Its browser-level reply omits sessionId, but the+ // connection-global command id still binds this exact terminal error.+ const detachedSessionError =+ pending.sessionId !== undefined &&+ !("sessionId" in message) &&+ hasError &&+ isRecord(message.error) &&+ message.error.code === -32_001 &&+ message.error.message === "Session with given id not found.";if ((pending.sessionId === undefined? "sessionId" in message- : message.sessionId !== pending.sessionId) ||+ : message.sessionId !== pending.sessionId && !detachedSessionError) ||hasResult === hasError) {this.#failPending("protocol_error");diff --git a/src/browser/PlaywrightScenarioServiceWorkers.ts b/src/browser/PlaywrightScenarioServiceWorkers.tsindex 35f1460a3..40b79dfc2 100644--- a/src/browser/PlaywrightScenarioServiceWorkers.ts+++ b/src/browser/PlaywrightScenarioServiceWorkers.ts@@ -1,7 +1,7 @@import { randomUUID } from "node:crypto";import { z } from "zod";-import type { Page } from "playwright-core";+import type { Frame, Page } from "playwright-core";import { browserObservationEndpointSchema } from "../domain/browserObservation.js";import { BrowserObservationError } from "../domain/browserObservationError.js";@@ -15,7 +15,14 @@ import {import { withPlaywrightExecutionBoundary } from "./PlaywrightExecutionBoundary.js";const OPERATION = "capture_browser_scenario" as const;+// Restoration performs several sequential CDP mutations before the transport's+// own bounded close. A single round-trip deadline is too short for the complete+// chain on a loaded Windows browser, while retries must still stay bounded.+const POLICY_CLEANUP_CONFIRMATION_TIMEOUT_MS = 5_000;const scriptResponse = z.object({ identifier: z.string() });+const restorationResponse = z.object({+ result: z.object({ value: z.literal("policy_owned").nullable() }),+});const attachedEvent = z.object({sessionId: z.string(),targetInfo: z.object({ type: z.string() }),@@ -23,6 +30,8 @@ const attachedEvent = z.object({const detachedEvent = z.object({ sessionId: z.string() });type PolicyTarget = {readonly id: string;+ readonly detached: Promise<void>;+ readonly markDetached: () => void;ready: Promise<void>;identifier?: string;};@@ -41,6 +50,7 @@ export class PlaywrightScenarioServiceWorkers {#closed = false;#released = false;#detached = false;+ #loadingStopped = false;#removeListener: (() => void) | undefined;#setup = new AbortController();@@ -101,6 +111,7 @@ export class PlaywrightScenarioServiceWorkers {if (targetInfo.type === "iframe") this.addTarget(sessionId);} else if (event.method === "Target.detachedFromTarget") {const id = detachedEvent.parse(event.params).sessionId;+ this.#targets.get(id)?.markDetached();this.#targets.delete(id);if (id === this.#session?.sessionId) this.#detached = true;}@@ -119,7 +130,17 @@ export class PlaywrightScenarioServiceWorkers {}private addTarget(id: string): void {- const target: PolicyTarget = { id, ready: Promise.resolve() };+ this.#targets.get(id)?.markDetached();+ let markDetached: () => void = () => undefined;+ const detached = new Promise<void>((resolve) => {+ markDetached = resolve;+ });+ const target: PolicyTarget = {+ id,+ detached,+ markDetached,+ ready: Promise.resolve(),+ };this.#targets.set(id, target);const ready = this.initializeTarget(target);target.ready = ready;@@ -187,15 +208,7 @@ export class PlaywrightScenarioServiceWorkers {private async settle(): Promise<void> {for (;;) {const targets = [...this.#targets.values()];- await Promise.all(- targets.map(async (target) => {- try {- await target.ready;- } catch (cause: unknown) {- if (this.#targets.get(target.id) === target) throw cause;- }- }),- );+ await Promise.all(targets.map((target) => this.settleTarget(target)));if (targets.length === this.#targets.size &&targets.every((target) => this.#targets.get(target.id) === target)@@ -204,6 +217,71 @@ export class PlaywrightScenarioServiceWorkers {}}+ private async settleTarget(target: PolicyTarget): Promise<void> {+ try {+ await Promise.race([target.ready, target.detached]);+ } catch (cause: unknown) {+ if (this.#targets.get(target.id) === target) throw cause;+ }+ }++ private async settleTargetForRestore(target: PolicyTarget): Promise<void> {+ try {+ await Promise.race([target.ready, target.detached]);+ } catch {+ // Setup already reports its own failure. Cleanup must continue from the+ // side effects that were acquired before it failed, such as an init+ // script whose identifier was returned before auto-attach was rejected.+ }+ }++ private restorationScript(): string {+ return `(() => {+ const restore = globalThis[${this.restoreKey}];+ if (typeof restore === "function" && restore(${this.secret}) === true) return null;+ const register = globalThis.ServiceWorkerContainer?.prototype.register;+ return typeof register === "function" && Object.hasOwn(register, Symbol.for(${this.marker}))+ ? "policy_owned"+ : null;+ })()`;+ }++ private async restoreMainFrame(id: string): Promise<void> {+ const { result } = restorationResponse.parse(+ await this.send(id, "Runtime.evaluate", {+ expression: this.restorationScript(),+ returnByValue: true,+ }),+ );+ if (result.value === "policy_owned")+ throw new Error(+ "service-worker policy restoration could not be confirmed",+ );+ }++ private async restorePlaywrightFrame(frame: Frame): Promise<void> {+ try {+ const failure = await frame.evaluate(this.restorationScript());+ if (failure === "policy_owned")+ throw new Error(+ "service-worker policy restoration could not be confirmed",+ );+ if (failure !== null)+ throw new BrowserObservationError(OPERATION, "protocol_error");+ } catch (cause: unknown) {+ if (!this.page.isClosed() && !frame.isDetached()) throw cause;+ }+ }++ private async stopMainFrame(frame: Frame): Promise<void> {+ try {+ await frame.evaluate("globalThis.stop()");+ this.#loadingStopped = true;+ } catch (cause: unknown) {+ if (!this.page.isClosed() && !frame.isDetached()) throw cause;+ }+ }+async assertBlocked(): Promise<void> {if (this.#session !== undefined) await this.settle();for (const frame of this.page.frames()) {@@ -246,7 +324,10 @@ export class PlaywrightScenarioServiceWorkers {if (this.#restoration === restoration) this.#restoration = undefined;},);- return withPlaywrightExecutionBoundary(() => restoration, 1_000);+ return withPlaywrightExecutionBoundary(+ () => restoration,+ POLICY_CLEANUP_CONFIRMATION_TIMEOUT_MS,+ );}private async restore(stopLoading: boolean): Promise<void> {@@ -255,13 +336,20 @@ export class PlaywrightScenarioServiceWorkers {const session = this.#session;if (session === undefined) return;if (!this.page.isClosed()) {+ const mainFrame = this.page.mainFrame();// This owner exists even with empty storage seeds. Stopped navigation is// independent of storage and restoration never waits for a load event.- if (stopLoading && !this.#detached && session.sessionId !== undefined)- await this.send(session.sessionId, "Page.stopLoading");+ if (stopLoading && !this.#loadingStopped) {+ if (!this.#detached && session.sessionId !== undefined) {+ await this.send(session.sessionId, "Page.stopLoading");+ this.#loadingStopped = true;+ } else {+ await this.stopMainFrame(mainFrame);+ }+ }await Promise.all(- [...this.#targets.values()].map(({ ready }) =>- ready.catch(() => undefined),+ [...this.#targets.values()].map((target) =>+ this.settleTargetForRestore(target),),);for (const target of this.#targets.values()) {@@ -280,19 +368,20 @@ export class PlaywrightScenarioServiceWorkers {}// Future documents cannot install our wrapper after the removals above.// A realm lost to navigation is not assumed restored: retain and retry.+ if (!this.#detached && session.sessionId !== undefined) {+ await this.restoreMainFrame(session.sessionId);+ } else {+ await this.restorePlaywrightFrame(mainFrame);+ }for (const frame of this.page.frames()) {+ // The owned CDP session evaluates the selected main realm directly,+ // without Playwright waiting on an in-flight document transition.+ if (frame === mainFrame) continue;if (frame.isDetached()) continue;- try {- await frame.evaluate(`(() => {- const restore = globalThis[${this.restoreKey}];- if (typeof restore === "function" && restore(${this.secret}) === true) return;- const register = globalThis.ServiceWorkerContainer?.prototype.register;- if (typeof register === "function" && Object.hasOwn(register, Symbol.for(${this.marker})))- throw new Error("service-worker policy restoration could not be confirmed");- })()`);- } catch (cause: unknown) {- if (!frame.isDetached()) throw cause;- }+ // An empty URL has no committed document realm to restore. Future+ // documents cannot install the wrapper after the script removals.+ if (frame.url().length === 0) continue;+ await this.restorePlaywrightFrame(frame);}}// Detaching the exact owned session also releases its iframe auto-attach.diff --git a/src/browser/PlaywrightScenarioSession.test.ts b/src/browser/PlaywrightScenarioSession.test.tsindex 366e4a78a..ae73b95b9 100644--- a/src/browser/PlaywrightScenarioSession.test.ts+++ b/src/browser/PlaywrightScenarioSession.test.ts@@ -15,7 +15,7 @@ const mocks = vi.hoisted(() => ({policySend: vi.fn(),policyTransportClose: vi.fn(),policyEvent: undefined as- | ((event: { method: string; params: unknown }) => void)+ | ((event: { method: string; params: unknown; sessionId?: string }) => void)| undefined,}));@@ -118,6 +118,7 @@ const fixture = () => {addInitScript: vi.fn(async (_script: unknown) => undefined),context: () => context,frames: () => [page],+ mainFrame: () => page,isDetached: () => false,isClosed: (): boolean => false,waitForLoadState: vi.fn(async () => undefined),@@ -152,20 +153,27 @@ const fixture = () => {mocks.storage = {initialize: vi.fn(async () => undefined),settle: vi.fn(async () => undefined),- close: vi.fn(async () => undefined),+ close: vi.fn(async (stopLoading = false) => ({+ loadingStopped: stopLoading,+ })),};return { cleanup, page, storage: mocks.storage };};+const policyResponse = (method: string): unknown =>+ method === "Page.addScriptToEvaluateOnNewDocument"+ ? { identifier: "owned-policy-script" }+ : method === "Runtime.evaluate"+ ? { result: { value: null } }+ : {};+beforeEach(() => {vi.clearAllMocks();mocks.policySend.mockReset();mocks.policyTransportClose.mockReset();mocks.policyEvent = undefined;mocks.policySend.mockImplementation(async (method: string) =>- method === "Page.addScriptToEvaluateOnNewDocument"- ? { identifier: "owned-policy-script" }- : {},+ policyResponse(method),);mocks.policyTransportClose.mockResolvedValue(undefined);});@@ -197,6 +205,292 @@ it("stops attached navigation without storage and retries rejected policy cleanuexpect(cleanup.close).toHaveBeenCalledTimes(1);});+it("assigns attached navigation stopping to the storage owner once", async () => {+ const { cleanup, storage } = fixture();+ const attached = browserScenarioSchema.parse({+ ...scenario,+ browser: {+ mode: "connect",+ cdp_endpoint: "http://127.0.0.1:9222",+ target_id: "target",+ },+ environment: { service_workers: "block" },+ });+ const session = await PlaywrightScenarioSession.open(attached, {}, {});++ await expect(session.close(true)).resolves.toBe("disconnected-external");+ expect(storage?.close).toHaveBeenCalledWith(true);+ expect(+ mocks.policySend.mock.calls.filter(+ ([method]) => method === "Page.stopLoading",+ ),+ ).toHaveLength(0);+ expect(cleanup.close).toHaveBeenCalledTimes(1);+});++it("transfers attached navigation stopping after storage cleanup fails", async () => {+ const { cleanup, storage } = fixture();+ const storageFailure = new Error("storage stop unconfirmed");+ storage?.close.mockRejectedValueOnce(storageFailure);+ const policyFailure = new Error("policy stop unconfirmed");+ const attached = browserScenarioSchema.parse({+ ...scenario,+ browser: {+ mode: "connect",+ cdp_endpoint: "http://127.0.0.1:9222",+ target_id: "target",+ },+ environment: { service_workers: "block" },+ });+ const session = await PlaywrightScenarioSession.open(attached, {}, {});+ mocks.policySend.mockRejectedValueOnce(policyFailure);++ await expect(session.close(true)).rejects.toMatchObject({+ errors: [policyFailure, storageFailure],+ });+ expect(cleanup.close).not.toHaveBeenCalled();+ await expect(session.close()).resolves.toBe("disconnected-external");+ expect(storage?.close).toHaveBeenCalledWith(true);+ expect(+ mocks.policySend.mock.calls.filter(+ ([method]) => method === "Page.stopLoading",+ ),+ ).toHaveLength(2);+ expect(cleanup.close).toHaveBeenCalledTimes(1);+});++it("transfers a late stop request after storage has already released", async () => {+ const { cleanup, storage } = fixture();+ const cancellation = new AbortController();+ storage?.close.mockResolvedValue({ loadingStopped: false });+ const attached = browserScenarioSchema.parse({+ ...scenario,+ browser: {+ mode: "connect",+ cdp_endpoint: "http://127.0.0.1:9222",+ target_id: "target",+ },+ environment: { service_workers: "block" },+ });+ const session = await PlaywrightScenarioSession.open(+ attached,+ {},+ {+ signal: cancellation.signal,+ },+ );+ const restorationFailure = new Error("registration restoration failed");+ let failRestoration = true;+ mocks.policySend.mockImplementation(async (method: string) => {+ if (method === "Runtime.evaluate" && failRestoration) {+ failRestoration = false;+ throw restorationFailure;+ }+ return policyResponse(method);+ });++ await expect(session.close(false)).rejects.toBe(restorationFailure);+ expect(cleanup.close).not.toHaveBeenCalled();+ cancellation.abort();+ await expect(session.close()).resolves.toBe("disconnected-external");+ expect(storage?.close.mock.calls).toEqual([[false], [true]]);+ expect(+ mocks.policySend.mock.calls.filter(+ ([method]) => method === "Page.stopLoading",+ ),+ ).toHaveLength(1);+ expect(cleanup.close).toHaveBeenCalledTimes(1);+});++it("retains transferred navigation stopping after setup cleanup fails", async () => {+ const { cleanup, storage } = fixture();+ const cancellation = new AbortController();+ const setupFailure = new Error("storage initialization failed");+ storage?.initialize.mockImplementationOnce(async () => {+ cancellation.abort();+ throw setupFailure;+ });+ storage?.close.mockRejectedValueOnce(new Error("storage stop unconfirmed"));+ const policyFailure = new Error("policy stop unconfirmed");+ let failPolicyStop = true;+ mocks.policySend.mockImplementation(async (method: string) => {+ if (method === "Page.stopLoading" && failPolicyStop) {+ failPolicyStop = false;+ throw policyFailure;+ }+ return policyResponse(method);+ });+ let retainedCleanup: (() => Promise<unknown>) | undefined;+ const attached = browserScenarioSchema.parse({+ ...scenario,+ browser: {+ mode: "connect",+ cdp_endpoint: "http://127.0.0.1:9222",+ target_id: "target",+ },+ environment: { service_workers: "block" },+ });++ await expect(+ PlaywrightScenarioSession.open(+ attached,+ {},+ {+ signal: cancellation.signal,+ retainCleanup: (close) => {+ retainedCleanup = close;+ },+ },+ ),+ ).rejects.toBeInstanceOf(AggregateError);+ expect(cleanup.close).not.toHaveBeenCalled();+ if (retainedCleanup === undefined)+ throw new Error("failed cleanup was not retained");+ await expect(retainedCleanup()).resolves.toBeUndefined();+ expect(+ mocks.policySend.mock.calls.filter(+ ([method]) => method === "Page.stopLoading",+ ),+ ).toHaveLength(2);+ expect(cleanup.close).toHaveBeenCalledTimes(1);+});++it("allows the bounded policy cleanup chain to cross one second", async () => {+ const { cleanup } = fixture();+ mocks.storage = undefined;+ const attached = browserScenarioSchema.parse({+ ...scenario,+ browser: {+ mode: "connect",+ cdp_endpoint: "http://127.0.0.1:9222",+ target_id: "target",+ },+ environment: { service_workers: "block" },+ storage: {},+ });+ const session = await PlaywrightScenarioSession.open(attached, {}, {});+ let releaseStop: () => void = () => undefined;+ let stopStarted: () => void = () => undefined;+ const stopped = new Promise<void>((resolve) => {+ releaseStop = resolve;+ });+ const started = new Promise<void>((resolve) => {+ stopStarted = resolve;+ });+ mocks.policySend.mockImplementation(async (method: string) => {+ if (method === "Page.stopLoading") {+ stopStarted();+ await stopped;+ }+ return policyResponse(method);+ });++ vi.useFakeTimers();+ try {+ let settled = false;+ const closing = session.close(true).then(+ () => {+ settled = true;+ return { ok: true as const };+ },+ (cause: unknown) => {+ settled = true;+ return { ok: false as const, cause };+ },+ );+ await started;+ await vi.advanceTimersByTimeAsync(1_100);+ expect(settled).toBe(false);+ releaseStop();+ await expect(closing).resolves.toEqual({ ok: true });+ } finally {+ vi.useRealTimers();+ }+ expect(cleanup.close).toHaveBeenCalledTimes(1);+});++it("does not await policy initialization after its child target detaches", async () => {+ const { cleanup } = fixture();+ mocks.storage = undefined;+ const attached = browserScenarioSchema.parse({+ ...scenario,+ browser: {+ mode: "connect",+ cdp_endpoint: "http://127.0.0.1:9222",+ target_id: "target",+ },+ environment: { service_workers: "block" },+ storage: {},+ });+ const session = await PlaywrightScenarioSession.open(attached, {}, {});+ let childStarted: () => void = () => undefined;+ let releaseChild: () => void = () => undefined;+ const started = new Promise<void>((resolve) => {+ childStarted = resolve;+ });+ const held = new Promise<void>((resolve) => {+ releaseChild = resolve;+ });+ mocks.policySend.mockImplementation(+ async (method: string, _params: unknown, target: string) => {+ if (method === "Page.enable" && target === "child-session") {+ childStarted();+ await held;+ }+ return policyResponse(method);+ },+ );+ mocks.policyEvent?.({+ method: "Target.attachedToTarget",+ params: {+ sessionId: "child-session",+ targetInfo: { type: "iframe" },+ },+ sessionId: "policy-session",+ });+ await started;+ const closing = session.close();+ mocks.policyEvent?.({+ method: "Target.detachedFromTarget",+ params: { sessionId: "child-session" },+ });+ try {+ await expect(closing).resolves.toBe("disconnected-external");+ } finally {+ releaseChild();+ }+ expect(cleanup.close).toHaveBeenCalledTimes(1);+});++it("skips policy restoration for a child without a committed document", async () => {+ const { cleanup, page } = fixture();+ mocks.storage = undefined;+ const pendingChild = {+ url: () => "",+ isDetached: () => false,+ evaluate: vi.fn(() => new Promise(() => undefined)),+ };+ const session = await PlaywrightScenarioSession.open(+ browserScenarioSchema.parse({+ ...scenario,+ browser: {+ mode: "connect",+ cdp_endpoint: "http://127.0.0.1:9222",+ target_id: "target",+ },+ environment: { service_workers: "block" },+ storage: {},+ }),+ {},+ {},+ );+ page.frames = () => [page, pendingChild as unknown as typeof page];++ await expect(session.close()).resolves.toBe("disconnected-external");+ expect(pendingChild.evaluate).not.toHaveBeenCalled();+ expect(cleanup.close).toHaveBeenCalledTimes(1);+});+it("rejects an init script accepted by CDP when the live realm is unprotected", async () => {const { page, cleanup } = fixture();page.evaluate@@ -229,6 +523,40 @@ it("rejects an init script accepted by CDP when the live realm is unprotected",expect(cleanup.close).toHaveBeenCalledTimes(1);});+it("restores an owned policy script after later setup fails", async () => {+ const { cleanup } = fixture();+ const setupFailure = new Error("auto-attach rejected");+ mocks.policySend.mockImplementation(async (method: string) => {+ if (method === "Target.setAutoAttach") throw setupFailure;+ return policyResponse(method);+ });+ const attached = browserScenarioSchema.parse({+ ...scenario,+ browser: {+ mode: "connect",+ cdp_endpoint: "http://127.0.0.1:9222",+ target_id: "target",+ },+ environment: { service_workers: "block" },+ });++ await expect(PlaywrightScenarioSession.open(attached, {}, {})).rejects.toBe(+ setupFailure,+ );+ expect(mocks.policySend).toHaveBeenCalledWith(+ "Page.removeScriptToEvaluateOnNewDocument",+ { identifier: "owned-policy-script" },+ "policy-session",+ );+ expect(+ mocks.policySend.mock.calls.some(+ ([method]) => method === "Runtime.evaluate",+ ),+ ).toBe(true);+ expect(mocks.policyTransportClose).toHaveBeenCalledTimes(1);+ expect(cleanup.close).toHaveBeenCalledTimes(1);+});+it("retains an owned script identifier after rejected removal", async () => {const { cleanup } = fixture();const attached = browserScenarioSchema.parse({@@ -283,6 +611,7 @@ it.each(["closed page", "detached target"])("releases its policy transport after a %s",async (terminal) => {const { page } = fixture();+ mocks.storage = undefined;const attached = browserScenarioSchema.parse({...scenario,browser: {@@ -291,6 +620,7 @@ it.each(["closed page", "detached target"])(target_id: "target",},environment: { service_workers: "block" },+ storage: {},});const session = await PlaywrightScenarioSession.open(attached, {}, {});if (terminal === "closed page") page.isClosed = () => true;@@ -299,16 +629,61 @@ it.each(["closed page", "detached target"])(method: "Target.detachedFromTarget",params: { sessionId: "policy-session" },});- await expect(session.close()).resolves.toBe("disconnected-external");+ await expect(session.close(true)).resolves.toBe("disconnected-external");expect(mocks.policySend.mock.calls.some(([method]) => method === "Target.detachFromTarget",),).toBe(false);expect(mocks.policyTransportClose).toHaveBeenCalledTimes(1);+ if (terminal === "detached target") {+ expect(page.evaluate).toHaveBeenCalledWith("globalThis.stop()");+ expect(page.evaluate).toHaveBeenCalledWith(+ expect.stringContaining("policy_owned"),+ );+ }},);+it("retains a detached policy connection until the main realm is restored", async () => {+ const { cleanup, page } = fixture();+ mocks.storage = undefined;+ const attached = browserScenarioSchema.parse({+ ...scenario,+ browser: {+ mode: "connect",+ cdp_endpoint: "http://127.0.0.1:9222",+ target_id: "target",+ },+ environment: { service_workers: "block" },+ storage: {},+ });+ const session = await PlaywrightScenarioSession.open(attached, {}, {});+ mocks.policyEvent?.({+ method: "Target.detachedFromTarget",+ params: { sessionId: "policy-session" },+ });+ page.evaluate+ .mockResolvedValueOnce(undefined)+ .mockResolvedValueOnce("policy_owned")+ .mockResolvedValueOnce(null);++ await expect(session.close(true)).rejects.toThrow(+ "service-worker policy restoration could not be confirmed",+ );+ expect(cleanup.close).not.toHaveBeenCalled();+ expect(mocks.policyTransportClose).not.toHaveBeenCalled();+ await expect(session.close()).resolves.toBe("disconnected-external");+ expect(page.evaluate).toHaveBeenCalledWith("globalThis.stop()");+ expect(+ page.evaluate.mock.calls.filter(+ ([script]) => script === "globalThis.stop()",+ ),+ ).toHaveLength(1);+ expect(mocks.policyTransportClose).toHaveBeenCalledTimes(1);+ expect(cleanup.close).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");@@ -379,7 +754,8 @@ it("blocks new attached service-worker registration without removing existing re});it("retains the attached connection when registration restoration fails", async () => {- const { cleanup, page } = fixture();+ const { cleanup } = fixture();+ mocks.storage = undefined;const attached = browserScenarioSchema.parse({...scenario,browser: {@@ -388,13 +764,26 @@ it("retains the attached connection when registration restoration fails", asynctarget_id: "target",},environment: { service_workers: "block" },+ storage: {},});const session = await PlaywrightScenarioSession.open(attached, {}, {});const failure = new Error("registration restoration failed");- page.evaluate.mockRejectedValueOnce(failure);- await expect(session.close()).rejects.toBe(failure);+ let failRestoration = true;+ mocks.policySend.mockImplementation(async (method: string) => {+ if (method === "Runtime.evaluate" && failRestoration) {+ failRestoration = false;+ throw failure;+ }+ return policyResponse(method);+ });+ await expect(session.close(true)).rejects.toBe(failure);expect(cleanup.close).not.toHaveBeenCalled();await expect(session.close()).resolves.toBe("disconnected-external");+ expect(+ mocks.policySend.mock.calls.filter(+ ([method]) => method === "Page.stopLoading",+ ),+ ).toHaveLength(1);expect(cleanup.close).toHaveBeenCalledTimes(1);await expect(session.close()).resolves.toBe("disconnected-external");});@@ -456,7 +845,7 @@ it("waits for a pending registration installation before cancelled cleanup", asyawait installed;return { identifier: "owned-policy-script" };}- return {};+ return policyResponse(method);});const cancellation = new AbortController();const opening = PlaywrightScenarioSession.open(@@ -482,9 +871,12 @@ it("waits for a pending registration installation before cancelled cleanup", asyexpect(page.evaluate).toHaveBeenCalledTimes(1);releaseInstallation();await outcome;- expect(page.evaluate.mock.calls.at(-1)?.[0]).toContain(- "policy restoration could not be confirmed",- );+ const restoration = mocks.policySend.mock.calls.find(+ ([method]) => method === "Runtime.evaluate",+ )?.[1];+ expect(restoration).toMatchObject({+ expression: expect.stringContaining("policy_owned"),+ });expect(mocks.policySend).toHaveBeenCalledWith("Page.stopLoading",{},diff --git a/src/browser/PlaywrightScenarioSession.ts b/src/browser/PlaywrightScenarioSession.tsindex 80537cbcd..63557da7b 100644--- a/src/browser/PlaywrightScenarioSession.ts+++ b/src/browser/PlaywrightScenarioSession.ts@@ -73,6 +73,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {private readonly serviceWorkers: PlaywrightScenarioServiceWorkers | undefined;private readonly signal: AbortSignal | undefined;#storageReleased = false;+ #policyStopsLoading = false;private constructor(private readonly opened: OpenedScenarioBrowser,@@ -260,19 +261,29 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {});} catch (cause: unknown) {let storageReleased = false;+ const storageStopsLoading =+ storage !== undefined && options.signal?.aborted === true;+ let policyStopsLoading = !storageStopsLoading;const cleanup = async () => {let storageFailure: { readonly cause: unknown } | undefined;let policyFailure: { readonly cause: unknown } | undefined;let browserFailure: { readonly cause: unknown } | undefined;if (!storageReleased) {try {- await storage?.close(options.signal?.aborted === true);+ const result = await storage?.close(storageStopsLoading);+ if (storageStopsLoading && result?.loadingStopped !== true)+ policyStopsLoading = true;} catch (failure: unknown) {storageFailure = { cause: failure };+ // Ownership transfers only after the storage attempt is no longer+ // in flight. Its failure does not establish that navigation stop+ // succeeded, so the policy owner must confirm it before release.+ policyStopsLoading = true;}}try {- if (!opened.cleanup.browserClosed) await serviceWorkers?.close(true);+ if (!opened.cleanup.browserClosed)+ await serviceWorkers?.close(policyStopsLoading);} catch (failure: unknown) {policyFailure = { cause: failure };}@@ -394,16 +405,21 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {let storageFailure: { readonly cause: unknown } | undefined;let policyFailure: { readonly cause: unknown } | undefined;let browserFailure: { readonly cause: unknown } | undefined;+ if (stopLoading && this.storage === undefined)+ this.#policyStopsLoading = true;if (!this.#storageReleased) {try {- await this.storage?.close(stopLoading);+ const result = await this.storage?.close(stopLoading);+ if (stopLoading && result?.loadingStopped !== true)+ this.#policyStopsLoading = true;} catch (failure: unknown) {storageFailure = { cause: failure };+ if (stopLoading) this.#policyStopsLoading = true;}}try {if (!this.opened.cleanup.browserClosed)- await this.serviceWorkers?.close(stopLoading);+ await this.serviceWorkers?.close(this.#policyStopsLoading);} catch (failure: unknown) {policyFailure = { cause: failure };}diff --git a/src/browser/PlaywrightScenarioStorage.test.ts b/src/browser/PlaywrightScenarioStorage.test.tsindex cef99364d..e1d2f0830 100644--- a/src/browser/PlaywrightScenarioStorage.test.ts+++ b/src/browser/PlaywrightScenarioStorage.test.ts@@ -25,13 +25,15 @@ class FakeCdp extends EventEmitter {this.calls.push({ method, params });if (method === this.holdMethod) {const response =- method === "Page.addScriptToEvaluateOnNewDocument"- ? { identifier: "late-script" }- : method === "Debugger.setBreakpointByUrl"- ? { breakpointId: "late-breakpoint" }- : method === "Storage.getStorageKey"- ? { storageKey: this.storageKey }- : {};+ method === "Target.getTargetInfo"+ ? { targetInfo: { targetId: "root-target" } }+ : method === "Page.addScriptToEvaluateOnNewDocument"+ ? { identifier: "late-script" }+ : method === "Debugger.setBreakpointByUrl"+ ? { breakpointId: "late-breakpoint" }+ : method === "Storage.getStorageKey"+ ? { storageKey: this.storageKey }+ : {};return new Promise((resolve) => {this.heldReply = () => resolve(response);});@@ -273,16 +275,61 @@ it("retries the owning CDP detach after a failed attempt", async () => {const owner = await createInitializedStorage(contextApi, page);cdp.failDetachCount = 1;- await expect(owner?.close()).rejects.toMatchObject({+ await expect(owner?.close(true)).rejects.toMatchObject({_tag: "BrowserObservationError",reason: "cleanup_failed",});expect(cdp.detachCalls).toBe(1);expect(cdp.listenerCount("Debugger.paused")).toBe(1);- await owner?.close();+ await expect(owner?.close(true)).resolves.toEqual({+ loadingStopped: true,+ });expect(cdp.detachCalls).toBe(2);expect(cdp.listenerCount("Debugger.paused")).toBe(0);+ expect(+ cdp.calls.filter(({ method }) => method === "Page.stopLoading"),+ ).toHaveLength(1);+});++it("reports an unconfirmed stop when root initialization is still pending", async () => {+ const cdp = new FakeCdp();+ cdp.holdMethod = "Target.getTargetInfo";+ const { page, contextApi } = fixture(cdp);+ const input = scenario();+ const owner = await PlaywrightScenarioStorage.create(+ { context: contextApi as never, page: page as never },+ input,+ BrowserScenarioSecrets.resolve(input, {})!,+ );+ expect(owner).toBeDefined();+ const initialization = owner?.initialize(page as never, contextApi as never);+ await waitForCall(cdp, "Target.getTargetInfo");++ const closing = owner?.close(true);+ cdp.releaseHeldReply();+ await expect(initialization).resolves.toBeUndefined();+ await expect(closing).resolves.toEqual({ loadingStopped: false });+ expect(+ cdp.calls.filter(({ method }) => method === "Page.stopLoading"),+ ).toHaveLength(0);+ expect(cdp.detachCalls).toBe(1);+});++it("reports and retains a confirmed navigation stop", async () => {+ const cdp = new FakeCdp();+ const { page, contextApi } = fixture(cdp);+ const owner = await createInitializedStorage(contextApi, page);++ await expect(owner?.close(true)).resolves.toEqual({+ loadingStopped: true,+ });+ await expect(owner?.close(true)).resolves.toEqual({+ loadingStopped: true,+ });+ expect(+ cdp.calls.filter(({ method }) => method === "Page.stopLoading"),+ ).toHaveLength(1);});it("does not create storage instrumentation when there are no storage seeds", async () => {diff --git a/src/browser/PlaywrightScenarioStorage.ts b/src/browser/PlaywrightScenarioStorage.tsindex b813d1a50..b0190c5f4 100644--- a/src/browser/PlaywrightScenarioStorage.ts+++ b/src/browser/PlaywrightScenarioStorage.ts@@ -106,6 +106,9 @@ type StorageInstallationOptions = {readonly retainCleanup?: (close: () => Promise<unknown>) => void;};type StoragePage = { readonly context: BrowserContext; readonly page: Page };+export type PlaywrightScenarioStorageCleanup = {+ readonly loadingStopped: boolean;+};/** Owns pre-script storage seeding and its CDP instrumentation for one scenario. */export class PlaywrightScenarioStorage {@@ -123,8 +126,9 @@ export class PlaywrightScenarioStorage {#generation = 0;#closed = false;#cleanupCompleted = false;+ #loadingStopped = false;#failure: BrowserObservationError | undefined;- #closePromise: Promise<void> | undefined;+ #closePromise: Promise<PlaywrightScenarioStorageCleanup> | undefined;#detachPromise: Promise<void> | undefined;#rootInitialization: Promise<void> | undefined;#work: Promise<void> = Promise.resolve();@@ -203,6 +207,7 @@ export class PlaywrightScenarioStorage {const rootInfo = targetInfoResponse.parse(await this.cdp.send("Target.getTargetInfo"),);+ if (this.#closed) return;const root = this.createTarget(undefined,rootInfo.targetInfo.targetId,@@ -210,7 +215,6 @@ export class PlaywrightScenarioStorage {this.cdp.send(method as Parameters<CDPSession["send"]>[0], params),);this.#targets.set("", root);- if (this.#closed) return;this.listen(page, context);const ready = this.initializeTarget(root);root.ready = ready;@@ -591,8 +595,9 @@ export class PlaywrightScenarioStorage {}}- close(stopLoading = false): Promise<void> {- if (this.#cleanupCompleted) return Promise.resolve();+ close(stopLoading = false): Promise<PlaywrightScenarioStorageCleanup> {+ if (this.#cleanupCompleted)+ return Promise.resolve({ loadingStopped: this.#loadingStopped });if (this.#closePromise !== undefined) return this.#closePromise;const closing = this.closeResources(stopLoading).catch((cause: unknown) => {throw new BrowserObservationError(@@ -614,17 +619,21 @@ export class PlaywrightScenarioStorage {return closing;}- private async closeResources(stopLoading: boolean): Promise<void> {+ private async closeResources(+ stopLoading: boolean,+ ): Promise<PlaywrightScenarioStorageCleanup> {this.#closed = true;let stopLoadingFailure: { readonly cause: unknown } | undefined;- if (stopLoading) {+ if (stopLoading && !this.#loadingStopped) {try {const root = this.#targets.get("");- if (root !== undefined)+ if (root !== undefined) {await withPlaywrightExecutionBoundary(() => root.send("Page.stopLoading"),STORAGE_CLEANUP_TIMEOUT_MS,);+ this.#loadingStopped = true;+ }} catch (cause: unknown) {stopLoadingFailure = { cause };}@@ -674,5 +683,6 @@ export class PlaywrightScenarioStorage {this.#replies.clear();this.#cleanupCompleted = true;if (stopLoadingFailure !== undefined) throw stopLoadingFailure.cause;+ return { loadingStopped: this.#loadingStopped };}}diff --git a/tests/boundary/browser/cdpConnection.test.ts b/tests/boundary/browser/cdpConnection.test.tsindex 71ef6a245..69ec74a9e 100644--- a/tests/boundary/browser/cdpConnection.test.ts+++ b/tests/boundary/browser/cdpConnection.test.ts@@ -20,6 +20,14 @@ const INVALID_REPLIES = [error: { code: -32_602, message: "Invalid params" },}),],+ [+ "detached-session error and result",+ (id: number) => ({+ id,+ result: {},+ error: { code: -32_001, message: "Session with given id not found." },+ }),+ ],["malformed error",(id: number) => ({@@ -34,6 +42,28 @@ const INVALID_REPLIES = ["foreign session id",(id: number) => ({ id, result: {}, sessionId: "foreign-session" }),],+ [+ "detached-session error with a foreign session id",+ (id: number) => ({+ id,+ error: { code: -32_001, message: "Session with given id not found." },+ sessionId: "foreign-session",+ }),+ ],+ [+ "unrouted detached-session message with another code",+ (id: number) => ({+ id,+ error: { code: -32_000, message: "Session with given id not found." },+ }),+ ],+ [+ "unrouted detached-session code with another message",+ (id: number) => ({+ id,+ error: { code: -32_001, message: "No session with given id" },+ }),+ ],] as const;const browsers: FakeCdpBrowser[] = [];@@ -145,6 +175,40 @@ describe("CDP connection", () => {}},);++ it("preserves Chromium's unrouted rejection for a detached flat session", async () => {+ const browser = await startFakeCdpBrowser({ hangOnMethod: "Page.enable" });+ browsers.push(browser);+ const connection = await CdpConnection.connect(+ browser.browserWebSocketUrl,+ "capture_browser_scenario",+ );+ try {+ const pending = connection.send("Page.enable", {}, "detached-session");+ const rejection = expect(pending).rejects.toMatchObject({+ command: "Page.enable",+ code: -32_001,+ reportedMessage: "Session with given id not found.",+ });+ await vi.waitFor(() => expect(browser.commands).toHaveLength(1));+ const command = browser.commands[0];+ if (command === undefined)+ throw new Error("Fake browser received no command");+ browser.emitRawMessage(+ JSON.stringify({+ id: command.id,+ error: {+ code: -32_001,+ message: "Session with given id not found.",+ },+ }),+ );+ await rejection;+ await expect(connection.send("Runtime.enable")).resolves.toEqual({});+ } finally {+ await connection.close();+ }+ });});describe("CDP connection payload budgets", () => {