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(cli): wait for dashboard daemon READY signal before returning from `cli show` (#40725)
Simon Knottd8c56b025364
diff --git a/packages/playwright-core/src/tools/cli-client/program.ts b/packages/playwright-core/src/tools/cli-client/program.tsindex e15a0e3654..1c8d21574d 100644--- a/packages/playwright-core/src/tools/cli-client/program.ts+++ b/packages/playwright-core/src/tools/cli-client/program.ts@@ -33,6 +33,7 @@ import { minimist } from './minimist';import type { ListData, ListedBrowser, Output } from './output';import type { ClientInfo, SessionFile } from './registry';import type { MinimistArgs } from './minimist';+import type { Readable } from 'stream';type GlobalOptions = {help?: boolean;@@ -229,12 +230,35 @@ export async function program(options?: { embedderVersion?: string}) {const foreground = args.port !== undefined;const child = spawn(process.execPath, daemonArgs, {detached: !foreground,- stdio: foreground ? 'inherit' : 'ignore',+ stdio: foreground ? 'inherit' : ['ignore', 'ignore', 'ignore', 'pipe'],});if (foreground) {await new Promise<void>(resolve => child.on('exit', () => resolve()));return;}+ const readyStream = (child.stdio as unknown as Readable[])[3];+ try {+ await new Promise<void>((resolve, reject) => {+ const settle = (err?: Error) => {+ clearTimeout(timer);+ readyStream.destroy();+ if (err)+ reject(err);+ else+ resolve();+ };+ const timer = setTimeout(() => settle(new Error('Dashboard daemon did not spin up within 60s, killing it')), 60_000);+ readyStream.once('data', () => settle());+ readyStream.once('error', err => settle(err));+ child.once('exit', (code, signal) => settle(new Error(`Dashboard daemon exited (code=${code}, signal=${signal}) before signaling READY`)));+ });+ } catch (err) {+ if (child.exitCode === null && child.signalCode === null) {+ child.kill('SIGKILL');+ await new Promise<void>(resolve => child.once('exit', () => resolve()));+ }+ throw err;+ }child.unref();output.show(sessionName, child.pid);return;diff --git a/packages/playwright-core/src/tools/dashboard/dashboardApp.ts b/packages/playwright-core/src/tools/dashboard/dashboardApp.tsindex 34b5bd4cfa..b0fd0143ff 100644--- a/packages/playwright-core/src/tools/dashboard/dashboardApp.ts+++ b/packages/playwright-core/src/tools/dashboard/dashboardApp.ts@@ -22,7 +22,6 @@ import http from 'http';import { HttpServer } from '@utils/httpServer';import { makeSocketPath } from '@utils/fileUtils';import { gracefullyProcessExitDoNotHang } from '@utils/processLauncher';-import { monotonicTime } from '@isomorphic/time';import { libPath } from '../../package';import { playwright } from '../../inprocess';import { findChromiumChannelBestEffort, registryDirectory } from '../../server/registry/index';@@ -341,21 +340,15 @@ export async function openDashboardApp() {socket.end();return;}- if (parsed.kill) {- // Write our PID so the kill client can wait for the process to fully exit,- // which guarantees the named pipe is released (especially on Windows).- // Start graceful shutdown only after the socket data has been flushed, so the- // kill client is guaranteed to receive the PID before we begin tearing down.- server?.close();- socket.end(JSON.stringify({ pid: process.pid }) + '\n', () => gracefullyProcessExitDoNotHang(0));- return;- }void statePromise.then(({ page, server: dashboard }) => {if (parsed.annotate) {page?.bringToFront().catch(() => {});dashboard.reveal(parsed);dashboard.triggerAnnotate();dashboard.registerAnnotateWaiter(socket);+ } else if (parsed.kill) {+ socket.end();+ gracefullyProcessExitDoNotHang(0);} else {page?.bringToFront().catch(() => {});dashboard.reveal(parsed);@@ -365,6 +358,7 @@ export async function openDashboardApp() {});});await statePromise;+ try { fs.writeSync(3, '.'); fs.closeSync(3); } catch {}}export async function openDashboardForContext(context: api.BrowserContext): Promise<void> {@@ -385,37 +379,14 @@ export async function openDashboardForContext(context: api.BrowserContext): Promasync function runKillClient(): Promise<void> {const socketPath = dashboardSocketPath();- const pid = await new Promise<number | undefined>((resolve, reject) => {+ await new Promise<void>(resolve => {const client = net.connect(socketPath);- let data = '';client.once('connect', () => {client.write(JSON.stringify({ kill: true }) + '\n');});- client.on('data', chunk => { data += chunk; });- client.once('end', () => {- let pid: number | undefined;- try { pid = JSON.parse(data.trim()).pid; } catch { }- if (pid === undefined)- reject(new Error('Dashboard did not return its PID'));- else- resolve(pid);- });- client.once('error', () => resolve(undefined));+ client.once('end', () => resolve());+ client.once('error', () => resolve());});- if (pid === undefined)- return;- // Poll until the daemon process exits — at that point the OS has released all- // its handles, including the named pipe, so the next acquisition won't see a stale pipe.- const deadline = monotonicTime() + 35000;- while (monotonicTime() < deadline) {- try {- process.kill(pid, 0);- } catch {- return;- }- await new Promise(r => setTimeout(r, 50));- }- throw new Error(`Dashboard process ${pid} did not exit within the deadline`);}async function runAnnotateClient(options: DashboardOptions): Promise<void> {diff --git a/tests/mcp/cli-fixtures.ts b/tests/mcp/cli-fixtures.tsindex 8c5ab020b3..32b960f73b 100644--- a/tests/mcp/cli-fixtures.ts+++ b/tests/mcp/cli-fixtures.ts@@ -60,7 +60,7 @@ export const test = baseTest.extend<{return page;});},- connectToDashboard: [async ({ cli, playwright }, use) => {+ connectToDashboard: async ({ cli, playwright }, use) => {await use(async (bindTitle: string) => {let endpoint = '';await expect(async () => {@@ -72,7 +72,7 @@ export const test = baseTest.extend<{return await playwright.chromium.connect(endpoint);});await cli('show', '--kill');- }, { timeout: 60000 }],+ },cli: async ({ mcpBrowser, mcpHeadless, childProcess }, use) => {await fs.promises.mkdir(test.info().outputPath('.playwright'), { recursive: true });@@ -81,7 +81,10 @@ export const test = baseTest.extend<{await use(async (...args: string[]) => {const cliArgs = args.filter(arg => typeof arg === 'string');const cliOptions = args.findLast(arg => typeof arg === 'object') || {};- const result = await runCli(childProcess, cliArgs, cliOptions, { mcpBrowser, mcpHeadless });+ const result = await test.step(+ `cli ${cliArgs.join(' ')}`,+ () => runCli(childProcess, cliArgs, cliOptions, { mcpBrowser, mcpHeadless })+ );if (result.daemonPid)allPids.push(result.daemonPid);if (result.dashboardPid)diff --git a/tests/mcp/playwright.config.ts b/tests/mcp/playwright.config.tsindex 86d4cd99a5..6a3895c34c 100644--- a/tests/mcp/playwright.config.ts+++ b/tests/mcp/playwright.config.ts@@ -54,6 +54,9 @@ export default defineConfig<TestOptions>({workers: undefined,reporter: reporters(),tag: process.env.PW_TAG,+ // Persistent context launch (the MCP default) is genuinely slow on Windows;+ // most tests in this suite use it.+ timeout: process.platform === 'win32' ? 60000 : 30000,projects: [{ name: 'chrome', metadata: { ...metadata, browserName: 'chromium', channel: 'chrome' }, testDir },{ name: 'chromium', use: { mcpBrowser: 'chromium' }, metadata: { ...metadata, browserName: 'chromium' }, testDir },