From 6bb89c58bfbcadfc8d4fad9d9c73474fe997174b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 30 Jul 2026 03:41:13 +0000 Subject: [PATCH 1/3] fix: clear stale dialog modal state when a dialog is closed out of band MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mirror microsoft/playwright#42032: listen for the dialogclosed page event and clear the matching dialog modal state, so an out-of-band dismissal (manual close in headed mode, CDP side-channel) no longer leaves a phantom modal state that blocks every snapshot-bearing tool. The event ships in Playwright 1.63; on the pinned 1.61.1 (and current stable 1.62.0, which predates the upstream branch cut) the listener is registered but never fires, which is harmless — it activates automatically on the next Playwright bump. The listener is registered through the tracked listen() helper so dispose() removes it on shared CDP contexts. Fixes #150 Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_014k8at4qpjdQnMfRVXX7Xz8 --- src/tab.ts | 12 +++++++ tests/tab.test.ts | 92 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+) diff --git a/src/tab.ts b/src/tab.ts index ab5d887b..f7d38646 100644 --- a/src/tab.ts +++ b/src/tab.ts @@ -83,6 +83,12 @@ export class Tab extends EventEmitter { }); }); listen('dialog', dialog => this._dialogShown(dialog)); + // Fires on Playwright >= 1.63 when a dialog is closed out of band (e.g. + // dismissed manually in headed mode or via a CDP side-channel); inert on + // the pinned 1.61.1, which never emits it. Without this, a stale dialog + // modal state blocks every snapshot-bearing tool until the user re-issues + // browser_handle_dialog for a dialog that is already gone. + listen('dialogclosed', dialog => this._dialogClosed(dialog)); listen('download', download => { void this._downloadStarted(download); }); @@ -123,6 +129,12 @@ export class Tab extends EventEmitter { }); } + private _dialogClosed(dialog: playwright.Dialog) { + const state = this._modalStates.find(state => state.type === 'dialog' && state.dialog === dialog); + if (state) + this.clearModalState(state); + } + private async _downloadStarted(download: playwright.Download) { const entry = { download, diff --git a/tests/tab.test.ts b/tests/tab.test.ts index 0809de30..cf3375e9 100644 --- a/tests/tab.test.ts +++ b/tests/tab.test.ts @@ -120,6 +120,98 @@ describe('Tab', () => { }); }); + describe('out-of-band dialog close', () => { + const makeDialog = (message = 'Hello') => ({ + type: () => 'alert', + message: () => message, + }) as any; + + it('sets a dialog modal state when a dialog opens', () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + mockPage.emit('dialog', makeDialog()); + expect(tab.modalStates()).toHaveLength(1); + expect(tab.modalStates()[0].type).toBe('dialog'); + }); + + it('clears the dialog modal state when the dialog closes out of band', () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + const dialog = makeDialog(); + mockPage.emit('dialog', dialog); + expect(tab.modalStates()).toHaveLength(1); + + mockPage.emit('dialogclosed', dialog); + expect(tab.modalStates()).toEqual([]); + }); + + it('unblocks snapshots after the dialog closes out of band', async () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + const dialog = makeDialog(); + mockPage.emit('dialog', dialog); + + const blocked = await tab.captureSnapshot(); + expect(blocked.ariaSnapshot).toBe(''); + expect(blocked.modalStates).toHaveLength(1); + + mockPage.emit('dialogclosed', dialog); + + const unblocked = await tab.captureSnapshot(); + expect(unblocked.ariaSnapshot).toBe('button "Submit" [ref=1]'); + expect(unblocked.modalStates).toEqual([]); + }); + + it('only clears the state of the dialog that actually closed', () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + const first = makeDialog('first'); + const second = makeDialog('second'); + mockPage.emit('dialog', first); + mockPage.emit('dialog', second); + expect(tab.modalStates()).toHaveLength(2); + + mockPage.emit('dialogclosed', first); + expect(tab.modalStates()).toHaveLength(1); + expect(tab.modalStates()[0].description).toContain('second'); + }); + + it('ignores a close event for a dialog it never tracked', () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + const tracked = makeDialog(); + mockPage.emit('dialog', tracked); + + mockPage.emit('dialogclosed', makeDialog('untracked')); + expect(tab.modalStates()).toHaveLength(1); + }); + + it('leaves non-dialog modal states alone', () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + mockPage.emit('filechooser', {}); + const dialog = makeDialog(); + mockPage.emit('dialog', dialog); + + mockPage.emit('dialogclosed', dialog); + expect(tab.modalStates()).toHaveLength(1); + expect(tab.modalStates()[0].type).toBe('fileChooser'); + }); + + it('is a no-op when no modal states exist', () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + expect(() => mockPage.emit('dialogclosed', makeDialog())).not.toThrow(); + expect(tab.modalStates()).toEqual([]); + }); + + it('stops listening after dispose', () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + const dialog = makeDialog(); + mockPage.emit('dialog', dialog); + expect(mockPage.listenerCount('dialogclosed')).toBe(1); + + tab.dispose(); + expect(mockPage.listenerCount('dialogclosed')).toBe(0); + + mockPage.emit('dialogclosed', dialog); + expect(tab.modalStates()).toHaveLength(1); + }); + }); + describe('isCurrentTab', () => { it('should return true when tab is current', () => { const tab = new Tab(mockContext, mockPage as any, onPageClose); From 3941fa039d69329a079a7265687a9e6beb486014 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 30 Jul 2026 04:36:55 +0000 Subject: [PATCH 2/3] chore: bump playwright and playwright-core to 1.62.0 Update the pinned codegen command in README.md and SKILL.md to match (enforced by the tools-axe docs-sync test), and refresh the dialogclosed comment in tab.ts to reference the new pin. The dialogclosed event itself remains a 1.63+ feature, so that listener stays inert on 1.62.0. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_014k8at4qpjdQnMfRVXX7Xz8 --- README.md | 2 +- SKILL.md | 2 +- package-lock.json | 22 +++++++++++----------- package.json | 4 ++-- src/tab.ts | 2 +- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index f7269e3f..8d4142f2 100644 --- a/README.md +++ b/README.md @@ -255,7 +255,7 @@ This works out of the box in every mode, including the default persistent-profil Record a session once with Playwright's codegen, then hand the file to the server: ```bash -npx playwright@1.61.1 codegen --save-storage=auth.json https://example.com/login +npx playwright@1.62.0 codegen --save-storage=auth.json https://example.com/login ``` Sign in in the opened browser, then close it — `auth.json` now holds the cookies and local storage. diff --git a/SKILL.md b/SKILL.md index 898fcf05..09d6ae23 100644 --- a/SKILL.md +++ b/SKILL.md @@ -123,7 +123,7 @@ Crawl and aggregate accessibility violations across multiple pages. Writes a JSO - `excludePathPatterns` - Regex patterns to skip (default: `logout|signout`) - `reportFile` - Custom output filename -**Behind a login:** the crawl shares the browser context, so signing in with `browser_navigate` / `browser_fill_form` first is enough. Alternatively record a session with `npx playwright@1.61.1 codegen --save-storage=auth.json ` (pinned to the server's own Playwright, so the recorded state matches what it replays) and start the server with `--storage-state ./auth.json` — every mode applies it (fresh contexts receive it at creation; the persistent profile runs in a fresh disposable profile built from the state and removed when the session closes, so it cannot combine with `--user-data-dir`; plain CDP attach installs it with `setStorageState()`, which resets cookies fully and origin storage for the state's origins plus any origins the connection has seen — origins from older history it never saw survive) except `--extension`, which errors out rather than wiping the browser you are already running. Extend `excludePathPatterns` with anything else that ends the session (account deletion, session revocation, account/locale switchers) — it replaces the default, so keep `logout|signout` in the list. If the crawl loses cookies it started with, the result opens with `WARNING: cookie(s) …` lines and the report carries a `sessionLosses` list naming, per lost cookie, the page reached after any redirect, even when that page failed to load; if one of them was the session cookie, everything scanned after that page was audited signed-out. Monitoring continues past the first loss (each cookie is reported once, where it vanished), and URLs discovered mid-crawl join cookie tracking before being visited. Cookie values are not compared and a cookie the browser dropped at its own expiry is ignored, but any other cookie the crawl started with and lost is reported — nothing marks a cookie as an authentication one. +**Behind a login:** the crawl shares the browser context, so signing in with `browser_navigate` / `browser_fill_form` first is enough. Alternatively record a session with `npx playwright@1.62.0 codegen --save-storage=auth.json ` (pinned to the server's own Playwright, so the recorded state matches what it replays) and start the server with `--storage-state ./auth.json` — every mode applies it (fresh contexts receive it at creation; the persistent profile runs in a fresh disposable profile built from the state and removed when the session closes, so it cannot combine with `--user-data-dir`; plain CDP attach installs it with `setStorageState()`, which resets cookies fully and origin storage for the state's origins plus any origins the connection has seen — origins from older history it never saw survive) except `--extension`, which errors out rather than wiping the browser you are already running. Extend `excludePathPatterns` with anything else that ends the session (account deletion, session revocation, account/locale switchers) — it replaces the default, so keep `logout|signout` in the list. If the crawl loses cookies it started with, the result opens with `WARNING: cookie(s) …` lines and the report carries a `sessionLosses` list naming, per lost cookie, the page reached after any redirect, even when that page failed to load; if one of them was the session cookie, everything scanned after that page was audited signed-out. Monitoring continues past the first loss (each cookie is reported once, where it vanished), and URLs discovered mid-crawl join cookie tracking before being visited. Cookie values are not compared and a cookie the browser dropped at its own expiry is ignored, but any other cookie the crawl started with and lost is reported — nothing marks a cookie as an authentication one. ### scan_page_matrix diff --git a/package-lock.json b/package-lock.json index 3d0da46e..724a3f28 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,8 +17,8 @@ "debug": "^4.4.3", "dotenv": "^17.4.2", "mime": "^4.1.0", - "playwright": "1.61.1", - "playwright-core": "1.61.1", + "playwright": "1.62.0", + "playwright-core": "1.62.0", "re2": "^1.24.1", "ws": "^8.21.1", "zod": "^4.4.3" @@ -4032,33 +4032,33 @@ } }, "node_modules/playwright": { - "version": "1.61.1", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz", - "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==", + "version": "1.62.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.0.tgz", + "integrity": "sha512-Z14dG305dgaLu6foB1TXQagFiW8JfSUIUaUuPaKQ6NtBPKF1P/qXcqfh6c6K/icPqdy37JmjbiBXf6JNg6Sylw==", "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.61.1" + "playwright-core": "1.62.0" }, "bin": { "playwright": "cli.js" }, "engines": { - "node": ">=18" + "node": ">=20" }, "optionalDependencies": { "fsevents": "2.3.2" } }, "node_modules/playwright-core": { - "version": "1.61.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz", - "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==", + "version": "1.62.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.0.tgz", + "integrity": "sha512-nsNRyq0r2zsG8AcRHWknc9QRA5XCueC7gWMrs+Gx2tlZn9hcl8zudfh00lhJPY1DE7NmZ6bDsT9g2yey8mXljA==", "license": "Apache-2.0", "bin": { "playwright-core": "cli.js" }, "engines": { - "node": ">=18" + "node": ">=20" } }, "node_modules/postcss": { diff --git a/package.json b/package.json index d31af17c..4084c2b6 100644 --- a/package.json +++ b/package.json @@ -50,8 +50,8 @@ "debug": "^4.4.3", "dotenv": "^17.4.2", "mime": "^4.1.0", - "playwright": "1.61.1", - "playwright-core": "1.61.1", + "playwright": "1.62.0", + "playwright-core": "1.62.0", "re2": "^1.24.1", "ws": "^8.21.1", "zod": "^4.4.3" diff --git a/src/tab.ts b/src/tab.ts index f7d38646..e8c0659f 100644 --- a/src/tab.ts +++ b/src/tab.ts @@ -85,7 +85,7 @@ export class Tab extends EventEmitter { listen('dialog', dialog => this._dialogShown(dialog)); // Fires on Playwright >= 1.63 when a dialog is closed out of band (e.g. // dismissed manually in headed mode or via a CDP side-channel); inert on - // the pinned 1.61.1, which never emits it. Without this, a stale dialog + // the pinned 1.62.0, which never emits it. Without this, a stale dialog // modal state blocks every snapshot-bearing tool until the user re-issues // browser_handle_dialog for a dialog that is already gone. listen('dialogclosed', dialog => this._dialogClosed(dialog)); From 4ac5499757cc8304ef08505193ab56cd86b3154f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 30 Jul 2026 05:30:08 +0000 Subject: [PATCH 3/3] fix: recover from dialogs already closed out of band on pinned Playwright Address review feedback on the dialogclosed listener being inert on 1.62.0 (the event ships in 1.63, which has no stable release yet): browser_handle_dialog now treats the two errors an already-closed dialog produces (the 'No dialog is showing' protocol error and the 'already handled' client-side guard, both verified against 1.62.0 Chromium) as a successful close, reporting the dialog as already closed instead of failing. The modal state is cleared either way, so the session recovers on the pinned version; the event listener takes over once Playwright is bumped to 1.63+. Adds unit coverage for the fallback and a real-browser test that reproduces the phantom-dialog scenario end to end: a CDP side-channel closes the dialog behind the tab's back, snapshots show only the stale dialog state, and browser_handle_dialog unblocks the session. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_014k8at4qpjdQnMfRVXX7Xz8 --- README.md | 1 + src/tab.ts | 5 +- src/tools/dialogs.ts | 22 ++++- tests/tools-dialogs.test.ts | 186 ++++++++++++++++++++++++++++++++++++ 4 files changed, 208 insertions(+), 6 deletions(-) create mode 100644 tests/tools-dialogs.test.ts diff --git a/README.md b/README.md index 8d4142f2..e46d5a48 100644 --- a/README.md +++ b/README.md @@ -571,6 +571,7 @@ Wait for text to appear/disappear or time to pass. #### `browser_handle_dialog` Handle browser dialogs (alerts, confirms, prompts). - Parameters: `accept` (boolean), `promptText` (optional) +- If the dialog was already closed outside the session (e.g. dismissed manually in a headed browser), the call succeeds, reports the dialog as already closed, and clears its leftover state instead of failing. #### `browser_file_upload` Upload files to the page. diff --git a/src/tab.ts b/src/tab.ts index e8c0659f..85f5fd62 100644 --- a/src/tab.ts +++ b/src/tab.ts @@ -85,9 +85,10 @@ export class Tab extends EventEmitter { listen('dialog', dialog => this._dialogShown(dialog)); // Fires on Playwright >= 1.63 when a dialog is closed out of band (e.g. // dismissed manually in headed mode or via a CDP side-channel); inert on - // the pinned 1.62.0, which never emits it. Without this, a stale dialog + // the pinned 1.62.0, which never emits it. Until then a stale dialog // modal state blocks every snapshot-bearing tool until the user re-issues - // browser_handle_dialog for a dialog that is already gone. + // browser_handle_dialog, whose already-closed fallback (tools/dialogs.ts) + // recovers the session on the pinned version. listen('dialogclosed', dialog => this._dialogClosed(dialog)); listen('download', download => { void this._downloadStarted(download); diff --git a/src/tools/dialogs.ts b/src/tools/dialogs.ts index c8eb57b2..a9250351 100644 --- a/src/tools/dialogs.ts +++ b/src/tools/dialogs.ts @@ -17,6 +17,14 @@ import { z } from 'zod'; import { defineTabTool } from './tool.js'; +// A dialog closed out of band (dismissed manually in headed mode, or through a +// CDP side-channel) fails accept()/dismiss() with one of these messages — the +// protocol error on the first attempt, the client-side guard on a repeat +// (both verified against Playwright 1.62.0 Chromium). The pinned Playwright +// has no dialogclosed event to observe the close directly, so this error is +// the only remaining signal that the dialog is already gone. +const dialogAlreadyClosedError = /no dialog is showing|dialog which is already handled/i; + const handleDialog = defineTabTool({ capability: 'core', @@ -40,10 +48,16 @@ const handleDialog = defineTabTool({ tab.clearModalState(dialogState); await tab.waitForCompletion(async () => { - if (params.accept) - await dialogState.dialog.accept(params.promptText); - else - await dialogState.dialog.dismiss(); + try { + if (params.accept) + await dialogState.dialog.accept(params.promptText); + else + await dialogState.dialog.dismiss(); + } catch (error) { + if (!(error instanceof Error) || !dialogAlreadyClosedError.test(error.message)) + throw error; + response.addResult('The dialog was already closed out of band; cleared its leftover state.'); + } }); }, diff --git a/tests/tools-dialogs.test.ts b/tests/tools-dialogs.test.ts new file mode 100644 index 00000000..c1713d32 --- /dev/null +++ b/tests/tools-dialogs.test.ts @@ -0,0 +1,186 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { chromium, type Browser, type BrowserContext } from 'playwright'; +import dialogTools from '../src/tools/dialogs.js'; +import { Response } from '../src/response.js'; +import { BrowserServerBackend } from '../src/browserServerBackend.js'; +import { resolveConfig } from '../src/config.js'; +import type { Context } from '../src/context.js'; +import type { Tab } from '../src/tab.js'; + +const handleDialogTool = dialogTools.find(t => t.schema.name === 'browser_handle_dialog')!; + +describe('browser_handle_dialog', () => { + let mockContext: Context; + let mockTab: Tab; + let response: Response; + let dialogState: any; + let dialog: { accept: ReturnType, dismiss: ReturnType }; + + beforeEach(() => { + dialog = { + accept: vi.fn().mockResolvedValue(undefined), + dismiss: vi.fn().mockResolvedValue(undefined), + }; + dialogState = { + type: 'dialog' as const, + description: '"confirm" dialog with message "Proceed?"', + dialog, + }; + mockTab = { + modalStates: vi.fn().mockReturnValue([dialogState]), + modalStatesMarkdown: vi.fn().mockReturnValue([]), + clearModalState: vi.fn(), + waitForCompletion: vi.fn().mockImplementation(async (cb: () => Promise) => await cb()), + } as any; + mockContext = { + currentTabOrDie: () => mockTab, + config: {}, + } as any; + response = new Response(mockContext, 'browser_handle_dialog', {}); + }); + + it('accepts a live dialog and clears its state', async () => { + await handleDialogTool.handle(mockContext, { accept: true, promptText: 'hi' }, response); + + expect(dialog.accept).toHaveBeenCalledWith('hi'); + expect(mockTab.clearModalState).toHaveBeenCalledWith(dialogState); + expect(response.isError()).not.toBe(true); + expect(response.result()).not.toContain('already closed'); + }); + + it('recovers when accept fails because the dialog was closed out of band', async () => { + dialog.accept.mockRejectedValue(new Error('dialog.accept: Protocol error (Page.handleJavaScriptDialog): No dialog is showing')); + + await handleDialogTool.handle(mockContext, { accept: true }, response); + + expect(mockTab.clearModalState).toHaveBeenCalledWith(dialogState); + expect(response.isError()).not.toBe(true); + expect(response.result()).toContain('already closed out of band'); + }); + + it('recovers when dismiss trips the already-handled client guard', async () => { + dialog.dismiss.mockRejectedValue(new Error('Cannot dismiss dialog which is already handled!')); + + await handleDialogTool.handle(mockContext, { accept: false }, response); + + expect(mockTab.clearModalState).toHaveBeenCalledWith(dialogState); + expect(response.isError()).not.toBe(true); + expect(response.result()).toContain('already closed out of band'); + }); + + it('still fails on errors that do not mean the dialog is gone', async () => { + dialog.accept.mockRejectedValue(new Error('dialog.accept: Timeout 5000ms exceeded')); + + await expect(handleDialogTool.handle(mockContext, { accept: true }, response)).rejects.toThrow('Timeout 5000ms exceeded'); + // The state was cleared up front, so the session is not wedged even here. + expect(mockTab.clearModalState).toHaveBeenCalledWith(dialogState); + }); + + it('does not rewrite ordinary text that merely resembles the errors', async () => { + dialog.accept.mockRejectedValue(new Error('page crashed while a dialog was open')); + + await expect(handleDialogTool.handle(mockContext, { accept: true }, response)).rejects.toThrow('page crashed'); + }); +}); + +const hasBundledChromium = await chromium.launch({ headless: true, chromiumSandbox: false }) + .then(async browser => { + await browser.close(); + return true; + }) + .catch(() => false); + +describe.skipIf(!hasBundledChromium)('phantom dialog recovery in a real browser', () => { + let browser: Browser | undefined; + let browserContext: BrowserContext | undefined; + let backend: BrowserServerBackend | undefined; + + afterEach(async () => { + backend?.serverClosed(); + await browserContext?.close().catch(() => undefined); + await browser?.close().catch(() => undefined); + browser = browserContext = backend = undefined; + }); + + it('unblocks the session after a dialog is closed through a CDP side-channel', async () => { + const config = await resolveConfig({ + browser: { + browserName: 'chromium', + isolated: true, + launchOptions: { headless: true, chromiumSandbox: false }, + }, + timeouts: { navigationTimeout: 15000, defaultTimeout: 5000 }, + }); + + backend = new BrowserServerBackend(config, { + createContext: async () => { + browser = await chromium.launch({ headless: true, chromiumSandbox: false }); + browserContext = await browser.newContext(); + await browserContext.route('http://fixture.local/**', route => route.fulfill({ + status: 200, + contentType: 'text/html; charset=utf-8', + body: 'Dialogs', + })); + return { + browserContext, + close: async () => { + await browserContext?.close(); + await browser?.close(); + }, + }; + }, + }); + await backend.initialize({} as any, { name: 'vitest', version: 'dialogs' }, []); + + const navigateResult = await backend.callTool('browser_navigate', { url: 'http://fixture.local/' }); + expect(navigateResult.isError).not.toBe(true); + + // The side-channel must attach before the dialog opens: a session that + // never saw the dialog open cannot handle it, and the paused renderer + // will not answer new attachments while the dialog is up. + const page = browserContext!.pages()[0]; + const cdp = await browserContext!.newCDPSession(page); + await cdp.send('Page.enable'); + + const evaluateResult = await backend.callTool('browser_evaluate', { function: '() => confirm("out of band?")' }); + expect((evaluateResult.content[0] as any).text).toContain('"confirm" dialog with message "out of band?"'); + + // Close the dialog behind the tab's back, as a human would in headed mode. + await cdp.send('Page.handleJavaScriptDialog', { accept: false }); + + // The tab never learns of the close on Playwright 1.62 (no dialogclosed + // event), so the stale modal state still starves snapshot-bearing tools: + // the response shows only the phantom dialog, never the page content. + const blockedResult = await backend.callTool('browser_snapshot', {}); + const blockedText = (blockedResult.content[0] as any).text as string; + expect(blockedText).toContain('"confirm" dialog with message "out of band?"'); + expect(blockedText).not.toContain('button "Ok"'); + + // ...but handling the phantom dialog recovers instead of dead-ending. + const handleResult = await backend.callTool('browser_handle_dialog', { accept: true }); + expect(handleResult.isError).not.toBe(true); + expect((handleResult.content[0] as any).text).toContain('already closed out of band'); + + const recoveredResult = await backend.callTool('browser_snapshot', {}); + expect(recoveredResult.isError).not.toBe(true); + const recoveredText = (recoveredResult.content[0] as any).text as string; + expect(recoveredText).toContain('button "Ok"'); + expect(recoveredText).not.toContain('"confirm" dialog'); + }); +});