Skip to content

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

feat(cli): support global config file at ~/.playwright/cli.config.json (#39836)

Yury Semikhatsky1d12d2076ef7
diff --git a/packages/playwright-core/src/tools/cli-client/program.ts b/packages/playwright-core/src/tools/cli-client/program.ts
index de3095bcb7..4b99b7d77e 100644
--- a/packages/playwright-core/src/tools/cli-client/program.ts
+++ b/packages/playwright-core/src/tools/cli-client/program.ts
@@ -20,7 +20,6 @@
import { execSync, spawn } from 'child_process';
import crypto from 'crypto';
-import fs from 'fs';
import os from 'os';
import path from 'path';
import { createClientInfo, explicitSessionName, Registry, resolveSessionName } from './registry';
@@ -28,7 +27,6 @@ import { Session, renderResolvedConfig } from './session';
import { serverRegistry } from '../../serverRegistry';
import { minimist } from './minimist';
-import type { Config } from '../mcp/config.d';
import type { ClientInfo, SessionFile } from './registry';
import type { BrowserDescriptor } from '../../serverRegistry';
import type { MinimistArgs } from './minimist';
@@ -156,7 +154,7 @@ export async function program(options?: { embedderVersion?: string}) {
await session.stop();
return;
case 'install':
- await install(args);
+ await runInitWorkspace(args);
return;
case 'install-browser':
await installBrowser();
@@ -201,50 +199,21 @@ async function runInSession(entry: SessionFile, clientInfo: ClientInfo, args: Mi
console.log(result.text);
}
-async function install(args: MinimistArgs) {
- const cwd = process.cwd();
-
- // Create .playwright folder to mark workspace root
- const playwrightDir = path.join(cwd, '.playwright');
- await fs.promises.mkdir(playwrightDir, { recursive: true });
- console.log(`✅ Workspace initialized at \`${cwd}\`.`);
-
- if (args.skills !== undefined) {
- const target = args.skills === 'agents' ? 'agents' : 'claude';
- const skillSourceDir = path.join(__dirname, 'skill');
- const skillDestDir = path.join(cwd, `.${target}`, 'skills', 'playwright-cli');
-
- if (!fs.existsSync(skillSourceDir)) {
- console.error('❌ Skills source directory not found:', skillSourceDir);
- process.exit(1);
- }
-
- await fs.promises.cp(skillSourceDir, skillDestDir, { recursive: true });
- console.log(`✅ Skills installed to \`${path.relative(cwd, skillDestDir)}\`.`);
- }
-
- await ensureConfiguredBrowserInstalled();
-}
-
-async function ensureConfiguredBrowserInstalled() {
- if (fs.existsSync(defaultConfigFile())) {
- const { registry } = await import('playwright-core/lib/server/registry/index');
- // Config exists, ensure configured browser is installed
- const data = await fs.promises.readFile(defaultConfigFile(), 'utf-8');
- const config = JSON.parse(data.charCodeAt(0) === 0xFEFF ? data.slice(1) : data) as Config;
- const browserName = config.browser?.browserName ?? 'chromium';
- const channel = config.browser?.launchOptions?.channel;
- if (!channel || channel.startsWith('chromium')) {
- const executable = registry.findExecutable(channel ?? browserName);
- if (executable && !fs.existsSync(executable?.executablePath()!))
- await registry.install([executable]);
- }
- } else {
- // No config exists, detect or install a browser and create config
- const channel = await findOrInstallDefaultBrowser();
- if (channel !== 'chrome')
- await createDefaultConfig(channel);
- }
+async function runInitWorkspace(args: MinimistArgs) {
+ const cliPath = require.resolve('../cli-daemon/program.js');
+ const daemonArgs: string[] = [cliPath, '--init-workspace', ...(args.skills ? ['--init-skills', String(args.skills)] : [])];
+ await new Promise<void>((resolve, reject) => {
+ const child = spawn(process.execPath, daemonArgs, {
+ stdio: 'inherit',
+ cwd: process.cwd(),
+ });
+ child.on('close', code => {
+ if (code === 0)
+ resolve();
+ else
+ reject(new Error(`Workspace initialization failed with exit code ${code}`));
+ });
+ });
}
async function installBrowser() {
@@ -253,40 +222,6 @@ async function installBrowser() {
program.parse(argv);
}
-async function createDefaultConfig(channel: string) {
- const config: Config = {
- browser: {
- browserName: 'chromium',
- launchOptions: {
- channel,
- },
- },
- };
- await fs.promises.writeFile(defaultConfigFile(), JSON.stringify(config, null, 2));
- console.log(`✅ Created default config for ${channel} at ${path.relative(process.cwd(), defaultConfigFile())}.`);
-}
-
-async function findOrInstallDefaultBrowser() {
- const { registry } = await import('playwright-core/lib/server/registry/index');
- const channels = ['chrome', 'msedge'];
- for (const channel of channels) {
- const executable = registry.findExecutable(channel);
- if (!executable?.executablePath())
- continue;
- console.log(`✅ Found ${channel}, will use it as the default browser.`);
- return channel;
- }
- const chromiumExecutable = registry.findExecutable('chromium');
- // Unlike channels, chromium executable path is always valid, even if the browser is not installed.
- if (!fs.existsSync(chromiumExecutable?.executablePath()!))
- await registry.install([chromiumExecutable]);
- return 'chromium';
-}
-
-function defaultConfigFile(): string {
- return path.resolve('.playwright', 'cli.config.json');
-}
-
async function killAllDaemons(): Promise<void> {
const platform = os.platform();
let killed = 0;
diff --git a/packages/playwright-core/src/tools/cli-daemon/DEPS.list b/packages/playwright-core/src/tools/cli-daemon/DEPS.list
index 23a1384c5c..85f03e1dc2 100644
--- a/packages/playwright-core/src/tools/cli-daemon/DEPS.list
+++ b/packages/playwright-core/src/tools/cli-daemon/DEPS.list
@@ -6,5 +6,6 @@
../../utilsBundle.ts
../../utils/
../../zodBundle.ts
+../../server/registry/index.ts
../../server/utils/
../../serverRegistry.ts
diff --git a/packages/playwright-core/src/tools/cli-daemon/program.ts b/packages/playwright-core/src/tools/cli-daemon/program.ts
index f7ecb290a9..762dbbfebc 100644
--- a/packages/playwright-core/src/tools/cli-daemon/program.ts
+++ b/packages/playwright-core/src/tools/cli-daemon/program.ts
@@ -17,6 +17,7 @@
/* eslint-disable no-console */
import fs from 'fs';
+import os from 'os';
import path from 'path';
import { startCliDaemonServer } from './daemon';
@@ -25,6 +26,7 @@ import { createBrowserWithInfo } from '../mcp/browserFactory';
import * as configUtils from '../mcp/config';
import { ClientInfo, createClientInfo } from '../cli-client/registry';
import { program } from '../../utilsBundle';
+import { registry as browserRegistry } from '../../server/registry/index';
import type { FullConfig } from '../mcp/config';
@@ -34,10 +36,17 @@ program.argument('[session-name]', 'name of the session to create or connect to'
.option('--browser <name>', 'browser to use (chromium, chrome, firefox, webkit)')
.option('--persistent', 'use a persistent browser context')
.option('--profile <path>', 'path to the user data dir')
- .option('--config <path>', 'path to the config file')
+ .option('--config <path>', 'path to the config file; by default uses .playwright/cli.config.json in the project directory and ~/.playwright/cli.config.json as global config')
.option('--attach <name-or-endpoint>', 'attach to a running Playwright browser by name or endpoint')
+ .option('--init-workspace', 'initialize workspace')
+ .option('--init-skills <value>', 'install skills for the given agent type ("claude" or "agents")')
.action(async (sessionName: string, options: any) => {
+ if (options.initWorkspace) {
+ await initWorkspace(options.initSkills);
+ return;
+ }
+
setupExitWatchdog();
const clientInfo = createClientInfo();
const mcpConfig = await resolveCLIConfig(clientInfo, sessionName, options);
@@ -69,6 +78,10 @@ function defaultConfigFile(): string {
return path.resolve('.playwright', 'cli.config.json');
}
+function globalConfigFile(): string {
+ return path.join(process.env['PWTEST_CLI_GLOBAL_CONFIG'] ?? os.homedir(), '.playwright', 'cli.config.json');
+}
+
export async function resolveCLIConfig(clientInfo: ClientInfo, sessionName: string, options: any): Promise<FullConfig> {
const config = options.config ? path.resolve(options.config) : undefined;
try {
@@ -90,6 +103,8 @@ export async function resolveCLIConfig(clientInfo: ClientInfo, sessionName: stri
const envOverrides = configUtils.configFromEnv();
const configFile = envOverrides.configFile ?? daemonOverrides.configFile;
const configInFile = await configUtils.loadConfig(configFile);
+ const globalConfigPath = fs.existsSync(globalConfigFile()) ? globalConfigFile() : undefined;
+ const globalConfigInFile = await configUtils.loadConfig(globalConfigPath);
let result = configUtils.mergeConfig(configUtils.defaultConfig, {
browser: {
@@ -99,6 +114,7 @@ export async function resolveCLIConfig(clientInfo: ClientInfo, sessionName: stri
}
});
+ result = configUtils.mergeConfig(result, globalConfigInFile);
result = configUtils.mergeConfig(result, configInFile);
result = configUtils.mergeConfig(result, daemonOverrides);
result = configUtils.mergeConfig(result, envOverrides);
@@ -122,3 +138,70 @@ export async function resolveCLIConfig(clientInfo: ClientInfo, sessionName: stri
return result;
}
+
+async function initWorkspace(initSkills: string | undefined) {
+ const cwd = process.cwd();
+ const playwrightDir = path.join(cwd, '.playwright');
+ await fs.promises.mkdir(playwrightDir, { recursive: true });
+ console.log(`✅ Workspace initialized at \`${cwd}\`.`);
+
+ if (initSkills) {
+ const skillSourceDir = path.join(__dirname, '../cli-client/skill');
+ const target = initSkills === 'agents' ? 'agents' : 'claude';
+ const skillDestDir = path.join(cwd, `.${target}`, 'skills', 'playwright-cli');
+ if (!fs.existsSync(skillSourceDir)) {
+ console.error('❌ Skills source directory not found:', skillSourceDir);
+ // eslint-disable-next-line no-restricted-properties
+ process.exit(1);
+ }
+ await fs.promises.cp(skillSourceDir, skillDestDir, { recursive: true });
+ console.log(`✅ Skills installed to \`${path.relative(cwd, skillDestDir)}\`.`);
+ }
+
+ await ensureConfiguredBrowserInstalled();
+}
+
+async function ensureConfiguredBrowserInstalled() {
+ if (fs.existsSync(defaultConfigFile()) || fs.existsSync(globalConfigFile())) {
+ // Config exists, ensure configured browser is installed
+ const clientInfo = createClientInfo();
+ const config = await resolveCLIConfig(clientInfo, 'default', {});
+ const browserName = config.browser.browserName;
+ const channel = config.browser.launchOptions.channel;
+ if (!channel || channel.startsWith('chromium')) {
+ const executable = browserRegistry.findExecutable(channel ?? browserName);
+ if (executable && !fs.existsSync(executable.executablePath()!))
+ await browserRegistry.install([executable]);
+ }
+ } else {
+ const channel = await findOrInstallDefaultBrowser();
+ if (channel !== 'chrome')
+ await createDefaultConfig(channel);
+ }
+}
+
+async function findOrInstallDefaultBrowser() {
+ const channels = ['chrome', 'msedge'];
+ for (const channel of channels) {
+ const executable = browserRegistry.findExecutable(channel);
+ if (!executable?.executablePath())
+ continue;
+ console.log(`✅ Found ${channel}, will use it as the default browser.`);
+ return channel;
+ }
+ const chromiumExecutable = browserRegistry.findExecutable('chromium');
+ if (!fs.existsSync(chromiumExecutable?.executablePath()!))
+ await browserRegistry.install([chromiumExecutable]);
+ return 'chromium';
+}
+
+async function createDefaultConfig(channel: string) {
+ const config = {
+ browser: {
+ browserName: 'chromium',
+ launchOptions: { channel },
+ },
+ };
+ await fs.promises.writeFile(defaultConfigFile(), JSON.stringify(config, null, 2));
+ console.log(`✅ Created default config for ${channel} at ${path.relative(process.cwd(), defaultConfigFile())}.`);
+}
diff --git a/tests/mcp/cli-config.spec.ts b/tests/mcp/cli-config.spec.ts
index e438b26018..3adf9e68b0 100644
--- a/tests/mcp/cli-config.spec.ts
+++ b/tests/mcp/cli-config.spec.ts
@@ -15,6 +15,7 @@
*/
import fs from 'fs';
+import path from 'path';
import { test, expect } from './cli-fixtures';
test('user-data-dir', async ({ cli, server }, testInfo) => {
@@ -101,3 +102,45 @@ test('isolated', async ({ cli, server }, testInfo) => {
await cli('open', server.PREFIX);
expect(fs.existsSync(testInfo.outputPath('daemon', 'default-user-data'))).toBe(false);
});
+
+test('global config', async ({ cli, server }, testInfo) => {
+ const fakeHome = testInfo.outputPath('home');
+ await fs.promises.mkdir(path.join(fakeHome, '.playwright'), { recursive: true });
+ await fs.promises.writeFile(path.join(fakeHome, '.playwright', 'cli.config.json'), JSON.stringify({
+ browser: {
+ contextOptions: {
+ viewport: { width: 800, height: 600 },
+ },
+ },
+ }, null, 2));
+
+ const env = { PWTEST_CLI_GLOBAL_CONFIG: fakeHome };
+ await cli('open', server.PREFIX, { env });
+ const { output } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight', { env });
+ expect(output).toContain('800x600');
+});
+
+test('project config overrides global config', async ({ cli, server }, testInfo) => {
+ const fakeHome = testInfo.outputPath('home');
+ await fs.promises.mkdir(path.join(fakeHome, '.playwright'), { recursive: true });
+ await fs.promises.writeFile(path.join(fakeHome, '.playwright', 'cli.config.json'), JSON.stringify({
+ browser: {
+ contextOptions: {
+ viewport: { width: 800, height: 600 },
+ },
+ },
+ }, null, 2));
+
+ await fs.promises.writeFile(testInfo.outputPath('.playwright', 'cli.config.json'), JSON.stringify({
+ browser: {
+ contextOptions: {
+ viewport: { width: 1024, height: 768 },
+ },
+ },
+ }, null, 2));
+
+ const env = { PWTEST_CLI_GLOBAL_CONFIG: fakeHome };
+ await cli('open', server.PREFIX, { env });
+ const { output } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight', { env });
+ expect(output).toContain('1024x768');
+});