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(extension): simplify cdp relay single-shot lifecycle (#40396)
Yury Semikhatskyc80bd946f9cf
diff --git a/packages/playwright-core/src/tools/mcp/cdpRelay.ts b/packages/playwright-core/src/tools/mcp/cdpRelay.tsindex 602d6ac8a0..eeb568ab33 100644--- a/packages/playwright-core/src/tools/mcp/cdpRelay.ts+++ b/packages/playwright-core/src/tools/mcp/cdpRelay.ts@@ -67,11 +67,11 @@ export class CDPRelayServer {private _cdpPath: string;private _extensionPath: string;private _wss: WebSocketServer;- private _playwrightConnection: WebSocket | null = null;+ private _cdpConnection: WebSocket | null = null;private _extensionConnection: ExtensionConnection | null = null;private _protocolVersion: number;private _handler: ExtensionProtocolHandler;- private _extensionConnectionPromise!: ManualPromise<void>;+ private _extensionConnectionPromise = new ManualPromise<void>();constructor(server: http.Server, browserChannel: string, userDataDir?: string, executablePath?: string) {this._wsHost = addressToString(server.address(), { protocol: 'ws' });@@ -96,7 +96,7 @@ export class CDPRelayServer {this._cdpPath = `/cdp/${uuid}`;this._extensionPath = `/extension/${uuid}`;- this._resetExtensionConnection();+ void this._extensionConnectionPromise.catch(logUnhandledError);this._wss = new wsServer({ server });this._wss.on('connection', this._onConnection.bind(this));}@@ -109,22 +109,15 @@ export class CDPRelayServer {return `${this._wsHost}${this._extensionPath}`;}- async ensureExtensionConnectionForMCPContext(clientName: string) {- debugLogger('Ensuring extension connection for MCP context');- if (this._extensionConnection)- return;- this._connectBrowser(clientName);+ async establishExtensionConnection(clientName: string) {+ debugLogger('Establishing extension connection');+ this._openConnectPageInBrowser(clientName);debugLogger('Waiting for incoming extension connection');- await Promise.race([- this._extensionConnectionPromise,- new Promise((_, reject) => setTimeout(() => {- reject(new Error(`Extension connection timeout. Make sure the "Playwright Extension" is installed. See https://github.com/microsoft/playwright-mcp/blob/main/packages/extension/README.md for installation instructions.`));- }, process.env.PWMCP_TEST_CONNECTION_TIMEOUT ? parseInt(process.env.PWMCP_TEST_CONNECTION_TIMEOUT, 10) : 5_000)),- ]);+ await this._extensionConnectionPromise;debugLogger('Extension connection established');}- private _connectBrowser(clientName: string) {+ private _openConnectPageInBrowser(clientName: string) {const mcpRelayEndpoint = `${this._wsHost}${this._extensionPath}`;const url = new URL(`chrome-extension://${playwrightExtensionId}/connect.html`);url.searchParams.set('mcpRelayUrl', mcpRelayEndpoint);@@ -166,12 +159,12 @@ export class CDPRelayServer {}stop(): void {- this.closeConnections('Server stopped');+ this._closeConnections('Server stopped');this._wss.close();}- closeConnections(reason: string) {- this._closePlaywrightConnection(reason);+ private _closeConnections(reason: string) {+ this._closeCDPConnection(reason);this._closeExtensionConnection(reason);}@@ -189,12 +182,17 @@ export class CDPRelayServer {}private _handlePlaywrightConnection(ws: WebSocket): void {- if (this._playwrightConnection) {+ if (!this._extensionConnection) {+ debugLogger('Rejecting Playwright connection: extension not connected');+ ws.close(1000, 'Extension not connected');+ return;+ }+ if (this._cdpConnection) {debugLogger('Rejecting second Playwright connection');ws.close(1000, 'Another CDP client already connected');return;}- this._playwrightConnection = ws;+ this._cdpConnection = ws;ws.on('message', async data => {try {const message = JSON.parse(data.toString());@@ -204,9 +202,6 @@ export class CDPRelayServer {}});ws.on('close', () => {- if (this._playwrightConnection !== ws)- return;- this._playwrightConnection = null;this._closeExtensionConnection('Playwright client disconnected');debugLogger('Playwright WebSocket closed');});@@ -218,21 +213,13 @@ export class CDPRelayServer {private _closeExtensionConnection(reason: string) {this._extensionConnection?.close(reason);- this._extensionConnectionPromise.reject(new Error(reason));- this._resetExtensionConnection();- }-- private _resetExtensionConnection() {- this._handler.reset();- this._extensionConnection = null;- this._extensionConnectionPromise = new ManualPromise();- void this._extensionConnectionPromise.catch(logUnhandledError);+ if (!this._extensionConnectionPromise.isDone())+ this._extensionConnectionPromise.reject(new Error(reason));}- private _closePlaywrightConnection(reason: string) {- if (this._playwrightConnection?.readyState === ws.OPEN)- this._playwrightConnection.close(1000, reason);- this._playwrightConnection = null;+ private _closeCDPConnection(reason: string) {+ if (this._cdpConnection?.readyState === ws.OPEN)+ this._cdpConnection.close(1000, reason);}private _handleExtensionConnection(ws: WebSocket): void {@@ -241,12 +228,9 @@ export class CDPRelayServer {return;}this._extensionConnection = new ExtensionConnection(ws);- this._extensionConnection.onclose = (c, reason) => {- debugLogger('Extension WebSocket closed:', reason, c === this._extensionConnection);- if (this._extensionConnection !== c)- return;- this._resetExtensionConnection();- this._closePlaywrightConnection(`Extension disconnected: ${reason}`);+ this._extensionConnection.onclose = reason => {+ debugLogger('Extension WebSocket closed:', reason);+ this._closeCDPConnection(`Extension disconnected: ${reason}`);};this._extensionConnection.onmessage = (method, params) => this._handler.handleExtensionEvent(method, params);this._extensionConnectionPromise.resolve();@@ -289,7 +273,7 @@ export class CDPRelayServer {private _sendToPlaywright(message: CDPResponse): void {debugLogger('→ Playwright:', `${message.method ?? `response(id=${message.id})`}`);- this._playwrightConnection?.send(JSON.stringify(message));+ this._cdpConnection?.send(JSON.stringify(message));}}@@ -307,7 +291,7 @@ class ExtensionConnection {private _lastId = 0;onmessage?: <M extends keyof ExtensionEvents>(method: M, params: ExtensionEvents[M]['params']) => void;- onclose?: (self: ExtensionConnection, reason: string) => void;+ onclose?: (reason: string) => void;constructor(ws: WebSocket) {this._ws = ws;@@ -372,7 +356,7 @@ class ExtensionConnection {private _onClose(event: websocket.CloseEvent) {debugLogger(`<ws closed> code=${event.code} reason=${event.reason}`);this._dispose();- this.onclose?.(this, event.reason);+ this.onclose?.(event.reason);}private _onError(event: websocket.ErrorEvent) {diff --git a/packages/playwright-core/src/tools/mcp/cdpRelayHandler.ts b/packages/playwright-core/src/tools/mcp/cdpRelayHandler.tsindex 93ab891970..fa70ed8a43 100644--- a/packages/playwright-core/src/tools/mcp/cdpRelayHandler.ts+++ b/packages/playwright-core/src/tools/mcp/cdpRelayHandler.ts@@ -34,6 +34,4 @@ export interface ExtensionProtocolHandler {handleCDPCommand(method: string, params: any, sessionId: string | undefined): Promise<{ result: any } | undefined>;// Forward a CDP command to the extension.forwardToExtension(method: string, params: any, sessionId: string | undefined): Promise<any>;- // Reset protocol state on extension disconnect/reconnect.- reset(): void;}diff --git a/packages/playwright-core/src/tools/mcp/cdpRelayV1.ts b/packages/playwright-core/src/tools/mcp/cdpRelayV1.tsindex 3aff2addae..c953639916 100644--- a/packages/playwright-core/src/tools/mcp/cdpRelayV1.ts+++ b/packages/playwright-core/src/tools/mcp/cdpRelayV1.ts@@ -87,8 +87,4 @@ export class ExtensionProtocolV1 implements ExtensionProtocolHandler {sessionId = undefined;return await this._sendCommand('forwardCDPCommand', { sessionId, method, params });}-- reset(): void {- this._connectedTabInfo = undefined;- }}diff --git a/packages/playwright-core/src/tools/mcp/cdpRelayV2.ts b/packages/playwright-core/src/tools/mcp/cdpRelayV2.tsindex 09291f7197..eb69160a23 100644--- a/packages/playwright-core/src/tools/mcp/cdpRelayV2.ts+++ b/packages/playwright-core/src/tools/mcp/cdpRelayV2.ts@@ -153,10 +153,6 @@ export class ExtensionProtocolV2 implements ExtensionProtocolHandler {]);}- reset(): void {- this._tabSessions.clear();- }-private async _attachTab(tabId: number): Promise<TabSession> {const existing = this._tabSessions.get(tabId);if (existing)diff --git a/packages/playwright-core/src/tools/mcp/extensionContextFactory.ts b/packages/playwright-core/src/tools/mcp/extensionContextFactory.tsindex fb7d95b7a2..579a665b19 100644--- a/packages/playwright-core/src/tools/mcp/extensionContextFactory.ts+++ b/packages/playwright-core/src/tools/mcp/extensionContextFactory.ts@@ -35,7 +35,7 @@ export async function createExtensionBrowser(config: FullConfig, clientName: strdebugLogger(`CDP relay server started, extension endpoint: ${relay.extensionEndpoint()}.`);try {- await relay.ensureExtensionConnectionForMCPContext(clientName);+ await relay.establishExtensionConnection(clientName);return await playwright.chromium.connectOverCDP(relay.cdpEndpoint(), { isLocal: true, timeout: 0 });} catch (error) {relay.stop();diff --git a/tests/extension/cli.spec.ts b/tests/extension/cli.spec.tsindex 9f15785a43..e6814ac94e 100644--- a/tests/extension/cli.spec.ts+++ b/tests/extension/cli.spec.ts@@ -66,6 +66,8 @@ test('daemon exits when user rejects the extension connection', async ({ startAttest('daemon exits when user closes the connect tab', async ({ startAttach }) => {const { confirmationPage, cliPromise } = await startAttach();+ // Wait for the page to fully load and the connection to the relay to be established before closing it.+ await expect(confirmationPage.getByRole('button', { name: 'Reject' })).toBeVisible();await confirmationPage.close();await expectDaemonExited(cliPromise);});diff --git a/tests/extension/extension.spec.ts b/tests/extension/extension.spec.tsindex 0ebb53c6a8..13d895bcb3 100644--- a/tests/extension/extension.spec.ts+++ b/tests/extension/extension.spec.ts@@ -190,27 +190,9 @@ test(`snapshot of an existing page`, async ({ browserWithExtension, startClient,});});-test(`extension not installed timeout`, async ({ startExtensionClient, server }) => {- const { browserContext, client } = await startExtensionClient({ PWMCP_TEST_CONNECTION_TIMEOUT: '100' });-- const confirmationPagePromise = browserContext.waitForEvent('page', page => {- return page.url().startsWith(`chrome-extension://${extensionId}/connect.html`);- });-- expect(await client.callTool({- name: 'browser_navigate',- arguments: { url: server.HELLO_WORLD },- })).toHaveResponse({- error: expect.stringMatching(/Extension connection timeout. Make sure the "Playwright.* is installed\./),- isError: true,- });-- await confirmationPagePromise;-});-testWithOldExtensionVersion(`works with old extension version`, async ({ startExtensionClient, server }) => {// Prelaunch the browser, so that it is properly closed after the test.- const { browserContext, client } = await startExtensionClient({ PWMCP_TEST_CONNECTION_TIMEOUT: '500' });+ const { browserContext, client } = await startExtensionClient();const confirmationPagePromise = browserContext.waitForEvent('page', page => {return page.url().startsWith(`chrome-extension://${extensionId}/connect.html`);@@ -231,24 +213,20 @@ testWithOldExtensionVersion(`works with old extension version`, async ({ startExtest(`extension needs update`, async ({ startExtensionClient, server }) => {// Prelaunch the browser, so that it is properly closed after the test.- const { browserContext, client } = await startExtensionClient({ PWMCP_TEST_CONNECTION_TIMEOUT: '500', PLAYWRIGHT_EXTENSION_PROTOCOL: '1000' });+ const { browserContext, client } = await startExtensionClient({ PLAYWRIGHT_EXTENSION_PROTOCOL: '1000' });const confirmationPagePromise = browserContext.waitForEvent('page', page => {return page.url().startsWith(`chrome-extension://${extensionId}/connect.html`);});- const navigateResponse = client.callTool({+ // The call hangs as MCP server never connects to the extension.+ client.callTool({name: 'browser_navigate',arguments: { url: server.HELLO_WORLD },- });+ }).catch(() => {});const confirmationPage = await confirmationPagePromise;await expect(confirmationPage.locator('.status-banner')).toContainText(`Playwright client trying to connect requires newer extension version`);-- expect(await navigateResponse).toHaveResponse({- error: expect.stringContaining('Extension connection timeout.'),- isError: true,- });});test(`custom executablePath`, async ({ startClient, server }) => {@@ -257,7 +235,6 @@ test(`custom executablePath`, async ({ startClient, server }) => {const { client } = await startClient({args: [`--extension`],- env: { PWMCP_TEST_CONNECTION_TIMEOUT: '1000' },config: {browser: {launchOptions: {@@ -267,15 +244,15 @@ test(`custom executablePath`, async ({ startClient, server }) => {},});- const navigateResponse = await client.callTool({+ // The call hangs as MCP server never connects to the extension.+ client.callTool({name: 'browser_navigate',arguments: { url: server.HELLO_WORLD },- });- expect(await navigateResponse).toHaveResponse({- error: expect.stringContaining('Extension connection timeout.'),- isError: true,- });- expect(await fs.readFile(test.info().outputPath('output.txt'), 'utf8')).toMatch(new RegExp(`Custom exec args.*chrome-extension://${extensionId}/connect\\.html\\?`));+ }).catch(() => {});+ await expect(async () => {+ const output = await fs.readFile(test.info().outputPath('output.txt'), 'utf8');+ expect(output).toMatch(new RegExp(`Custom exec args.*chrome-extension://${extensionId}/connect\\.html\\?`));+ }).toPass();});test(`bypass connection dialog with token`, async ({ browserWithExtension, startClient, server }) => {