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
feat(dashboard): add openDashboardForContext entry point (#40506)
Pavel Feldman459fb7b62e51
diff --git a/packages/dashboard/src/dashboardChannel.ts b/packages/dashboard/src/dashboardChannel.tsindex fb484cbfcb..2fe3b8799e 100644--- a/packages/dashboard/src/dashboardChannel.ts+++ b/packages/dashboard/src/dashboardChannel.ts@@ -47,9 +47,7 @@ export interface DashboardChannel {closeTab(params: { browser: string; context: string; page: string }): Promise<void>;newTab(params: { browser: string; context: string }): Promise<void>;closeSession(params: { browser: string }): Promise<void>;- deleteSessionData(params: { browser: string }): Promise<void>;setVisible(params: { visible: boolean }): Promise<void>;- reveal(params: { path: string }): Promise<void>;navigate(params: { url: string }): Promise<void>;back(): Promise<void>;diff --git a/packages/dashboard/src/dashboardModel.ts b/packages/dashboard/src/dashboardModel.tsindex 0817f3725d..3896ab71d1 100644--- a/packages/dashboard/src/dashboardModel.ts+++ b/packages/dashboard/src/dashboardModel.ts@@ -92,10 +92,6 @@ export class DashboardModel {void this._client.closeSession({ browser: descriptor.browser.guid });}- deleteSessionData(descriptor: BrowserDescriptor) {- void this._client.deleteSessionData({ browser: descriptor.browser.guid });- }-setVisible(visible: boolean) {void this._client.setVisible({ visible });}diff --git a/packages/playwright-core/src/tools/dashboard/dashboardApp.ts b/packages/playwright-core/src/tools/dashboard/dashboardApp.tsindex 20dfa9fe61..f5b699d0dd 100644--- a/packages/playwright-core/src/tools/dashboard/dashboardApp.ts+++ b/packages/playwright-core/src/tools/dashboard/dashboardApp.ts@@ -28,9 +28,12 @@ import { findChromiumChannelBestEffort, registryDirectory } from '../../server/rimport { minimist } from '../cli-client/minimist';import { saveOutputFile } from '../trace/traceUtils';import { DashboardConnection } from './dashboardController';+import { RegistrySessionProvider } from './registrySessionProvider';+import { IdentitySessionProvider } from './identitySessionProvider';import type * as api from '../../..';import type { AnnotationData } from '@dashboard/dashboardChannel';+import type { SessionProvider } from './sessionProvider';// HMR: build-time flag — `true` in watch builds, `false` in release. esbuild// replaces the identifier via `define`, so the static branch pays zero runtime@@ -42,9 +45,10 @@ type DashboardServer = {reveal: (options: DashboardOptions) => void;triggerAnnotate: () => void;registerAnnotateWaiter: (socket: net.Socket) => void;+ close: () => Promise<void>;};-async function startDashboardServer(options: DashboardOptions): Promise<DashboardServer> {+async function startDashboardServer(provider: SessionProvider, options: DashboardOptions): Promise<DashboardServer> {const httpServer = new HttpServer();const dashboardDir = libPath('vite', 'dashboard');@@ -67,7 +71,7 @@ async function startDashboardServer(options: DashboardOptions): Promise<DashboarhttpServer.createWebSocket(() => {let connection: DashboardConnection;// eslint-disable-next-line prefer-const- connection = new DashboardConnection(() => connections.delete(connection), () => {+ connection = new DashboardConnection(provider, () => connections.delete(connection), () => {if (currentReveal.pageId)connection.revealPage(currentReveal.pageId);else if (currentReveal.sessionName)@@ -131,7 +135,8 @@ async function startDashboardServer(options: DashboardOptions): Promise<Dashboarsocket.on('error', cleanup);};- return { url: httpServer.urlPrefix('human-readable'), reveal, triggerAnnotate, registerAnnotateWaiter };+ const close = () => httpServer.stop();+ return { url: httpServer.urlPrefix('human-readable'), reveal, triggerAnnotate, registerAnnotateWaiter, close };}function attachDashboardStaticServer(httpServer: HttpServer, dashboardDir: string) {@@ -157,13 +162,13 @@ async function attachDashboardDevServer(httpServer: HttpServer) {// HMR endasync function innerOpenDashboardApp(options: DashboardOptions): Promise<{ page: api.Page; server: DashboardServer }> {- const server = await startDashboardServer(options);- const { page } = await launchApp('dashboard');+ const server = await startDashboardServer(new RegistrySessionProvider(), options);+ const { page } = await launchApp('dashboard', { onClose: () => gracefullyProcessExitDoNotHang(0) });await page.goto(server.url);return { page, server };}-async function launchApp(appName: string) {+async function launchApp(appName: string, options?: { onClose?: () => void }) {const channel = findChromiumChannelBestEffort('javascript');const context = await playwright.chromium.launchPersistentContext('', {ignoreDefaultArgs: ['--enable-automation'],@@ -192,9 +197,7 @@ async function launchApp(appName: string) {});}- page.on('close', () => {- gracefullyProcessExitDoNotHang(0);- });+ page.on('close', () => options?.onClose?.());const image = await fs.promises.readFile(libPath('tools', 'dashboard', 'appIcon.png'));// This is local Playwright, so I can access private methods.@@ -299,7 +302,7 @@ export async function openDashboardApp() {console.error('Unhandled promise rejection:', error);});if (options.port !== undefined) {- const { url } = await startDashboardServer(options);+ const { url } = await startDashboardServer(new RegistrySessionProvider(), options);// eslint-disable-next-line no-consoleconsole.log(`Listening on ${url}`);selfDestructOnParentGone();@@ -352,6 +355,22 @@ export async function openDashboardApp() {await statePromise;}+export async function openDashboardForContext(context: api.BrowserContext): Promise<void> {+ const server = await startDashboardServer(new IdentitySessionProvider(context), {});++ let closed = false;+ const close = async () => {+ if (closed)+ return;+ closed = true;+ await server.close();+ };++ const { page } = await launchApp('dashboard', { onClose: () => { void close(); } });+ context.on('close', () => { void close(); });+ await page.goto(server.url);+}+async function runKillClient(): Promise<void> {const socketPath = dashboardSocketPath();await new Promise<void>(resolve => {diff --git a/packages/playwright-core/src/tools/dashboard/dashboardController.ts b/packages/playwright-core/src/tools/dashboard/dashboardController.tsindex 8b6305a166..c52868d4b9 100644--- a/packages/playwright-core/src/tools/dashboard/dashboardController.ts+++ b/packages/playwright-core/src/tools/dashboard/dashboardController.ts@@ -21,98 +21,25 @@ import crypto from 'crypto';import { execFile } from 'child_process';import { Disposable } from '@isomorphic/disposable';import { eventsHelper } from '@utils/eventsHelper';-import { connectToBrowserAcrossVersions } from '../utils/connect';-import { serverRegistry } from '../../serverRegistry';import { createClientInfo } from '../cli-client/registry';+import { SessionProviderEvent } from './sessionProvider';+import type * as api from '../../..';import type { Transport } from '@utils/httpServer';import type { AnnotationData, Tab } from '@dashboard/dashboardChannel';import type { BrowserDescriptor } from '../../serverRegistry';--type BrowserTrackerCallbacks = {- onTabsChanged: () => void;- onContextClosed: (context: api.BrowserContext) => void;-};--class BrowserTracker {- readonly descriptor: BrowserDescriptor;- readonly browser: api.Browser;- private _callbacks: BrowserTrackerCallbacks;- private _contextListeners = new Map<api.BrowserContext, Disposable[]>();- private _browserListeners: Disposable[] = [];-- static async create(descriptor: BrowserDescriptor, callbacks: BrowserTrackerCallbacks): Promise<BrowserTracker | undefined> {- try {- const browser = await connectToBrowserAcrossVersions(descriptor);- const slot = new BrowserTracker(descriptor, browser, callbacks);- for (const context of browser.contexts())- slot._wireContext(context);- slot._browserListeners.push(eventsHelper.addEventListener(browser, 'context', (context: api.BrowserContext) => {- slot._wireContext(context);- }));- return slot;- } catch {- return undefined;- }- }-- private constructor(descriptor: BrowserDescriptor, browser: api.Browser, callbacks: BrowserTrackerCallbacks) {- this.descriptor = descriptor;- this.browser = browser;- this._callbacks = callbacks;- }-- contexts(): api.BrowserContext[] {- return this.browser.contexts();- }-- dispose() {- this._browserListeners.forEach(d => d.dispose());- this._browserListeners = [];- for (const listeners of this._contextListeners.values())- listeners.forEach(d => d.dispose());- this._contextListeners.clear();- }-- private _wireContext(context: api.BrowserContext) {- if (this._contextListeners.has(context))- return;- const onTabsChanged = () => this._callbacks.onTabsChanged();- const listeners: Disposable[] = [- eventsHelper.addEventListener(context, 'page', onTabsChanged),- eventsHelper.addEventListener(context, 'pageload', onTabsChanged),- eventsHelper.addEventListener(context, 'pageclose', onTabsChanged),- eventsHelper.addEventListener(context, 'framenavigated', (frame: api.Frame) => {- if (frame === frame.page().mainFrame())- this._callbacks.onTabsChanged();- }),- eventsHelper.addEventListener(context, 'close', () => {- const ls = this._contextListeners.get(context);- if (ls) {- ls.forEach(d => d.dispose());- this._contextListeners.delete(context);- }- this._callbacks.onContextClosed(context);- this._callbacks.onTabsChanged();- }),- ];- this._contextListeners.set(context, listeners);- this._callbacks.onTabsChanged();- }-}+import type { SessionProvider } from './sessionProvider';export class DashboardConnection implements Transport {sendEvent?: (method: string, params: any) => void;close?: () => void;- private _browsers = new Map<string, BrowserTracker>();+ private _provider: SessionProvider;private _attachedPage: AttachedPage | undefined;private _onclose: () => void;private _onconnected?: () => void;private _onAnnotationSubmit?: (base64Png: string | undefined, ariaSnapshot: string, annotations: AnnotationData[]) => void;- private _serverRegistryDispose?: () => void;- private _pushSessionsScheduled = false;private _pushTabsScheduled = false;private _visible = true;private _pendingReveal: { sessionName?: string; workspaceDir?: string; pageId?: string } | undefined;@@ -121,7 +48,8 @@ export class DashboardConnection implements Transport {_recordingDir: string;_streams = new Map<string, { handle: fs.promises.FileHandle; path: string }>();- constructor(onclose: () => void, onconnected?: () => void, onAnnotationSubmit?: (base64Png: string | undefined, ariaSnapshot: string, annotations: AnnotationData[]) => void) {+ constructor(provider: SessionProvider, onclose: () => void, onconnected?: () => void, onAnnotationSubmit?: (base64Png: string | undefined, ariaSnapshot: string, annotations: AnnotationData[]) => void) {+ this._provider = provider;this._onclose = onclose;this._onconnected = onconnected;this._onAnnotationSubmit = onAnnotationSubmit;@@ -129,20 +57,24 @@ export class DashboardConnection implements Transport {}onconnect() {- this._serverRegistryDispose = serverRegistry.watch();- serverRegistry.on('added', this._pushSessions);- serverRegistry.on('removed', this._pushSessions);- serverRegistry.on('changed', this._pushSessions);- this._pushSessions();+ this._provider.on(SessionProviderEvent.SessionsChanged, () => {+ this._pushSessions();+ void this._tryRevealPending();+ });+ this._provider.on(SessionProviderEvent.TabsChanged, () => this._pushTabs());+ this._provider.on(SessionProviderEvent.ContextClosed, context => {+ if (this._attachedPage?.page.context() === context) {+ this._attachedPage.dispose();+ this._attachedPage = undefined;+ }+ });+ this._provider.on(SessionProviderEvent.AttachRequested, page => { void this._switchAttachedTo(page); });+ this._provider.start();this._onconnected?.();}onclose() {- serverRegistry.off('added', this._pushSessions);- serverRegistry.off('removed', this._pushSessions);- serverRegistry.off('changed', this._pushSessions);- this._serverRegistryDispose?.();- this._serverRegistryDispose = undefined;+ this._provider.dispose();this._attachedPage?.dispose();this._attachedPage = undefined;for (const stream of this._streams.values()) {@@ -152,9 +84,6 @@ export class DashboardConnection implements Transport {.catch(() => {});}this._streams.clear();- for (const tracker of this._browsers.values())- tracker.dispose();- this._browsers.clear();this._onclose();}@@ -173,14 +102,14 @@ export class DashboardConnection implements Transport {}async selectTab(params: { browser: string; context: string; page: string }) {- const page = this._findPage(params);+ const page = this._provider.findPage(params);if (page)await this._switchAttachedTo(page);this._pushTabs();}async newTab(params: { browser: string; context: string }) {- const context = this._findContext(params);+ const context = this._provider.findContext(params);if (!context)return;const page = await context.newPage();@@ -189,23 +118,12 @@ export class DashboardConnection implements Transport {}async closeTab(params: { browser: string; context: string; page: string }) {- const page = this._findPage(params);+ const page = this._provider.findPage(params);await page?.close({ reason: 'Closed in Dashboard' });}async closeSession(params: { browser: string }) {- const descriptor = serverRegistry.readDescriptor(params.browser);- const browser = await connectToBrowserAcrossVersions(descriptor);- try {- await Promise.all(browser.contexts().map(context => context.close()));- await browser.close();- } catch {- // best-effort- }- }-- async deleteSessionData(params: { browser: string }) {- await serverRegistry.deleteUserData(params.browser);+ await this._provider.closeSession(params.browser);}async setVisible(params: { visible: boolean }) {@@ -229,14 +147,14 @@ export class DashboardConnection implements Transport {const pending = this._pendingReveal;if (!pending)return;- const allPages = [...this._browsers.values()].flatMap(s => s.browser.contexts().flatMap(c => c.pages().map(p => ({ slot: s, page: p }))));+ const allPages = this._provider.contextEntries().flatMap(e => e.context.pages().map(page => ({ entry: e, page })));let page: api.Page | undefined;if (pending.pageId !== undefined) {- page = allPages.find(({ page }) => pageId(page) === pending.pageId)?.page;+ page = allPages.find(({ page: p }) => pageId(p) === pending.pageId)?.page;} else if (pending.sessionName !== undefined) {- page = allPages.find(({ slot }) =>- slot.descriptor.title === pending.sessionName- && (pending.workspaceDir === undefined || slot.descriptor.workspaceDir === pending.workspaceDir))?.page;+ page = allPages.find(({ entry }) =>+ entry.descriptor.title === pending.sessionName+ && (pending.workspaceDir === undefined || entry.descriptor.workspaceDir === pending.workspaceDir))?.page;}if (!page)return;@@ -308,6 +226,14 @@ export class DashboardConnection implements Transport {this.sendEvent?.('cancelAnnotate', {});}+ artifactsDirFor(context: api.BrowserContext): string {+ for (const entry of this._provider.contextEntries()) {+ if (entry.context === context)+ return entry.descriptor.browser.launchOptions.artifactsDir ?? this._recordingDir;+ }+ return this._recordingDir;+ }+_pushTabs() {if (this._pushTabsScheduled)return;@@ -323,22 +249,31 @@ export class DashboardConnection implements Transport {});}+ private _pushSessions() {+ void (async () => {+ try {+ const sessions = await this._provider.sessions();+ this.emitSessions(sessions);+ } catch {+ // best-effort+ }+ })();+ }+private async _aggregateTabs(): Promise<Tab[]> {const attachedPage = this._attachedPage?.page;const tasks: Promise<Tab>[] = [];- for (const { browser } of this._browsers.values()) {- for (const context of browser.contexts()) {- for (const page of context.pages()) {- tasks.push((async () => ({- browser: browserId(browser),- context: contextId(context),- page: pageId(page),- title: await page.title().catch(() => ''),- url: page.url(),- selected: page === attachedPage,- faviconUrl: await faviconUrl(page),- }))());- }+ for (const { browser, context } of this._provider.contextEntries()) {+ for (const page of context.pages()) {+ tasks.push((async () => ({+ browser: browserId(browser),+ context: contextId(context),+ page: pageId(page),+ title: await page.title().catch(() => ''),+ url: page.url(),+ selected: page === attachedPage,+ faviconUrl: await faviconUrl(page),+ }))());}}return await Promise.all(tasks);@@ -348,13 +283,7 @@ export class DashboardConnection implements Transport {if (this._attachedPage?.page === page)return;this._attachedPage?.dispose();- const browser = page.context().browser();- const slot = browser ? [...this._browsers.values()].find(s => s.browser === browser) : undefined;- if (!slot) {- this._attachedPage = undefined;- return;- }- const attached = new AttachedPage(this, slot, page);+ const attached = new AttachedPage(this, page);this._attachedPage = attached;try {await attached.init();@@ -378,101 +307,22 @@ export class DashboardConnection implements Transport {void this._switchAttachedTo(next);this._pushTabs();}-- private _pushSessions = () => {- if (this._pushSessionsScheduled)- return;- this._pushSessionsScheduled = true;- queueMicrotask(async () => {- this._pushSessionsScheduled = false;- try {- const byWs = await serverRegistry.list();- const sessions: BrowserDescriptor[] = [];- for (const list of byWs.values()) {- for (const status of list) {- if (status.title.startsWith('--playwright-internal'))- continue;- sessions.push(status);- }- }- await this._reconcile(sessions);- await this._tryRevealPending();- this.emitSessions(sessions);- this._pushTabs();- } catch {- // best-effort- }- });- };-- private async _reconcile(sessions: BrowserDescriptor[]) {- const connectable = new Map<string, BrowserDescriptor>();- for (const status of sessions)- connectable.set(status.browser.guid, status);-- for (const [guid, slot] of this._browsers) {- if (connectable.has(guid))- continue;- if (this._attachedPage && this._attachedPage.page.context().browser() === slot.browser) {- this._attachedPage.dispose();- this._attachedPage = undefined;- }- slot.dispose();- this._browsers.delete(guid);- }-- for (const [guid, status] of connectable) {- if (this._browsers.has(guid))- continue;- const slot = await BrowserTracker.create(status, {- onTabsChanged: () => this._pushTabs(),- onContextClosed: context => {- if (this._attachedPage?.page.context() === context) {- this._attachedPage.dispose();- this._attachedPage = undefined;- }- },- });- if (!slot)- continue;- if (this._browsers.has(guid)) {- slot.dispose();- continue;- }- this._browsers.set(guid, slot);- }- }-- private _findContext(params: { browser: string; context: string }): api.BrowserContext | undefined {- const slot = this._browsers.get(params.browser);- if (!slot)- return undefined;- return slot.contexts().find(c => contextId(c) === params.context);- }-- private _findPage(params: { browser: string; context: string; page: string }): api.Page | undefined {- const context = this._findContext(params);- return context?.pages().find(p => pageId(p) === params.page);- }}class AttachedPage {private _owner: DashboardConnection;- private _slot: BrowserTracker;private _page: api.Page;private _listeners: Disposable[] = [];private _screencastRunning = false;private _recordingPath: string | null = null;private _disposed = false;- constructor(owner: DashboardConnection, slot: BrowserTracker, page: api.Page) {+ constructor(owner: DashboardConnection, page: api.Page) {this._owner = owner;- this._slot = slot;this._page = page;}get page(): api.Page { return this._page; }- private get _descriptor(): BrowserDescriptor { return this._slot.descriptor; }async init() {this._listeners.push(@@ -556,7 +406,7 @@ class AttachedPage {}async startRecording() {- const artifactsDir = this._descriptor.browser.launchOptions.artifactsDir ?? this._owner._recordingDir;+ const artifactsDir = this._owner.artifactsDirFor(this._page.context());this._recordingPath = path.join(artifactsDir, `recording-${Date.now()}.webm`);if (this._screencastRunning)await this._restartScreencast(this._page);diff --git a/packages/playwright-core/src/tools/dashboard/identitySessionProvider.ts b/packages/playwright-core/src/tools/dashboard/identitySessionProvider.tsnew file mode 100644index 0000000000..13d383f835--- /dev/null+++ b/packages/playwright-core/src/tools/dashboard/identitySessionProvider.ts@@ -0,0 +1,127 @@+/**+ * 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 { EventEmitter } from 'events';+import { Disposable } from '@isomorphic/disposable';+import { eventsHelper } from '@utils/eventsHelper';+import { packageJSON, packageRoot } from '../../package';+import { SessionProviderEvent } from './sessionProvider';++import type * as api from '../../../types/types';+import type { BrowserDescriptor, BrowserInfo } from '../../serverRegistry';+import type { ContextEntry, SessionProvider, SessionProviderEventMap } from './sessionProvider';++export class IdentitySessionProvider extends EventEmitter<SessionProviderEventMap> implements SessionProvider {+ private _context: api.BrowserContext;+ private _browser: api.Browser;+ private _descriptor: BrowserDescriptor;+ private _listeners: Disposable[] = [];+ private _closed = false;++ constructor(context: api.BrowserContext) {+ super();+ const browser = context.browser();+ if (!browser)+ throw new Error('SingleContextDashboardProvider requires a context with an attached browser');+ this._context = context;+ this._browser = browser;+ this._descriptor = synthesiseDescriptor(browser);+ }++ start(): void {+ const emitTabsChanged = () => this.emit(SessionProviderEvent.TabsChanged);+ this._listeners.push(+ eventsHelper.addEventListener(this._context, 'page', emitTabsChanged),+ eventsHelper.addEventListener(this._context, 'pageload', emitTabsChanged),+ eventsHelper.addEventListener(this._context, 'pageclose', emitTabsChanged),+ eventsHelper.addEventListener(this._context, 'framenavigated', (frame: api.Frame) => {+ if (frame === frame.page().mainFrame())+ this.emit(SessionProviderEvent.TabsChanged);+ }),+ eventsHelper.addEventListener(this._context, 'close', () => {+ this._closed = true;+ this.emit(SessionProviderEvent.ContextClosed, this._context);+ this.emit(SessionProviderEvent.TabsChanged);+ }),+ );+ this.emit(SessionProviderEvent.SessionsChanged);+ this.emit(SessionProviderEvent.TabsChanged);+ const firstPage = this._context.pages()[0];+ if (firstPage)+ this.emit(SessionProviderEvent.AttachRequested, firstPage);+ }++ dispose(): void {+ this._listeners.forEach(d => d.dispose());+ this._listeners = [];+ this.removeAllListeners();+ }++ async sessions(): Promise<BrowserDescriptor[]> {+ return this._closed ? [] : [this._descriptor];+ }++ contextEntries(): ContextEntry[] {+ if (this._closed)+ return [];+ return [{ browser: this._browser, context: this._context, descriptor: this._descriptor }];+ }++ findContext(params: { browser: string; context: string }): api.BrowserContext | undefined {+ if (this._closed)+ return undefined;+ if (params.browser !== this._descriptor.browser.guid)+ return undefined;+ if (contextId(this._context) !== params.context)+ return undefined;+ return this._context;+ }++ findPage(params: { browser: string; context: string; page: string }): api.Page | undefined {+ const context = this.findContext(params);+ return context?.pages().find(p => pageId(p) === params.page);+ }++ async closeSession(): Promise<void> {+ // No-op: lifecycle of the user-provided context is managed by the caller.+ }+}++function synthesiseDescriptor(browser: api.Browser): BrowserDescriptor {+ const browserName = browser.browserType().name() as BrowserInfo['browserName'];+ const browserInfo: BrowserInfo = {+ // eslint-disable-next-line no-restricted-syntax -- _guid is very conservative.+ guid: (browser as any)._guid,+ browserName,+ launchOptions: {},+ };+ return {+ title: 'Playwright',+ playwrightVersion: packageJSON.version,+ playwrightLib: packageRoot,+ browser: browserInfo,+ };+}++function pageId(p: api.Page): string {+ // eslint-disable-next-line no-restricted-syntax -- _guid is very conservative.+ return (p as any)._guid;+}++function contextId(c: api.BrowserContext): string {+ // eslint-disable-next-line no-restricted-syntax -- _guid is very conservative.+ return (c as any)._guid;+}diff --git a/packages/playwright-core/src/tools/dashboard/registrySessionProvider.ts b/packages/playwright-core/src/tools/dashboard/registrySessionProvider.tsnew file mode 100644index 0000000000..3f3fa3216d--- /dev/null+++ b/packages/playwright-core/src/tools/dashboard/registrySessionProvider.ts@@ -0,0 +1,226 @@+/**+ * 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 { EventEmitter } from 'events';+import { Disposable } from '@isomorphic/disposable';+import { eventsHelper } from '@utils/eventsHelper';+import { connectToBrowserAcrossVersions } from '../utils/connect';+import { serverRegistry } from '../../serverRegistry';+import { SessionProviderEvent } from './sessionProvider';++import type * as api from '../../../types/types';+import type { BrowserDescriptor } from '../../serverRegistry';+import type { ContextEntry, SessionProvider, SessionProviderEventMap } from './sessionProvider';++type BrowserTrackerCallbacks = {+ onTabsChanged: () => void;+ onContextClosed: (context: api.BrowserContext) => void;+};++class BrowserTracker {+ readonly descriptor: BrowserDescriptor;+ readonly browser: api.Browser;+ private _callbacks: BrowserTrackerCallbacks;+ private _contextListeners = new Map<api.BrowserContext, Disposable[]>();+ private _browserListeners: Disposable[] = [];++ static async create(descriptor: BrowserDescriptor, callbacks: BrowserTrackerCallbacks): Promise<BrowserTracker | undefined> {+ try {+ const browser = await connectToBrowserAcrossVersions(descriptor);+ const slot = new BrowserTracker(descriptor, browser, callbacks);+ for (const context of browser.contexts())+ slot._wireContext(context);+ slot._browserListeners.push(eventsHelper.addEventListener(browser, 'context', (context: api.BrowserContext) => {+ slot._wireContext(context);+ }));+ return slot;+ } catch {+ return undefined;+ }+ }++ private constructor(descriptor: BrowserDescriptor, browser: api.Browser, callbacks: BrowserTrackerCallbacks) {+ this.descriptor = descriptor;+ this.browser = browser;+ this._callbacks = callbacks;+ }++ contexts(): api.BrowserContext[] {+ return this.browser.contexts();+ }++ dispose() {+ this._browserListeners.forEach(d => d.dispose());+ this._browserListeners = [];+ for (const listeners of this._contextListeners.values())+ listeners.forEach(d => d.dispose());+ this._contextListeners.clear();+ }++ private _wireContext(context: api.BrowserContext) {+ if (this._contextListeners.has(context))+ return;+ const onTabsChanged = () => this._callbacks.onTabsChanged();+ const listeners: Disposable[] = [+ eventsHelper.addEventListener(context, 'page', onTabsChanged),+ eventsHelper.addEventListener(context, 'pageload', onTabsChanged),+ eventsHelper.addEventListener(context, 'pageclose', onTabsChanged),+ eventsHelper.addEventListener(context, 'framenavigated', (frame: api.Frame) => {+ if (frame === frame.page().mainFrame())+ this._callbacks.onTabsChanged();+ }),+ eventsHelper.addEventListener(context, 'close', () => {+ const ls = this._contextListeners.get(context);+ if (ls) {+ ls.forEach(d => d.dispose());+ this._contextListeners.delete(context);+ }+ this._callbacks.onContextClosed(context);+ this._callbacks.onTabsChanged();+ }),+ ];+ this._contextListeners.set(context, listeners);+ this._callbacks.onTabsChanged();+ }+}++export class RegistrySessionProvider extends EventEmitter<SessionProviderEventMap> implements SessionProvider {+ private _trackers = new Map<string, BrowserTracker>();+ private _serverRegistryDispose?: () => void;+ private _pushSessionsScheduled = false;++ start(): void {+ this._serverRegistryDispose = serverRegistry.watch();+ serverRegistry.on('added', this._scheduleSessions);+ serverRegistry.on('removed', this._scheduleSessions);+ serverRegistry.on('changed', this._scheduleSessions);+ this._scheduleSessions();+ }++ dispose(): void {+ serverRegistry.off('added', this._scheduleSessions);+ serverRegistry.off('removed', this._scheduleSessions);+ serverRegistry.off('changed', this._scheduleSessions);+ this._serverRegistryDispose?.();+ this._serverRegistryDispose = undefined;+ for (const tracker of this._trackers.values())+ tracker.dispose();+ this._trackers.clear();+ this.removeAllListeners();+ }++ async sessions(): Promise<BrowserDescriptor[]> {+ const byWs = await serverRegistry.list();+ const sessions: BrowserDescriptor[] = [];+ for (const list of byWs.values()) {+ for (const status of list) {+ if (status.title.startsWith('--playwright-internal'))+ continue;+ sessions.push(status);+ }+ }+ return sessions;+ }++ contextEntries(): ContextEntry[] {+ const entries: ContextEntry[] = [];+ for (const tracker of this._trackers.values()) {+ for (const context of tracker.contexts())+ entries.push({ browser: tracker.browser, context, descriptor: tracker.descriptor });+ }+ return entries;+ }++ findContext(params: { browser: string; context: string }): api.BrowserContext | undefined {+ const tracker = this._trackers.get(params.browser);+ if (!tracker)+ return undefined;+ return tracker.contexts().find(c => contextId(c) === params.context);+ }++ findPage(params: { browser: string; context: string; page: string }): api.Page | undefined {+ const context = this.findContext(params);+ return context?.pages().find(p => pageId(p) === params.page);+ }++ async closeSession(browserId: string): Promise<void> {+ const descriptor = serverRegistry.readDescriptor(browserId);+ const browser = await connectToBrowserAcrossVersions(descriptor);+ try {+ await Promise.all(browser.contexts().map(context => context.close()));+ await browser.close();+ } catch {+ // best-effort+ }+ }++ private _scheduleSessions = () => {+ if (this._pushSessionsScheduled)+ return;+ this._pushSessionsScheduled = true;+ queueMicrotask(async () => {+ this._pushSessionsScheduled = false;+ try {+ const sessions = await this.sessions();+ await this._reconcile(sessions);+ this.emit(SessionProviderEvent.SessionsChanged);+ this.emit(SessionProviderEvent.TabsChanged);+ } catch {+ // best-effort+ }+ });+ };++ private async _reconcile(sessions: BrowserDescriptor[]) {+ const connectable = new Map<string, BrowserDescriptor>();+ for (const status of sessions)+ connectable.set(status.browser.guid, status);++ for (const [guid, tracker] of this._trackers) {+ if (connectable.has(guid))+ continue;+ tracker.dispose();+ this._trackers.delete(guid);+ }++ for (const [guid, status] of connectable) {+ if (this._trackers.has(guid))+ continue;+ const tracker = await BrowserTracker.create(status, {+ onTabsChanged: () => this.emit(SessionProviderEvent.TabsChanged),+ onContextClosed: context => this.emit(SessionProviderEvent.ContextClosed, context),+ });+ if (!tracker)+ continue;+ if (this._trackers.has(guid)) {+ tracker.dispose();+ continue;+ }+ this._trackers.set(guid, tracker);+ }+ }++}++function pageId(p: api.Page): string {+ // eslint-disable-next-line no-restricted-syntax -- _guid is very conservative.+ return (p as any)._guid;+}++function contextId(c: api.BrowserContext): string {+ // eslint-disable-next-line no-restricted-syntax -- _guid is very conservative.+ return (c as any)._guid;+}diff --git a/packages/playwright-core/src/tools/dashboard/sessionProvider.ts b/packages/playwright-core/src/tools/dashboard/sessionProvider.tsnew file mode 100644index 0000000000..e05804f19c--- /dev/null+++ b/packages/playwright-core/src/tools/dashboard/sessionProvider.ts@@ -0,0 +1,50 @@+/**+ * 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 type { EventEmitter } from 'events';++import type * as api from '../../../types/types';+import type { BrowserDescriptor } from '../../serverRegistry';++export type ContextEntry = {+ browser: api.Browser;+ context: api.BrowserContext;+ descriptor: BrowserDescriptor;+};++export const SessionProviderEvent = {+ SessionsChanged: 'sessionsChanged',+ TabsChanged: 'tabsChanged',+ ContextClosed: 'contextClosed',+ AttachRequested: 'attachRequested',+} as const;++export type SessionProviderEventMap = {+ [SessionProviderEvent.SessionsChanged]: [];+ [SessionProviderEvent.TabsChanged]: [];+ [SessionProviderEvent.ContextClosed]: [context: api.BrowserContext];+ [SessionProviderEvent.AttachRequested]: [page: api.Page];+};++export interface SessionProvider extends EventEmitter<SessionProviderEventMap> {+ start(): void;+ sessions(): Promise<BrowserDescriptor[]>;+ closeSession(browserId: string): Promise<void>;+ contextEntries(): ContextEntry[];+ findContext(params: { browser: string; context: string }): api.BrowserContext | undefined;+ findPage(params: { browser: string; context: string; page: string }): api.Page | undefined;+ dispose(): void;+}diff --git a/packages/playwright-core/src/tools/index.ts b/packages/playwright-core/src/tools/index.tsindex 000ef8036d..69e3cfe559 100644--- a/packages/playwright-core/src/tools/index.ts+++ b/packages/playwright-core/src/tools/index.ts@@ -30,7 +30,7 @@ export { decorateMCPCommand } from './mcp/program';export { program as cliProgram } from './cli-client/program';export { generateHelp, generateHelpJSON } from './cli-daemon/helpGenerator';export { decorateProgram as decorateCliDaemonProgram } from './cli-daemon/program';-export { openDashboardApp } from './dashboard/dashboardApp';+export { openDashboardApp, openDashboardForContext } from './dashboard/dashboardApp';export type { ContextConfig } from './backend/context';export type { CallToolRequest, CallToolResult, Tool } from './backend/tool';