Skip to content

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

Revert "fix(mcp): wait if profile is still in use (#37303)" (#37319)

Yury Semikhatskya14094d36446
diff --git a/packages/playwright/src/mcp/browser/browserContextFactory.ts b/packages/playwright/src/mcp/browser/browserContextFactory.ts
index d2e9f7de31..e4320b3a1a 100644
--- a/packages/playwright/src/mcp/browser/browserContextFactory.ts
+++ b/packages/playwright/src/mcp/browser/browserContextFactory.ts
@@ -22,7 +22,6 @@ import path from 'path';
import * as playwright from 'playwright-core';
import { registryDirectory } from 'playwright-core/lib/server/registry/index';
import { startTraceViewerServer } from 'playwright-core/lib/server';
-import { findBrowserProcess, getBrowserExecPath } from './processUtils';
import { logUnhandledError, testDebug } from '../log';
import { outputFile } from './config';
@@ -175,28 +174,28 @@ class PersistentContextFactory implements BrowserContextFactory {
const browserType = playwright[this.config.browser.browserName];
for (let i = 0; i < 5; i++) {
- if (!await alreadyRunning(this.config, browserType, userDataDir))
- break;
- // User data directory is already in use, wait for the previous browser instance to close.
- await new Promise(resolve => setTimeout(resolve, 1000));
- }
- try {
- const browserContext = await browserType.launchPersistentContext(userDataDir, {
- tracesDir,
- ...this.config.browser.launchOptions,
- ...this.config.browser.contextOptions,
- handleSIGINT: false,
- handleSIGTERM: false,
- });
- const close = () => this._closeBrowserContext(browserContext, userDataDir);
- return { browserContext, close };
- } catch (error: any) {
- 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.`);
- if (error.message.includes('ProcessSingleton') || error.message.includes('Invalid URL'))
- throw new Error(`Browser is already in use for ${userDataDir}, use --isolated to run multiple instances of the same browser`);
- throw error;
+ try {
+ const browserContext = await browserType.launchPersistentContext(userDataDir, {
+ tracesDir,
+ ...this.config.browser.launchOptions,
+ ...this.config.browser.contextOptions,
+ handleSIGINT: false,
+ handleSIGTERM: false,
+ });
+ const close = () => this._closeBrowserContext(browserContext, userDataDir);
+ return { browserContext, close };
+ } catch (error: any) {
+ 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.`);
+ if (error.message.includes('ProcessSingleton') || error.message.includes('Invalid URL')) {
+ // User data directory is already in use, try again.
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ continue;
+ }
+ 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) {
@@ -218,13 +217,6 @@ class PersistentContextFactory implements BrowserContextFactory {
}
}
-async function alreadyRunning(config: FullConfig, browserType: playwright.BrowserType, userDataDir: string) {
- const execPath = config.browser.launchOptions.executablePath ?? getBrowserExecPath(config.browser.launchOptions.channel ?? browserType.name());
- if (!execPath)
- return false;
- return !!findBrowserProcess(execPath, userDataDir);
-}
-
async function injectCdpPort(browserConfig: FullConfig['browser']) {
if (browserConfig.browserName === 'chromium')
(browserConfig.launchOptions as any).cdpPort = await findFreePort();
diff --git a/packages/playwright/src/mcp/browser/processUtils.ts b/packages/playwright/src/mcp/browser/processUtils.ts
deleted file mode 100644
index 45584b4861..0000000000
--- a/packages/playwright/src/mcp/browser/processUtils.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * 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 childProcess from 'child_process';
-
-import { registry } from 'playwright-core/lib/server/registry/index';
-
-// TODO: make browserType.executablePath() return it.
-export function getBrowserExecPath(channelOrName: string): string | undefined {
- return registry.findExecutable(channelOrName)?.executablePath('javascript');
-}
-
-export function findBrowserProcess(execPath: string, arg: string): string | null {
- switch (process.platform) {
- case 'darwin':
- return findProcessMacos(execPath, arg);
- case 'linux':
- return findProcessLinux(execPath, arg);
- case 'win32':
- return findProcessWindows(execPath, arg);
- default:
- return null;
- }
-}
-
-function findProcessLinux(execPath: string, arg: string): string | null {
- const psResult = childProcess.spawnSync('ps', ['-eo', 'pid=,args=']);
- return findMatchingLine(psResult.stdout.toString(), execPath, arg);
-}
-
-function findProcessMacos(execPath: string, arg: string): string | null {
- const psResult = childProcess.spawnSync('ps', ['-axo', 'pid=,command=']);
- return findMatchingLine(psResult.stdout.toString(), execPath, arg);
-}
-
-function findProcessWindows(execPath: string, arg: string): string | null {
- const filter = `$_.ExecutablePath -eq '${execPath}' -and $_.CommandLine.Contains('${arg}') -and $_.CommandLine -notmatch '--type'`;
- const ps = childProcess.spawnSync(
- 'powershell.exe',
- [
- '-NoProfile',
- '-Command',
- `Get-CimInstance Win32_Process | Where-Object { ${filter} } | Select-Object -Property ProcessId,CommandLine | ForEach-Object { "$($_.ProcessId) $($_.CommandLine)" }`
- ],
- { encoding: 'utf8' }
- );
-
- if (ps.status !== 0)
- return null;
-
- return findMatchingLine(ps.stdout.toString(), execPath, arg);
-}
-
-function findMatchingLine(psOutput: string, execPath: string, arg: string): string | null {
- const lines = psOutput.split('\n').map(l => l.trim()).filter(Boolean);
- for (const line of lines) {
- // Chrome child process have --type argument, we only return the browser process.
- if (line.includes(execPath) && line.includes(arg) && !line.includes('--type'))
- return line;
- }
- return null;
-}
diff --git a/tests/mcp/launch.spec.ts b/tests/mcp/launch.spec.ts
index deca384b7e..f7f0171aa9 100644
--- a/tests/mcp/launch.spec.ts
+++ b/tests/mcp/launch.spec.ts
@@ -167,46 +167,3 @@ test('isolated context with storage state', async ({ startClient, server }, test
pageState: expect.stringContaining(`Storage: session-value`),
});
});
-
-test('persistent context already running', async ({ startClient, server, mcpBrowser }, testInfo) => {
- const userDataDir = testInfo.outputPath('user-data-dir');
- const { client } = await startClient({
- args: [`--user-data-dir=${userDataDir}`],
- });
- await client.callTool({
- name: 'browser_navigate',
- arguments: { url: server.HELLO_WORLD },
- });
-
- const { client: client2, stderr } = await startClient({
- args: [`--user-data-dir=${userDataDir}`],
- });
- const navigationPromise = client2.callTool({
- name: 'browser_navigate',
- arguments: { url: server.HELLO_WORLD },
- });
-
- const wait = await Promise.race([
- navigationPromise.then(() => 'done'),
- new Promise(resolve => setTimeout(resolve, 1_000)).then(() => 'timeout'),
- ]);
- expect(wait).toBe('timeout');
-
- // Check that the second client is trying to launch the browser.
- await expect.poll(() => formatOutput(stderr()), { timeout: 0 }).toEqual([
- 'create context',
- 'create browser context (persistent)',
- 'lock user data dir'
- ]);
-
- // Close first client's browser.
- await client.callTool({
- name: 'browser_close',
- arguments: { url: server.HELLO_WORLD },
- });
-
- const result = await navigationPromise;
- expect(result).toHaveResponse({
- pageState: expect.stringContaining(`- generic [active] [ref=e1]: Hello, world!`),
- });
-});