Skip to content

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

chore: pass daemon session config to the server (#39060)

Pavel Feldmande8df95e3542
diff --git a/packages/playwright/src/mcp/browser/config.ts b/packages/playwright/src/mcp/browser/config.ts
index 7c0eb9b6e2..916a2e81bf 100644
--- a/packages/playwright/src/mcp/browser/config.ts
+++ b/packages/playwright/src/mcp/browser/config.ts
@@ -26,6 +26,7 @@ import { firstRootPath } from '../sdk/server';
import type * as playwright from '../../../types/test';
import type { Config, ToolCapability } from '../config';
import type { ClientInfo } from '../sdk/server';
+import type { SessionConfig } from '../terminal/program';
type ViewportSize = { width: number; height: number };
@@ -42,9 +43,7 @@ export type CLIOptions = {
codegen?: 'typescript' | 'none';
config?: string;
consoleLevel?: 'error' | 'warning' | 'info' | 'debug';
- daemon?: string;
- daemonDataDir?: string;
- daemonHeaded?: boolean;
+ daemonSession?: string;
device?: string;
extension?: boolean;
executablePath?: string;
@@ -107,22 +106,6 @@ export const defaultConfig: FullConfig = {
},
};
-const defaultDaemonConfig = (cliOptions: CLIOptions) => mergeConfig(defaultConfig, {
- browser: {
- userDataDir: '<daemon-data-dir>',
- launchOptions: {
- headless: !cliOptions.daemonHeaded,
- },
- contextOptions: {
- viewport: cliOptions.daemonHeaded ? null : { width: 1280, height: 720 },
- },
- },
- outputMode: 'file',
- snapshot: {
- mode: 'full',
- },
-});
-
type BrowserUserConfig = NonNullable<Config['browser']>;
export type FullConfig = Config & {
@@ -146,6 +129,8 @@ export type FullConfig = Config & {
navigation: number;
},
skillMode?: boolean;
+ configFile?: string;
+ sessionConfig?: SessionConfig;
};
export async function resolveConfig(config: Config): Promise<FullConfig> {
@@ -153,25 +138,27 @@ export async function resolveConfig(config: Config): Promise<FullConfig> {
}
export async function resolveCLIConfig(cliOptions: CLIOptions): Promise<FullConfig> {
- const configInFile = await loadConfig(cliOptions.config);
const envOverrides = configFromEnv();
+ const daemonOverrides = await configForDaemonSession(cliOptions);
const cliOverrides = configFromCLIOptions(cliOptions);
- let result = cliOptions.daemon ? defaultDaemonConfig(cliOptions) : defaultConfig;
+ const configFile = cliOverrides.configFile ?? envOverrides.configFile ?? daemonOverrides.configFile;
+ const configInFile = await loadConfig(configFile);
+
+ let result = defaultConfig;
result = mergeConfig(result, configInFile);
+ result = mergeConfig(result, daemonOverrides);
result = mergeConfig(result, envOverrides);
result = mergeConfig(result, cliOverrides);
- if (cliOptions.daemon)
+ if (daemonOverrides.sessionConfig) {
result.skillMode = true;
- if (result.browser.userDataDir === '<daemon-data-dir>') {
- // No custom value provided, use the daemon data dir.
- const browserToken = result.browser.launchOptions?.channel ?? result.browser?.browserName;
- const userDataDir = `${cliOptions.daemonDataDir}-${browserToken}`;
-
- // Use default user profile with extension.
- if (!result.extension)
+ if (!result.extension && !result.browser.userDataDir && daemonOverrides.sessionConfig.userDataDirPrefix) {
+ // No custom value provided, use the daemon data dir.
+ const browserToken = result.browser.launchOptions?.channel ?? result.browser?.browserName;
+ const userDataDir = `${daemonOverrides.sessionConfig.userDataDirPrefix}-${browserToken}`;
result.browser.userDataDir = userDataDir;
+ }
}
if (result.browser.browserName === 'chromium' && result.browser.launchOptions.chromiumSandbox === undefined) {
@@ -181,7 +168,15 @@ export async function resolveCLIConfig(cliOptions: CLIOptions): Promise<FullConf
result.browser.launchOptions.chromiumSandbox = true;
}
+ result.configFile = configFile;
+ result.sessionConfig = daemonOverrides.sessionConfig;
+
+ // Daemon has different defaults.
+ if (result.sessionConfig && result.browser.launchOptions.headless !== false)
+ result.browser.contextOptions.viewport ??= { width: 1280, height: 720 };
+
await validateConfig(result);
+
return result;
}
@@ -202,7 +197,7 @@ async function validateConfig(config: FullConfig): Promise<void> {
throw new Error('saveVideo is not supported when sharedBrowserContext is true');
}
-export function configFromCLIOptions(cliOptions: CLIOptions): Config {
+export function configFromCLIOptions(cliOptions: CLIOptions): Config & { configFile?: string } {
let browserName: 'chromium' | 'firefox' | 'webkit' | undefined;
let channel: string | undefined;
switch (cliOptions.browser) {
@@ -269,7 +264,7 @@ export function configFromCLIOptions(cliOptions: CLIOptions): Config {
if (cliOptions.grantPermissions)
contextOptions.permissions = cliOptions.grantPermissions;
- const result: Config = {
+ const config: Config = {
browser: {
browserName,
isolated: cliOptions.isolated,
@@ -313,10 +308,10 @@ export function configFromCLIOptions(cliOptions: CLIOptions): Config {
},
};
- return result;
+ return { ...config, configFile: cliOptions.config };
}
-function configFromEnv(): Config {
+function configFromEnv(): Config & { configFile?: string } {
const options: CLIOptions = {};
options.allowedHosts = commaSeparatedList(process.env.PLAYWRIGHT_MCP_ALLOWED_HOSTNAMES);
options.allowedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_ALLOWED_ORIGINS);
@@ -364,6 +359,23 @@ function configFromEnv(): Config {
return configFromCLIOptions(options);
}
+async function configForDaemonSession(cliOptions: CLIOptions): Promise<Config & { configFile?: string, sessionConfig?: SessionConfig }> {
+ if (!cliOptions.daemonSession)
+ return {};
+
+ const sessionConfig = await fs.promises.readFile(cliOptions.daemonSession, 'utf-8').then(data => JSON.parse(data) as SessionConfig);
+ const config = configFromCLIOptions({
+ config: sessionConfig.cli.config,
+ browser: sessionConfig.cli.browser,
+ isolated: sessionConfig.cli.isolated,
+ headless: !sessionConfig.cli.headed,
+ extension: sessionConfig.cli.extension,
+ outputMode: 'file',
+ snapshotMode: 'full',
+ });
+ return { ...config, sessionConfig };
+}
+
async function loadConfig(configFile: string | undefined): Promise<Config> {
if (!configFile)
return {};
diff --git a/packages/playwright/src/mcp/browser/response.ts b/packages/playwright/src/mcp/browser/response.ts
index 6c57185c5a..f1e432e573 100644
--- a/packages/playwright/src/mcp/browser/response.ts
+++ b/packages/playwright/src/mcp/browser/response.ts
@@ -142,6 +142,8 @@ export class Response {
const text: string[] = [];
for (const section of sections) {
+ if (!section.content.length)
+ continue;
text.push(`### ${section.title}`);
if (section.codeframe)
text.push(`\`\`\`${section.codeframe}`);
diff --git a/packages/playwright/src/mcp/program.ts b/packages/playwright/src/mcp/program.ts
index c5c34400a7..506acb6e4c 100644
--- a/packages/playwright/src/mcp/program.ts
+++ b/packages/playwright/src/mcp/program.ts
@@ -77,10 +77,7 @@ export function decorateCommand(command: Command, version: string) {
.option('--user-data-dir <path>', 'path to the user data directory. If not specified, a temporary directory will be created.')
.option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280x720"', resolutionParser.bind(null, '--viewport-size'))
.addOption(new ProgramOption('--vision', 'Legacy option, use --caps=vision instead').hideHelp())
- .addOption(new ProgramOption('--daemon <socket>', 'run as daemon').hideHelp())
- .addOption(new ProgramOption('--daemon-data-dir <path>', 'path to the daemon data directory.').hideHelp())
- .addOption(new ProgramOption('--daemon-headed', 'run daemon in headed mode').hideHelp())
- .addOption(new ProgramOption('--daemon-version <version>', 'version of this daemon').hideHelp())
+ .addOption(new ProgramOption('--daemon-session <path>', 'path to the daemon config.').hideHelp())
.action(async options => {
// normalize the --no-sandbox option: sandbox = true => nothing was passed, sandbox = false => --no-sandbox was passed.
@@ -110,7 +107,7 @@ export function decorateCommand(command: Command, version: string) {
const browserContextFactory = contextFactory(config);
const extensionContextFactory = new ExtensionContextFactory(config.browser.launchOptions.channel || 'chrome', config.browser.userDataDir, config.browser.launchOptions.executablePath);
- if (options.daemon) {
+ if (config.sessionConfig) {
const contextFactory = config.extension ? extensionContextFactory : browserContextFactory;
const serverBackendFactory: mcpServer.ServerBackendFactory = {
name: 'Playwright',
@@ -118,7 +115,7 @@ export function decorateCommand(command: Command, version: string) {
version,
create: () => new BrowserServerBackend(config, contextFactory, { allTools: true })
};
- const socketPath = await startMcpDaemonServer(options.daemon, serverBackendFactory, options.daemonVersion);
+ const socketPath = await startMcpDaemonServer(config.sessionConfig, serverBackendFactory);
console.error(`Daemon server listening on ${socketPath}`);
return;
}
diff --git a/packages/playwright/src/mcp/terminal/commands.ts b/packages/playwright/src/mcp/terminal/commands.ts
index 1bf0be76df..62d04df115 100644
--- a/packages/playwright/src/mcp/terminal/commands.ts
+++ b/packages/playwright/src/mcp/terminal/commands.ts
@@ -26,10 +26,10 @@ const open = declareCommand({
description: 'Open URL',
category: 'core',
args: z.object({
- url: z.string().describe('The URL to navigate to'),
+ url: z.string().optional().describe('The URL to navigate to'),
}),
toolName: 'browser_navigate',
- toolParams: ({ url }) => ({ url }),
+ toolParams: ({ url }) => ({ url: url || 'about:blank' }),
});
const close = declareCommand({
@@ -498,6 +498,17 @@ const sessionList = declareCommand({
toolParams: () => ({}),
});
+const sessionRestart = declareCommand({
+ name: 'session-restart',
+ description: 'Restart session',
+ category: 'session',
+ args: z.object({
+ name: z.string().optional().describe('Name of the session to restart. If omitted, current session is restarted.'),
+ }),
+ toolName: '',
+ toolParams: () => ({}),
+});
+
const sessionStop = declareCommand({
name: 'session-stop',
description: 'Stop session',
@@ -617,6 +628,7 @@ const commandsArray: AnyCommandSchema[] = [
// session category
sessionList,
sessionStop,
+ sessionRestart,
sessionStopAll,
sessionDelete,
];
diff --git a/packages/playwright/src/mcp/terminal/daemon.ts b/packages/playwright/src/mcp/terminal/daemon.ts
index 75ac62fcb7..e48711267a 100644
--- a/packages/playwright/src/mcp/terminal/daemon.ts
+++ b/packages/playwright/src/mcp/terminal/daemon.ts
@@ -29,6 +29,7 @@ import { parseCommand } from './command';
import type { ServerBackendFactory } from '../sdk/server';
import type * as mcp from '../sdk/exports';
+import type { SessionConfig } from './program';
const daemonDebug = debug('pw:daemon');
@@ -42,14 +43,11 @@ async function socketExists(socketPath: string): Promise<boolean> {
return false;
}
-/**
- * Start a daemon server listening on Unix domain socket (Unix) or named pipe (Windows).
- */
export async function startMcpDaemonServer(
- socketPath: string,
+ sessionConfig: SessionConfig,
serverBackendFactory: ServerBackendFactory,
- daemonVersion: string
): Promise<string> {
+ const { socketPath, version } = sessionConfig;
// Clean up existing socket file on Unix
if (os.platform() !== 'win32' && await socketExists(socketPath)) {
daemonDebug(`Socket already exists, removing: ${socketPath}`);
@@ -85,26 +83,10 @@ export async function startMcpDaemonServer(
const server = net.createServer(socket => {
daemonDebug('new client connection');
- const connection = new SocketConnection(socket, daemonVersion);
+ const connection = new SocketConnection(socket, version);
connection.onclose = () => {
daemonDebug('client disconnected');
};
- connection.onversionerror = (id, e) => {
- if (daemonVersion === 'undefined-for-test')
- return false;
-
- if (semverGreater(daemonVersion, e.received)) {
- // eslint-disable-next-line no-console
- connection.send({ id, error: `Client is too old: daemon is ${daemonVersion}, client is ${e.received}.` }).catch(e => console.error(e));
- } else {
- gracefullyProcessExitDoNotHang(0, async () => {
- // eslint-disable-next-line no-console
- await connection.send({ id, error: `Daemon is too old: daemon is ${daemonVersion}, client is ${e.received}. Stopping it.` }).catch(e => console.error(e));
- server.close();
- });
- }
- return true;
- };
connection.onmessage = async message => {
const { id, method, params } = message;
try {
@@ -170,17 +152,3 @@ function parseCliCommand(args: Record<string, string> & { _: string[] }): { tool
throw new Error('Command is required');
return parseCommand(command, args);
}
-
-function semverGreater(a: string, b: string): boolean {
- a = a.replace(/-next$/, '');
- b = b.replace(/-next$/, '');
- const aParts = a.split('.').map(Number);
- const bParts = b.split('.').map(Number);
- for (let i = 0; i < 4; i++) {
- if (aParts[i] > bParts[i])
- return true;
- if (aParts[i] < bParts[i])
- return false;
- }
- return false;
-}
diff --git a/packages/playwright/src/mcp/terminal/program.ts b/packages/playwright/src/mcp/terminal/program.ts
index 8e37cb67fc..0394252432 100644
--- a/packages/playwright/src/mcp/terminal/program.ts
+++ b/packages/playwright/src/mcp/terminal/program.ts
@@ -26,38 +26,58 @@ import os from 'os';
import path from 'path';
import { SocketConnection } from './socketConnection';
-import type { Section } from '../browser/response';
-
-export type StructuredResponse = {
- isError?: boolean;
- text?: string;
- sections: Section[];
+type MinimistArgs = {
+ _: string[];
+ [key: string]: any;
};
-type SessionOptions = {
- config?: string;
- headed?: boolean;
- extension?: boolean;
- daemonVersion: string;
- browser?: string;
- isolated?: boolean;
+export type SessionConfig = {
+ version: string;
+ socketPath: string;
+ cli: {
+ headed?: boolean;
+ extension?: boolean;
+ browser?: string;
+ isolated?: boolean;
+ config?: string;
+ };
+ userDataDirPrefix?: string;
};
class Session {
readonly name: string;
- private _socketPath: string;
private _connection: SocketConnection | undefined;
private _nextMessageId = 1;
private _callbacks = new Map<number, { resolve: (o: any) => void, reject: (e: Error) => void, method: string, params: any }>();
- private _options: SessionOptions;
+ private _config: SessionConfig;
+ private _clientVersion: string;
- constructor(name: string, options: SessionOptions) {
+ constructor(clientVersion: string, name: string, options: SessionConfig) {
this.name = name;
- this._socketPath = this._daemonSocketPath();
- this._options = options;
+ this._clientVersion = clientVersion;
+ this._config = options;
+ }
+
+ config(): SessionConfig {
+ return this._config;
+ }
+
+ isCompatible(): boolean {
+ return this._clientVersion === this._config.version;
+ }
+
+ checkCompatible() {
+ if (!this.isCompatible()) {
+ throw new Error(`Client is v${this._clientVersion}, session '${this.name}' is v${this._config.version}. Run
+
+ playwright-cli session-restart${this.name !== 'default' ? ` ${this.name}` : ''}
+
+to restart the session daemon.`);
+ }
}
- async run(args: any) {
+ async run(args: MinimistArgs) {
+ this.checkCompatible();
return await this._send('run', { args, cwd: process.cwd() });
}
@@ -74,14 +94,13 @@ class Session {
this.close();
if (os.platform() !== 'win32')
- await fs.promises.unlink(this._socketPath).catch(() => {});
+ await fs.promises.unlink(this._config.socketPath).catch(() => {});
console.log(`Session '${this.name}' stopped.`);
}
- async restart(options: SessionOptions): Promise<void> {
+ async restart(config: SessionConfig): Promise<void> {
await this.stop();
-
- this._options = options;
+ this._config = config;
await this._startDaemonIfNeeded();
}
@@ -92,7 +111,7 @@ class Session {
id: messageId,
method,
params,
- version: this._options.daemonVersion,
+ version: this._config.version,
};
const responsePromise = new Promise<any>((resolve, reject) => {
this._callbacks.set(messageId, { resolve, reject, method, params });
@@ -121,12 +140,13 @@ class Session {
return;
}
- for (const dir of matchingEntries) {
- const userDataDir = path.resolve(daemonProfilesDir, dir);
+ for (const entry of matchingEntries) {
+ const userDataDir = path.resolve(daemonProfilesDir, entry);
for (let i = 0; i < 5; i++) {
try {
await fs.promises.rm(userDataDir, { recursive: true });
- console.log(`Deleted user data for session '${this.name}'.`);
+ if (entry.startsWith('ud-'))
+ console.log(`Deleted user data for session '${this.name}'.`);
break;
} catch (e: any) {
if (e.code === 'ENOENT') {
@@ -143,12 +163,12 @@ class Session {
async _connect(): Promise<{ socket?: net.Socket, error?: Error }> {
return await new Promise(resolve => {
- const socket = net.createConnection(this._socketPath, () => {
+ const socket = net.createConnection(this._config.socketPath, () => {
resolve({ socket });
});
socket.on('error', error => {
if (os.platform() !== 'win32')
- void fs.promises.unlink(this._socketPath).catch(() => {}).then(() => resolve({ error }));
+ void fs.promises.unlink(this._config.socketPath).catch(() => {}).then(() => resolve({ error }));
else
resolve({ error });
});
@@ -172,20 +192,8 @@ class Session {
if (!socket)
socket = await this._startDaemon();
- this._connection = new SocketConnection(socket, this._options.daemonVersion);
+ this._connection = new SocketConnection(socket, this._config.version);
this._connection.onmessage = message => this._onMessage(message);
- this._connection.onversionerror = (id, e) => {
- if (e.received && e.received !== 'undefined-for-test') {
- // This is daemon telling us the version is bad.
- return false;
- }
-
- // This will only happen once when hitting the non-versione-aware daemon.
- // Only kill daemon if it is older.
- console.error(`Daemon is older than client, killing it.`);
- this.stop().then(() => process.exit(1)).catch(() => process.exit(1));
- return true;
- };
this._connection.onclose = () => this.close();
return this._connection;
}
@@ -207,36 +215,25 @@ class Session {
private async _startDaemon(): Promise<net.Socket> {
await fs.promises.mkdir(daemonProfilesDir, { recursive: true });
- 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}`] : [];
- const headedArg = this._options.headed ? [`--daemon-headed`] : [];
- const extensionArg = this._options.extension ? [`--extension`] : [];
- const isolatedArg = this._options.isolated ? [`--isolated`] : [];
- const browserArg = this._options.browser ? [`--browser=${this._options.browser}`] : [];
- const sessionOptionsFile = path.resolve(daemonProfilesDir, `${this.name}.session`);
- await fs.promises.writeFile(sessionOptionsFile, JSON.stringify({ ...this._options, _: undefined }, null, 2));
+ const sessionConfigFile = path.resolve(daemonProfilesDir, `${this.name}.session`);
+ this._config.version = this._clientVersion;
+ await fs.promises.writeFile(sessionConfigFile, JSON.stringify(this._config, null, 2));
const outLog = path.join(daemonProfilesDir, 'out.log');
const errLog = path.join(daemonProfilesDir, 'err.log');
const out = fs.openSync(outLog, 'w');
const err = fs.openSync(errLog, 'w');
- const child = spawn(process.execPath, [
+ const args = [
cliPath,
'run-mcp-server',
`--output-dir=${outputDir}`,
- `--daemon=${this._socketPath}`,
- `--daemon-data-dir=${userDataDir}`,
- `--daemon-version=${this._options.daemonVersion}`,
- ...configArg,
- ...headedArg,
- ...extensionArg,
- ...isolatedArg,
- ...browserArg,
- ], {
+ `--daemon-session=${sessionConfigFile}`,
+ ];
+
+ const child = spawn(process.execPath, args, {
detached: true,
stdio: ['ignore', out, err],
cwd: process.cwd(), // Will be used as root.
@@ -244,8 +241,8 @@ class Session {
child.unref();
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)}\`.`);
+ if (this._config.cli.config)
+ console.log(`- Using config file at \`${path.relative(process.cwd(), this._config.cli.config)}\`.`);
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.`);
@@ -269,43 +266,34 @@ class Session {
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 ${this._socketPath} after ${maxRetries * retryDelay}ms`);
+ console.error(`Failed to connect to daemon at ${this._config.socketPath} after ${maxRetries * retryDelay}ms`);
if (outData.length)
console.log(outData);
if (errData.length)
console.error(errData);
process.exit(1);
}
-
- 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);
- }
}
class SessionManager {
+ readonly clientVersion: string;
readonly sessions: Map<string, Session>;
- readonly options: SessionOptions;
- private constructor(sessions: Map<string, Session>, options: SessionOptions) {
+ private constructor(clientVersion: string, sessions: Map<string, Session>, args: MinimistArgs) {
+ this.clientVersion = clientVersion;
this.sessions = sessions;
- this.options = options;
}
- static async create(options: SessionOptions): Promise<SessionManager> {
+ static async create(clientVersion: string, args: MinimistArgs): Promise<SessionManager> {
const dir = daemonProfilesDir;
- const sessions = new Map<string, Session>([
- ['default', new Session('default', options)],
- ]);
+ const sessions = new Map<string, Session>();
const files = await fs.promises.readdir(dir).catch(() => []);
for (const file of files) {
try {
if (file.endsWith('.session')) {
const sessionName = path.basename(file, '.session');
- sessions.set(sessionName, new Session(sessionName, options));
+ const sessionConfig = await fs.promises.readFile(path.join(dir, file), 'utf-8').then(data => JSON.parse(data)) as SessionConfig;
+ sessions.set(sessionName, new Session(clientVersion, sessionName, sessionConfig));
continue;
}
@@ -313,24 +301,26 @@ class SessionManager {
if (file.startsWith('ud-')) {
// Session is like ud-<sessionName>-browserName
const sessionName = file.split('-')[1];
- if (!sessions.has(sessionName))
- sessions.set(sessionName, new Session(sessionName, options));
+ if (!sessions.has(sessionName)) {
+ const sessionConfig = sessionConfigFromArgs('0.0.61', sessionName, { _: [] });
+ sessions.set(sessionName, new Session(clientVersion, sessionName, sessionConfig));
+ }
}
} catch {
}
}
- return new SessionManager(sessions, options);
+ return new SessionManager(clientVersion, sessions, args);
}
- async run(args: any): Promise<void> {
+ async run(args: MinimistArgs): Promise<void> {
const sessionName = this._resolveSessionName(args.session);
let session = this.sessions.get(sessionName);
if (!session) {
- session = new Session(sessionName, { ...this.options, ...args });
+ session = new Session(this.clientVersion, sessionName, sessionConfigFromArgs(this.clientVersion, sessionName, args));
this.sessions.set(sessionName, session);
}
- for (const globalOption of ['browser', 'config', 'daemonVersion', 'extension', 'headed', 'help', 'isolated', 'session', 'version'])
+ for (const globalOption of ['browser', 'config', 'extension', 'headed', 'help', 'isolated', 'session', 'version'])
delete args[globalOption];
const result = await session.run(args);
console.log(result.text);
@@ -359,14 +349,26 @@ class SessionManager {
this.sessions.delete(sessionName);
}
+ async restart(sessionName?: string): Promise<void> {
+ sessionName = this._resolveSessionName(sessionName);
+ const session = this.sessions.get(sessionName);
+ if (!session) {
+ console.log(`Session '${sessionName}' does not exist.`);
+ return;
+ }
+ await session.restart(session.config());
+ session.close();
+ }
+
async configure(args: any): Promise<void> {
const sessionName = this._resolveSessionName(args.session);
let session = this.sessions.get(sessionName);
+ const sessionConfig = sessionConfigFromArgs(this.clientVersion, sessionName, args);
if (!session) {
- session = new Session(sessionName, this.options);
+ session = new Session(this.clientVersion, sessionName, sessionConfig);
this.sessions.set(sessionName, session);
}
- await session.restart({ ...this.options, ...args });
+ await session.restart(sessionConfig);
session.close();
}
@@ -384,14 +386,20 @@ async function handleSessionCommand(sessionManager: SessionManager, subcommand:
const sessions = sessionManager.sessions;
console.log('Sessions:');
for (const session of sessions.values()) {
- const liveMarker = await session.canConnect() ? ' (live)' : '';
- console.log(` ${session.name}${liveMarker}`);
+ const liveMarker = await session.canConnect() ? `[running] ` : '[stopped] ';
+ const restartMarker = !session.isCompatible() ? ` - v${session.config().version}, needs restart` : '';
+ console.log(` ${liveMarker}${session.name}${restartMarker}`);
}
if (sessions.size === 0)
console.log(' (no sessions)');
return;
}
+ if (subcommand === 'restart') {
+ await sessionManager.restart(args._[1]);
+ return;
+ }
+
if (subcommand === 'stop') {
await sessionManager.stop(args._[1]);
return;
@@ -449,8 +457,9 @@ const booleanOptions = [
];
export async function program(options: { version: string }) {
+ const version = process.env.PLAYWRIGHT_CLI_VERSION_FOR_TEST || options.version;
const argv = process.argv.slice(2);
- const args = require('minimist')(argv, { boolean: booleanOptions });
+ const args: MinimistArgs = require('minimist')(argv, { boolean: booleanOptions });
for (const option of booleanOptions) {
if (!argv.includes(`--${option}`) && !argv.includes(`--no-${option}`))
delete args[option];
@@ -460,7 +469,7 @@ export async function program(options: { version: string }) {
const commandName = args._[0];
if (args.version || args.v) {
- console.log(options.version);
+ console.log(version);
process.exit(0);
}
@@ -474,13 +483,14 @@ export async function program(options: { version: string }) {
}
process.exit(0);
}
+
if (!command) {
console.error(`Unknown command: ${commandName}\n`);
console.log(help.global);
process.exit(1);
}
- const sessionManager = await SessionManager.create({ daemonVersion: options.version, ...args });
+ const sessionManager = await SessionManager.create(version, args);
if (commandName.startsWith('session')) {
const subcommand = args._[0].split('-').slice(1).join('-');
await handleSessionCommand(sessionManager, subcommand, args);
@@ -502,15 +512,31 @@ export async function program(options: { version: string }) {
const outputDir = path.join(process.cwd(), '.playwright-cli');
-function resolveConfigFile(configParam: string | undefined) {
- const configFile = configParam || process.env.PLAYWRIGHT_CLI_CONFIG;
- if (configFile)
- return path.resolve(process.cwd(), configFile);
+function 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);
+}
+function sessionConfigFromArgs(version: string, sessionName: string, args: MinimistArgs): SessionConfig {
+ let config = args.config;
try {
- if (fs.existsSync(path.resolve(process.cwd(), 'playwright-cli.json')))
- return path.resolve(process.cwd(), 'playwright-cli.json');
+ if (!config && fs.existsSync('playwright-cli.json'))
+ config = path.resolve('playwright-cli.json');
} catch {
}
- return undefined;
+ return {
+ version,
+ socketPath: daemonSocketPath(sessionName),
+ cli: {
+ headed: args.headed,
+ extension: args.extension,
+ browser: args.browser,
+ isolated: args.isolated,
+ config,
+ },
+ userDataDirPrefix: path.resolve(daemonProfilesDir, `ud-${sessionName}`),
+ };
}
diff --git a/packages/playwright/src/mcp/terminal/socketConnection.ts b/packages/playwright/src/mcp/terminal/socketConnection.ts
index ba72baa63c..9ea6dc5761 100644
--- a/packages/playwright/src/mcp/terminal/socketConnection.ts
+++ b/packages/playwright/src/mcp/terminal/socketConnection.ts
@@ -87,3 +87,17 @@ export class SocketConnection {
}
}
}
+
+export function compareSemver(a: string, b: string): number {
+ a = a.replace(/-[\w]+$/, '');
+ b = b.replace(/-[\w]+$/, '');
+ const aParts = a.split('.').map(Number);
+ const bParts = b.split('.').map(Number);
+ for (let i = 0; i < 3; i++) {
+ if (aParts[i] > bParts[i])
+ return 1;
+ if (aParts[i] < bParts[i])
+ return -1;
+ }
+ return 0;
+}
diff --git a/tests/mcp/cli-fixtures.ts b/tests/mcp/cli-fixtures.ts
index 793d2c0936..2e97537863 100644
--- a/tests/mcp/cli-fixtures.ts
+++ b/tests/mcp/cli-fixtures.ts
@@ -65,6 +65,7 @@ async function runCli(childProcess: CommonFixtures['childProcess'], args: string
cwd: cliOptions.cwd ?? testInfo.outputPath(),
env: {
...process.env,
+ ...cliOptions.env,
PLAYWRIGHT_DAEMON_INSTALL_DIR: testInfo.outputPath(),
PLAYWRIGHT_DAEMON_SESSION_DIR: testInfo.outputPath('daemon'),
PLAYWRIGHT_DAEMON_SOCKETS_DIR: path.join(testInfo.project.outputDir, 'daemon-sockets'),
diff --git a/tests/mcp/cli.spec.ts b/tests/mcp/cli.spec.ts
index 2b249ab968..92630db7dd 100644
--- a/tests/mcp/cli.spec.ts
+++ b/tests/mcp/cli.spec.ts
@@ -442,13 +442,13 @@ test.describe('session', () => {
test('session-list', async ({ cli, server }) => {
const { output: emptyOutput } = await cli('session-list');
expect(emptyOutput).toContain('Sessions:');
- expect(emptyOutput).toContain(' default');
+ expect(emptyOutput).toContain(' (no sessions)');
await cli('open', server.HELLO_WORLD);
const { output: listOutput } = await cli('session-list');
expect(listOutput).toContain('Sessions:');
- expect(listOutput).toContain('default (live)');
+ expect(listOutput).toContain(' [running] default');
});
test('session-stop', async ({ cli, server }) => {
@@ -458,7 +458,7 @@ test.describe('session', () => {
expect(output).toContain(`Session 'default' stopped.`);
const { output: listOutput } = await cli('session-list');
- expect(listOutput).not.toContain('(live)');
+ expect(listOutput).toContain('[stopped] default');
});
test('session-stop named session', async ({ cli, server }) => {
@@ -478,13 +478,13 @@ test.describe('session', () => {
await cli('open', '--session=session2', server.HELLO_WORLD);
const { output: listBefore } = await cli('session-list');
- expect(listBefore).toContain('session1 (live)');
- expect(listBefore).toContain('session2 (live)');
+ expect(listBefore).toContain('[running] session1');
+ expect(listBefore).toContain('[running] session2');
await cli('session-stop-all');
const { output: listAfter } = await cli('session-list');
- expect(listAfter).not.toContain('(live)');
+ expect(listAfter).not.toContain('[running]');
});
test('session-delete', async ({ cli, server, mcpBrowser }, testInfo) => {
@@ -520,17 +520,32 @@ test.describe('session', () => {
await cli('open', server.HELLO_WORLD);
const { output: listBefore } = await cli('session-list');
- expect(listBefore).toContain('default (live)');
+ expect(listBefore).toContain('[running] default');
// Close the browser - this will cause the daemon to exit so the command may fail
await cli('run-code', '() => page.context().browser().close()').catch(() => {});
- await expect.poll(() => cli('session-list').then(r => r.output)).not.toContain('(live)');
+ await expect.poll(() => cli('session-list').then(r => r.output)).toContain('[stopped]');
});
-});
-test.describe('config', () => {
- test('should work', async ({ cli, server }, testInfo) => {
+ test('session restart', async ({ cli, server }, testInfo) => {
+ const config = { browser: { contextOptions: { viewport: { width: 700, height: 500 } } } };
+ const configPath = testInfo.outputPath('config.json');
+ await fs.promises.writeFile(configPath, JSON.stringify(config, null, 2));
+ {
+ await cli('open', server.HELLO_WORLD, '--config=' + configPath);
+ const { output } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight');
+ expect(output).toContain('700x500');
+ await cli('close');
+ }
+ {
+ await cli('open', server.HELLO_WORLD);
+ const { output } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight');
+ expect(output).toContain('700x500');
+ }
+ });
+
+ test('config should work', async ({ cli, server }, testInfo) => {
// Start a session with default config
await cli('open', server.PREFIX);
const { output: beforeOutput } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight');
@@ -556,39 +571,17 @@ test.describe('config', () => {
});
test.describe('versions', () => {
- test('old client', async ({ cli, server }) => {
- await cli('config', '--daemonVersion=2.0.0');
- const { error, exitCode } = await cli('open', server.PREFIX);
- expect(exitCode).toBe(1);
- expect(error).toMatch(/Client is too old: daemon is 2\.0\.0, client is 1.*/);
- });
-
- test('old daemon', async ({ cli, server }) => {
- await cli('config');
- {
- const { error, exitCode } = await cli('open', server.PREFIX, '--daemonVersion=2.0.0');
- expect(exitCode).toBe(1);
- expect(error).toMatch(/Daemon is too old: daemon is 1.*, client is 2\.0\.0. Stopping it/);
- }
- {
- const { output, exitCode } = await cli('open', server.PREFIX, '--daemonVersion=2.0.0');
- expect(exitCode).toBe(0);
- expect(output).toContain('Daemon for `default` session started with pid');
- await cli('session-stop', '--daemonVersion=2.0.0');
- }
- });
-
- test('very old daemon', async ({ cli, server }) => {
- {
- const { exitCode } = await cli('open', server.PREFIX, '--daemonVersion=undefined-for-test');
- expect(exitCode).toBe(0);
- }
-
- {
- const { exitCode, error } = await cli('open', server.PREFIX);
- expect(exitCode).toBe(1);
- expect(error).toContain('Daemon is older than client, killing it.');
- }
+ test('old client', async ({ cli }) => {
+ await cli('open', { env: { PLAYWRIGHT_CLI_VERSION_FOR_TEST: '2.0.0' } });
+ const { output: output1 } = await cli('session-list');
+ expect(output1).toContain(' [running] default - v2.0.0, needs restart');
+
+ await cli('session-stop');
+ const { output: output2 } = await cli('session-list');
+ expect(output2).toContain(' [stopped] default - v2.0.0, needs restart');
+ await cli('session-delete');
+ const { output: output3 } = await cli('session-list');
+ expect(output3).toContain(' (no sessions)');
});
});
@@ -612,9 +605,9 @@ test.describe('parsing', () => {
});
test('missing argument', async ({ cli, server }) => {
- const { error, exitCode } = await cli('open');
+ const { error, exitCode } = await cli('keyup');
expect(exitCode).toBe(1);
- expect(error).toContain(`error: 'url' argument: expected string, received undefined`);
+ expect(error).toContain(`error: 'key' argument: expected string, received undefined`);
});
test('wrong argument type', async ({ cli, server }) => {
@@ -647,13 +640,18 @@ test.describe('isolated', () => {
const sessionFile = testInfo.outputPath('daemon', 'default.session');
expect(fs.existsSync(sessionFile)).toBe(true);
const sessionOptions = JSON.parse(await fs.promises.readFile(sessionFile, 'utf-8'));
- expect(sessionOptions).toEqual(expect.objectContaining({
- isolated: true,
- }));
+ expect(sessionOptions).toEqual({
+ cli: {
+ isolated: true,
+ },
+ socketPath: expect.any(String),
+ userDataDirPrefix: expect.any(String),
+ version: expect.any(String),
+ });
const { output: listOutput } = await cli('session-list');
expect(listOutput).toContain('Sessions:');
- expect(listOutput).toContain('default (live)');
+ expect(listOutput).toContain(' [running] default');
});
});