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): do not force-kill the browser on close (#43229)
Pavel Feldmana01040c80748
diff --git a/packages/playwright-core/src/tools/cli-daemon/daemon.ts b/packages/playwright-core/src/tools/cli-daemon/daemon.tsindex b71dcc477e..96edb6f76a 100644--- a/packages/playwright-core/src/tools/cli-daemon/daemon.ts+++ b/packages/playwright-core/src/tools/cli-daemon/daemon.ts@@ -46,7 +46,7 @@ async function socketExists(socketPath: string): Promise<boolean> {return false;}-async function monitorSocketPath(socketPath: string): Promise<void> {+async function monitorSocketPath(socketPath: string, onGone: () => void): Promise<void> {if (process.platform === 'win32')return;@@ -55,7 +55,7 @@ async function monitorSocketPath(socketPath: string): Promise<void> {async function checkSocketPath() {const currentStat = await fs.promises.stat(socketPath).catch(() => undefined);if (!currentStat || !currentStat.isSocket() || currentStat.dev !== socketStat.dev || currentStat.ino !== socketStat.ino) {- gracefullyProcessExitDoNotHang(0);+ onGone();return;}scheduleSocketCheck();@@ -79,7 +79,6 @@ export async function startCliDaemonServer(options: {ownership?: 'attached' | 'own',persistent?: boolean,- exitOnClose?: boolean,idleTimer?: IdleTimer,}): Promise<string> {@@ -109,12 +108,7 @@ export async function startCliDaemonServer(const { id, method, params } = message;try {if (method === 'stop') {- await deleteSessionFile(clientInfo, sessionConfig);- const sendAck = async () => connection.send({ id, result: 'ok' }).catch(() => {});- if (options?.exitOnClose)- gracefullyProcessExitDoNotHang(0, () => sendAck());- else- await sendAck();+ await exit(async () => connection.send({ id, result: 'ok' }).catch(() => {}));} else if (method === 'run') {const { toolName, toolParams } = parseCliCommand(params.args);toolParams._meta = { cwd: params.cwd, raw: params.raw || params.json, json: !!params.json };@@ -131,11 +125,19 @@ export async function startCliDaemonServer(});decorateServer(server);- browserContext.on('close', () => Promise.resolve().then(async () => {++ // A stop request, the browser closing and the socket going away all end the daemon, and+ // exiting itself closes the browser and removes the socket. Exit only once: closing the+ // browser again while it is closing force-kills it.+ let exiting = false;+ async function exit(onExit?: () => Promise<void>) {+ if (exiting)+ return;+ exiting = true;await deleteSessionFile(clientInfo, sessionConfig);- if (options?.exitOnClose)- gracefullyProcessExitDoNotHang(0);- }));+ gracefullyProcessExitDoNotHang(0, onExit);+ }+ browserContext.on('close', () => void exit());await new Promise<void>((resolve, reject) => {server.on('error', reject);@@ -144,7 +146,7 @@ export async function startCliDaemonServer(await saveSessionFile(clientInfo, sessionConfig);options.idleTimer?.poke();- await monitorSocketPath(socketPath);+ await monitorSocketPath(socketPath, () => void exit());return socketPath;}@@ -182,7 +184,6 @@ function daemonSocketPath(clientInfo: ClientInfo, sessionName: string): string {function createSessionConfig(clientInfo: ClientInfo, sessionName: string, browserInfo: BrowserInfo, options: {ownership?: 'attached' | 'own',persistent?: boolean,- exitOnStop?: boolean,} = {}): SessionConfig {return {name: sessionName,diff --git a/packages/playwright-core/src/tools/cli-daemon/program.ts b/packages/playwright-core/src/tools/cli-daemon/program.tsindex 1e2b39af7b..6211c2d56c 100644--- a/packages/playwright-core/src/tools/cli-daemon/program.ts+++ b/packages/playwright-core/src/tools/cli-daemon/program.ts@@ -69,7 +69,7 @@ export function decorateProgram(program: Command) {if (!browserContext)throw new Error('Error: unable to connect to a browser that does not have any contexts');const persistent = options.persistent || options.profile || mcpConfig.browser.userDataDir ? true : undefined;- const socketPath = await startCliDaemonServer(sessionName, browserContext, browserInfo, mcpConfig, clientInfo, mcpClientInfo, { persistent, exitOnClose: true, ownership, idleTimer });+ const socketPath = await startCliDaemonServer(sessionName, browserContext, browserInfo, mcpConfig, clientInfo, mcpClientInfo, { persistent, ownership, idleTimer });console.log(`Daemon listening on ${socketPath}\n`);} catch (error) {console.log(error);diff --git a/tests/mcp/cli-session.spec.ts b/tests/mcp/cli-session.spec.tsindex bbbc039b19..d260743f57 100644--- a/tests/mcp/cli-session.spec.ts+++ b/tests/mcp/cli-session.spec.ts@@ -51,6 +51,19 @@ test('close', async ({ cli, server }) => {expect(listOutput).toContain('(no browsers)');});+test('close lets the browser exit on its own', {+ annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright-cli/issues/475' },+}, async ({ cli, server }, testInfo) => {+ const logFile = testInfo.outputPath('daemon.log');+ const { daemonPid } = await cli('open', server.HELLO_WORLD, { env: { DEBUG: 'pw:browser', DEBUG_FILE: logFile } });+ await cli('close');+ await expect.poll(() => isProcessAlive(daemonPid)).toBe(false);++ const log = await fs.promises.readFile(logFile, 'utf-8');+ expect(log).toContain('<gracefully close start>');+ expect(log).not.toContain('<forcefully close>');+});+test('idle timeout shuts the session down', async ({ cli, server }) => {await cli('open', '--idle-timeout=3000', server.HELLO_WORLD);const { output } = await cli('list');