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
chore(cli): incognito-by-default (#39139)
Pavel Feldman342ae256bd41
diff --git a/packages/playwright/src/mcp/browser/config.ts b/packages/playwright/src/mcp/browser/config.tsindex 5f40b2de81..042e84853c 100644--- a/packages/playwright/src/mcp/browser/config.ts+++ b/packages/playwright/src/mcp/browser/config.ts@@ -87,6 +87,7 @@ export const defaultConfig: FullConfig = {contextOptions: {viewport: null,},+ isolated: false,},console: {level: 'info',@@ -107,6 +108,15 @@ export const defaultConfig: FullConfig = {},};+const defaultDaemonConfig: FullConfig = mergeConfig(defaultConfig, {+ browser: {+ launchOptions: {+ headless: true,+ },+ isolated: true,+ }+});+type BrowserUserConfig = NonNullable<Config['browser']>;export type FullConfig = Config & {@@ -114,6 +124,7 @@ export type FullConfig = Config & {browserName: 'chromium' | 'firefox' | 'webkit';launchOptions: NonNullable<BrowserUserConfig['launchOptions']>;contextOptions: NonNullable<BrowserUserConfig['contextOptions']>;+ isolated: boolean;},console: {level: 'error' | 'warning' | 'info' | 'debug';@@ -145,10 +156,7 @@ export async function resolveCLIConfig(cliOptions: CLIOptions): Promise<FullConfconst configFile = cliOverrides.configFile ?? envOverrides.configFile ?? daemonOverrides.configFile;const configInFile = await loadConfig(configFile);- let result = defaultConfig;- // Daemon session is always headless by default.- if (cliOptions.daemonSession)- result.browser.launchOptions.headless = true;+ let result = cliOptions.daemonSession ? defaultDaemonConfig : defaultConfig;result = mergeConfig(result, configInFile);result = mergeConfig(result, daemonOverrides);result = mergeConfig(result, envOverrides);@@ -373,9 +381,10 @@ async function configForDaemonSession(cliOptions: CLIOptions): Promise<Config &const config = configFromCLIOptions({config: sessionConfig.cli.config,browser: sessionConfig.cli.browser,- isolated: sessionConfig.cli.isolated,+ isolated: sessionConfig.cli.persistent === true ? false : undefined,headless: sessionConfig.cli.headed ? false : undefined,extension: sessionConfig.cli.extension,+ userDataDir: sessionConfig.cli.profile,outputMode: 'file',snapshotMode: 'full',});diff --git a/packages/playwright/src/mcp/terminal/commands.ts b/packages/playwright/src/mcp/terminal/commands.tsindex ffbb59e032..cfcefac916 100644--- a/packages/playwright/src/mcp/terminal/commands.ts+++ b/packages/playwright/src/mcp/terminal/commands.ts@@ -23,11 +23,19 @@ import type { AnyCommandSchema } from './command';const open = declareCommand({name: 'open',- description: 'Open URL',+ description: 'Open browser',category: 'core',args: z.object({url: z.string().optional().describe('The URL to navigate to'),}),+ options: z.object({+ browser: z.string().optional().describe('Browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.'),+ config: z.string().optional().describe('Path to the configuration file'),+ extension: z.boolean().optional().describe('Connect to browser extension'),+ headed: z.boolean().optional().describe('Run browser in headed mode'),+ persistent: z.boolean().optional().describe('Use persistent browser profile'),+ profile: z.string().optional().describe('Use persistent browser profile, store profile in specified directory.'),+ }),toolName: 'browser_navigate',toolParams: ({ url }) => ({ url: url || 'about:blank' }),});@@ -41,6 +49,17 @@ const close = declareCommand({toolParams: () => ({}),});+const goto = declareCommand({+ name: 'goto',+ description: 'Navigate to a URL',+ category: 'core',+ args: z.object({+ url: z.string().describe('The URL to navigate to'),+ }),+ toolName: 'browser_navigate',+ toolParams: ({ url }) => ({ url }),+});+const goBack = declareCommand({name: 'go-back',description: 'Go back to the previous page',@@ -743,30 +762,8 @@ 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',- category: 'session',- args: z.object({- name: z.string().optional().describe('Name of the session to stop. If omitted, current session is stopped.'),- }),- toolName: '',- toolParams: () => ({}),-});--const sessionStopAll = declareCommand({- name: 'session-stop-all',+const sessionCloseAll = declareCommand({+ name: 'session-close-all',description: 'Stop all sessions',category: 'session',toolName: '',@@ -781,27 +778,10 @@ const killAll = declareCommand({toolParams: () => ({}),});-const sessionDelete = declareCommand({- name: 'session-delete',+const deleteData = declareCommand({+ name: 'delete-data',description: 'Delete session data',- category: 'session',- args: z.object({- name: z.string().optional().describe('Name of the session to delete. If omitted, current session is deleted.'),- }),- toolName: '',- toolParams: ({ name }) => ({ name }),-});--const config = declareCommand({- name: 'config',- description: 'Restart session with new config, defaults to `playwright-cli.json`',- category: 'config',- options: z.object({- browser: z.string().optional().describe('Browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.'),- config: z.string().optional().describe('Path to the configuration file'),- headed: z.boolean().optional().describe('Run browser in headed mode'),- ['in-memory']: z.boolean().optional().describe('Keep the browser profile in memory, do not save it to disk.'),- }),+ category: 'core',toolName: '',toolParams: () => ({}),});@@ -839,6 +819,7 @@ const commandsArray: AnyCommandSchema[] = [// core categoryopen,close,+ goto,type,click,doubleClick,@@ -856,6 +837,7 @@ const commandsArray: AnyCommandSchema[] = [dialogDismiss,resize,runCode,+ deleteData,// navigation categorygoBack,@@ -908,7 +890,6 @@ const commandsArray: AnyCommandSchema[] = [unroute,// config category- config,configPrint,// install category@@ -924,10 +905,7 @@ const commandsArray: AnyCommandSchema[] = [// session categorysessionList,- sessionStop,- sessionRestart,- sessionStopAll,- sessionDelete,+ sessionCloseAll,killAll,];diff --git a/packages/playwright/src/mcp/terminal/helpGenerator.ts b/packages/playwright/src/mcp/terminal/helpGenerator.tsindex 53574cdcd4..7459981243 100644--- a/packages/playwright/src/mcp/terminal/helpGenerator.ts+++ b/packages/playwright/src/mcp/terminal/helpGenerator.ts@@ -101,12 +101,7 @@ export function generateHelp() {}lines.push('\nGlobal options:');- lines.push(formatWithGap(' --browser <browser>', 'browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge'));- lines.push(formatWithGap(' --config <path>', 'create a session with custom config, defaults to `playwright-cli.json`'));- lines.push(formatWithGap(' --extension', 'connect to a running browser instance using Playwright MCP Bridge extension'));- lines.push(formatWithGap(' --headed', 'create a headed session'));lines.push(formatWithGap(' --help [command]', 'print help'));- lines.push(formatWithGap(' --in-memory', 'keep the browser profile in memory, do not save it to disk'));lines.push(formatWithGap(' --session', 'run command in the scope of a specific session'));lines.push(formatWithGap(' --version', 'print version'));diff --git a/packages/playwright/src/mcp/terminal/program.ts b/packages/playwright/src/mcp/terminal/program.tsindex e43443a41c..e9dac222a3 100644--- a/packages/playwright/src/mcp/terminal/program.ts+++ b/packages/playwright/src/mcp/terminal/program.ts@@ -38,7 +38,8 @@ export type SessionConfig = {headed?: boolean;extension?: boolean;browser?: string;- isolated?: boolean;+ persistent?: boolean;+ profile?: string;config?: string;};userDataDirPrefix?: string;@@ -83,7 +84,7 @@ to restart the session daemon.`);}}- async run(args: MinimistArgs) {+ async run(args: MinimistArgs): Promise<{ text: string }> {this.checkCompatible();return await this._send('run', { args, cwd: process.cwd() });}@@ -98,19 +99,13 @@ to restart the session daemon.`);if (e.message !== 'Session closed')throw e;});- this.close();+ this.disconnect();if (os.platform() !== 'win32')await fs.promises.unlink(this._config.socketPath).catch(() => {});console.log(`Session '${this.name}' stopped.`);}- async restart(config: SessionConfig): Promise<void> {- await this.stop();- this._config = config;- await this._startDaemonIfNeeded();- }-private async _send(method: string, params: any = {}): Promise<any> {const connection = await this._startDaemonIfNeeded();const messageId = this._nextMessageId++;@@ -127,7 +122,7 @@ to restart the session daemon.`);return result;}- close() {+ disconnect() {if (!this._connection)return;for (const callback of this._callbacks.values())@@ -137,7 +132,7 @@ to restart the session daemon.`);this._connection = undefined;}- async delete() {+ async deleteData() {await this.stop();const dataDirs = await fs.promises.readdir(this._clientInfo.daemonProfilesDir).catch(() => []);@@ -201,7 +196,7 @@ to restart the session daemon.`);this._connection = new SocketConnection(socket, this._config.version);this._connection.onmessage = message => this._onMessage(message);- this._connection.onclose = () => this.close();+ this._connection.onclose = () => this.disconnect();return this._connection;}@@ -246,18 +241,17 @@ to restart the session daemon.`);});child.unref();- console.log(`### Daemon for \`${this.name}\` session started with pid ${child.pid}.`);+ console.log(`### Session \`${this.name}\` started with pid ${child.pid}.`);const configArgs = configToFormattedArgs(this._config.cli);if (configArgs.length) {console.log(`- Session options:`);for (const flag of configArgs)console.log(` ${flag}`);}- const sessionSuffix = this.name !== 'default' ? ` "${this.name}"` : '';const sessionOption = this.name !== 'default' ? ` --session="${this.name}"` : '';- console.log(`- playwright-cli session-stop${sessionSuffix} # to stop when done.`);- console.log(`- playwright-cli${sessionOption} config [options] # to change session options.`);- console.log(`- playwright-cli session-delete${sessionSuffix} # to delete session data.`);+ console.log(formatWithGap(`- playwright-cli${sessionOption} close`, `# to stop when done.`));+ console.log(formatWithGap(`- playwright-cli${sessionOption} open [options]`, `# to reopen with new config.`));+ console.log(formatWithGap(`- playwright-cli${sessionOption} delete-data`, `# to delete session data.`));// Wait for the socket to become available with retries.const maxRetries = 50;@@ -290,12 +284,12 @@ class SessionManager {readonly clientInfo: ClientInfo;readonly sessions: Map<string, Session>;- private constructor(clientInfo: ClientInfo, sessions: Map<string, Session>, args: MinimistArgs) {+ private constructor(clientInfo: ClientInfo, sessions: Map<string, Session>) {this.clientInfo = clientInfo;this.sessions = sessions;}- static async create(clientInfo: ClientInfo, args: MinimistArgs): Promise<SessionManager> {+ static async create(clientInfo: ClientInfo): Promise<SessionManager> {const dir = clientInfo.daemonProfilesDir;const sessions = new Map<string, Session>();const files = await fs.promises.readdir(dir).catch(() => []);@@ -323,35 +317,41 @@ class SessionManager {} catch {}}- return new SessionManager(clientInfo, sessions, args);+ return new SessionManager(clientInfo, sessions);}- async run(args: MinimistArgs): Promise<void> {+ async open(args: MinimistArgs): Promise<void> {const sessionName = this._resolveSessionName(args.session);let session = this.sessions.get(sessionName);+ if (session)+ await session.stop();++ session = new Session(this.clientInfo, sessionName, sessionConfigFromArgs(this.clientInfo, sessionName, args));+ this.sessions.set(sessionName, session);+ await this.run(args);+ }++ async run(args: MinimistArgs): Promise<void> {+ const sessionName = this._resolveSessionName(args.session);+ const session = this.sessions.get(sessionName);if (!session) {- session = new Session(this.clientInfo, sessionName, sessionConfigFromArgs(this.clientInfo, sessionName, args));- this.sessions.set(sessionName, session);- } else {- if (hasGlobalArgs(args)) {- const configFromArgs = sessionConfigFromArgs(this.clientInfo, sessionName, args);- const formattedArgs = configToFormattedArgs(configFromArgs.cli);- console.log('The session is already configured. To change session options, run:');- console.log('');- console.log(` playwright-cli${sessionName !== 'default' ? ` --session=${sessionName}` : ''} config ${formattedArgs.join(' ')}`);- process.exit(1);- }+ const configFromArgs = sessionConfigFromArgs(this.clientInfo, sessionName, args);+ const formattedArgs = configToFormattedArgs(configFromArgs.cli);+ console.log(`The session '${sessionName}' is not open, please run open first:`);+ console.log('');+ console.log(` playwright-cli${sessionName !== 'default' ? ` --session=${sessionName}` : ''} open ${formattedArgs.join(' ')}`);+ process.exit(1);}- for (const globalOption of globalArgs)+ for (const globalOption of globalOptions)delete args[globalOption];const result = await session.run(args);console.log(result.text);- session.close();+ session.disconnect();}- async stop(sessionName?: string): Promise<void> {- sessionName = this._resolveSessionName(sessionName);+ async close(options: GlobalOptions): Promise<void> {+ const sessionName = this._resolveSessionName(options.session);const session = this.sessions.get(sessionName);if (!session || !await session.canConnect()) {console.log(`Session '${sessionName}' is not running.`);@@ -361,40 +361,17 @@ class SessionManager {await session.stop();}- async delete(sessionName?: string): Promise<void> {- sessionName = this._resolveSessionName(sessionName);+ async deleteData(options: GlobalOptions): Promise<void> {+ const sessionName = this._resolveSessionName(options.session);const session = this.sessions.get(sessionName);if (!session) {console.log(`No user data found for session '${sessionName}'.`);return;}- await session.delete();+ await session.deleteData();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.clientInfo, sessionName, args);- if (!session) {- session = new Session(this.clientInfo, sessionName, sessionConfig);- this.sessions.set(sessionName, session);- }- await session.restart(sessionConfig);- session.close();- }-private _resolveSessionName(sessionName?: string): string {if (sessionName)return sessionName;@@ -404,60 +381,6 @@ class SessionManager {}}-async function handleSessionCommand(sessionManager: SessionManager, subcommand: string, args: any): Promise<void> {- if (subcommand === 'list') {- const sessions = sessionManager.sessions;- console.log('Sessions:');- for (const session of sessions.values()) {- 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;- }-- if (subcommand === 'stop-all') {- const sessions = sessionManager.sessions;- for (const session of sessions.values())- await session.stop();- return;- }-- if (subcommand === 'kill-all') {- await killAllDaemons();- return;- }-- if (subcommand === 'delete') {- await sessionManager.delete(args._[1]);- return;- }-- if (subcommand === 'config') {- if (args.print) {- await sessionManager.run(args);- return;- }- await sessionManager.configure(args);- return;- }-- console.error(`Unknown session subcommand: ${subcommand}`);- process.exit(1);-}-function createClientInfo(packageLocation: string): ClientInfo {const packageJSON = require(packageLocation);const installationDir = process.env.PLAYWRIGHT_CLI_INSTALLATION_FOR_TEST || packageLocation;@@ -491,15 +414,41 @@ const daemonProfilesDir = (installationDirHash: string) => {return path.join(localCacheDir, 'ms-playwright', 'daemon', installationDirHash);};-const booleanOptions = [+type GlobalOptions = {+ help?: boolean;+ session?: string;+ version?: boolean;+};++type OpenOptions = {+ browser?: string;+ config?: string;+ extension?: boolean;+ headed?: boolean;+ persistent?: boolean;+ profile?: string;+};++const globalOptions: (keyof (GlobalOptions & OpenOptions))[] = [+ 'browser',+ 'config','extension','headed','help',- 'in-memory',- 'print',+ 'persistent',+ 'profile',+ 'session','version',];+const booleanOptions: (keyof (GlobalOptions & OpenOptions))[] = [+ 'help',+ 'version',+ 'extension',+ 'headed',+ 'persistent'+];+export async function program(packageLocation: string) {const clientInfo = createClientInfo(packageLocation);@@ -511,14 +460,14 @@ export async function program(packageLocation: string) {}const help = require('./help.json');- const commandName = args._[0];+ const commandName = args._?.[0];if (args.version || args.v) {console.log(clientInfo.version);process.exit(0);}- const command = help.commands[commandName];+ const command = commandName && help.commands[commandName];if (args.help || args.h) {if (command) {console.log(command);@@ -535,34 +484,45 @@ export async function program(packageLocation: string) {process.exit(1);}- const sessionManager = await SessionManager.create(clientInfo, args);- if (commandName.startsWith('session-')) {- const subcommand = args._[0].split('-').slice(1).join('-');- await handleSessionCommand(sessionManager, subcommand, args);- return;- }-- if (commandName === 'config') {- await handleSessionCommand(sessionManager, 'config', args);- return;- }+ const sessionManager = await SessionManager.create(clientInfo);- if (commandName === 'close') {- await handleSessionCommand(sessionManager, 'stop', args);- return;- }-- if (commandName === 'kill-all') {- await handleSessionCommand(sessionManager, 'kill-all', args);- return;- }-- if (commandName === 'install-skills') {- await installSkills();- return;+ switch (commandName) {+ case 'session-list': {+ const sessions = sessionManager.sessions;+ console.log('Sessions:');+ for (const session of sessions.values()) {+ 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;+ }+ case 'session-close-all': {+ const sessions = sessionManager.sessions;+ for (const session of sessions.values())+ await session.stop();+ return;+ }+ case 'delete-data':+ await sessionManager.deleteData(args as GlobalOptions);+ return;+ case 'kill-all':+ await killAllDaemons();+ return;+ case 'open':+ await sessionManager.open(args);+ return;+ case 'close':+ await sessionManager.close(args as GlobalOptions);+ return;+ case 'install-skills':+ await installSkills();+ return;+ default:+ await sessionManager.run(args);}-- await sessionManager.run(args);}async function installSkills() {@@ -587,12 +547,16 @@ function daemonSocketPath(clientInfo: ClientInfo, sessionName: string): string {}function sessionConfigFromArgs(clientInfo: ClientInfo, sessionName: string, args: MinimistArgs): SessionConfig {- let config = args.config;+ let config = args.config ? path.resolve(args.config) : undefined;try {if (!config && fs.existsSync('playwright-cli.json'))config = path.resolve('playwright-cli.json');} catch {}++ if (!args.persistent && args.profile)+ args.persistent = true;+return {version: clientInfo.version,socketPath: daemonSocketPath(clientInfo, sessionName),@@ -600,20 +564,15 @@ function sessionConfigFromArgs(clientInfo: ClientInfo, sessionName: string, argsheaded: args.headed,extension: args.extension,browser: args.browser,- isolated: args['in-memory'],+ persistent: args.persistent,+ profile: args.profile,config,},userDataDirPrefix: path.resolve(clientInfo.daemonProfilesDir, `ud-${sessionName}`),};}-const globalArgs = ['browser', 'config', 'extension', 'headed', 'help', 'in-memory', 'version', 'session'];--function hasGlobalArgs(args: MinimistArgs): boolean {- return globalArgs.some(option => args[option] !== undefined);-}--function configToFormattedArgs(config: SessionConfig['cli']): string[] {+function configToFormattedArgs(cli: SessionConfig['cli']): string[] {const args: string[] = [];const add = (flag: string, value: string | boolean | undefined) => {if (typeof value === 'boolean' && value)@@ -621,11 +580,12 @@ function configToFormattedArgs(config: SessionConfig['cli']): string[] {else if (typeof value === 'string')args.push(`--${flag}=${value}`);};- add('browser', config.browser);- add('config', config.config ? path.relative(process.cwd(), config.config) : undefined);- add('extension', config.extension);- add('headed', config.headed);- add('in-memory', config.isolated);+ add('browser', cli.browser);+ add('config', cli.config ? path.relative(process.cwd(), cli.config) : undefined);+ add('extension', cli.extension);+ add('headed', cli.headed);+ add('persistent', cli.persistent);+ add('profile', cli.profile);return args;}@@ -676,3 +636,8 @@ async function killAllDaemons(): Promise<void> {else if (killed > 0)console.log(`Killed ${killed} daemon process${killed === 1 ? '' : 'es'}.`);}++function formatWithGap(prefix: string, text: string, threshold: number = 40) {+ const indent = Math.max(1, threshold - prefix.length);+ return prefix + ' '.repeat(indent) + text;+}diff --git a/packages/playwright/src/skill/SKILL.md b/packages/playwright/src/skill/SKILL.mdindex df5c91e9d1..ea1b960e2f 100644--- a/packages/playwright/src/skill/SKILL.md+++ b/packages/playwright/src/skill/SKILL.md@@ -167,13 +167,15 @@ playwright-cli open --browser=msedge# Connect to browser via extensionplaywright-cli open --extension-# Configure the session-playwright-cli config --config my-config.json-playwright-cli config --headed --in-memory --browser=firefox-# Configure named session-playwright-cli --session=mysession config my-config.json-# Start with configured session+# Use persistent profile (by default profile is in-memory)+playwright-cli open --persistent+# Use persistent profile with custom directory+playwright-cli open --profile=/path/to/profile++# Start with config fileplaywright-cli open --config=my-config.json++playwright-cli close # stop the default session```### Sessions@@ -181,13 +183,13 @@ playwright-cli open --config=my-config.json```bashplaywright-cli --session=mysession open example.complaywright-cli --session=mysession click e6+playwright-cli --session=mysession close # stop a named session+playwright-cli --session=mysession delete-data # delete user data for named session+playwright-cli session-list-playwright-cli session-stop mysession-playwright-cli session-restart mysession-playwright-cli session-stop-all-playwright-cli session-delete-playwright-cli session-delete mysession-playwright-cli kill-all # forcefully kill all daemon processes (for stale/zombie processes)+playwright-cli session-close-all # stop all sessions+playwright-cli delete-data # delete user data for default session+playwright-cli kill-all # forcefully kill all daemon processes (for stale/zombie processes)```## Example: Form submissiondiff --git a/packages/playwright/src/skill/references/session-management.md b/packages/playwright/src/skill/references/session-management.mdindex 4c06b7e036..36eef9775c 100644--- a/packages/playwright/src/skill/references/session-management.md+++ b/packages/playwright/src/skill/references/session-management.md@@ -34,20 +34,19 @@ Each session has independent:# List all sessionsplaywright-cli session-list-# Stop a specific session-playwright-cli session-stop mysession+# Stop a session (close the browser)+playwright-cli close # stop the default session+playwright-cli --session=mysession close # stop a named session# Stop all sessions-playwright-cli session-stop-all+playwright-cli session-close-all# Forcefully kill all daemon processes (for stale/zombie processes)playwright-cli kill-all-# Restart a session (useful after version updates)-playwright-cli session-restart mysession--# Delete session data (cookies, storage, etc.)-playwright-cli session-delete mysession+# Delete session user data (profile directory)+playwright-cli delete-data # delete default session data+playwright-cli --session=mysession delete-data # delete named session data```## Environment Variable@@ -79,9 +78,7 @@ playwright-cli --session=site2 snapshotplaywright-cli --session=site3 snapshot# Cleanup-playwright-cli --session=site1 close-playwright-cli --session=site2 close-playwright-cli --session=site3 close+playwright-cli session-close-all```### A/B Testing Sessions@@ -96,13 +93,16 @@ playwright-cli --session=variant-a screenshotplaywright-cli --session=variant-b screenshot```-### Testing without persistent profile+### Persistent Profile-Use `--in-memory` flag to keep the browser profile in memory only:+By default, browser profile is kept in memory only. Use `--persistent` flag on `open` to persist the browser profile to disk:```bash-# Session data won't persist to disk-playwright-cli --in-memory open https://example.com+# Use persistent profile (auto-generated location)+playwright-cli open https://example.com --persistent++# Use persistent profile with custom directory+playwright-cli open https://example.com --profile=/path/to/profile```## Default Session@@ -113,25 +113,25 @@ When `--session` is omitted, commands use the default session:# These use the same default sessionplaywright-cli open https://example.complaywright-cli snapshot-playwright-cli close # Closes default session+playwright-cli close # Stops default session```## Session Configuration-Configure a session with specific settings:+Configure a session with specific settings when opening:```bash-# Configure session with config file-playwright-cli --session=mysession config --config=playwright-cli.json+# Open with config file+playwright-cli open https://example.com --config=playwright-cli.json-# Configure session with specific browser-playwright-cli --session=mysession config --browser=firefox+# Open with specific browser+playwright-cli open https://example.com --browser=firefox-# Configure session in headed mode-playwright-cli --session=mysession config --headed+# Open in headed mode+playwright-cli open https://example.com --headed-# Restart session to apply changes-playwright-cli session-restart mysession+# Open with persistent profile+playwright-cli open https://example.com --persistent```## Best Practices@@ -151,11 +151,11 @@ playwright-cli --session=s1 open https://github.com```bash# Stop sessions when done-playwright-cli session-stop auth-playwright-cli session-stop scrape+playwright-cli --session=auth close+playwright-cli --session=scrape close# Or stop all at once-playwright-cli session-stop-all+playwright-cli session-close-all# If sessions become unresponsive or zombie processes remainplaywright-cli kill-all@@ -165,5 +165,5 @@ playwright-cli kill-all```bash# Remove old session data to free disk space-playwright-cli session-delete oldsession+playwright-cli --session=oldsession delete-data```diff --git a/packages/playwright/src/skill/references/storage-state.md b/packages/playwright/src/skill/references/storage-state.mdindex 2c0ebca370..c856db5e40 100644--- a/packages/playwright/src/skill/references/storage-state.md+++ b/packages/playwright/src/skill/references/storage-state.md@@ -272,4 +272,4 @@ playwright-cli open https://example.com- Add `*.auth-state.json` to `.gitignore`- Delete state files after automation completes- Use environment variables for sensitive data-- Consider using `--in-memory` mode for sensitive operations+- By default, sessions run in-memory mode which is safer for sensitive operationsdiff --git a/tests/mcp/cli-config.spec.ts b/tests/mcp/cli-config.spec.tsindex 50f6ac0d31..e6dab49b34 100644--- a/tests/mcp/cli-config.spec.ts+++ b/tests/mcp/cli-config.spec.ts@@ -24,7 +24,7 @@ test('user-data-dir', async ({ cli, server }, testInfo) => {},};await fs.promises.writeFile(testInfo.outputPath('config.json'), JSON.stringify(config, null, 2));- await cli('open', `--config=config.json`, server.PREFIX);+ await cli('open', '--persistent', `--config=config.json`, server.PREFIX);expect(fs.existsSync(testInfo.outputPath('my-data-dir'))).toBe(true);});@@ -42,59 +42,10 @@ test('context options', async ({ cli, server }, testInfo) => {expect(output).toContain('800x600');});-test('headless options from config is respected', async ({ cli, server, mcpBrowser }, testInfo) => {- test.skip(mcpBrowser !== 'chrome', 'HeadlessChrome detection only works in Chromium');- const config = {- browser: {- launchOptions: {- headless: false,- },- },- };- await fs.promises.writeFile(testInfo.outputPath('playwright-cli.json'), JSON.stringify(config, null, 2));- const options = { env: { PLAYWRIGHT_MCP_HEADLESS: undefined } };- await cli('open', server.PREFIX, options);- const { output } = await cli('eval', 'navigator.userAgent', options);- expect(output).not.toContain('HeadlessChrome');- expect(output).toContain(' Chrome/');-});--test('config-print prints merged config from file, env and cli', async ({ cli, server }, testInfo) => {- // Config file provides viewport and timeouts.- const fileConfig = {- browser: {- contextOptions: {- viewport: { width: 800, height: 600 },- },- },- timeouts: {- action: 10000,- navigation: 30000,- },- };- await fs.promises.writeFile(testInfo.outputPath('playwright-cli.json'), JSON.stringify(fileConfig, null, 2));-- // Env var overrides navigation timeout (30000 from file → 45000 from env).- const env = { PLAYWRIGHT_MCP_TIMEOUT_NAVIGATION: '45000' };-- // CLI arg: --in-memory sets browser.isolated = true.- await cli('open', '--in-memory', server.PREFIX, { env });-- // Query the resolved config from the running daemon.- const { output } = await cli('config-print', { env });- const configBegin = output.indexOf('{');- expect(configBegin).not.toBe(-1);- const config = JSON.parse(output.slice(configBegin));-- // From config file.- expect(config.browser.contextOptions.viewport).toEqual({ width: 800, height: 600 });- expect(config.timeouts.action).toBe(10000);-- // Env var overrides file value.- expect(config.timeouts.navigation).toBe(45000);-- // From CLI arg (--in-memory).- expect(config.browser.isolated).toBe(true);+test('config-print prints merged config', async ({ cli }) => {+ await cli('open');+ const { output } = await cli('config-print');+ expect(output).toContain('"browser"');});test('isolated', async ({ cli, server }, testInfo) => {diff --git a/tests/mcp/cli-core.spec.ts b/tests/mcp/cli-core.spec.tsindex e8a483eb6c..3dbadaed1d 100644--- a/tests/mcp/cli-core.spec.ts+++ b/tests/mcp/cli-core.spec.ts@@ -184,7 +184,7 @@ test('snapshot', async ({ cli, server }, testInfo) => {{const nested = testInfo.outputPath('nested');await fs.promises.mkdir(nested, { recursive: true });- const { output } = await cli('open', server.HELLO_WORLD, { cwd: nested });+ const { output } = await cli('goto', server.HELLO_WORLD, { cwd: nested });expect(output).toContain('..' + path.sep + '.playwright-cli' + path.sep + 'page-');}});diff --git a/tests/mcp/cli-devtools.spec.ts b/tests/mcp/cli-devtools.spec.tsindex 357e713275..c49d2c5905 100644--- a/tests/mcp/cli-devtools.spec.ts+++ b/tests/mcp/cli-devtools.spec.ts@@ -81,12 +81,12 @@ test('tracing-start-stop', async ({ cli, server }) => {});test('video-start-stop', async ({ cli, server }) => {+ await cli('open', server.HELLO_WORLD);const { output: videoStartOutput } = await cli('video-start');expect(videoStartOutput).toContain('Video recording started.');- await cli('open', server.HELLO_WORLD);const { output: tabNewOutput } = await cli('tab-new');expect(tabNewOutput).toContain('1: (current) [](about:blank)');- await cli('open', server.EMPTY_PAGE);+ await cli('goto', server.EMPTY_PAGE);await cli('tab-select', '0');const { output: tabCloseOutput } = await cli('tab-close');expect(tabCloseOutput).toContain(`0: (current) [](${server.EMPTY_PAGE})`);diff --git a/tests/mcp/cli-fixtures.ts b/tests/mcp/cli-fixtures.tsindex 5baa4b7448..f01a904943 100644--- a/tests/mcp/cli-fixtures.ts+++ b/tests/mcp/cli-fixtures.ts@@ -42,7 +42,7 @@ export const test = baseTest.extend<{});for (const session of sessions) {- await runCli(childProcess, ['session-stop', session.name], {}, { mcpBrowser, mcpHeadless }, []).catch(e => {+ await runCli(childProcess, ['--session=' + session.name, 'close'], {}, { mcpBrowser, mcpHeadless }, []).catch(e => {if (!e.message.includes('is not running'))throw e;});@@ -83,7 +83,7 @@ async function runCli(childProcess: CommonFixtures['childProcess'], args: stringsnapshot = await loadSnapshot(cli.stdout);const attachments = loadAttachments(cli.stdout);- const matches = cli.stdout.includes('Daemon for') ? cli.stdout.match(/Daemon for `(.+)` session started with pid (\d+)\./) : undefined;+ const matches = cli.stdout.includes('Session') ? cli.stdout.match(/Session `(.+)` started with pid (\d+)\./) : undefined;const [, sessionName, pid] = matches ?? [];if (sessionName && pid)sessions.push({ name: sessionName, pid: +pid });diff --git a/tests/mcp/cli-isolated.spec.ts b/tests/mcp/cli-isolated.spec.tsindex 67acfbdb64..3c160d7b5c 100644--- a/tests/mcp/cli-isolated.spec.ts+++ b/tests/mcp/cli-isolated.spec.ts@@ -17,17 +17,16 @@import fs from 'fs';import { test, expect } from './cli-fixtures';-test('should not save user data', async ({ cli, server, mcpBrowser }, testInfo) => {- await cli('open', server.HELLO_WORLD, '--in-memory');+test('should not save user data by default (in-memory mode)', async ({ cli, server, mcpBrowser }, testInfo) => {+ // Default behavior is now in-memory (isolated), no flag needed+ await cli('open', server.HELLO_WORLD);const dataDir = testInfo.outputPath('daemon', 'ud-default-' + mcpBrowser);expect(fs.existsSync(dataDir)).toBe(false);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({- cli: {- isolated: true,- },+ cli: {},socketPath: expect.any(String),userDataDirPrefix: expect.any(String),version: expect.any(String),@@ -37,3 +36,38 @@ test('should not save user data', async ({ cli, server, mcpBrowser }, testInfo)expect(listOutput).toContain('Sessions:');expect(listOutput).toContain(' [running] default');});++test('should save user data with --persistent flag', async ({ cli, server, mcpBrowser }, testInfo) => {+ await cli('open', server.HELLO_WORLD, '--persistent');+ const dataDir = testInfo.outputPath('daemon', 'ud-default-' + mcpBrowser);+ expect(fs.existsSync(dataDir)).toBe(true);+ 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({+ cli: {+ persistent: true,+ },+ socketPath: expect.any(String),+ userDataDirPrefix: expect.any(String),+ version: expect.any(String),+ });+});++test('should use custom user data dir with --profile=<dir>', async ({ cli, server }, testInfo) => {+ const customDir = testInfo.outputPath('custom-profile');+ await cli('open', server.HELLO_WORLD, `--profile=${customDir}`);+ expect(fs.existsSync(customDir)).toBe(true);+ 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({+ cli: {+ persistent: true,+ profile: customDir,+ },+ socketPath: expect.any(String),+ userDataDirPrefix: expect.any(String),+ version: expect.any(String),+ });+});diff --git a/tests/mcp/cli-misc.spec.ts b/tests/mcp/cli-misc.spec.tsindex 47c38b54c2..a07a896cc7 100644--- a/tests/mcp/cli-misc.spec.ts+++ b/tests/mcp/cli-misc.spec.ts@@ -27,19 +27,6 @@ test('daemon shuts down on browser launch failure', async ({ cli, server }) => {expect(second.output).toContain('Page URL');});-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)');-});-test('install', async ({ cli, server, mcpBrowser }) => {test.skip(mcpBrowser !== 'chromium', 'Test only chromium');await cli('open', server.HELLO_WORLD);diff --git a/tests/mcp/cli-navigation.spec.ts b/tests/mcp/cli-navigation.spec.tsindex 90141ffeb1..32bd07b9d0 100644--- a/tests/mcp/cli-navigation.spec.ts+++ b/tests/mcp/cli-navigation.spec.ts@@ -18,7 +18,7 @@ import { test, expect } from './cli-fixtures';test('go-back', async ({ cli, server }) => {await cli('open', server.HELLO_WORLD);- await cli('open', server.PREFIX);+ await cli('goto', server.PREFIX);const { output } = await cli('go-back');expect(output).toContain(`### Page- Page URL: ${server.HELLO_WORLD}@@ -27,7 +27,7 @@ test('go-back', async ({ cli, server }) => {test('go-forward', async ({ cli, server }) => {await cli('open', server.PREFIX);- await cli('open', server.HELLO_WORLD);+ await cli('goto', server.HELLO_WORLD);await cli('go-back');const { output } = await cli('go-forward');expect(output).toContain(`### Pagediff --git a/tests/mcp/cli-parsing.spec.ts b/tests/mcp/cli-parsing.spec.tsindex 3b8a8c954e..4f8d42a67e 100644--- a/tests/mcp/cli-parsing.spec.ts+++ b/tests/mcp/cli-parsing.spec.ts@@ -29,18 +29,21 @@ test('too many arguments', async ({ cli, server }) => {});test('wrong option type', async ({ cli, server }) => {+ await cli('open', server.HELLO_WORLD);const { error, exitCode } = await cli('type', 'foo', '--submit=bar');expect(exitCode).toBe(1);expect(error).toContain(`error: '--submit' option: expected boolean, received string`);});test('missing argument', async ({ cli, server }) => {+ await cli('open', server.HELLO_WORLD);const { error, exitCode } = await cli('keyup');expect(exitCode).toBe(1);expect(error).toContain(`error: 'key' argument: expected string, received undefined`);});test('wrong argument type', async ({ cli, server }) => {+ await cli('open', server.HELLO_WORLD);const { error, exitCode } = await cli('mousemove', '12', 'foo');expect(exitCode).toBe(1);expect(error).toContain(`error: 'y' argument: expected number, received string`);diff --git a/tests/mcp/cli-session.spec.ts b/tests/mcp/cli-session.spec.tsindex 2d36a85486..15808ad065 100644--- a/tests/mcp/cli-session.spec.ts+++ b/tests/mcp/cli-session.spec.ts@@ -29,82 +29,68 @@ test('session-list', async ({ cli, server }) => {expect(listOutput).toContain(' [running] default');});-test('session-stop', async ({ cli, server }) => {+test('close', async ({ cli, server }) => {await cli('open', server.HELLO_WORLD);- const { output } = await cli('session-stop');+ const { output } = await cli('close');expect(output).toContain(`Session 'default' stopped.`);const { output: listOutput } = await cli('session-list');expect(listOutput).toContain('[stopped] default');});-test('session-stop named session', async ({ cli, server }) => {- await cli('open', '--session=mysession', server.HELLO_WORLD);+test('close named session', async ({ cli, server }) => {+ await cli('--session=mysession', 'open', server.HELLO_WORLD);- const { output } = await cli('session-stop', 'mysession');+ const { output } = await cli('--session=mysession', 'close');expect(output).toContain(`Session 'mysession' stopped.`);});-test('session-stop non-running session', async ({ cli }) => {- const { output } = await cli('session-stop', 'nonexistent');+test('close non-running session', async ({ cli }) => {+ const { output } = await cli('--session=nonexistent', 'close');expect(output).toContain(`Session 'nonexistent' is not running.`);});-test('session-stop-all', async ({ cli, server }) => {- await cli('open', '--session=session1', server.HELLO_WORLD);- await cli('open', '--session=session2', server.HELLO_WORLD);+test('session-close-all', async ({ cli, server }) => {+ await cli('--session=session1', 'open', server.HELLO_WORLD);+ await cli('--session=session2', 'open', server.HELLO_WORLD);const { output: listBefore } = await cli('session-list');expect(listBefore).toContain('[running] session1');expect(listBefore).toContain('[running] session2');- await cli('session-stop-all');+ await cli('session-close-all');const { output: listAfter } = await cli('session-list');expect(listAfter).not.toContain('[running]');});-test('kill-all', async ({ cli, server }) => {- await cli('open', '--session=killsession1', server.HELLO_WORLD);- await cli('open', '--session=killsession2', server.HELLO_WORLD);-- const { output: listBefore } = await cli('session-list');- expect(listBefore).toContain('[running] killsession1');- expect(listBefore).toContain('[running] killsession2');-- const { output } = await cli('kill-all');- expect(output).toContain('Killed daemon process');-- await expect.poll(() => cli('session-list').then(r => r.output)).not.toContain('[running]');-});--test('session-delete', async ({ cli, server, mcpBrowser }, testInfo) => {- await cli('open', server.HELLO_WORLD);+test('delete-data', async ({ cli, server, mcpBrowser }, testInfo) => {+ await cli('open', server.HELLO_WORLD, '--persistent');const dataDir = testInfo.outputPath('daemon', 'ud-default-' + mcpBrowser);expect(fs.existsSync(dataDir)).toBe(true);- const { output } = await cli('session-delete');+ const { output } = await cli('delete-data');expect(output).toContain(`Deleted user data for session 'default'.`);expect(fs.existsSync(dataDir)).toBe(false);});-test('session-delete named session', async ({ cli, server, mcpBrowser }, testInfo) => {- await cli('open', '--session=mysession', server.HELLO_WORLD);+test('delete-data named session', async ({ cli, server, mcpBrowser }, testInfo) => {+ await cli('--session=mysession', 'open', server.HELLO_WORLD, '--persistent');const dataDir = testInfo.outputPath('daemon', 'ud-mysession-' + mcpBrowser);expect(fs.existsSync(dataDir)).toBe(true);- const { output } = await cli('session-delete', 'mysession');+ const { output } = await cli('--session=mysession', 'delete-data');expect(output).toContain(`Deleted user data for session 'mysession'.`);expect(fs.existsSync(dataDir)).toBe(false);});-test('session-delete non-existent session', async ({ cli }) => {- const { output } = await cli('session-delete', 'nonexistent');+test('delete-data non-existent session', async ({ cli }) => {+ const { output } = await cli('--session=nonexistent', 'delete-data');expect(output).toContain(`No user data found for session 'nonexistent'.`);});@@ -120,7 +106,7 @@ test('session stops when browser exits', async ({ cli, server }) => {await expect.poll(() => cli('session-list').then(r => r.output)).toContain('[stopped]');});-test('session restart', async ({ cli, server }, testInfo) => {+test('session reopen with different config', 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));@@ -128,39 +114,15 @@ test('session restart', async ({ cli, server }, testInfo) => {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');}{+ // Reopen without config should use default viewportawait cli('open', server.HELLO_WORLD);const { output } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight');- expect(output).toContain('700x500');+ expect(output).toContain('1280x720');}});-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');- expect(beforeOutput).toContain('1280x720');-- const config = {- browser: {- contextOptions: {- viewport: { width: 700, height: 500 },- },- },- };- const configPath = testInfo.outputPath('session-config.json');- await fs.promises.writeFile(configPath, JSON.stringify(config, null, 2));-- const { output: configureOutput } = await cli('config', '--config=' + configPath);- expect(configureOutput).toContain(`--config=`);-- await cli('open', server.PREFIX);- const { output: afterOutput } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight');- expect(afterOutput).toContain('700x500');-});-test('session start should print session options', async ({ cli, server }, testInfo) => {const configPath = testInfo.outputPath('my-config.json');await fs.promises.writeFile(configPath, JSON.stringify({}, null, 2));@@ -170,25 +132,3 @@ test('session start should print session options', async ({ cli, server }, testIexpect(output).toContain('--headed');expect(output).toContain('--config=my-config.json');});--test('session mismatch should report error for default session', async ({ cli, server }) => {- // Start a default session- await cli('open', server.HELLO_WORLD);-- // Try to pass global options to the already running session- const { output, exitCode } = await cli('snapshot', '--headed');- expect(exitCode).toBe(1);- expect(output).toContain('The session is already configured.');- expect(output).toContain('playwright-cli config --headed');-});--test('session mismatch should report error for named session', async ({ cli, server }) => {- // Start a named session- await cli('open', '--session=mismatch-named', server.HELLO_WORLD);-- // Try to pass global options to the already running session- const { output, exitCode } = await cli('snapshot', '--session=mismatch-named', '--headed');- expect(exitCode).toBe(1);- expect(output).toContain('The session is already configured.');- expect(output).toContain('playwright-cli --session=mismatch-named config --headed');-});diff --git a/tests/mcp/cli-storage.spec.ts b/tests/mcp/cli-storage.spec.tsindex 0c6238febd..5fe3473f27 100644--- a/tests/mcp/cli-storage.spec.ts+++ b/tests/mcp/cli-storage.spec.ts@@ -120,7 +120,7 @@ test('state-save and state-load roundtrip', async ({ cli, server, mcpBrowser },await cli('state-load', testInfo.outputPath('roundtrip-state.json'));// Reload to pick up cookies- await cli('open', server.EMPTY_PAGE);+ await cli('goto', server.EMPTY_PAGE);// Verify storage was restoredconst { output: restoredResult } = await cli('eval', '() => document.cookie + "|" + localStorage.getItem("roundtripKey")');