Skip to content

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

chore(cli): pass session file around w/o client info (#39393)

Pavel Feldman9ca2a51fb61c
diff --git a/packages/devtools/src/grid.tsx b/packages/devtools/src/grid.tsx
index 42640a3ba3..7f47895fb4 100644
--- a/packages/devtools/src/grid.tsx
+++ b/packages/devtools/src/grid.tsx
@@ -20,7 +20,7 @@ import { DevToolsClient } from './devtoolsClient';
import { navigate } from './index';
import { Screencast } from './screencast';
-import type { SessionConfig } from '../../playwright/src/cli/client/registry';
+import type { SessionFile } from '../../playwright/src/cli/client/registry';
import type { Tab } from './devtoolsChannel';
import type { SessionModel, SessionStatus } from './sessionModel';
@@ -43,7 +43,7 @@ export const Grid: React.FC<{ model: SessionModel }> = ({ model }) => {
const workspaceGroups = React.useMemo(() => {
const groups = new Map<string, SessionStatus[]>();
for (const session of sessions) {
- const key = session.config.workspaceDir || 'Global';
+ const key = session.file.config.workspaceDir || 'Global';
let list = groups.get(key);
if (!list) {
list = [];
@@ -52,7 +52,7 @@ export const Grid: React.FC<{ model: SessionModel }> = ({ model }) => {
list.push(session);
}
for (const list of groups.values())
- list.sort((a, b) => a.config.name.localeCompare(b.config.name));
+ list.sort((a, b) => a.file.config.name.localeCompare(b.file.config.name));
// Current workspace first, then alphabetical.
const entries = [...groups.entries()];
@@ -86,7 +86,7 @@ export const Grid: React.FC<{ model: SessionModel }> = ({ model }) => {
</div>
{isExpanded && (
<div className='session-chips'>
- {entries.map(({ config, canConnect }) => <SessionChip key={config.socketPath} config={config} canConnect={canConnect} visible={isExpanded} model={model} />)}
+ {entries.map(({ file, canConnect }) => <SessionChip key={file.config.socketPath} sessionFile={file} canConnect={canConnect} visible={isExpanded} model={model} />)}
</div>
)}
</div>
@@ -96,7 +96,8 @@ export const Grid: React.FC<{ model: SessionModel }> = ({ model }) => {
</div>);
};
-const SessionChip: React.FC<{ config: SessionConfig; canConnect: boolean; visible: boolean; model: SessionModel }> = ({ config, canConnect, visible, model }) => {
+const SessionChip: React.FC<{ sessionFile: SessionFile; canConnect: boolean; visible: boolean; model: SessionModel }> = ({ sessionFile, canConnect, visible, model }) => {
+ const { config } = sessionFile;
const href = '#session=' + encodeURIComponent(config.socketPath);
const wsUrl = model.wsUrls.get(config.socketPath);
@@ -143,7 +144,7 @@ const SessionChip: React.FC<{ config: SessionConfig; canConnect: boolean; visibl
onClick={e => {
e.preventDefault();
e.stopPropagation();
- void model.closeSession(config);
+ void model.closeSession(sessionFile);
}}
>
<svg viewBox='0 0 12 12' fill='none' stroke='currentColor' strokeWidth='1.5' strokeLinecap='round'>
@@ -159,7 +160,7 @@ const SessionChip: React.FC<{ config: SessionConfig; canConnect: boolean; visibl
onClick={e => {
e.preventDefault();
e.stopPropagation();
- void model.deleteSessionData(config);
+ void model.deleteSessionData(sessionFile);
}}
>
<svg viewBox='0 0 16 16' fill='none' stroke='currentColor' strokeWidth='1.2' strokeLinecap='round' strokeLinejoin='round'>
@@ -173,7 +174,7 @@ const SessionChip: React.FC<{ config: SessionConfig; canConnect: boolean; visibl
<div className='screencast-container'>
{channel && <Screencast channel={channel} />}
{!canConnect && <div className='screencast-placeholder'>Session closed</div>}
- {canConnect && !channel && wsUrl === null && <div className='screencast-placeholder'>Not supported &mdash; v{config.version}</div>}
+ {canConnect && !channel && wsUrl === null && <div className='screencast-placeholder'>Not supported &mdash; v{sessionFile.config.version}</div>}
{canConnect && !channel && wsUrl === undefined && <div className='screencast-placeholder'>Connecting</div>}
</div>
</a>
diff --git a/packages/devtools/src/sessionModel.ts b/packages/devtools/src/sessionModel.ts
index e0512cbd37..78731a91e7 100644
--- a/packages/devtools/src/sessionModel.ts
+++ b/packages/devtools/src/sessionModel.ts
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import type { ClientInfo, SessionConfig } from '../../playwright/src/cli/client/registry';
+import type { ClientInfo, SessionFile } from '../../playwright/src/cli/client/registry';
export type SessionStatus = {
- config: SessionConfig;
+ file: SessionFile;
canConnect: boolean;
};
@@ -67,7 +67,7 @@ export class SessionModel {
}
sessionBySocketPath(socketPath: string): SessionStatus | undefined {
- return this.sessions.find(s => s.config.socketPath === socketPath);
+ return this.sessions.find(s => s.file.config.socketPath === socketPath);
}
private async _fetchSessions() {
@@ -86,7 +86,7 @@ export class SessionModel {
for (const session of this.sessions) {
if (session.canConnect)
- this._obtainDevtoolsUrl(session.config);
+ this._obtainDevtoolsUrl(session.file);
}
}
this.error = undefined;
@@ -102,32 +102,33 @@ export class SessionModel {
await this._fetchSessions();
}
- async closeSession(config: SessionConfig) {
+ async closeSession(sessionFile: SessionFile) {
await fetch('/api/sessions/close', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ config }),
+ body: JSON.stringify({ sessionFile }),
});
await this._fetchSessions();
}
- async deleteSessionData(config: SessionConfig) {
+ async deleteSessionData(sessionFile: SessionFile) {
await fetch('/api/sessions/delete-data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ config }),
+ body: JSON.stringify({ sessionFile }),
});
await this._fetchSessions();
}
- private _obtainDevtoolsUrl(config: SessionConfig) {
+ private _obtainDevtoolsUrl(sessionFile: SessionFile) {
+ const { config } = sessionFile;
if (this._knownTimestamps.get(config.socketPath) === config.timestamp)
return;
this._knownTimestamps.set(config.socketPath, config.timestamp);
fetch('/api/sessions/devtools-start', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ config }),
+ body: JSON.stringify({ sessionFile }),
}).then(async resp => {
if (resp.ok) {
const { url } = await resp.json();
diff --git a/packages/playwright/src/cli/client/devtoolsApp.ts b/packages/playwright/src/cli/client/devtoolsApp.ts
index e5056d2e5b..f5d121e9d8 100644
--- a/packages/playwright/src/cli/client/devtoolsApp.ts
+++ b/packages/playwright/src/cli/client/devtoolsApp.ts
@@ -28,7 +28,8 @@ import { Session } from './session';
import type http from 'http';
import type { Page } from 'playwright-core';
-import type { ClientInfo, SessionConfig } from './registry';
+import type { ClientInfo, SessionFile } from './registry';
+import type { SessionStatus } from '@devtools/sessionModel';
function readBody(request: http.IncomingMessage): Promise<any> {
return new Promise((resolve, reject) => {
@@ -46,6 +47,13 @@ function readBody(request: http.IncomingMessage): Promise<any> {
});
}
+async function parseRequest(request: http.IncomingMessage): Promise<{ sessionFile: SessionFile, args?: any }> {
+ const body = await readBody(request);
+ if (!body.sessionFile)
+ throw new Error('Dashboard app is too old, please close it and open again');
+ return { sessionFile: body.sessionFile };
+}
+
function sendJSON(response: http.ServerResponse, data: any, statusCode = 200) {
response.statusCode = statusCode;
response.setHeader('Content-Type', 'application/json');
@@ -58,13 +66,13 @@ async function handleApiRequest(clientInfo: ClientInfo, request: http.IncomingMe
if (apiPath === '/api/sessions/list' && request.method === 'GET') {
const registry = await Registry.load();
- const sessions: { config: SessionConfig, canConnect: boolean }[] = [];
- for (const [, entries] of registry.entryMap()) {
- for (const entry of entries) {
- const session = new Session(clientInfo, entry.config);
+ const sessions: SessionStatus[] = [];
+ for (const [, files] of registry.entryMap()) {
+ for (const file of files) {
+ const session = new Session(file);
const canConnect = await session.canConnect();
- if (canConnect || entry.config.cli.persistent)
- sessions.push({ config: entry.config, canConnect });
+ if (canConnect || file.config.cli.persistent)
+ sessions.push({ file: file, canConnect });
}
}
sendJSON(response, { sessions, clientInfo });
@@ -72,39 +80,31 @@ async function handleApiRequest(clientInfo: ClientInfo, request: http.IncomingMe
}
if (apiPath === '/api/sessions/close' && request.method === 'POST') {
- const body = await readBody(request);
- if (!body.config)
- throw new Error('Missing "config" parameter');
- await new Session(clientInfo, body.config).stop();
+ const { sessionFile } = await parseRequest(request);
+ await new Session(sessionFile).stop();
sendJSON(response, { success: true });
return;
}
if (apiPath === '/api/sessions/delete-data' && request.method === 'POST') {
- const body = await readBody(request);
- if (!body.config)
- throw new Error('Missing "config" parameter');
- await new Session(clientInfo, body.config).deleteData();
+ const { sessionFile } = await parseRequest(request);
+ await new Session(sessionFile).deleteData();
sendJSON(response, { success: true });
return;
}
if (apiPath === '/api/sessions/run' && request.method === 'POST') {
- const body = await readBody(request);
- if (!body.config)
- throw new Error('Missing "config" parameter');
- if (!body.args)
+ const { sessionFile, args } = await parseRequest(request);
+ if (!args)
throw new Error('Missing "args" parameter');
- const result = await new Session(clientInfo, body.config).run(body.args);
+ const result = await new Session(sessionFile).run(clientInfo, args);
sendJSON(response, { result });
return;
}
if (apiPath === '/api/sessions/devtools-start' && request.method === 'POST') {
- const body = await readBody(request);
- if (!body.config)
- throw new Error('Missing "config" parameter');
- const result = await new Session(clientInfo, body.config).run({ _: ['devtools-start'] });
+ const { sessionFile } = await parseRequest(request);
+ const result = await new Session(sessionFile).run(clientInfo, { _: ['devtools-start'] });
const match = result.text.match(/Server is listening on: (.+)/);
if (!match)
throw new Error('Failed to parse screencast URL from: ' + result.text);
diff --git a/packages/playwright/src/cli/client/program.ts b/packages/playwright/src/cli/client/program.ts
index 9826339a42..9cc6afd3a9 100644
--- a/packages/playwright/src/cli/client/program.ts
+++ b/packages/playwright/src/cli/client/program.ts
@@ -26,7 +26,7 @@ import { createClientInfo, Registry } from './registry';
import { Session, renderResolvedConfig } from './session';
import type { Config } from '../../mcp/config';
-import type { SessionConfig, ClientInfo } from './registry';
+import type { SessionConfig, ClientInfo, SessionFile } from './registry';
type MinimistArgs = {
_: string[];
@@ -136,7 +136,7 @@ export async function program(options?: { embedderVersion?: string}) {
case 'close-all': {
const entries = registry.entries(clientInfo);
for (const entry of entries)
- await new Session(clientInfo, entry.config).stop(true);
+ await new Session(entry).stop(true);
return;
}
case 'delete-data': {
@@ -145,7 +145,7 @@ export async function program(options?: { embedderVersion?: string}) {
console.log(`No user data found for browser '${sessionName}'.`);
return;
}
- await new Session(clientInfo, entry.config).deleteData();
+ await new Session(entry).deleteData();
return;
}
case 'kill-all': {
@@ -155,22 +155,28 @@ export async function program(options?: { embedderVersion?: string}) {
case 'open': {
const entry = registry.entry(clientInfo, sessionName);
if (entry)
- await new Session(clientInfo, entry.config).stop(true);
- const session = new Session(clientInfo, sessionConfigFromArgs(clientInfo, sessionName, args));
+ await new Session(entry).stop(true);
+ const config = sessionConfigFromArgs(clientInfo, sessionName, args);
+ const sessionFile: SessionFile = {
+ daemonDir: clientInfo.daemonProfilesDir,
+ file: path.join(clientInfo.daemonProfilesDir, `${sessionName}.session`),
+ config,
+ };
+ const session = new Session(sessionFile);
// Stale session.
if (await session.canConnect())
await session.stop(true);
for (const globalOption of globalOptions)
delete args[globalOption];
- const result = await session.run(args);
+ const result = await session.run(clientInfo, args);
console.log(result.text);
return;
}
case 'close':
const closeEntry = registry.entry(clientInfo, sessionName);
- const session = closeEntry ? new Session(clientInfo, closeEntry.config) : undefined;
+ const session = closeEntry ? new Session(closeEntry) : undefined;
if (!session || !await session.canConnect()) {
console.log(`Browser '${sessionName}' is not open.`);
return;
@@ -203,7 +209,7 @@ export async function program(options?: { embedderVersion?: string}) {
for (const globalOption of globalOptions)
delete args[globalOption];
- const result = await new Session(clientInfo, defaultEntry.config).run(args);
+ const result = await new Session(defaultEntry).run(clientInfo, args);
console.log(result.text);
}
}
@@ -389,16 +395,16 @@ async function listSessions(registry: Registry, clientInfo: ClientInfo, all: boo
if (!list.length)
continue;
console.log(`${workspace}:`);
- await gcAndPrintSessions(list.map(entry => new Session(clientInfo, entry.config)));
+ await gcAndPrintSessions(clientInfo, list.map(entry => new Session(entry)));
}
} else {
console.log('### Browsers');
const entries = registry.entries(clientInfo);
- await gcAndPrintSessions(entries.map(entry => new Session(clientInfo, entry.config)));
+ await gcAndPrintSessions(clientInfo, entries.map(entry => new Session(entry)));
}
}
-async function gcAndPrintSessions(sessions: Session[]) {
+async function gcAndPrintSessions(clientInfo: ClientInfo, sessions: Session[]) {
const running: Session[] = [];
const stopped: Session[] = [];
@@ -415,22 +421,22 @@ async function gcAndPrintSessions(sessions: Session[]) {
}
for (const session of running)
- console.log(await renderSessionStatus(session));
+ console.log(await renderSessionStatus(clientInfo, session));
for (const session of stopped)
- console.log(await renderSessionStatus(session));
+ console.log(await renderSessionStatus(clientInfo, session));
if (running.length === 0 && stopped.length === 0)
console.log(' (no browsers)');
}
-async function renderSessionStatus(session: Session) {
+async function renderSessionStatus(clientInfo: ClientInfo, session: Session) {
const text: string[] = [];
const config = session.config;
const canConnect = await session.canConnect();
text.push(`- ${session.name}:`);
text.push(` - status: ${canConnect ? 'open' : 'closed'}`);
- if (canConnect && !session.isCompatible())
+ if (canConnect && !session.isCompatible(clientInfo))
text.push(` - version: v${config.version} [incompatible please re-open]`);
if (config.resolvedConfig)
text.push(...renderResolvedConfig(config.resolvedConfig));
diff --git a/packages/playwright/src/cli/client/registry.ts b/packages/playwright/src/cli/client/registry.ts
index 15c69ad517..48a769fee2 100644
--- a/packages/playwright/src/cli/client/registry.ts
+++ b/packages/playwright/src/cli/client/registry.ts
@@ -46,63 +46,64 @@ export type SessionConfig = {
resolvedConfig?: FullConfig
};
-export type SessionEntry = {
+export type SessionFile = {
file: string;
+ daemonDir: string;
config: SessionConfig;
};
export class Registry {
- private _entries: Map<string, SessionEntry[]>;
+ private _files: Map<string, SessionFile[]>;
- private constructor(entries: Map<string, SessionEntry[]>) {
- this._entries = entries;
+ private constructor(files: Map<string, SessionFile[]>) {
+ this._files = files;
}
- entry(clientInfo: ClientInfo, sessionName: string): SessionEntry | undefined {
+ entry(clientInfo: ClientInfo, sessionName: string): SessionFile | undefined {
const key = clientInfo.workspaceDir || clientInfo.workspaceDirHash;
- const entries = this._entries.get(key) || [];
+ const entries = this._files.get(key) || [];
return entries.find(entry => entry.config.name === sessionName);
}
- entries(clientInfo: ClientInfo): SessionEntry[] {
+ entries(clientInfo: ClientInfo): SessionFile[] {
const key = clientInfo.workspaceDir || clientInfo.workspaceDirHash;
- return this._entries.get(key) || [];
+ return this._files.get(key) || [];
}
- entryMap(): Map<string, SessionEntry[]> {
- return this._entries;
+ entryMap(): Map<string, SessionFile[]> {
+ return this._files;
}
- static async loadSessionEntry(file: string): Promise<SessionEntry | undefined> {
+ private static async _loadSessionEntry(daemonDir: string, file: string): Promise<SessionFile | undefined> {
try {
- const data = await fs.promises.readFile(file, 'utf-8');
+ const fileName = path.join(daemonDir, file);
+ const data = await fs.promises.readFile(fileName, 'utf-8');
const config = JSON.parse(data) as SessionConfig;
// Sessions from 0.1.0 support.
if (!config.name)
config.name = path.basename(file, '.session');
if (!config.timestamp)
config.timestamp = 0;
- return { file, config };
+ return { file: fileName, config, daemonDir };
} catch {
return undefined;
}
}
static async load(): Promise<Registry> {
- const sessions = new Map<string, SessionEntry[]>();
+ const sessions = new Map<string, SessionFile[]>();
const hashDirs = await fs.promises.readdir(baseDaemonDir).catch(() => []);
for (const workspaceDirHash of hashDirs) {
- const hashDir = path.join(baseDaemonDir, workspaceDirHash);
- const stat = await fs.promises.stat(hashDir);
+ const daemonDir = path.join(baseDaemonDir, workspaceDirHash);
+ const stat = await fs.promises.stat(daemonDir);
if (!stat.isDirectory())
continue;
- const files = await fs.promises.readdir(hashDir).catch(() => []);
+ const files = await fs.promises.readdir(daemonDir).catch(() => []);
for (const file of files) {
if (!file.endsWith('.session'))
continue;
- const fileName = path.join(hashDir, file);
- const entry = await Registry.loadSessionEntry(fileName);
+ const entry = await Registry._loadSessionEntry(daemonDir, file);
if (!entry)
continue;
const key = entry.config.workspaceDir || workspaceDirHash;
diff --git a/packages/playwright/src/cli/client/session.ts b/packages/playwright/src/cli/client/session.ts
index 3478be219e..a520eeab2b 100644
--- a/packages/playwright/src/cli/client/session.ts
+++ b/packages/playwright/src/cli/client/session.ts
@@ -26,7 +26,7 @@ import path from 'path';
import { compareSemver, SocketConnection } from './socketConnection';
import type { FullConfig } from '../../mcp/browser/config';
-import type { SessionConfig, ClientInfo } from './registry';
+import type { SessionConfig, ClientInfo, SessionFile } from './registry';
type MinimistArgs = {
_: string[];
@@ -36,24 +36,24 @@ type MinimistArgs = {
export class Session {
readonly name: string;
readonly config: SessionConfig;
+ private _sessionFile: SessionFile;
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 _clientInfo: ClientInfo;
- constructor(clientInfo: ClientInfo, options: SessionConfig) {
- this._clientInfo = clientInfo;
- this.config = options;
- this.name = options.name;
+ constructor(sessionFile: SessionFile) {
+ this.config = sessionFile.config;
+ this.name = this.config.name;
+ this._sessionFile = sessionFile;
}
- isCompatible(): boolean {
- return compareSemver(this._clientInfo.version, this.config.version) >= 0;
+ isCompatible(clientInfo: ClientInfo): boolean {
+ return compareSemver(clientInfo.version, this.config.version) >= 0;
}
- checkCompatible() {
- if (!this.isCompatible()) {
- throw new Error(`Client is v${this._clientInfo.version}, session '${this.name}' is v${this.config.version}. Run
+ checkCompatible(clientInfo: ClientInfo) {
+ if (!this.isCompatible(clientInfo)) {
+ throw new Error(`Client is v${clientInfo.version}, session '${this.name}' is v${this.config.version}. Run
playwright-cli${this.name !== 'default' ? ` -s=${this.name}` : ''} open
@@ -66,8 +66,8 @@ to restart the browser session.`);
this.disconnect();
}
- async run(args: MinimistArgs, cwd?: string): Promise<{ text: string }> {
- this.checkCompatible();
+ async run(clientInfo: ClientInfo, args: MinimistArgs, cwd?: string): Promise<{ text: string }> {
+ this.checkCompatible(clientInfo);
const result = await this._send('run', { args, cwd: cwd || process.cwd() });
this.disconnect();
return result;
@@ -114,7 +114,7 @@ to restart the browser session.`);
async deleteData() {
await this.stop();
- const dataDirs = await fs.promises.readdir(this._clientInfo.daemonProfilesDir).catch(() => []);
+ const dataDirs = await fs.promises.readdir(this._sessionFile.daemonDir).catch(() => []);
const matchingEntries = dataDirs.filter(file => file === `${this.name}.session` || file.startsWith(`ud-${this.name}-`));
if (matchingEntries.length === 0) {
console.log(`No user data found for browser '${this.name}'.`);
@@ -122,7 +122,7 @@ to restart the browser session.`);
}
for (const entry of matchingEntries) {
- const userDataDir = path.resolve(this._clientInfo.daemonProfilesDir, entry);
+ const userDataDir = path.resolve(this._sessionFile.daemonDir, entry);
for (let i = 0; i < 5; i++) {
try {
await fs.promises.rm(userDataDir, { recursive: true });
@@ -194,26 +194,21 @@ to restart the browser 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 });
+ await fs.promises.mkdir(this._sessionFile.daemonDir, { recursive: true });
const cliPath = path.join(__dirname, '../../../cli.js');
- const sessionConfigFile = this._sessionFile('.session');
- this.config.version = this._clientInfo.version;
+ this.config.version = this.config.version;
this.config.timestamp = Date.now();
- await fs.promises.writeFile(sessionConfigFile, JSON.stringify(this.config, null, 2));
+ await fs.promises.writeFile(this._sessionFile.file, JSON.stringify(this.config, null, 2));
- const errLog = this._sessionFile('.err');
+ const errLog = this._sessionFile.file.replace('.session', '.err');
const err = fs.openSync(errLog, 'w');
const args = [
cliPath,
'run-cli-server',
- `--daemon-session=${sessionConfigFile}`,
+ `--daemon-session=${this._sessionFile.file}`,
];
const child = spawn(process.execPath, args, {
@@ -275,7 +270,7 @@ to restart the browser session.`);
console.log(`---`);
this.config.timestamp = Date.now();
- await fs.promises.writeFile(sessionConfigFile, JSON.stringify(this.config, null, 2));
+ await fs.promises.writeFile(this._sessionFile.file, JSON.stringify(this.config, null, 2));
return socket;
}
@@ -297,7 +292,7 @@ to restart the browser session.`);
}
async deleteSessionConfig() {
- await fs.promises.rm(this._sessionFile('.session')).catch(() => {});
+ await fs.promises.rm(this._sessionFile.file).catch(() => {});
}
}