Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore: implement browser restart on headless mismatch (#38896)
Pavel Feldman8cdce5ab8b84
diff --git a/packages/playwright/src/mcp/browser/browserContextFactory.ts b/packages/playwright/src/mcp/browser/browserContextFactory.tsindex abec50f070..24dae33682 100644--- a/packages/playwright/src/mcp/browser/browserContextFactory.ts+++ b/packages/playwright/src/mcp/browser/browserContextFactory.ts@@ -47,13 +47,21 @@ export type BrowserContextFactoryResult = {close: () => Promise<void>;};+export type HeadlessOption = {+ forceHeadless?: 'headless' | 'headed';+};++type CreateContextOptions = HeadlessOption & {+ toolName?: string;+};+export interface BrowserContextFactory {- createContext(clientInfo: ClientInfo, abortSignal: AbortSignal, toolName: string | undefined): Promise<BrowserContextFactoryResult>;+ createContext(clientInfo: ClientInfo, abortSignal: AbortSignal, options: CreateContextOptions): Promise<BrowserContextFactoryResult>;}export function identityBrowserContextFactory(browserContext: playwright.BrowserContext): BrowserContextFactory {return {- createContext: async (clientInfo: ClientInfo, abortSignal: AbortSignal, toolName: string | undefined) => {+ createContext: async (clientInfo: ClientInfo, abortSignal: AbortSignal, options: CreateContextOptions) => {return {browserContext,close: async () => {}@@ -72,11 +80,11 @@ class BaseContextFactory implements BrowserContextFactory {this.config = config;}- protected async _obtainBrowser(clientInfo: ClientInfo): Promise<playwright.Browser> {+ protected async _obtainBrowser(clientInfo: ClientInfo, options: CreateContextOptions): Promise<playwright.Browser> {if (this._browserPromise)return this._browserPromise;testDebug(`obtain browser (${this._logName})`);- this._browserPromise = this._doObtainBrowser(clientInfo);+ this._browserPromise = this._doObtainBrowser(clientInfo, options);void this._browserPromise.then(browser => {browser.on('disconnected', () => {this._browserPromise = undefined;@@ -87,13 +95,13 @@ class BaseContextFactory implements BrowserContextFactory {return this._browserPromise;}- protected async _doObtainBrowser(clientInfo: ClientInfo): Promise<playwright.Browser> {+ protected async _doObtainBrowser(clientInfo: ClientInfo, options: CreateContextOptions): Promise<playwright.Browser> {throw new Error('Not implemented');}- async createContext(clientInfo: ClientInfo): Promise<BrowserContextFactoryResult> {+ async createContext(clientInfo: ClientInfo, _: AbortSignal, options: CreateContextOptions): Promise<BrowserContextFactoryResult> {testDebug(`create browser context (${this._logName})`);- const browser = await this._obtainBrowser(clientInfo);+ const browser = await this._obtainBrowser(clientInfo, options);const browserContext = await this._doCreateContext(browser, clientInfo);await addInitScript(browserContext, this.config.browser.initScript);return {@@ -123,7 +131,7 @@ class IsolatedContextFactory extends BaseContextFactory {super('isolated', config);}- protected override async _doObtainBrowser(clientInfo: ClientInfo): Promise<playwright.Browser> {+ protected override async _doObtainBrowser(clientInfo: ClientInfo, options: CreateContextOptions): Promise<playwright.Browser> {await injectCdpPort(this.config.browser);const browserType = playwright[this.config.browser.browserName];const tracesDir = await computeTracesDir(this.config, clientInfo);@@ -134,6 +142,7 @@ class IsolatedContextFactory extends BaseContextFactory {...this.config.browser.launchOptions,handleSIGINT: false,handleSIGTERM: false,+ ...(options.forceHeadless !== undefined ? { headless: options.forceHeadless === 'headless' } : {}),}).catch(error => {if (error.message.includes('Executable doesn\'t exist'))throw new Error(`Browser specified in your config is not installed. Either install it (likely) or change the config.`);@@ -192,7 +201,7 @@ class PersistentContextFactory implements BrowserContextFactory {this.config = config;}- async createContext(clientInfo: ClientInfo): Promise<BrowserContextFactoryResult> {+ async createContext(clientInfo: ClientInfo, abortSignal: AbortSignal, options: CreateContextOptions): Promise<BrowserContextFactoryResult> {await injectCdpPort(this.config.browser);testDebug('create browser context (persistent)');const userDataDir = this.config.browser.userDataDir ?? await this._createUserDataDir(clientInfo);@@ -215,6 +224,7 @@ class PersistentContextFactory implements BrowserContextFactory {'--disable-extensions',],assistantMode: true,+ ...(options.forceHeadless !== undefined ? { headless: options.forceHeadless === 'headless' } : {}),};try {const browserContext = await browserType.launchPersistentContext(userDataDir, launchOptions);@@ -317,10 +327,10 @@ export class SharedContextFactory implements BrowserContextFactory {this._baseFactory = baseFactory;}- async createContext(clientInfo: ClientInfo, abortSignal: AbortSignal, toolName: string | undefined): Promise<{ browserContext: playwright.BrowserContext, close: () => Promise<void> }> {+ async createContext(clientInfo: ClientInfo, abortSignal: AbortSignal, options: { toolName?: string }): Promise<{ browserContext: playwright.BrowserContext, close: () => Promise<void> }> {if (!this._contextPromise) {testDebug('create shared browser context');- this._contextPromise = this._baseFactory.createContext(clientInfo, abortSignal, toolName);+ this._contextPromise = this._baseFactory.createContext(clientInfo, abortSignal, options);}const { browserContext } = await this._contextPromise;diff --git a/packages/playwright/src/mcp/browser/context.ts b/packages/playwright/src/mcp/browser/context.tsindex c0e3e80b7c..9d87c5bc7e 100644--- a/packages/playwright/src/mcp/browser/context.ts+++ b/packages/playwright/src/mcp/browser/context.ts@@ -30,6 +30,7 @@ import type { BrowserContextFactory, BrowserContextFactoryResult } from './browsimport type { SessionLog } from './sessionLog';import type { Tracing } from '../../../../playwright-core/src/client/tracing';import type { ClientInfo } from '../sdk/server';+import type { HeadlessOption } from './browserContextFactory';const testDebug = debug('pw:mcp:test');@@ -45,6 +46,7 @@ export class Context {readonly sessionLog: SessionLog | undefined;readonly options: ContextOptions;private _browserContextPromise: Promise<BrowserContextFactoryResult> | undefined;+ private _browserContextOption: HeadlessOption | undefined;private _browserContextFactory: BrowserContextFactory;private _tabs: Tab[] = [];private _currentTab: Tab | undefined;@@ -84,7 +86,7 @@ export class Context {}async newTab(): Promise<Tab> {- const { browserContext } = await this._ensureBrowserContext();+ const { browserContext } = await this._ensureBrowserContext({});const page = await browserContext.newPage();this._currentTab = this._tabs.find(t => t.page === page)!;return this._currentTab;@@ -99,8 +101,8 @@ export class Context {return tab;}- async ensureTab(): Promise<Tab> {- const { browserContext } = await this._ensureBrowserContext();+ async ensureTab(options: HeadlessOption = {}): Promise<Tab> {+ const { browserContext } = await this._ensureBrowserContext(options);if (!this._currentTab)await browserContext.newPage();return this._currentTab!;@@ -161,6 +163,7 @@ export class Context {const promise = this._browserContextPromise;this._browserContextPromise = undefined;+ this._browserContextOption = undefined;await promise.then(async ({ browserContext, close }) => {if (this.config.saveTrace)@@ -189,29 +192,33 @@ export class Context {}}- async ensureBrowserContext(): Promise<playwright.BrowserContext> {- const { browserContext } = await this._ensureBrowserContext();+ async ensureBrowserContext(options: HeadlessOption = {}): Promise<playwright.BrowserContext> {+ const { browserContext } = await this._ensureBrowserContext(options);return browserContext;}- private _ensureBrowserContext() {- if (!this._browserContextPromise) {- this._browserContextPromise = this._setupBrowserContext();- this._browserContextPromise.catch(() => {- this._browserContextPromise = undefined;- });- }+ private _ensureBrowserContext(options: HeadlessOption) {+ if (this._browserContextPromise && (options.forceHeadless === undefined || this._browserContextOption?.forceHeadless === options.forceHeadless))+ return this._browserContextPromise;++ const closePrework = this._browserContextPromise ? this.closeBrowserContext() : Promise.resolve();+ this._browserContextPromise = closePrework.then(() => this._setupBrowserContext(options));+ this._browserContextPromise.catch(() => {+ this._browserContextPromise = undefined;+ this._browserContextOption = undefined;+ });+ this._browserContextOption = options;return this._browserContextPromise;}- private async _setupBrowserContext(): Promise<BrowserContextFactoryResult> {+ private async _setupBrowserContext(options: HeadlessOption): Promise<BrowserContextFactoryResult> {if (this._closeBrowserContextPromise)throw new Error('Another browser context is being closed.');// TODO: move to the browser context factory to make it based on isolation mode.if (this.config.testIdAttribute)selectors.setTestIdAttribute(this.config.testIdAttribute);- const result = await this._browserContextFactory.createContext(this._clientInfo, this._abortController.signal, this._runningToolName);+ const result = await this._browserContextFactory.createContext(this._clientInfo, this._abortController.signal, { toolName: this._runningToolName, ...options });const { browserContext } = result;if (!this.config.allowUnrestrictedFileAccess) {(browserContext as any)._setAllowedProtocols(['http:', 'https:', 'about:', 'data:']);diff --git a/packages/playwright/src/mcp/browser/tools.ts b/packages/playwright/src/mcp/browser/tools.tsindex d33da63e0d..efc6a88649 100644--- a/packages/playwright/src/mcp/browser/tools.ts+++ b/packages/playwright/src/mcp/browser/tools.ts@@ -25,6 +25,7 @@ import keyboard from './tools/keyboard';import mouse from './tools/mouse';import navigate from './tools/navigate';import network from './tools/network';+import open from './tools/open';import pdf from './tools/pdf';import runCode from './tools/runCode';import snapshot from './tools/snapshot';@@ -46,9 +47,10 @@ export const browserTools: Tool<any>[] = [...form,...install,...keyboard,+ ...mouse,...navigate,...network,- ...mouse,+ ...open,...pdf,...runCode,...screenshot,diff --git a/packages/playwright/src/mcp/browser/tools/open.ts b/packages/playwright/src/mcp/browser/tools/open.tsnew file mode 100644index 0000000000..245473b865--- /dev/null+++ b/packages/playwright/src/mcp/browser/tools/open.ts@@ -0,0 +1,56 @@+/**+ * 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 { z } from 'playwright-core/lib/mcpBundle';+import { defineTool } from './tool';++const open = defineTool({+ capability: 'internal',++ schema: {+ name: 'browser_open',+ title: 'Open URL',+ description: 'Open a URL in the browser',+ inputSchema: z.object({+ url: z.string().describe('The URL to open'),+ headed: z.boolean().optional().describe('Run browser in headed mode'),+ }),+ type: 'action',+ },++ handle: async (context, params, response) => {+ const forceHeadless = params.headed ? 'headed' : 'headless';+ const tab = await context.ensureTab({ forceHeadless });+ let url = params.url;+ try {+ new URL(url);+ } catch (e) {+ if (url.startsWith('localhost'))+ url = 'http://' + url;+ else+ url = 'https://' + url;+ }++ await tab.navigate(url);++ response.setIncludeSnapshot();+ response.addCode(`await page.goto('${params.url}');`);+ },+});++export default [+ open,+];diff --git a/packages/playwright/src/mcp/config.d.ts b/packages/playwright/src/mcp/config.d.tsindex 513d12dc30..5f82604f13 100644--- a/packages/playwright/src/mcp/config.d.ts+++ b/packages/playwright/src/mcp/config.d.ts@@ -16,7 +16,7 @@import type * as playwright from 'playwright-core';-export type ToolCapability = 'core' | 'core-tabs' | 'core-install' | 'vision' | 'pdf' | 'testing' | 'tracing';+export type ToolCapability = 'core' | 'core-tabs' | 'core-install' | 'vision' | 'pdf' | 'testing' | 'tracing' | 'internal';export type Config = {/**diff --git a/packages/playwright/src/mcp/extension/extensionContextFactory.ts b/packages/playwright/src/mcp/extension/extensionContextFactory.tsindex c6bc1cb51f..6783d7b62c 100644--- a/packages/playwright/src/mcp/extension/extensionContextFactory.ts+++ b/packages/playwright/src/mcp/extension/extensionContextFactory.ts@@ -36,8 +36,8 @@ export class ExtensionContextFactory implements BrowserContextFactory {this._executablePath = executablePath;}- async createContext(clientInfo: ClientInfo, abortSignal: AbortSignal, toolName: string | undefined): Promise<{ browserContext: playwright.BrowserContext, close: () => Promise<void> }> {- const browser = await this._obtainBrowser(clientInfo, abortSignal, toolName);+ async createContext(clientInfo: ClientInfo, abortSignal: AbortSignal, options: { toolName?: string }): Promise<{ browserContext: playwright.BrowserContext, close: () => Promise<void> }> {+ const browser = await this._obtainBrowser(clientInfo, abortSignal, options?.toolName);return {browserContext: browser.contexts()[0],close: async () => {diff --git a/packages/playwright/src/mcp/program.ts b/packages/playwright/src/mcp/program.tsindex 452b6d6d18..d09ee22a64 100644--- a/packages/playwright/src/mcp/program.ts+++ b/packages/playwright/src/mcp/program.ts@@ -116,6 +116,7 @@ export function decorateCommand(command: Command, version: string) {config.outputMode = 'file';config.codegen = 'none';config.snapshot.mode = 'full';+ config.capabilities = ['core', 'internal', 'tracing', 'pdf', 'vision'];const serverBackendFactory: mcpServer.ServerBackendFactory = {name: 'Playwright',diff --git a/packages/playwright/src/mcp/terminal/cli.ts b/packages/playwright/src/mcp/terminal/cli.tsindex da6b904f6b..25ba506b02 100644--- a/packages/playwright/src/mcp/terminal/cli.ts+++ b/packages/playwright/src/mcp/terminal/cli.ts@@ -32,8 +32,8 @@ const debugCli = debug('pw:cli');const packageJSON = require('../../../package.json');-async function runCliCommand(args: any, options: { headless?: boolean } = {}) {- const session = await connectToDaemon(options);+async function runCliCommand(args: any) {+ const session = await connectToDaemon();const result = await session.runCliCommand(args);console.log(result);session.dispose();@@ -130,7 +130,7 @@ function daemonSocketPath(): string {return path.resolve(playwrightCacheDir(), 'daemon', socketDir, socketName);}-async function connectToDaemon(options: { headless?: boolean }): Promise<SocketSession> {+async function connectToDaemon(): Promise<SocketSession> {const socketPath = daemonSocketPath();debugCli(`Connecting to daemon at ${socketPath}`);@@ -147,7 +147,7 @@ async function connectToDaemon(options: { headless?: boolean }): Promise<SocketSconst cliPath = path.join(__dirname, '../../../cli.js');debugCli(`Will launch daemon process: ${cliPath}`);- const child = spawn(process.execPath, [cliPath, 'run-mcp-server', `--daemon=${socketPath}`, ...(options.headless ? ['--headless'] : [])], {+ const child = spawn(process.execPath, [cliPath, 'run-mcp-server', `--daemon=${socketPath}`], {detached: true,stdio: 'ignore',cwd: process.cwd(), // Will be used as root.diff --git a/packages/playwright/src/mcp/terminal/commands.ts b/packages/playwright/src/mcp/terminal/commands.tsindex 41006924c1..7fb195b842 100644--- a/packages/playwright/src/mcp/terminal/commands.ts+++ b/packages/playwright/src/mcp/terminal/commands.ts@@ -132,7 +132,7 @@ const open = declareCommand({options: z.object({headed: z.boolean().default(false).describe('Run browser in headed mode'),}),- toolName: 'browser_navigate',+ toolName: 'browser_open',toolParams: ({ url }, { headed }) => ({ url, headed }),});diff --git a/tests/mcp/generator.spec.ts b/tests/mcp/generator.spec.tsindex af3a1b3695..8aab01b679 100644--- a/tests/mcp/generator.spec.ts+++ b/tests/mcp/generator.spec.ts@@ -45,6 +45,7 @@ test('generator tools intent', async ({ startClient }) => {'browser_mouse_move_xy','browser_navigate','browser_navigate_back',+ 'browser_open','browser_press_key','browser_resize','browser_run_code',