Skip to content

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

chore: always create session objects (#39005)

Pavel Feldman74299c0e31b3
diff --git a/packages/playwright-core/src/server/utils/processLauncher.ts b/packages/playwright-core/src/server/utils/processLauncher.ts
index 148b340ec7..6c491d0f48 100644
--- a/packages/playwright-core/src/server/utils/processLauncher.ts
+++ b/packages/playwright-core/src/server/utils/processLauncher.ts
@@ -55,15 +55,15 @@ export async function gracefullyCloseAll() {
await Promise.all(Array.from(gracefullyCloseSet).map(gracefullyClose => gracefullyClose().catch(e => {})));
}
-export function gracefullyProcessExitDoNotHang(code: number) {
+export function gracefullyProcessExitDoNotHang(code: number, onExit?: () => Promise<void>) {
// Force exit after 30 seconds.
+ const beforeExit = onExit ? () => onExit().catch(() => {}) : () => Promise.resolve();
// eslint-disable-next-line no-restricted-properties
- setTimeout(() => process.exit(code), 30000);
+ const callback = () => beforeExit().then(() => process.exit(code));
+
+ setTimeout(callback, 30000);
// Meanwhile, try to gracefully close all browsers.
- gracefullyCloseAll().then(() => {
- // eslint-disable-next-line no-restricted-properties
- process.exit(code);
- });
+ gracefullyCloseAll().then(callback);
}
function exitHandler() {
diff --git a/packages/playwright/src/mcp/terminal/commands.ts b/packages/playwright/src/mcp/terminal/commands.ts
index f6a89064de..e9ccb88bb1 100644
--- a/packages/playwright/src/mcp/terminal/commands.ts
+++ b/packages/playwright/src/mcp/terminal/commands.ts
@@ -38,7 +38,7 @@ const close = declareCommand({
description: 'Close the page',
category: 'core',
args: z.object({}),
- toolName: 'browser_close',
+ toolName: '',
toolParams: () => ({}),
});
diff --git a/packages/playwright/src/mcp/terminal/daemon.ts b/packages/playwright/src/mcp/terminal/daemon.ts
index ec9ba55fa9..880e17e7a8 100644
--- a/packages/playwright/src/mcp/terminal/daemon.ts
+++ b/packages/playwright/src/mcp/terminal/daemon.ts
@@ -88,9 +88,10 @@ export async function startMcpDaemonServer(
daemonDebug('received command', method);
if (method === 'stop') {
daemonDebug('stop command received, shutting down');
- await connection.send({ id, result: 'ok' });
- server.close();
- gracefullyProcessExitDoNotHang(0);
+ gracefullyProcessExitDoNotHang(0, async () => {
+ await connection.send({ id, result: 'ok' }).catch(() => {});
+ server.close();
+ });
} else if (method === 'run') {
const { toolName, toolParams } = parseCliCommand(params.args);
const response = await backend.callTool(toolName, toolParams, () => {});
diff --git a/packages/playwright/src/mcp/terminal/program.ts b/packages/playwright/src/mcp/terminal/program.ts
index 75854db921..70fbae675e 100644
--- a/packages/playwright/src/mcp/terminal/program.ts
+++ b/packages/playwright/src/mcp/terminal/program.ts
@@ -36,15 +36,16 @@ export type StructuredResponse = {
class Session {
readonly name: string;
- private _connection: SocketConnection;
+ private _socketPath: string;
+ private _connection: SocketConnection | undefined;
private _nextMessageId = 1;
- private _callbacks = new Map<number, { resolve: (o: any) => void, reject: (e: Error) => void }>();
+ private _callbacks = new Map<number, { resolve: (o: any) => void, reject: (e: Error) => void, method: string, params: any }>();
+ private _options: { config?: string, headed?: boolean };
- constructor(name: string, connection: SocketConnection) {
+ constructor(name: string, options: { config?: string, headed?: boolean }) {
this.name = name;
- this._connection = connection;
- this._connection.onmessage = message => this._onMessage(message);
- this._connection.onclose = () => this.close();
+ this._socketPath = this._daemonSocketPath();
+ this._options = options;
}
async run(args: any) {
@@ -52,11 +53,31 @@ class Session {
}
async stop(): Promise<void> {
- await this._send('stop');
+ if (!await this.canConnect()) {
+ console.log(`Session '${this.name}' is not running.`);
+ return;
+ }
+
+ await this._send('stop').catch(e => {
+ if (e.message !== 'Session closed')
+ throw e;
+ });
this.close();
+
+ if (os.platform() !== 'win32')
+ await fs.promises.unlink(this._socketPath).catch(() => {});
+ console.log(`Session '${this.name}' stopped.`);
+ }
+
+ async restart(options: { config?: string, headed?: boolean }): Promise<void> {
+ await this.stop();
+
+ this._options = options;
+ await this._startDaemonIfNeeded();
}
private async _send(method: string, params: any = {}): Promise<any> {
+ const connection = await this._startDaemonIfNeeded();
const messageId = this._nextMessageId++;
const message = {
id: messageId,
@@ -64,110 +85,42 @@ class Session {
params,
};
const responsePromise = new Promise<any>((resolve, reject) => {
- this._callbacks.set(messageId, { resolve, reject });
+ this._callbacks.set(messageId, { resolve, reject, method, params });
});
- const [result] = await Promise.all([responsePromise, this._connection.send(message)]);
+ const [result] = await Promise.all([responsePromise, connection.send(message)]);
return result;
}
close() {
+ if (!this._connection)
+ return;
for (const callback of this._callbacks.values())
callback.reject(new Error('Session closed'));
this._callbacks.clear();
this._connection.close();
+ this._connection = undefined;
}
- private _onMessage(object: any) {
- if (object.id && this._callbacks.has(object.id)) {
- const callback = this._callbacks.get(object.id)!;
- this._callbacks.delete(object.id);
- if (object.error)
- callback.reject(new Error(object.error));
- else
- callback.resolve(object.result);
- } else if (object.id) {
- throw new Error(`Unexpected message id: ${object.id}`);
- } else {
- throw new Error(`Unexpected message without id: ${JSON.stringify(object)}`);
- }
- }
-}
+ async delete() {
+ await this.stop();
-type SessionManagerOptions = { config?: string, headed?: boolean };
-
-class SessionManager {
- private _options: SessionManagerOptions;
-
- constructor(options: SessionManagerOptions) {
- this._options = options;
- }
-
- async list(): Promise<Map<string, boolean>> {
- const dir = daemonProfilesDir;
- try {
- const files = await fs.promises.readdir(dir);
- const sessions = new Map<string, boolean>();
- for (const file of files) {
- if (file.startsWith('ud-')) {
- // Session is like ud-<sessionName>-browserName
- const sessionName = file.split('-')[1];
- const live = await this._canConnect(sessionName);
- sessions.set(sessionName, live);
- }
- }
- return sessions;
- } catch {
- return new Map<string, boolean>();
- }
- }
-
- async run(args: any): Promise<void> {
- const sessionName = this._resolveSessionName(args.session);
- const session = await this._connect(sessionName);
- const result = await session.run(args);
- await printResponse(result);
- session.close();
- }
-
- async stop(sessionName?: string): Promise<void> {
- sessionName = this._resolveSessionName(sessionName);
-
- if (!await this._canConnect(sessionName)) {
- console.log(`Session '${sessionName}' is not running.`);
- return;
- }
-
- const session = await this._connect(sessionName);
- await session.stop();
- console.log(`Session '${sessionName}' stopped.`);
- }
-
- async delete(sessionName?: string): Promise<void> {
- sessionName = this._resolveSessionName(sessionName);
-
- // Stop the session if it's running
- if (await this._canConnect(sessionName)) {
- const session = await this._connect(sessionName);
- await session.stop();
- }
-
- // Delete user data directory
const dataDirs = await fs.promises.readdir(daemonProfilesDir).catch(() => []);
- const matchingDirs = dataDirs.filter(dir => dir.startsWith(`ud-${sessionName}-`));
+ const matchingDirs = dataDirs.filter(dir => dir.startsWith(`ud-${this.name}-`));
if (matchingDirs.length === 0) {
- console.log(`No user data found for session '${sessionName}'.`);
+ console.log(`No user data found for session '${this.name}'.`);
return;
}
+ console.log(matchingDirs);
for (const dir of matchingDirs) {
const userDataDir = path.resolve(daemonProfilesDir, dir);
for (let i = 0; i < 5; i++) {
try {
await fs.promises.rm(userDataDir, { recursive: true });
- console.log(`Deleted user data for session '${sessionName}'.`);
+ console.log(`Deleted user data for session '${this.name}'.`);
break;
} catch (e: any) {
if (e.code === 'ENOENT') {
- console.log(`No user data found for session '${sessionName}'.`);
+ console.log(`No user data found for session '${this.name}'.`);
break;
}
await new Promise(resolve => setTimeout(resolve, 1000));
@@ -176,42 +129,63 @@ class SessionManager {
}
}
}
+ }
- // Also try to delete the socket file if it exists
- if (os.platform() !== 'win32') {
- const socketPath = this._daemonSocketPath(sessionName);
- await fs.promises.unlink(socketPath).catch(() => {});
+ async _connect(): Promise<{ socket?: net.Socket, error?: Error }> {
+ return await new Promise(resolve => {
+ const socket = net.createConnection(this._socketPath, () => {
+ resolve({ socket });
+ });
+ socket.on('error', error => {
+ if (os.platform() !== 'win32')
+ void fs.promises.unlink(this._socketPath).catch(() => {}).then(() => resolve({ error }));
+ else
+ resolve({ error });
+ });
+ });
+ }
+
+ async canConnect(): Promise<boolean> {
+ const { socket } = await this._connect();
+ if (socket) {
+ socket.destroy();
+ return true;
}
+ return false;
}
- async configure(args: any): Promise<void> {
- const sessionName = this._resolveSessionName(args.session);
+ private async _startDaemonIfNeeded() {
+ if (this._connection)
+ return this._connection;
- if (await this._canConnect(sessionName)) {
- const session = await this._connect(sessionName);
- await session.stop();
- }
+ let { socket } = await this._connect();
+ if (!socket)
+ socket = await this._startDaemon();
- this._options.config = args._[1];
- const session = await this._connect(sessionName);
- session.close();
+ this._connection = new SocketConnection(socket);
+ this._connection.onmessage = message => this._onMessage(message);
+ this._connection.onclose = () => this.close();
+ return this._connection;
}
- private async _connect(sessionName: string): Promise<Session> {
- const socketPath = this._daemonSocketPath(sessionName);
-
- if (await this._canConnect(sessionName)) {
- try {
- return await this._connectToSocket(sessionName, socketPath);
- } catch (e) {
- // Connection failed, delete the stale socket file.
- if (os.platform() !== 'win32')
- await fs.promises.unlink(socketPath).catch(() => {});
- }
+ private _onMessage(object: any) {
+ if (object.id && this._callbacks.has(object.id)) {
+ const callback = this._callbacks.get(object.id)!;
+ this._callbacks.delete(object.id);
+ if (object.error)
+ callback.reject(new Error(object.error));
+ else
+ callback.resolve(object.result);
+ } else if (object.id) {
+ throw new Error(`Unexpected message id: ${object.id}`);
+ } else {
+ throw new Error(`Unexpected message without id: ${JSON.stringify(object)}`);
}
+ }
+ private async _startDaemon(): Promise<net.Socket> {
await fs.promises.mkdir(daemonProfilesDir, { recursive: true });
- const userDataDir = path.resolve(daemonProfilesDir, `ud-${sessionName}`);
+ const userDataDir = path.resolve(daemonProfilesDir, `ud-${this.name}`);
const cliPath = path.join(__dirname, '../../../cli.js');
const configFile = resolveConfigFile(this._options.config);
const configArg = configFile !== undefined ? [`--config=${configFile}`] : [];
@@ -225,7 +199,7 @@ class SessionManager {
const child = spawn(process.execPath, [
cliPath,
'run-mcp-server',
- `--daemon=${socketPath}`,
+ `--daemon=${this._socketPath}`,
`--daemon-data-dir=${userDataDir}`,
...configArg,
...headedArg,
@@ -236,10 +210,10 @@ class SessionManager {
});
child.unref();
- console.log(`<!-- Daemon for \`${sessionName}\` session started with pid ${child.pid}.`);
+ console.log(`<!-- Daemon for \`${this.name}\` session started with pid ${child.pid}.`);
if (configFile)
console.log(`- Using config file at \`${path.relative(process.cwd(), configFile)}\`.`);
- const sessionSuffix = sessionName !== 'default' ? ` "${sessionName}"` : '';
+ const sessionSuffix = this.name !== 'default' ? ` "${this.name}"` : '';
console.log(`- You can stop the session daemon with \`playwright-cli session-stop${sessionSuffix}\` when done.`);
console.log(`- You can delete the session data with \`playwright-cli session-delete${sessionSuffix}\` when done.`);
console.log('-->');
@@ -248,11 +222,13 @@ class SessionManager {
const maxRetries = 50;
const retryDelay = 100; // ms
for (let i = 0; i < maxRetries; i++) {
- await new Promise(resolve => setTimeout(resolve, 100));
+ await new Promise(resolve => setTimeout(resolve, retryDelay));
try {
- return await this._connectToSocket(sessionName, socketPath);
+ const { socket } = await this._connect();
+ if (socket)
+ return socket;
} catch (e) {
- if (e.code !== 'ENOENT')
+ if (e.code !== 'ENOENT' && e.code !== 'ECONNREFUSED')
throw e;
}
}
@@ -260,7 +236,7 @@ class SessionManager {
const outData = await fs.promises.readFile(outLog, 'utf-8').catch(() => '');
const errData = await fs.promises.readFile(errLog, 'utf-8').catch(() => '');
- console.error(`Failed to connect to daemon at ${socketPath} after ${maxRetries * retryDelay}ms`);
+ console.error(`Failed to connect to daemon at ${this._socketPath} after ${maxRetries * retryDelay}ms`);
if (outData.length)
console.log(outData);
if (errData.length)
@@ -268,27 +244,87 @@ class SessionManager {
process.exit(1);
}
- private async _connectToSocket(sessionName: string, socketPath: string): Promise<Session> {
- const socket = await new Promise<net.Socket>((resolve, reject) => {
- const socket = net.createConnection(socketPath, () => {
- resolve(socket);
- });
- socket.on('error', reject);
- });
- return new Session(sessionName, new SocketConnection(socket));
+ private _daemonSocketPath(): string {
+ const socketName = `${this.name}.sock`;
+ if (os.platform() === 'win32')
+ return `\\\\.\\pipe\\${installationDirHash}-${socketName}`;
+ const socketsDir = process.env.PLAYWRIGHT_DAEMON_SOCKETS_DIR || path.join(os.tmpdir(), 'playwright-cli');
+ return path.join(socketsDir, installationDirHash, socketName);
}
+}
- private async _canConnect(sessionName: string): Promise<boolean> {
- const socketPath = this._daemonSocketPath(sessionName);
- return new Promise<boolean>(resolve => {
- const socket = net.createConnection(socketPath, () => {
- socket.destroy();
- resolve(true);
- });
- socket.on('error', () => {
- resolve(false);
- });
- });
+type SessionOptions = { config?: string, headed?: boolean };
+
+class SessionManager {
+ readonly sessions: Map<string, Session>;
+
+ private constructor(sessions: Map<string, Session>) {
+ this.sessions = sessions;
+ }
+
+ static async create(options: SessionOptions): Promise<SessionManager> {
+ const dir = daemonProfilesDir;
+ const sessions = new Map<string, Session>([
+ ['default', new Session('default', options)],
+ ]);
+ try {
+ const files = await fs.promises.readdir(dir);
+ for (const file of files) {
+ if (file.startsWith('ud-')) {
+ // Session is like ud-<sessionName>-browserName
+ const sessionName = file.split('-')[1];
+ sessions.set(sessionName, new Session(sessionName, options));
+ }
+ }
+ } catch {
+ }
+ return new SessionManager(sessions);
+ }
+
+ async run(args: any): Promise<void> {
+ const sessionName = this._resolveSessionName(args.session);
+ let session = this.sessions.get(sessionName);
+ if (!session) {
+ session = new Session(sessionName, args);
+ this.sessions.set(sessionName, session);
+ }
+
+ const result = await session.run(args);
+ await printResponse(result);
+ session.close();
+ }
+
+ async stop(sessionName?: string): Promise<void> {
+ sessionName = this._resolveSessionName(sessionName);
+ const session = this.sessions.get(sessionName);
+ if (!session || !await session.canConnect()) {
+ console.log(`Session '${sessionName}' is not running.`);
+ return;
+ }
+
+ await session.stop();
+ }
+
+ async delete(sessionName?: string): Promise<void> {
+ sessionName = this._resolveSessionName(sessionName);
+ const session = this.sessions.get(sessionName);
+ if (!session) {
+ console.log(`No user data found for session '${sessionName}'.`);
+ return;
+ }
+ await session.delete();
+ this.sessions.delete(sessionName);
+ }
+
+ async configure(args: any): Promise<void> {
+ const sessionName = this._resolveSessionName(args.session);
+ let session = this.sessions.get(sessionName);
+ if (!session) {
+ session = new Session(sessionName, {});
+ this.sessions.set(sessionName, session);
+ }
+ await session.restart({ ...args, config: args._[1] });
+ session.close();
}
private _resolveSessionName(sessionName?: string): string {
@@ -298,23 +334,15 @@ class SessionManager {
return process.env.PLAYWRIGHT_CLI_SESSION;
return 'default';
}
-
- private _daemonSocketPath(sessionName: string): string {
- const socketName = `${sessionName}.sock`;
- if (os.platform() === 'win32')
- return `\\\\.\\pipe\\${installationDirHash}-${socketName}`;
- const socketsDir = process.env.PLAYWRIGHT_DAEMON_SOCKETS_DIR || path.join(os.tmpdir(), 'playwright-cli');
- return path.join(socketsDir, installationDirHash, socketName);
- }
}
async function handleSessionCommand(sessionManager: SessionManager, subcommand: string, args: any): Promise<void> {
if (subcommand === 'list') {
- const sessions = await sessionManager.list();
+ const sessions = sessionManager.sessions;
console.log('Sessions:');
- for (const [sessionName, live] of sessions.entries()) {
- const liveMarker = live ? ' (live)' : '';
- console.log(` ${sessionName}${liveMarker}`);
+ for (const session of sessions.values()) {
+ const liveMarker = await session.canConnect() ? ' (live)' : '';
+ console.log(` ${session.name}${liveMarker}`);
}
if (sessions.size === 0)
console.log(' (no sessions)');
@@ -327,9 +355,9 @@ async function handleSessionCommand(sessionManager: SessionManager, subcommand:
}
if (subcommand === 'stop-all') {
- const sessions = await sessionManager.list();
- for (const sessionName of sessions.keys())
- await sessionManager.stop(sessionName);
+ const sessions = sessionManager.sessions;
+ for (const session of sessions.values())
+ await session.stop();
return;
}
@@ -401,7 +429,7 @@ export async function program(options: { version: string }) {
process.exit(1);
}
- const sessionManager = new SessionManager(args);
+ const sessionManager = await SessionManager.create(args);
if (commandName.startsWith('session')) {
const subcommand = args._[0].split('-').slice(1).join('-');
await handleSessionCommand(sessionManager, subcommand, args);
@@ -413,15 +441,12 @@ export async function program(options: { version: string }) {
return;
}
- try {
- await sessionManager.run(args);
- } catch (e) {
- // Close command stops the daemon.
- if (commandName === 'close' && 'Session closed' === (e as Error).message)
- console.log(e.message);
- else
- throw e;
+ if (commandName === 'close') {
+ await handleSessionCommand(sessionManager, 'stop', args);
+ return;
}
+
+ await sessionManager.run(args);
}
export async function printResponse(response: StructuredResponse) {
diff --git a/tests/mcp/cli-fixtures.ts b/tests/mcp/cli-fixtures.ts
index 0ef9b81c05..c41cc2ee10 100644
--- a/tests/mcp/cli-fixtures.ts
+++ b/tests/mcp/cli-fixtures.ts
@@ -39,7 +39,10 @@ export const test = baseTest.extend<{
});
for (const session of sessions) {
- await runCli(childProcess, ['session-stop', session.name], { mcpBrowser, mcpHeadless }, []);
+ await runCli(childProcess, ['session-stop', session.name], { mcpBrowser, mcpHeadless }, []).catch(e => {
+ if (!e.message.includes('is not running'))
+ throw e;
+ });
killProcessGroup(session.pid);
}
diff --git a/tests/mcp/cli.spec.ts b/tests/mcp/cli.spec.ts
index b51fcb7dcb..d7aef87187 100644
--- a/tests/mcp/cli.spec.ts
+++ b/tests/mcp/cli.spec.ts
@@ -42,7 +42,7 @@ test.describe('core', () => {
test('close', async ({ cli, server }) => {
await cli('open', server.HELLO_WORLD);
const { output } = await cli('close');
- expect(output).toContain(`Session closed`);
+ expect(output).toContain(`Session 'default' stopped.`);
});
test('click button', async ({ cli, server }) => {
@@ -404,7 +404,7 @@ test.describe('session', () => {
test('session-list', async ({ cli, server }) => {
const { output: emptyOutput } = await cli('session-list');
expect(emptyOutput).toContain('Sessions:');
- expect(emptyOutput).toContain('(no sessions)');
+ expect(emptyOutput).toContain(' default');
await cli('open', server.HELLO_WORLD);