Skip to content

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

chore: attach resolved config to the session (#39159)

Pavel Feldman743016b4a3dc
diff --git a/packages/playwright/src/mcp/program.ts b/packages/playwright/src/mcp/program.ts
index c3c3b1ba7c..37270e0160 100644
--- a/packages/playwright/src/mcp/program.ts
+++ b/packages/playwright/src/mcp/program.ts
@@ -116,6 +116,10 @@ export function decorateCommand(command: Command, version: string) {
version,
create: () => new BrowserServerBackend(config, contextFactory, { allTools: true })
};
+ console.error(`### Config`);
+ console.error('```json');
+ console.error(JSON.stringify(config, null, 2));
+ console.error('```');
const socketPath = await startMcpDaemonServer(config.sessionConfig, serverBackendFactory);
console.error(`Daemon server listening on ${socketPath}`);
return;
diff --git a/packages/playwright/src/mcp/terminal/program.ts b/packages/playwright/src/mcp/terminal/program.ts
index a0160ebf26..988d79f3a1 100644
--- a/packages/playwright/src/mcp/terminal/program.ts
+++ b/packages/playwright/src/mcp/terminal/program.ts
@@ -25,6 +25,7 @@ import net from 'net';
import os from 'os';
import path from 'path';
import { SocketConnection } from './socketConnection';
+import type { FullConfig } from '../browser/config';
type MinimistArgs = {
_: string[];
@@ -44,6 +45,7 @@ export type SessionConfig = {
};
userDataDirPrefix?: string;
workspaceDir?: string;
+ resolvedConfig?: FullConfig
};
type ClientInfo = {
@@ -97,7 +99,7 @@ to restart the session daemon.`);
}
await this._stopDaemon();
- console.log(`Browser '${this.name}' closed.`);
+ console.log(`Browser '${this.name}' closed`);
console.log('');
}
@@ -210,20 +212,20 @@ to restart the session daemon.`);
}
}
- private _sessionConfigFile() {
- return path.resolve(this._clientInfo.daemonProfilesDir, `${this.name}.session`);
+ private _sessionFile(suffix: string) {
+ return path.resolve(this._clientInfo.daemonProfilesDir, `${this.name}${suffix}`);
}
private async _startDaemon(): Promise<net.Socket> {
await fs.promises.mkdir(this._clientInfo.daemonProfilesDir, { recursive: true });
const cliPath = path.join(__dirname, '../../../cli.js');
- const sessionConfigFile = this._sessionConfigFile();
+ const sessionConfigFile = this._sessionFile('.session');
this._config.version = this._clientInfo.version;
await fs.promises.writeFile(sessionConfigFile, JSON.stringify(this._config, null, 2));
- const outLog = path.join(this._clientInfo.daemonProfilesDir, 'out.log');
- const errLog = path.join(this._clientInfo.daemonProfilesDir, 'err.log');
+ const outLog = this._sessionFile('.out');
+ const errLog = this._sessionFile('.err');
const out = fs.openSync(outLog, 'w');
const err = fs.openSync(errLog, 'w');
@@ -240,20 +242,6 @@ to restart the session daemon.`);
});
child.unref();
- console.log(`### Browser \`${this.name}\` opened with pid ${child.pid}.`);
- const configArgs = configToFormattedArgs(this._config.cli);
- if (configArgs.length) {
- console.log(`- Browser options:`);
- for (const flag of configArgs)
- console.log(` ${flag}`);
- }
- const sessionOption = this.name !== 'default' ? ` -b ${this.name}` : '';
- 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 profile data dir`));
- console.log(`---`);
- console.log(``);
-
// Wait for the socket to become available with retries.
const retryDelay = [100, 200, 400]; // ms
let totalWaited = 0;
@@ -262,8 +250,26 @@ to restart the session daemon.`);
totalWaited += retryDelay[i] || 1000;
try {
const { socket } = await this._connect();
- if (socket)
+ if (socket) {
+ console.log(`### Browser \`${this.name}\` opened with pid ${child.pid}.`);
+ const resolvedConfig = await parseResolvedConfig(errLog);
+ if (resolvedConfig) {
+ this._config.resolvedConfig = resolvedConfig;
+ console.log(`- ${this.name}:`);
+ console.log(renderResolvedConfig(resolvedConfig).join('\n'));
+ }
+ const sessionOption = this.name !== 'default' ? ` -b ${this.name}` : '';
+ console.log(``);
+ console.log(`\`\`\`bash`);
+ console.log(formatWithGap(`> playwright-cli${sessionOption} close`, `# to close 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 profile data dir`));
+ console.log(`\`\`\``);
+ console.log(``);
+
+ await fs.promises.writeFile(sessionConfigFile, JSON.stringify(this._config, null, 2));
return socket;
+ }
} catch (e) {
if (e.code !== 'ENOENT' && e.code !== 'ECONNREFUSED')
throw e;
@@ -295,7 +301,7 @@ to restart the session daemon.`);
}
async deleteSessionConfig() {
- await fs.promises.rm(this._sessionConfigFile()).catch(() => {});
+ await fs.promises.rm(this._sessionFile('.session')).catch(() => {});
}
}
@@ -603,23 +609,6 @@ function sessionConfigFromArgs(clientInfo: ClientInfo, sessionName: string, args
};
}
-function configToFormattedArgs(cli: SessionConfig['cli']): string[] {
- const args: string[] = [];
- const add = (flag: string, value: string | boolean | undefined) => {
- if (typeof value === 'boolean' && value)
- args.push(`--${flag}`);
- else if (typeof value === 'string')
- args.push(`--${flag}=${value}`);
- };
- 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;
-}
-
async function killAllDaemons(): Promise<void> {
const platform = os.platform();
let killed = 0;
@@ -670,7 +659,7 @@ async function killAllDaemons(): Promise<void> {
async function listSessions(sessionManager: SessionManager): Promise<void> {
const sessions = sessionManager.sessions;
- console.log('Browsers:');
+ console.log('### Browsers');
await gcAndPrintSessions([...sessions.values()]);
}
@@ -746,16 +735,46 @@ async function renderSessionStatus(session: Session) {
const text: string[] = [];
const config = session.config();
const canConnect = await session.canConnect();
- const isPersistent = config.cli.persistent;
- const statusMarker = canConnect ? '[open]' : '[closed]';
- const persistentMarker = isPersistent ? ' [persistent]' : '';
const restartMarker = canConnect && !session.isCompatible() ? ` - v${config.version}, please reopen` : '';
- text.push(` ${session.name} ${statusMarker}${persistentMarker}${restartMarker}`);
- configToFormattedArgs(config.cli).forEach(arg => text.push(` ${arg}`));
+ text.push(`- ${session.name}:`);
+ text.push(` - status: ${canConnect ? 'open' : 'closed'}${restartMarker}`);
+ if (config.resolvedConfig)
+ text.push(...renderResolvedConfig(config.resolvedConfig));
return text.join('\n');
}
+function renderResolvedConfig(resolvedConfig: FullConfig) {
+ const channel = resolvedConfig.browser.launchOptions.channel ?? resolvedConfig.browser.browserName;
+ const lines = [];
+ if (channel)
+ lines.push(` - browser-type: ${channel}`);
+ if (resolvedConfig.browser.isolated)
+ lines.push(` - user-data-dir: <in-memory>`);
+ else
+ lines.push(` - user-data-dir: ${resolvedConfig.browser.userDataDir}`);
+ lines.push(` - headed: ${!resolvedConfig.browser.launchOptions.headless}`);
+ return lines;
+}
+
function formatWithGap(prefix: string, text: string, threshold: number = 40) {
const indent = Math.max(1, threshold - prefix.length);
return prefix + ' '.repeat(indent) + text;
}
+
+async function parseResolvedConfig(logFile: string): Promise<FullConfig | null> {
+ const logData = await fs.promises.readFile(logFile, 'utf-8').catch(() => '');
+ const marker = '### Config\n```json\n';
+ const markerIndex = logData.indexOf(marker);
+ if (markerIndex === -1)
+ return null;
+ const jsonStart = markerIndex + marker.length;
+ const jsonEnd = logData.indexOf('\n```', jsonStart);
+ if (jsonEnd === -1)
+ throw null;
+ const jsonString = logData.substring(jsonStart, jsonEnd).trim();
+ try {
+ return JSON.parse(jsonString) as FullConfig;
+ } catch {
+ return null;
+ }
+}
diff --git a/tests/mcp/cli-core.spec.ts b/tests/mcp/cli-core.spec.ts
index 8bf56f99b2..e1ed6d254d 100644
--- a/tests/mcp/cli-core.spec.ts
+++ b/tests/mcp/cli-core.spec.ts
@@ -31,7 +31,7 @@ test('open', async ({ cli, server }) => {
test('close', async ({ cli, server }) => {
await cli('open', server.HELLO_WORLD);
const { output } = await cli('close');
- expect(output).toContain(`Browser 'default' closed.`);
+ expect(output).toContain(`Browser 'default' closed`);
});
test('click button', async ({ cli, server }) => {
diff --git a/tests/mcp/cli-fixtures.ts b/tests/mcp/cli-fixtures.ts
index e7705ef325..eaef8a9774 100644
--- a/tests/mcp/cli-fixtures.ts
+++ b/tests/mcp/cli-fixtures.ts
@@ -83,7 +83,7 @@ async function runCli(childProcess: CommonFixtures['childProcess'], args: string
snapshot = await loadSnapshot(cli.stdout);
const attachments = loadAttachments(cli.stdout);
- const matches = cli.stdout.includes('Session') ? cli.stdout.match(/Session `(.+)` started with pid (\d+)\./) : undefined;
+ const matches = cli.stdout.includes('### Browser') ? cli.stdout.match(/Browser `(.+)` opened 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.ts
index 177b4b6c01..a67c540f94 100644
--- a/tests/mcp/cli-isolated.spec.ts
+++ b/tests/mcp/cli-isolated.spec.ts
@@ -29,11 +29,16 @@ test('should not save user data by default (in-memory mode)', async ({ cli, serv
userDataDirPrefix: expect.any(String),
version: expect.any(String),
workspaceDir: testInfo.outputPath(),
+ resolvedConfig: expect.any(Object),
});
const { output: listOutput } = await cli('list');
- expect(listOutput).toContain('Browsers:');
- expect(listOutput).toContain(' default');
+ expect(listOutput).toContain(`### Browsers
+- default:
+ - status: open
+ - browser-type: chrome
+ - user-data-dir: <in-memory>
+ - headed: false`);
});
test('should save user data with --persistent flag', async ({ cli, server, mcpBrowser }, testInfo) => {
@@ -49,6 +54,7 @@ test('should save user data with --persistent flag', async ({ cli, server, mcpBr
userDataDirPrefix: expect.any(String),
version: expect.any(String),
workspaceDir: testInfo.outputPath(),
+ resolvedConfig: expect.any(Object),
});
});
@@ -66,5 +72,6 @@ test('should use custom user data dir with --profile=<dir>', async ({ cli, serve
userDataDirPrefix: expect.any(String),
version: expect.any(String),
workspaceDir: testInfo.outputPath(),
+ resolvedConfig: expect.any(Object),
});
});
diff --git a/tests/mcp/cli-session.spec.ts b/tests/mcp/cli-session.spec.ts
index 20ba2e1a9e..545d4e0745 100644
--- a/tests/mcp/cli-session.spec.ts
+++ b/tests/mcp/cli-session.spec.ts
@@ -20,21 +20,21 @@ import { test, expect, daemonFolder } from './cli-fixtures';
test('list', async ({ cli, server }) => {
const { output: emptyOutput } = await cli('list');
- expect(emptyOutput).toContain('Browsers:');
+ expect(emptyOutput).toContain('### Browsers');
expect(emptyOutput).toContain(' (no browsers)');
await cli('open', server.HELLO_WORLD);
const { output: listOutput } = await cli('list');
- expect(listOutput).toContain('Browsers:');
- expect(listOutput).toContain(' default');
+ expect(listOutput).toContain('### Browsers');
+ expect(listOutput).toContain('- default:');
});
test('close', async ({ cli, server }) => {
await cli('open', server.HELLO_WORLD);
const { output } = await cli('close');
- expect(output).toContain(`Browser 'default' closed.`);
+ expect(output).toContain(`Browser 'default' closed`);
const { output: listOutput } = await cli('list');
expect(listOutput).toContain('(no browsers)');
@@ -44,7 +44,7 @@ test('close named session', async ({ cli, server }) => {
await cli('-b', 'mysession', 'open', server.HELLO_WORLD);
const { output } = await cli('-b', 'mysession', 'close');
- expect(output).toContain(`Browser 'mysession' closed.`);
+ expect(output).toContain(`Browser 'mysession' closed`);
});
test('close non-running session', async ({ cli }) => {
@@ -52,16 +52,17 @@ test('close non-running session', async ({ cli }) => {
expect(output).toContain(`Browser 'nonexistent' is not open.`);
});
-test('stopped persistent session shows in list', async ({ cli, server }) => {
+test('persistent session shows in list after close', async ({ cli, server }) => {
await cli('open', server.HELLO_WORLD, '--persistent');
const { output: listBefore } = await cli('list');
- expect(listBefore).toContain('default [open] [persistent]');
+ expect(listBefore).toContain('- default:');
+ expect(listBefore).not.toContain('<in-memory>');
await cli('close');
const { output: listAfter } = await cli('list');
- expect(listAfter).toContain('default [closed] [persistent]');
+ expect(listAfter).toContain('- default:');
});
test('close-all', async ({ cli, server }) => {
@@ -138,14 +139,14 @@ test('session reopen with different config', async ({ cli, server }, testInfo) =
}
});
-test('session start should print session options', async ({ cli, server }, testInfo) => {
+test('session start should print browser config', async ({ cli, server }, testInfo) => {
const configPath = testInfo.outputPath('my-config.json');
await fs.promises.writeFile(configPath, JSON.stringify({}, null, 2));
const { output } = await cli('open', '--headed', '--config=' + configPath, server.HELLO_WORLD);
- expect(output).toContain('Browser options:');
- expect(output).toContain('--headed');
- expect(output).toContain('--config=my-config.json');
+ expect(output).toContain('### Browser `default` opened');
+ expect(output).toContain('- default:');
+ expect(output).toContain('- headed:');
});
test('workspace isolation - sessions in different workspaces are isolated', async ({ cli, server }, testInfo) => {