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
fix(mcp): respect fs-based lock file for chromium family (#39377)
Pavel Feldmanaa71b38b9191
diff --git a/packages/playwright/src/mcp/browser/browserContextFactory.ts b/packages/playwright/src/mcp/browser/browserContextFactory.tsindex a5e1cffd65..9beb6a87dd 100644--- a/packages/playwright/src/mcp/browser/browserContextFactory.ts+++ b/packages/playwright/src/mcp/browser/browserContextFactory.ts@@ -190,8 +190,6 @@ class PersistentContextFactory implements BrowserContextFactory {readonly name = 'persistent';readonly description = 'Create a new persistent browser context';- private _userDataDirs = new Set<string>();-constructor(config: FullConfig) {this.config = config;}@@ -204,52 +202,45 @@ class PersistentContextFactory implements BrowserContextFactory {if (tracesDir && this.config.saveTrace)await startTraceServer(this.config, tracesDir);- this._userDataDirs.add(userDataDir);+ if (await isProfileLocked5Times(userDataDir))+ throw new Error(`User data directory ${userDataDir} is already in use by another browser process. Use --isolated to run multiple instances of the same browser.`);+testDebug('lock user data dir', userDataDir);const browserType = playwright[this.config.browser.browserName];- for (let i = 0; i < 5; i++) {- const launchOptions: LaunchOptions & BrowserContextOptions = {- tracesDir,- ...this.config.browser.launchOptions,- ...await browserContextOptionsFromConfig(this.config, clientInfo),- handleSIGINT: false,- handleSIGTERM: false,- ignoreDefaultArgs: [- '--disable-extensions',- ],- assistantMode: true,- };- try {- const browserContext = await browserType.launchPersistentContext(userDataDir, launchOptions);- await addInitScript(browserContext, this.config.browser.initScript);- const close = () => this._closeBrowserContext(browserContext, userDataDir);- return { browserContext, close };- } catch (error: any) {- if (error.message.includes('Executable doesn\'t exist'))- throwBrowserIsNotInstalledError(this.config);- if (error.message.includes('cannot open shared object file: No such file or directory')) {- const browserName = launchOptions.channel ?? this.config.browser.browserName;- throw new Error(`Missing system dependencies required to run browser ${browserName}. Install them with: sudo npx playwright install-deps ${browserName}`);- }- if (error.message.includes('ProcessSingleton') ||- // On Windows the process exits silently with code 21 when the profile is in use.- error.message.includes('exitCode=21')) {- // User data directory is already in use, try again.- await new Promise(resolve => setTimeout(resolve, 1000));- continue;- }- throw error;+ const launchOptions: LaunchOptions & BrowserContextOptions = {+ tracesDir,+ ...this.config.browser.launchOptions,+ ...await browserContextOptionsFromConfig(this.config, clientInfo),+ handleSIGINT: false,+ handleSIGTERM: false,+ ignoreDefaultArgs: [+ '--disable-extensions',+ ],+ assistantMode: true,+ };+ try {+ const browserContext = await browserType.launchPersistentContext(userDataDir, launchOptions);+ await addInitScript(browserContext, this.config.browser.initScript);+ const close = () => this._closeBrowserContext(browserContext, userDataDir);+ return { browserContext, close };+ } catch (error: any) {+ if (error.message.includes('Executable doesn\'t exist'))+ throwBrowserIsNotInstalledError(this.config);+ if (error.message.includes('cannot open shared object file: No such file or directory')) {+ const browserName = launchOptions.channel ?? this.config.browser.browserName;+ throw new Error(`Missing system dependencies required to run browser ${browserName}. Install them with: sudo npx playwright install-deps ${browserName}`);}+ if (error.message.includes('ProcessSingleton') || error.message.includes('exitCode=21'))+ throw new Error(`Browser is already in use for ${userDataDir}, use --isolated to run multiple instances of the same browser`);+ throw error;}- throw new Error(`Browser is already in use for ${userDataDir}, use --isolated to run multiple instances of the same browser`);}private async _closeBrowserContext(browserContext: playwright.BrowserContext, userDataDir: string) {testDebug('close browser context (persistent)');testDebug('release user data dir', userDataDir);await browserContext.close().catch(() => {});- this._userDataDirs.delete(userDataDir);if (process.env.PWMCP_PROFILES_DIR_FOR_TEST && userDataDir.startsWith(process.env.PWMCP_PROFILES_DIR_FOR_TEST))await fs.promises.rm(userDataDir, { recursive: true }).catch(logUnhandledError);testDebug('close browser context complete (persistent)');@@ -367,6 +358,41 @@ async function browserContextOptionsFromConfig(config: FullConfig, clientInfo: Creturn result;}+async function isProfileLocked5Times(userDataDir: string): Promise<boolean> {+ for (let i = 0; i < 5; i++) {+ if (!isProfileLocked(userDataDir))+ return false;+ await new Promise(f => setTimeout(f, 1000));+ }+ return true;+}++export function isProfileLocked(userDataDir: string): boolean {+ const lockFile = process.platform === 'win32' ? 'lockfile' : 'SingletonLock';+ const lockPath = path.join(userDataDir, lockFile);++ if (process.platform === 'win32') {+ try {+ const fd = fs.openSync(lockPath, 'r+');+ fs.closeSync(fd);+ return false;+ } catch (e: any) {+ return e.code !== 'ENOENT';+ }+ }++ try {+ const target = fs.readlinkSync(lockPath);+ const pid = parseInt(target.split('-').pop() || '', 10);+ if (isNaN(pid))+ return false;+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+}+function throwBrowserIsNotInstalledError(config: FullConfig): never {const channel = config.browser.launchOptions?.channel ?? config.browser.browserName;if (config.skillMode)diff --git a/tests/mcp/profile-lock.spec.ts b/tests/mcp/profile-lock.spec.tsnew file mode 100644index 0000000000..3d902e4551--- /dev/null+++ b/tests/mcp/profile-lock.spec.ts@@ -0,0 +1,96 @@+/**+ * 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 { chromium } from 'playwright';++import { test, expect } from './fixtures';+import { isProfileLocked } from '../../packages/playwright/lib/mcp/browser/browserContextFactory';++test('isProfileLocked returns false for empty directory', async ({ mcpBrowser }, testInfo) => {+ test.skip(!['chromium', 'chrome', 'msedge'].includes(mcpBrowser!), 'Chromium-only');+ const dir = testInfo.outputPath('profile');+ expect(isProfileLocked(dir)).toBe(false);+});++test('isProfileLocked detects a real browser holding the profile', async ({ mcpBrowser }, testInfo) => {+ test.skip(!['chromium', 'chrome', 'msedge'].includes(mcpBrowser!), 'Chromium-only');+ const userDataDir = testInfo.outputPath('user-data-dir');+ const context = await chromium.launchPersistentContext(userDataDir, {+ channel: mcpBrowser === 'chromium' ? undefined : mcpBrowser,+ headless: true,+ });+ try {+ expect(isProfileLocked(userDataDir)).toBe(true);+ } finally {+ await context.close();+ }+});++test('isProfileLocked returns false after browser closes', async ({ mcpBrowser }, testInfo) => {+ test.skip(!['chromium', 'chrome', 'msedge'].includes(mcpBrowser!), 'Chromium-only');+ const userDataDir = testInfo.outputPath('user-data-dir');+ const context = await chromium.launchPersistentContext(userDataDir, {+ channel: mcpBrowser === 'chromium' ? undefined : mcpBrowser,+ headless: true,+ });+ await context.close();+ expect(isProfileLocked(userDataDir)).toBe(false);+});++test('locked profile produces actionable error on navigate', async ({ mcpBrowser, startClient, server }, testInfo) => {+ test.skip(!['chromium', 'chrome', 'msedge'].includes(mcpBrowser!), 'Chromium-only');+ const userDataDir = testInfo.outputPath('user-data-dir');+ const context = await chromium.launchPersistentContext(userDataDir, {+ channel: mcpBrowser,+ headless: true,+ });+ try {+ const { client } = await startClient({+ args: [`--user-data-dir=${userDataDir}`],+ });+ const result = await client.callTool({+ name: 'browser_navigate',+ arguments: { url: server.HELLO_WORLD },+ });+ expect(result).toHaveResponse({+ isError: true,+ error: expect.stringContaining('already in use'),+ });+ } finally {+ await context.close();+ }+});++test('stale profile does not prevent browser launch', async ({ mcpBrowser, startClient, server }, testInfo) => {+ test.skip(!['chromium', 'chrome', 'msedge'].includes(mcpBrowser!), 'Chromium-only');+ const userDataDir = testInfo.outputPath('user-data-dir');+ // Launch and close a browser to leave behind a stale user data dir.+ const context = await chromium.launchPersistentContext(userDataDir, {+ channel: mcpBrowser,+ headless: true,+ });+ await context.close();++ const { client } = await startClient({+ args: [`--user-data-dir=${userDataDir}`],+ });+ expect(await client.callTool({+ name: 'browser_navigate',+ arguments: { url: server.HELLO_WORLD },+ })).toHaveResponse({+ snapshot: expect.stringContaining('Hello, world!'),+ });+});