Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

fix(mcp): recover from page renderer crash (#40617)

Yury Semikhatsky1109b9bcce14
diff --git a/packages/playwright-core/src/tools/backend/context.ts b/packages/playwright-core/src/tools/backend/context.ts
index 852ff4c2eb..c1604bd83a 100644
--- a/packages/playwright-core/src/tools/backend/context.ts
+++ b/packages/playwright-core/src/tools/backend/context.ts
@@ -180,9 +180,16 @@ export class Context {
}
async ensureTab(): Promise<Tab> {
- const browserContext = await this.ensureBrowserContext();
+ await this.ensureBrowserContext();
+ const crashed = this._currentTab?.crashed;
+ if (crashed) {
+ await this._currentTab!.page.close().catch(() => {});
+ this._currentTab = undefined;
+ }
if (!this._currentTab)
- await browserContext.newPage();
+ await this.newTab();
+ if (crashed)
+ this._currentTab!.logErrorMessage('Page crashed and was reset to about:blank.');
return this._currentTab!;
}
diff --git a/packages/playwright-core/src/tools/backend/response.ts b/packages/playwright-core/src/tools/backend/response.ts
index eda678a846..54eb8c0cf6 100644
--- a/packages/playwright-core/src/tools/backend/response.ts
+++ b/packages/playwright-core/src/tools/backend/response.ts
@@ -300,6 +300,8 @@ export function renderTabMarkdown(tab: TabHeader): string[] {
const lines = [`- Page URL: ${tab.url}`];
if (tab.title)
lines.push(`- Page Title: ${tab.title}`);
+ if (tab.crashed)
+ lines.push(`- Page status: crashed`);
if (tab.console.errors || tab.console.warnings)
lines.push(`- Console: ${tab.console.errors} errors, ${tab.console.warnings} warnings`);
return lines;
@@ -313,7 +315,8 @@ export function renderTabsMarkdown(tabs: TabHeader[]): string[] {
for (let i = 0; i < tabs.length; i++) {
const tab = tabs[i];
const current = tab.current ? ' (current)' : '';
- lines.push(`- ${i}:${current} [${tab.title}](${tab.url})`);
+ const crashed = tab.crashed ? ' [crashed]' : '';
+ lines.push(`- ${i}:${current} [${tab.title}](${tab.url})${crashed}`);
}
return lines;
}
diff --git a/packages/playwright-core/src/tools/backend/tab.ts b/packages/playwright-core/src/tools/backend/tab.ts
index 0fac1073be..65e85c1ae1 100644
--- a/packages/playwright-core/src/tools/backend/tab.ts
+++ b/packages/playwright-core/src/tools/backend/tab.ts
@@ -76,6 +76,7 @@ export type TabHeader = {
title: string;
url: string;
current: boolean;
+ crashed: boolean;
console: { total: number, warnings: number, errors: number };
};
@@ -89,10 +90,11 @@ type TabSnapshot = {
export class Tab extends EventEmitter<TabEventsInterface> {
readonly context: Context;
readonly page: playwright.Page;
- private _lastHeader: TabHeader = { title: 'about:blank', url: 'about:blank', current: false, console: { total: 0, warnings: 0, errors: 0 } };
+ private _lastHeader: TabHeader = { title: 'about:blank', url: 'about:blank', current: false, crashed: false, console: { total: 0, warnings: 0, errors: 0 } };
private _downloads: Download[] = [];
private _requests: playwright.Request[] = [];
private _onPageClose: (tab: Tab) => void;
+ crashed = false;
private _modalStates: ModalState[] = [];
private _initializedPromise: Promise<void>;
private _recentEventEntries: EventEntry[] = [];
@@ -115,6 +117,7 @@ export class Tab extends EventEmitter<TabEventsInterface> {
eventsHelper.addEventListener(p, 'response', response => this._handleResponse(response)),
eventsHelper.addEventListener(p, 'requestfailed', request => this._handleRequestFailed(request)),
eventsHelper.addEventListener(p, 'close', () => this._onClose()),
+ eventsHelper.addEventListener(p, 'crash', () => { this.crashed = true; }),
eventsHelper.addEventListener(p, 'filechooser', chooser => {
this.setModalState({
type: 'fileChooser',
@@ -254,6 +257,10 @@ export class Tab extends EventEmitter<TabEventsInterface> {
this._consoleLog.appendLine(wallTime, message.toString());
}
+ logErrorMessage(text: string) {
+ this._handleConsoleMessage(pageErrorToConsoleMessage(new Error(text)));
+ }
+
private _addLogEntry(entry: EventEntry) {
this._recentEventEntries.push(entry);
}
@@ -265,14 +272,19 @@ export class Tab extends EventEmitter<TabEventsInterface> {
async headerSnapshot(): Promise<TabHeader & { changed: boolean }> {
let title: string | undefined;
- await this._raceAgainstModalStates(async () => {
- title = await this.page.title();
- });
+ let consoleCounts = { total: 0, errors: 0, warnings: 0 };
+ if (!this.crashed) {
+ await this._raceAgainstModalStates(async () => {
+ title = await this.page.title();
+ });
+ consoleCounts = await this.consoleMessageCount();
+ }
const newHeader: TabHeader = {
title: title ?? '',
url: this.page.url(),
current: this.isCurrentTab(),
- console: await this.consoleMessageCount()
+ crashed: this.crashed,
+ console: consoleCounts,
};
if (!tabHeaderEquals(this._lastHeader, newHeader)) {
@@ -570,6 +582,7 @@ function tabHeaderEquals(a: TabHeader, b: TabHeader): boolean {
return a.title === b.title &&
a.url === b.url &&
a.current === b.current &&
+ a.crashed === b.crashed &&
a.console.errors === b.console.errors &&
a.console.warnings === b.console.warnings &&
a.console.total === b.console.total;
diff --git a/tests/mcp/crash.spec.ts b/tests/mcp/crash.spec.ts
new file mode 100644
index 0000000000..51fb603984
--- /dev/null
+++ b/tests/mcp/crash.spec.ts
@@ -0,0 +1,84 @@
+/**
+ * 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 { utils } from '../../packages/playwright-core/lib/coreBundle';
+import { test, expect, parseResponse, consoleEntries } from './fixtures';
+
+test.describe('crash recovery', () => {
+ test.skip(({ mcpBrowser }) => mcpBrowser !== 'chromium' && mcpBrowser !== 'chrome', 'chrome://crash is chromium-specific');
+ test.skip(utils.hostPlatform.startsWith('ubuntu24.04'), 'never dispatches the crash event');
+
+ test.beforeEach(async ({ client, server }) => {
+ await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: server.HELLO_WORLD },
+ });
+ });
+
+ test('resets to about:blank and logs the crash', async ({ client, server }) => {
+ await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: 'chrome://crash' },
+ });
+
+ const response = parseResponse(await client.callTool({
+ name: 'browser_snapshot',
+ }));
+ expect(response.page).toBe('- Page URL: about:blank');
+
+ const log = await consoleEntries(response);
+ expect(log).toContain('Page crashed and was reset to about:blank.');
+
+ expect(await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: server.HELLO_WORLD },
+ })).toHaveResponse({
+ page: `- Page URL: ${server.HELLO_WORLD}\n- Page Title: Title`,
+ });
+ });
+
+ test('lists only one tab', async ({ client }) => {
+ await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: 'chrome://crash' },
+ });
+
+ expect(await client.callTool({
+ name: 'browser_tabs',
+ arguments: { action: 'list' },
+ })).toHaveResponse({
+ result: `- 0: (current) [](about:blank)`,
+ });
+ });
+
+ test('marks non-current crashed tab in the tab list', async ({ client, server }) => {
+ await client.callTool({
+ name: 'browser_tabs',
+ arguments: { action: 'new', url: 'chrome://crash' },
+ });
+ await client.callTool({
+ name: 'browser_tabs',
+ arguments: { action: 'select', index: 0 },
+ });
+
+ expect(await client.callTool({
+ name: 'browser_tabs',
+ arguments: { action: 'list' },
+ })).toHaveResponse({
+ result: `- 0: (current) [Title](${server.HELLO_WORLD})\n- 1: [](about:blank) [crashed]`,
+ });
+ });
+});