Skip to content

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

chore: show devtools upon tray => show (#39219)

Pavel Feldmancb18921c32de
diff --git a/packages/devtools/src/devtools.tsx b/packages/devtools/src/devtools.tsx
index cafd8bf6e5..ce0935ce0d 100644
--- a/packages/devtools/src/devtools.tsx
+++ b/packages/devtools/src/devtools.tsx
@@ -55,7 +55,8 @@ export const DevTools: React.FC = () => {
React.useEffect(() => {
const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
- const transport = new DevToolsTransport(wsProtocol + '//' + location.host + '/ws');
+ const guid = new URLSearchParams(location.search).get('ws');
+ const transport = new DevToolsTransport(wsProtocol + '//' + location.host + '/' + guid);
transportRef.current = transport;
transport.onopen = () => setStatus({ text: 'Connected', cls: 'connected' });
diff --git a/packages/playwright-core/src/server/devtoolsController.ts b/packages/playwright-core/src/server/devtoolsController.ts
index b9ba885662..0c89b7ffb6 100644
--- a/packages/playwright-core/src/server/devtoolsController.ts
+++ b/packages/playwright-core/src/server/devtoolsController.ts
@@ -15,7 +15,7 @@
*/
import path from 'path';
-import { eventsHelper } from '../utils';
+import { createGuid, eventsHelper } from '../utils';
import { HttpServer } from './utils/httpServer';
import { BrowserContext } from './browserContext';
import { Page } from './page';
@@ -48,10 +48,10 @@ export class DevToolsController {
return this._httpServer.serveFile(request, response, resolved);
});
- this._httpServer.createWebSocket(() => new DevToolsConnection(this._context, this._screencastOptions), 'ws');
-
+ const guid = createGuid();
+ this._httpServer.createWebSocket(() => new DevToolsConnection(this._context, this._screencastOptions), guid);
await this._httpServer.start({ port: options.port, host: options.host });
- return this._httpServer.urlPrefix('human-readable');
+ return this._httpServer.urlPrefix('human-readable') + `?ws=${guid}`;
}
async stop() {
diff --git a/packages/playwright-core/src/server/index.ts b/packages/playwright-core/src/server/index.ts
index 3f127cb915..df4b183504 100644
--- a/packages/playwright-core/src/server/index.ts
+++ b/packages/playwright-core/src/server/index.ts
@@ -28,4 +28,5 @@ export { createPlaywright } from './playwright';
export type { DispatcherScope } from './dispatchers/dispatcher';
export type { Playwright } from './playwright';
-export { installRootRedirect, openTraceInBrowser, openTraceViewerApp, startTraceViewerServer } from './trace/viewer/traceViewer';
+export { installRootRedirect, openTraceInBrowser, openTraceViewerApp, startTraceViewerServer, openUrlInApp } from './trace/viewer/traceViewer';
+export { ProgressController } from './progress';
diff --git a/packages/playwright-core/src/server/trace/viewer/traceViewer.ts b/packages/playwright-core/src/server/trace/viewer/traceViewer.ts
index 392fe08eeb..91f9f1f43b 100644
--- a/packages/playwright-core/src/server/trace/viewer/traceViewer.ts
+++ b/packages/playwright-core/src/server/trace/viewer/traceViewer.ts
@@ -210,6 +210,26 @@ export async function openTraceInBrowser(url: string) {
await open(url.replace('0.0.0.0', 'localhost')).catch(() => {});
}
+export async function openUrlInApp(url: string, options?: { name?: string }) {
+ const localPlaywright = createPlaywright({ sdkLanguage: 'javascript', isInternalPlaywright: true });
+ const { context, page } = await launchApp(localPlaywright['chromium'], {
+ sdkLanguage: 'javascript',
+ windowSize: { width: 1280, height: 800 },
+ persistentContextOptions: {
+ headless: false,
+ },
+ });
+
+ const controller = new ProgressController();
+ await controller.run(async progress => {
+ await context._browser._defaultContext!._loadDefaultContextAsIs(progress);
+ if (options?.name)
+ await syncLocalStorageWithSettings(page, options.name);
+ await page.mainFrame().goto(progress, url);
+ });
+ return page;
+}
+
class StdinServer implements Transport {
private _pollTimer: NodeJS.Timeout | undefined;
private _traceUrl: string | undefined;
diff --git a/packages/playwright/src/mcp/browser/tools.ts b/packages/playwright/src/mcp/browser/tools.ts
index 633b018761..ce3366c589 100644
--- a/packages/playwright/src/mcp/browser/tools.ts
+++ b/packages/playwright/src/mcp/browser/tools.ts
@@ -32,6 +32,7 @@ import route from './tools/route';
import runCode from './tools/runCode';
import snapshot from './tools/snapshot';
import screenshot from './tools/screenshot';
+import show from './tools/show';
import storage from './tools/storage';
import tabs from './tools/tabs';
import tracing from './tools/tracing';
@@ -61,6 +62,7 @@ export const browserTools: Tool<any>[] = [
...route,
...runCode,
...screenshot,
+ ...show,
...snapshot,
...storage,
...tabs,
diff --git a/packages/playwright/src/mcp/browser/tools/show.ts b/packages/playwright/src/mcp/browser/tools/show.ts
new file mode 100644
index 0000000000..863b0d8761
--- /dev/null
+++ b/packages/playwright/src/mcp/browser/tools/show.ts
@@ -0,0 +1,42 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { z } from 'playwright-core/lib/mcpBundle';
+import { defineTool } from './tool';
+
+const show = defineTool({
+ capability: 'devtools',
+
+ schema: {
+ name: 'browser_show',
+ title: 'Show browser DevTools',
+ description: 'Show browser DevTools',
+ inputSchema: z.object({
+ host: z.string().optional().describe('Host to use'),
+ port: z.number().optional().describe('Port to use'),
+ guid: z.string().optional().describe('Endpoint guid to expose'),
+ }),
+ type: 'action',
+ },
+
+ handle: async (context, params, response) => {
+ const browserContext = await context.ensureBrowserContext();
+ const { url } = await (browserContext as any)._devtoolsStart(params);
+ response.addTextResult('Show server is listening on: ' + url);
+ },
+});
+
+export default [show];
diff --git a/packages/playwright/src/mcp/terminal/commands.ts b/packages/playwright/src/mcp/terminal/commands.ts
index a87176600d..f8beb4ae82 100644
--- a/packages/playwright/src/mcp/terminal/commands.ts
+++ b/packages/playwright/src/mcp/terminal/commands.ts
@@ -763,6 +763,15 @@ const videoStop = declareCommand({
toolParams: ({ filename }) => ({ filename }),
});
+const show = declareCommand({
+ name: 'show',
+ description: 'Show browser DevTools',
+ category: 'devtools',
+ args: z.object({}),
+ toolName: 'browser_show',
+ toolParams: () => ({}),
+});
+
// Sessions
const sessionList = declareCommand({
@@ -925,6 +934,7 @@ const commandsArray: AnyCommandSchema[] = [
// devtools category
networkRequests,
+ show,
tracingStart,
tracingStop,
videoStart,
diff --git a/packages/playwright/src/mcp/terminal/program.ts b/packages/playwright/src/mcp/terminal/program.ts
index 9f5e652bda..3d88fa257a 100644
--- a/packages/playwright/src/mcp/terminal/program.ts
+++ b/packages/playwright/src/mcp/terminal/program.ts
@@ -38,29 +38,25 @@ type MinimistArgs = {
export class Session {
readonly name: string;
+ readonly config: SessionConfig;
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 _config: SessionConfig;
private _clientInfo: ClientInfo;
constructor(clientInfo: ClientInfo, options: SessionConfig) {
this._clientInfo = clientInfo;
- this._config = options;
+ this.config = options;
this.name = options.name;
}
- config(): SessionConfig {
- return this._config;
- }
-
isCompatible(): boolean {
- return this._clientInfo.version === this._config.version;
+ return this._clientInfo.version === this.config.version;
}
checkCompatible() {
if (!this.isCompatible()) {
- throw new Error(`Client is v${this._clientInfo.version}, session '${this.name}' is v${this._config.version}. Run
+ throw new Error(`Client is v${this._clientInfo.version}, session '${this.name}' is v${this.config.version}. Run
playwright-cli${this.name !== 'default' ? ` -s=${this.name}` : ''} open
@@ -94,7 +90,7 @@ to restart the browser session.`);
id: messageId,
method,
params,
- version: this._config.version,
+ version: this.config.version,
};
const responsePromise = new Promise<any>((resolve, reject) => {
this._callbacks.set(messageId, { resolve, reject, method, params });
@@ -146,12 +142,12 @@ to restart the browser session.`);
async _connect(): Promise<{ socket?: net.Socket, error?: Error }> {
return await new Promise(resolve => {
- const socket = net.createConnection(this._config.socketPath, () => {
+ const socket = net.createConnection(this.config.socketPath, () => {
resolve({ socket });
});
socket.on('error', error => {
if (os.platform() !== 'win32')
- void fs.promises.unlink(this._config.socketPath).catch(() => {}).then(() => resolve({ error }));
+ void fs.promises.unlink(this.config.socketPath).catch(() => {}).then(() => resolve({ error }));
else
resolve({ error });
});
@@ -175,7 +171,7 @@ to restart the browser session.`);
if (!socket)
socket = await this._startDaemon();
- this._connection = new SocketConnection(socket, this._config.version);
+ this._connection = new SocketConnection(socket, this.config.version);
this._connection.onmessage = message => this._onMessage(message);
this._connection.onclose = () => this.disconnect();
return this._connection;
@@ -205,8 +201,8 @@ to restart the browser session.`);
const cliPath = path.join(__dirname, '../../../cli.js');
const sessionConfigFile = this._sessionFile('.session');
- this._config.version = this._clientInfo.version;
- await fs.promises.writeFile(sessionConfigFile, JSON.stringify(this._config, null, 2));
+ this.config.version = this._clientInfo.version;
+ await fs.promises.writeFile(sessionConfigFile, JSON.stringify(this.config, null, 2));
const errLog = this._sessionFile('.err');
const err = fs.openSync(errLog, 'w');
@@ -269,17 +265,17 @@ to restart the browser session.`);
console.log(`### Browser \`${this.name}\` opened with pid ${child.pid}.`);
const resolvedConfig = await parseResolvedConfig(outLog);
if (resolvedConfig) {
- this._config.resolvedConfig = resolvedConfig;
+ this.config.resolvedConfig = resolvedConfig;
console.log(`- ${this.name}:`);
console.log(renderResolvedConfig(resolvedConfig).join('\n'));
}
console.log(`---`);
- await fs.promises.writeFile(sessionConfigFile, JSON.stringify(this._config, null, 2));
+ await fs.promises.writeFile(sessionConfigFile, JSON.stringify(this.config, null, 2));
return socket;
}
- console.error(`Failed to connect to daemon at ${this._config.socketPath}`);
+ console.error(`Failed to connect to daemon at ${this.config.socketPath}`);
process.exit(1);
}
@@ -287,10 +283,10 @@ to restart the browser session.`);
let error: Error | undefined;
await this._send('stop').catch(e => { error = e; });
if (os.platform() !== 'win32')
- await fs.promises.unlink(this._config.socketPath).catch(() => {});
+ await fs.promises.unlink(this.config.socketPath).catch(() => {});
this.disconnect();
- if (!this._config.cli.persistent)
+ if (!this.config.cli.persistent)
await this.deleteSessionConfig();
if (error && !error?.message?.includes('Session closed'))
throw error;
@@ -437,18 +433,18 @@ export async function program() {
return;
}
case 'close-all': {
- const configs = registry.configs(clientInfo);
- for (const config of configs)
- await new Session(clientInfo, config).stop(true);
+ const entries = registry.entries(clientInfo);
+ for (const entry of entries)
+ await new Session(clientInfo, entry.config).stop(true);
return;
}
case 'delete-data': {
- const config = registry.config(clientInfo, sessionName);
- if (!config) {
+ const entry = registry.entry(clientInfo, sessionName);
+ if (!entry) {
console.log(`No user data found for browser '${sessionName}'.`);
return;
}
- await new Session(clientInfo, config).deleteData();
+ await new Session(clientInfo, entry.config).deleteData();
return;
}
case 'kill-all': {
@@ -456,9 +452,9 @@ export async function program() {
return;
}
case 'open': {
- const config = registry.config(clientInfo, sessionName);
- if (config)
- await new Session(clientInfo, config).stop(true);
+ 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));
for (const globalOption of globalOptions)
delete args[globalOption];
@@ -468,8 +464,8 @@ export async function program() {
}
case 'close':
- const config = registry.config(clientInfo, sessionName);
- const session = config ? new Session(clientInfo, config) : undefined;
+ const closeEntry = registry.entry(clientInfo, sessionName);
+ const session = closeEntry ? new Session(clientInfo, closeEntry.config) : undefined;
if (!session || !await session.canConnect()) {
console.log(`Browser '${sessionName}' is not open.`);
return;
@@ -489,8 +485,8 @@ export async function program() {
return;
}
default: {
- const config = registry.config(clientInfo, sessionName);
- if (!config) {
+ const defaultEntry = registry.entry(clientInfo, sessionName);
+ if (!defaultEntry) {
console.log(`The browser '${sessionName}' is not open, please run open first`);
console.log('');
console.log(` playwright-cli${sessionName !== 'default' ? ` -s=${sessionName}` : ''} open [params]`);
@@ -499,7 +495,7 @@ export async function program() {
for (const globalOption of globalOptions)
delete args[globalOption];
- const result = await new Session(clientInfo, config).run(args);
+ const result = await new Session(clientInfo, defaultEntry.config).run(args);
console.log(result.text);
}
}
@@ -670,21 +666,21 @@ async function killAllDaemons(): Promise<void> {
async function listSessions(registry: Registry, clientInfo: ClientInfo, all: boolean): Promise<void> {
if (all) {
- const configs = registry.configMap();
- if (configs.size === 0) {
+ const entries = registry.entryMap();
+ if (entries.size === 0) {
console.log('No browsers found.');
return;
}
- for (const [workspace, list] of configs) {
+ for (const [workspace, list] of entries) {
if (!list.length)
continue;
console.log(`${workspace}:`);
- await gcAndPrintSessions(list.map(config => new Session(clientInfo, config)));
+ await gcAndPrintSessions(list.map(entry => new Session(clientInfo, entry.config)));
}
} else {
console.log('### Browsers');
- const configs = registry.configs(clientInfo);
- await gcAndPrintSessions(configs.map(config => new Session(clientInfo, config)));
+ const entries = registry.entries(clientInfo);
+ await gcAndPrintSessions(entries.map(entry => new Session(clientInfo, entry.config)));
}
}
@@ -697,7 +693,7 @@ async function gcAndPrintSessions(sessions: Session[]) {
if (canConnect) {
running.push(session);
} else {
- if (session.config().cli.persistent)
+ if (session.config.cli.persistent)
stopped.push(session);
else
await session.deleteSessionConfig();
@@ -716,7 +712,7 @@ async function gcAndPrintSessions(sessions: Session[]) {
async function renderSessionStatus(session: Session) {
const text: string[] = [];
- const config = session.config();
+ const config = session.config;
const canConnect = await session.canConnect();
text.push(`- ${session.name}:`);
text.push(` - status: ${canConnect ? 'open' : 'closed'}`);
diff --git a/packages/playwright/src/mcp/terminal/registry.ts b/packages/playwright/src/mcp/terminal/registry.ts
index 6be8b57957..325d656815 100644
--- a/packages/playwright/src/mcp/terminal/registry.ts
+++ b/packages/playwright/src/mcp/terminal/registry.ts
@@ -44,30 +44,48 @@ export type SessionConfig = {
resolvedConfig?: FullConfig
};
+export type SessionEntry = {
+ file: string;
+ config: SessionConfig;
+};
+
export class Registry {
- private _configs: Map<string, SessionConfig[]>;
+ private _entries: Map<string, SessionEntry[]>;
- private constructor(configs: Map<string, SessionConfig[]>) {
- this._configs = configs;
+ private constructor(entries: Map<string, SessionEntry[]>) {
+ this._entries = entries;
}
- config(clientInfo: ClientInfo, sessionName: string): SessionConfig | undefined {
+ entry(clientInfo: ClientInfo, sessionName: string): SessionEntry | undefined {
const key = clientInfo.workspaceDir || clientInfo.workspaceDirHash;
- const configs = this._configs.get(key) || [];
- return configs.find(config => config.name === sessionName);
+ const entries = this._entries.get(key) || [];
+ return entries.find(entry => entry.config.name === sessionName);
}
- configs(clientInfo: ClientInfo): SessionConfig[] {
+ entries(clientInfo: ClientInfo): SessionEntry[] {
const key = clientInfo.workspaceDir || clientInfo.workspaceDirHash;
- return this._configs.get(key) || [];
+ return this._entries.get(key) || [];
+ }
+
+ entryMap(): Map<string, SessionEntry[]> {
+ return this._entries;
}
- configMap(): Map<string, SessionConfig[]> {
- return this._configs;
+ static async loadSessionEntry(file: string): Promise<SessionEntry | undefined> {
+ try {
+ const data = await fs.promises.readFile(file, 'utf-8');
+ const config = JSON.parse(data) as SessionConfig;
+ // Sessions from 0.1.0 support.
+ if (!config.name)
+ config.name = path.basename(file, '.session');
+ return { file, config };
+ } catch {
+ return undefined;
+ }
}
static async load(): Promise<Registry> {
- const sessions = new Map<string, SessionConfig[]>();
+ const sessions = new Map<string, SessionEntry[]>();
const hashDirs = await fs.promises.readdir(baseDaemonDir).catch(() => []);
for (const workspaceDirHash of hashDirs) {
const hashDir = path.join(baseDaemonDir, workspaceDirHash);
@@ -80,18 +98,16 @@ export class Registry {
if (!file.endsWith('.session'))
continue;
const fileName = path.join(hashDir, file);
- const sessionName = path.basename(file, '.session');
- const sessionConfig = await fs.promises.readFile(fileName, 'utf-8').then(data => JSON.parse(data)) as SessionConfig;
- // Support for 0.1.0 where session name was not stored in the file.
- if (!sessionConfig.name)
- sessionConfig.name = sessionName;
- const key = sessionConfig.workspaceDir || workspaceDirHash;
+ const entry = await Registry.loadSessionEntry(fileName);
+ if (!entry)
+ continue;
+ const key = entry.config.workspaceDir || workspaceDirHash;
let list = sessions.get(key);
if (!list) {
list = [];
sessions.set(key, list);
}
- list.push(sessionConfig);
+ list.push(entry);
}
}
return new Registry(sessions);
diff --git a/packages/playwright/src/mcp/terminal/trayDaemon.ts b/packages/playwright/src/mcp/terminal/trayDaemon.ts
index d3abcc818c..9d41dfe51d 100644
--- a/packages/playwright/src/mcp/terminal/trayDaemon.ts
+++ b/packages/playwright/src/mcp/terminal/trayDaemon.ts
@@ -18,12 +18,14 @@ import fs from 'fs';
import net from 'net';
import path from 'path';
import os from 'os';
+
+import { openUrlInApp, ProgressController } from 'playwright-core/lib/server';
import { gracefullyProcessExitDoNotHang } from 'playwright-core/lib/utils';
import { createClientInfo, Session } from './program';
import { Registry } from './registry';
-import type { SessionConfig } from './registry';
+import type { SessionEntry } from './registry';
import type { MenuItem } from '@trayjs/trayjs';
const socketsDir = process.env.PLAYWRIGHT_DAEMON_SOCKETS_DIR || path.join(os.tmpdir(), 'playwright-cli');
@@ -52,26 +54,27 @@ function acquireSingleton(): Promise<net.Server> {
}
let lastId = 0;
-const idToConfig = new Map<string, SessionConfig>();
+const idToEntry = new Map<string, SessionEntry>();
async function onMenuRequested(): Promise<MenuItem[]> {
const registry = await Registry.load();
- const map = registry.configMap();
+ const map = registry.entryMap();
const items: MenuItem[] = [];
let first = true;
- idToConfig.clear();
- for (const [workspace, configs] of map) {
+ idToEntry.clear();
+ for (const [workspace, entries] of map) {
if (!first)
items.push({ id: '', separator: true });
first = false;
const shortName = path.basename(workspace);
items.push({ id: '', title: shortName, enabled: false });
- for (const config of configs) {
- idToConfig.set(String(++lastId), config);
+ for (const entry of entries) {
+ idToEntry.set(String(++lastId), entry);
items.push({
id: ``,
- title: config.name,
+ title: entry.config.name,
items: [
+ { id: `show:${lastId}`, title: 'Show' },
{ id: `close:${lastId}`, title: 'Close' },
],
});
@@ -105,8 +108,13 @@ async function main() {
onClicked: (id: string) => {
if (id === 'quit')
tray.quit();
- if (id.startsWith('close:'))
- session(id.substring('close:'.length))?.stop().catch(() => {});
+ if (id.startsWith('show:'))
+ show(idToEntry.get(id.substring('show:'.length))).catch(() => {});
+ if (id.startsWith('close:')) {
+ const entry = idToEntry.get(id.substring('close:'.length));
+ if (entry)
+ new Session(createClientInfo(), entry.config).stop().catch(() => {});
+ }
},
onMenuRequested,
});
@@ -121,12 +129,47 @@ async function main() {
tray.on('close', () => gracefullyProcessExitDoNotHang(0));
}
-function session(id: string): Session | undefined {
- const config = idToConfig.get(id);
- if (!config)
+async function runShow(entry: SessionEntry): Promise<string | undefined> {
+ const s = new Session(createClientInfo(), entry.config);
+ const { text } = await s.run({ _: ['show'] });
+ return text.match(/Show server is listening on: (.+)/)?.[1];
+}
+
+async function show(entry: SessionEntry | undefined) {
+ if (!entry)
+ return;
+ const url = await runShow(entry);
+ if (!url)
+ return;
+
+ const page = await openUrlInApp(url, { name: 'devtools' }).catch(() => null);
+ if (!page)
return;
- const clientInfo = createClientInfo();
- return new Session(clientInfo, config);
+
+ let closed = false;
+ page.on('close', () => {
+ closed = true;
+ });
+
+ while (!closed) {
+ await new Promise(resolve => setTimeout(resolve, 2000));
+ if (closed)
+ break;
+ try {
+ const freshEntry = await Registry.loadSessionEntry(entry.file);
+ if (!freshEntry)
+ continue;
+ const newUrl = await runShow(freshEntry);
+ if (!newUrl)
+ continue;
+ const controller = new ProgressController();
+ await controller.run(async progress => {
+ await page.mainFrame().goto(progress, newUrl);
+ });
+ } catch {
+ // Session might be restarting, try again next poll.
+ }
+ }
}
void main();