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(extension): introduce BrowserModel with explicit handshake (#40411)
Yury Semikhatsky16a3c2f68ffe
diff --git a/packages/extension/src/background.ts b/packages/extension/src/background.tsindex e131b449ba..0afc41b87c 100644--- a/packages/extension/src/background.ts+++ b/packages/extension/src/background.ts@@ -19,15 +19,16 @@ import { PendingConnections } from './pendingConnection';import { ConnectedTabGroup, cleanupStalePlaywrightGroups, isNonDebuggableUrl } from './connectedTabGroup';type PageMessage = {- type: 'connectToMCPRelay';+ type: 'connectionRequested';mcpRelayUrl: string;protocolVersion: number;} | {type: 'getTabs';} | {type: 'connectToTab';- tabId?: number;- windowId?: number;+ // Picked in the connect page; absent when the user clicked plain "Allow"+ // without selecting a tab.+ tab?: chrome.tabs.Tab;clientName?: string;} | {type: 'getConnectionStatus';@@ -54,7 +55,7 @@ class PlaywrightExtension {// Promise-based message handling is not supported in Chrome: https://issues.chromium.org/issues/40753031private _onMessage(message: PageMessage, sender: chrome.runtime.MessageSender, sendResponse: (response: any) => void) {switch (message.type) {- case 'connectToMCPRelay':+ case 'connectionRequested':this._pendingConnections.create(sender.tab!.id!, message.mcpRelayUrl, message.protocolVersion).then(() => sendResponse({ success: true }),(error: any) => sendResponse({ success: false, error: error.message }));@@ -64,13 +65,17 @@ class PlaywrightExtension {tabs => sendResponse({ success: true, tabs, currentTabId: sender.tab?.id }),(error: any) => sendResponse({ success: false, error: error.message }));return true;- case 'connectToTab':- const tabId = message.tabId || sender.tab?.id!;- const windowId = message.windowId || sender.tab?.windowId!;- this._connectTab(sender.tab!.id!, tabId, windowId, message.clientName).then(+ case 'connectToTab': {+ // Plain "Allow" (no specific pick) falls back to the connect page itself+ // so `ConnectedTabGroup` always has a concrete tab to start from. Both+ // sender.tab and UI-supplied tabs come from chrome.tabs.query / runtime+ // message sender, where `id` is always defined.+ const selectedTab = (message.tab ?? sender.tab!) as chrome.tabs.Tab & { id: number };+ this._connectTab(sender.tab!.id!, selectedTab, message.clientName).then(() => sendResponse({ success: true }),(error: any) => sendResponse({ success: false, error: error.message }));return true; // Return true to indicate that the response will be sent asynchronously+ }case 'getConnectionStatus':sendResponse({connectedTabIds: this._activeGroup?.connectedTabIds() ?? [],@@ -93,16 +98,16 @@ class PlaywrightExtension {}}- private async _connectTab(selectorTabId: number, tabId: number, windowId: number, clientName: string | undefined): Promise<void> {+ private async _connectTab(selectorTabId: number, tab: chrome.tabs.Tab & { id: number }, clientName: string | undefined): Promise<void> {try {await this._cleanupPromise;this._disconnect('Another connection is requested');- const pending = this._pendingConnections.take(selectorTabId);- if (!pending)+ const connection = await this._pendingConnections.take(selectorTabId);+ if (!connection)throw new Error('Pending client connection closed');- const group = new ConnectedTabGroup(pending.connection, tabId);+ const group = new ConnectedTabGroup(connection, tab);group.onclose = () => {if (this._activeGroup === group) {this._activeGroup = undefined;@@ -113,14 +118,14 @@ class PlaywrightExtension {this._activeClientName = clientName;await Promise.all([- chrome.tabs.update(tabId, { active: true }),- chrome.windows.update(windowId, { focused: true }),- ]);+ chrome.tabs.update(tab.id, { active: true }),+ chrome.windows.update(tab.windowId, { focused: true }),+ ]).catch(() => {});- if (tabId !== selectorTabId)+ if (tab.id !== selectorTabId)await chrome.tabs.remove(selectorTabId).catch(() => {});} catch (error: any) {- debugLog(`Failed to connect tab ${tabId}:`, error.message);+ debugLog(`Failed to connect tab ${tab.id}:`, error.message);throw error;}}diff --git a/packages/extension/src/connectedTabGroup.ts b/packages/extension/src/connectedTabGroup.tsindex 90ed6973de..dd08c72668 100644--- a/packages/extension/src/connectedTabGroup.ts+++ b/packages/extension/src/connectedTabGroup.ts@@ -55,11 +55,8 @@ export class ConnectedTabGroup {onclose?: () => void;- constructor(connection: RelayConnection, selectedTabId: number) {+ constructor(connection: RelayConnection, selectedTab: chrome.tabs.Tab) {this._connection = connection;- // Resolves the pending extension.selectTab command from cdpRelay; the relay- // will attach the selected tab and _onTabAttached pulls it into the group.- this._connection.setSelectedTab(selectedTabId);this._connection.onclose = () => this._onConnectionClose();this._connection.ontabattached = (tabId: number) => this._onTabAttached(tabId);this._connection.ontabdetached = (tabId: number) => this._onTabDetached(tabId);@@ -67,6 +64,12 @@ export class ConnectedTabGroup {this._onTabRemovedListener = this._onTabRemoved.bind(this);chrome.tabs.onUpdated.addListener(this._onTabUpdatedListener);chrome.tabs.onRemoved.addListener(this._onTabRemovedListener);+ // Seed the relay with the user-selected tab, then close out the initial+ // handshake. The relay holds Playwright-side CDP traffic until+ // `didInitialize` arrives, so it sees a fully populated tab model by the+ // time it handles `Target.setAutoAttach`.+ this._connection.attachTab(selectedTab);+ this._connection.didInitialize();}connectedTabIds(): number[] {diff --git a/packages/extension/src/pendingConnection.ts b/packages/extension/src/pendingConnection.tsindex 000e350f03..d8aec26d75 100644--- a/packages/extension/src/pendingConnection.ts+++ b/packages/extension/src/pendingConnection.ts@@ -16,85 +16,107 @@import { RelayConnection, debugLog } from './relayConnection';-// A RelayConnection opened by the connect page that has not yet been promoted-// to an active ConnectedTabGroup (the user hasn't picked a tab). Owns the-// RelayConnection until `connection` is handed off.-export class PendingConnection {- readonly connection: RelayConnection;- readonly selectorTabId: number;+interface PendingEntry {+ connect(): Promise<RelayConnection>;+ close(reason: string): void;+}++class EagerPending implements PendingEntry {+ private _connection: RelayConnection;onclose?: () => void;- private constructor(connection: RelayConnection, selectorTabId: number) {- this.connection = connection;- this.selectorTabId = selectorTabId;- this.connection.onclose = () => this.onclose?.();+ static async create(mcpRelayUrl: string, protocolVersion: number): Promise<EagerPending> {+ const connection = await openRelayConnection(mcpRelayUrl, protocolVersion);+ return new EagerPending(connection);}- static async connect(selectorTabId: number, mcpRelayUrl: string, protocolVersion: number): Promise<PendingConnection> {- try {- const socket = new WebSocket(mcpRelayUrl);- await new Promise<void>((resolve, reject) => {- socket.onopen = () => resolve();- socket.onerror = () => reject(new Error('WebSocket error'));- setTimeout(() => reject(new Error('Connection timeout')), 5000);- });- const connection = new RelayConnection(socket, protocolVersion);- return new PendingConnection(connection, selectorTabId);- } catch (error: any) {- const message = `Failed to connect to MCP relay: ${error.message}`;- debugLog(message);- throw new Error(message);- }+ private constructor(connection: RelayConnection) {+ this._connection = connection;+ this._connection.onclose = () => this.onclose?.();+ }++ async connect(): Promise<RelayConnection> {+ return this._connection;}close(reason: string): void {- this.connection.close(reason);+ this._connection.close(reason);+ }+}++class DeferredPending implements PendingEntry {+ constructor(private _mcpRelayUrl: string, private _protocolVersion: number) {}++ async connect(): Promise<RelayConnection> {+ return openRelayConnection(this._mcpRelayUrl, this._protocolVersion);+ }++ close(_reason: string): void {}}-// Collection of PendingConnections keyed by their selector (connect page) tab.-// Owns the tab-removal listener that closes pendings whose selector tab went-// away, and notifies the connect page when the relay drops its socket.export class PendingConnections {- private _map = new Map<number, PendingConnection>();+ private _map = new Map<number, PendingEntry>();constructor() {chrome.tabs.onRemoved.addListener(this._onTabRemoved.bind(this));}+ // v1 opens the relay WS eagerly — the daemon expects a prompt connection.+ // v2 records only the descriptor; the WS opens lazily in `take` once the+ // user clicks Allow.async create(selectorTabId: number, mcpRelayUrl: string, protocolVersion: number): Promise<void> {- const pending = await PendingConnection.connect(selectorTabId, mcpRelayUrl, protocolVersion);- pending.onclose = () => {- const existed = this._map.delete(selectorTabId);- if (existed)- chrome.tabs.sendMessage(selectorTabId, { type: 'pendingConnectionClosed' }).catch(() => {});+ if (protocolVersion !== 1) {+ this._map.set(selectorTabId, new DeferredPending(mcpRelayUrl, protocolVersion));+ return;+ }+ const entry = await EagerPending.create(mcpRelayUrl, protocolVersion);+ entry.onclose = () => {+ if (this._map.get(selectorTabId) !== entry)+ return;+ this._map.delete(selectorTabId);+ chrome.tabs.sendMessage(selectorTabId, { type: 'pendingConnectionClosed' }).catch(() => {});};- this._map.set(selectorTabId, pending);+ this._map.set(selectorTabId, entry);}reject(selectorTabId: number): void {- const pending = this._map.get(selectorTabId);- if (!pending)+ const entry = this._map.get(selectorTabId);+ if (!entry)return;this._map.delete(selectorTabId);- pending.close('Rejected by user');+ entry.close('Rejected by user');}- // Hands off ownership of the pending connection. The caller is expected to- // immediately transfer its RelayConnection to an active ConnectedTabGroup, which- // replaces `onclose` so the pending's handler no longer fires.- take(selectorTabId: number): PendingConnection | undefined {- const pending = this._map.get(selectorTabId);- if (pending)- this._map.delete(selectorTabId);- return pending;+ async take(selectorTabId: number): Promise<RelayConnection | undefined> {+ const entry = this._map.get(selectorTabId);+ if (!entry)+ return undefined;+ this._map.delete(selectorTabId);+ return entry.connect();}private _onTabRemoved(tabId: number): void {- const pending = this._map.get(tabId);- if (!pending)+ const entry = this._map.get(tabId);+ if (!entry)return;this._map.delete(tabId);- pending.close('Browser tab closed');+ entry.close('Browser tab closed');+ }+}++async function openRelayConnection(mcpRelayUrl: string, protocolVersion: number): Promise<RelayConnection> {+ try {+ const socket = new WebSocket(mcpRelayUrl);+ await new Promise<void>((resolve, reject) => {+ socket.onopen = () => resolve();+ socket.onerror = () => reject(new Error('WebSocket error'));+ setTimeout(() => reject(new Error('Connection timeout')), 5000);+ });+ return new RelayConnection(socket, protocolVersion);+ } catch (error: any) {+ const message = `Failed to connect to MCP relay: ${error.message}`;+ debugLog(message);+ throw new Error(message);}}diff --git a/packages/extension/src/protocolHandlers.ts b/packages/extension/src/protocolHandlers.tsindex b68c30f966..f7f7173ad4 100644--- a/packages/extension/src/protocolHandlers.ts+++ b/packages/extension/src/protocolHandlers.ts@@ -22,7 +22,6 @@ export type ProtocolCommand = {// The narrow surface of RelayConnection that protocol handlers use.export interface RelayContext {- readonly selectedTab: Promise<number>;readonly attachedTabs: ReadonlySet<number>;sendMessage(message: any): void;// Records that a tab's debugger is now attached. Fires ontabattached on the@@ -38,31 +37,35 @@ export interface ProtocolHandler {// Forwards an already-filtered chrome.* event (concerning a currently-attached// tab) to the relay. Shape is protocol-specific.forwardChromeEvent(fullMethod: string, args: any[]): void;- // The UI added a tab to the Playwright group. Handler tells the relay the- // tab is now available; the relay attaches via the usual command path.+ // The UI added a tab to the Playwright group, whether as the initial pick+ // from the connect page or from a later drag-in. Handler tells the relay+ // the tab is now available; the relay attaches via the usual command path.onUserAttachRequest(tab: chrome.tabs.Tab): void;// The UI removed a tab. RelayConnection has already detached the debugger// and called notifyTabDetached; the handler only sends the wire-level// detach notification (if the protocol has one).onUserDetachRequest(tabId: number): void;+ // Signals that the initial set of `onUserAttachRequest` calls is complete.+ // For v2 this sends `extension.initialized` so the relay can unblock CDP+ // traffic from Playwright; v1 has no handshake and ignores it.+ didInitialize(): void;}// ─── Protocol v1 (legacy single-tab) ───────────────────────────────────────export class ProtocolV1Handler implements ProtocolHandler {private _context: RelayContext;+ private _selectedTabPromise: Promise<number>;+ private _selectedTabResolve!: (tabId: number) => void;constructor(context: RelayContext) {this._context = context;+ this._selectedTabPromise = new Promise(resolve => this._selectedTabResolve = resolve);}async handleCommand(message: ProtocolCommand): Promise<any> {- if (message.method === 'extension.selectTab') {- const tabId = await this._context.selectedTab;- return { tabId };- }if (message.method === 'attachToTab') {- const tabId = await this._context.selectedTab;+ const tabId = await this._selectedTabPromise;const debuggee: chrome.debugger.Debuggee = { tabId };await chrome.debugger.attach(debuggee, '1.3');this._context.notifyTabAttached(tabId);@@ -94,14 +97,23 @@ export class ProtocolV1Handler implements ProtocolHandler {});}- onUserAttachRequest(_tab: chrome.tabs.Tab): void {- // v1 is single-tab by design; dragging extra tabs into the group is a no-op.+ onUserAttachRequest(tab: chrome.tabs.Tab): void {+ // v1 is single-tab by design: the first attach call determines the tab+ // used by the pending `attachToTab` command. Later attach requests are+ // silently ignored (Promise.resolve is a no-op once resolved).+ if (tab.id !== undefined)+ this._selectedTabResolve(tab.id);}onUserDetachRequest(_tabId: number): void {// v1 has no wire-level detach notification; when the last tab detaches the// socket closes and the relay notices.}++ didInitialize(): void {+ // v1 has no initial-tab-list handshake. `_selectedTabPromise` is resolved+ // by the first `onUserAttachRequest`, which already unblocks `attachToTab`.+ }}// ─── Protocol v2 (reflective chrome.*) ─────────────────────────────────────@@ -124,10 +136,6 @@ export class ProtocolV2Handler implements ProtocolHandler {}async handleCommand(message: ProtocolCommand): Promise<any> {- if (message.method === 'extension.selectTab') {- const tabId = await this._context.selectedTab;- return { tabId };- }if (ALLOWED_CHROME_COMMANDS.has(message.method)) {const args = (message.params ?? []) as any[];const result = await invokeChromeMethod(message.method, args);@@ -152,6 +160,13 @@ export class ProtocolV2Handler implements ProtocolHandler {this._context.sendMessage({ method: 'chrome.tabs.onCreated', params: [tab] });}+ didInitialize(): void {+ // Signals the end of the initial-tab handshake. The relay holds CDP+ // traffic from Playwright until it sees this event, so that+ // `Target.setAutoAttach` is answered from a populated tab model.+ this._context.sendMessage({ method: 'extension.initialized', params: [] });+ }+onUserDetachRequest(tabId: number): void {// chrome.debugger.detach does not fire onDetach for the caller, so we// synthesize one so the relay notices the tab is gone.diff --git a/packages/extension/src/relayConnection.ts b/packages/extension/src/relayConnection.tsindex ec04faa3fd..72160b09fe 100644--- a/packages/extension/src/relayConnection.ts+++ b/packages/extension/src/relayConnection.ts@@ -51,8 +51,6 @@ export class RelayConnection {// Once we've attached at least one tab, detaching the last one closes the connection.private _hasEverAttached = false;private _eventListeners: Array<{ remove: () => void }> = [];- private _selectedTabPromise: Promise<number>;- private _selectedTabResolve!: (tabId: number) => void;private _closed = false;onclose?: () => void;@@ -65,9 +63,7 @@ export class RelayConnection {constructor(ws: WebSocket, protocolVersion: number) {this._ws = ws;- this._selectedTabPromise = new Promise(resolve => this._selectedTabResolve = resolve);const context: RelayContext = {- selectedTab: this._selectedTabPromise,attachedTabs: this._attachedTabs,sendMessage: msg => this._sendMessage(msg),notifyTabAttached: tabId => this._notifyTabAttached(tabId),@@ -81,9 +77,11 @@ export class RelayConnection {this._ws.onclose = () => this._onClose();}- // Resolves the pending extension.selectTab call from cdpRelay.- setSelectedTab(tabId: number): void {- this._selectedTabResolve(tabId);+ // Signals the end of the initial-tab handshake — call after the initial+ // round of `attachTab` invocations. For v2 this sends `extension.initialized`+ // so the relay can unblock Playwright CDP traffic; v1 has no handshake.+ didInitialize(): void {+ this._handler.didInitialize();}close(message: string): void {diff --git a/packages/extension/src/ui/connect.tsx b/packages/extension/src/ui/connect.tsxindex fd449a5259..4b50034ee0 100644--- a/packages/extension/src/ui/connect.tsx+++ b/packages/extension/src/ui/connect.tsx@@ -19,8 +19,6 @@ import { createRoot } from 'react-dom/client';import { Button, TabItem } from './tabItem';import { AuthTokenSection, getOrCreateAuthToken } from './authToken';-import type { TabInfo } from './tabItem';-type Status =| { type: 'connecting'; message: string }| { type: 'connected'; message: string }@@ -30,12 +28,11 @@ type Status =const SUPPORTED_PROTOCOL_VERSION = 2;const ConnectApp: React.FC = () => {- const [tabs, setTabs] = useState<TabInfo[]>([]);+ const [tabs, setTabs] = useState<chrome.tabs.Tab[]>([]);const [status, setStatus] = useState<Status | null>(null);const [showButtons, setShowButtons] = useState(true);const [showTabList, setShowTabList] = useState(true);const [clientInfo, setClientInfo] = useState('unknown');- const [mcpRelayUrl, setMcpRelayUrl] = useState('');useEffect(() => {const runAsync = async () => {@@ -58,8 +55,6 @@ const ConnectApp: React.FC = () => {return;}- setMcpRelayUrl(relayUrl);-try {const client = JSON.parse(params.get('client') || '{}');const info = `${client.name || 'unknown'}`;@@ -87,11 +82,14 @@ const ConnectApp: React.FC = () => {});return;}+ // The background decides per protocolVersion: v1 opens the relay WS+ // immediately (the daemon expects a prompt connection); v2 just records+ // the descriptor and defers the WS until the user clicks Allow.+ await connectionRequested(relayUrl, requestedVersion);const expectedToken = getOrCreateAuthToken();const token = params.get('token');if (token === expectedToken) {- await connectToMCPRelay(relayUrl, requestedVersion);await handleConnectToTab();return;}@@ -100,8 +98,6 @@ const ConnectApp: React.FC = () => {return;}- await connectToMCPRelay(relayUrl, requestedVersion);-// If this is a browser_navigate command, hide the tab list and show simple allow/rejectif (params.get('newTab') === 'true')setShowTabList(false);@@ -120,8 +116,8 @@ const ConnectApp: React.FC = () => {chrome.runtime.sendMessage({ type: 'rejectConnection' }).catch(() => {});}, []);- const connectToMCPRelay = useCallback(async (mcpRelayUrl: string, protocolVersion: number) => {- const response = await chrome.runtime.sendMessage({ type: 'connectToMCPRelay', mcpRelayUrl, protocolVersion });+ const connectionRequested = useCallback(async (mcpRelayUrl: string, protocolVersion: number) => {+ const response = await chrome.runtime.sendMessage({ type: 'connectionRequested', mcpRelayUrl, protocolVersion });if (!response.success)handleReject(response.error);}, [handleReject]);@@ -134,15 +130,14 @@ const ConnectApp: React.FC = () => {setStatus({ type: 'error', message: 'Failed to load tabs: ' + response.error });}, []);- const handleConnectToTab = useCallback(async (tab?: TabInfo) => {+ const handleConnectToTab = useCallback(async (tab?: chrome.tabs.Tab) => {setShowButtons(false);setShowTabList(false);try {const response = await chrome.runtime.sendMessage({type: 'connectToTab',- tabId: tab?.id,- windowId: tab?.windowId,+ tab,clientName: clientInfo,});@@ -160,7 +155,7 @@ const ConnectApp: React.FC = () => {message: `"${clientInfo}" failed to connect: ${e}`});}- }, [clientInfo, mcpRelayUrl]);+ }, [clientInfo]);useEffect(() => {const listener = (message: any) => {diff --git a/packages/extension/src/ui/status.tsx b/packages/extension/src/ui/status.tsxindex 6559e12ae7..4869b0b94c 100644--- a/packages/extension/src/ui/status.tsx+++ b/packages/extension/src/ui/status.tsx@@ -17,12 +17,10 @@import React, { useState, useEffect } from 'react';import { createRoot } from 'react-dom/client';import { Button, TabItem } from './tabItem';--import type { TabInfo } from './tabItem';import { AuthTokenSection } from './authToken';const StatusApp: React.FC = () => {- const [connectedTabs, setConnectedTabs] = useState<TabInfo[]>([]);+ const [connectedTabs, setConnectedTabs] = useState<chrome.tabs.Tab[]>([]);const [clientName, setClientName] = useState<string | undefined>(undefined);useEffect(() => {@@ -31,21 +29,7 @@ const StatusApp: React.FC = () => {const loadStatus = async () => {const { connectedTabIds, clientName } = await chrome.runtime.sendMessage({ type: 'getConnectionStatus' });- const tabs: TabInfo[] = [];- for (const tabId of (connectedTabIds as number[] ?? [])) {- try {- const tab = await chrome.tabs.get(tabId);- tabs.push({- id: tab.id!,- windowId: tab.windowId!,- title: tab.title!,- url: tab.url!,- favIconUrl: tab.favIconUrl- });- } catch {- // Tab may have been closed.- }- }+ const tabs = await Promise.all((connectedTabIds as number[] ?? []).map(tabId => chrome.tabs.get(tabId)));setConnectedTabs(tabs);setClientName(clientName);};@@ -81,7 +65,7 @@ const StatusApp: React.FC = () => {<TabItemkey={tab.id}tab={tab}- onClick={() => openTab(tab.id)}+ onClick={() => openTab(tab.id!)}/>))}</div>diff --git a/packages/extension/src/ui/tabItem.tsx b/packages/extension/src/ui/tabItem.tsxindex 148374292f..afb5bde32e 100644--- a/packages/extension/src/ui/tabItem.tsx+++ b/packages/extension/src/ui/tabItem.tsx@@ -16,14 +16,6 @@import React from 'react';-export interface TabInfo {- id: number;- windowId: number;- title: string;- url: string;- favIconUrl?: string;-}-export const Button: React.FC<{ variant: 'primary' | 'default' | 'reject'; onClick: () => void; children: React.ReactNode }> = ({variant,onClick,@@ -38,7 +30,7 @@ export const Button: React.FC<{ variant: 'primary' | 'default' | 'reject'; onCliexport interface TabItemProps {- tab: TabInfo;+ tab: chrome.tabs.Tab;onClick?: () => void;button?: React.ReactNode;}diff --git a/packages/playwright-core/src/tools/mcp/browserModel.ts b/packages/playwright-core/src/tools/mcp/browserModel.tsnew file mode 100644index 0000000000..695bc7fa34--- /dev/null+++ b/packages/playwright-core/src/tools/mcp/browserModel.ts@@ -0,0 +1,221 @@+/**+ * 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.+ */++/**+ * Browser-side tab model used by the v2 relay. Owns the mapping between+ * chrome tab ids and CDP session ids, and is the single place that+ * translates between the chrome.* dialect spoken by the extension and the+ * CDP dialect spoken by Playwright.+ *+ * Lifecycle:+ * 1. Extension connects and, after the user allows, pushes a+ * `chrome.tabs.onCreated` for each initial tab followed by+ * `extension.initialized`. The model records these as "known" tabs+ * without attaching yet.+ * 2. The relay observes `ready()` resolving and unpauses the Playwright ws.+ * 3. Playwright sends `Target.setAutoAttach` → model calls+ * `enableAutoAttach()`, which attaches to every known tab and emits+ * `Target.attachedToTarget` for each.+ * 4. Subsequent tab creates / debugger detaches / removes flow through the+ * same model inputs and are translated into CDP events on the fly.+ */++import { logUnhandledError } from './log';++import type { CDPMessage, SendCommand, SendToCDPClient } from './cdpRelayHandler';+import type { DebuggerSession, Debuggee, Tab } from './protocol';++type TabSession = {+ tabId: number;+ sessionId: string;+ targetInfo: any;+ // Child CDP sessionIds (workers, oopifs, ...) belonging to this tab,+ // tracked via Target.attachedToTarget / Target.detachedFromTarget events.+ childSessions: Set<string>;+};++export class BrowserModel {+ private _sendToExtension: SendCommand;+ // Set only while a Playwright CDP connection is attached (see+ // `connectOverCDP`). Before that, any attempt to emit to Playwright is a+ // no-op — the model is observation-only during the extension handshake.+ private _sendToCDPClient: SendToCDPClient | null = null;+ // Tabs observed via chrome.tabs.onCreated, whether or not the debugger is attached yet.+ private _knownTabs = new Map<number, Tab>();+ // Subset of _knownTabs we've attached the debugger to and assigned a sessionId.+ private _tabSessions = new Map<number, TabSession>();+ private _autoAttach = false;+ private _nextSessionId = 1;++ constructor(sendToExtension: SendCommand) {+ this._sendToExtension = sendToExtension;+ }++ // Wires the model's CDP output sink. Called by the handler once the+ // extension handshake is done and a Playwright CDP client is ready to+ // receive events. Before this call the model is observation-only —+ // `Target.attachedToTarget` etc. would be answered into a black hole.+ connectOverCDP(sendToCDPClient: SendToCDPClient): void {+ this._sendToCDPClient = sendToCDPClient;+ }++ private _emit(message: CDPMessage): void {+ this._sendToCDPClient?.(message);+ }++ // ─── Extension → model inputs ─────────────────────────────────────────++ onTabCreated(tab: Tab): void {+ if (tab.id === undefined)+ return;+ this._knownTabs.set(tab.id, tab);+ if (this._autoAttach)+ void this._attachTab(tab.id).catch(logUnhandledError);+ }++ onTabRemoved(tabId: number): void {+ this._knownTabs.delete(tabId);+ this._detachTab(tabId);+ }++ onDebuggerEvent(source: DebuggerSession, method: string, params: any): void {+ if (source.tabId === undefined)+ return;+ const tabSession = this._tabSessions.get(source.tabId);+ if (!tabSession)+ return;+ // Track child CDP sessions so we can route subsequent commands for+ // them to the correct tab. Target.attachedToTarget introduces a new+ // sessionId belonging to the same tab; Target.detachedFromTarget+ // releases it.+ const childSessionId = (params as { sessionId?: string } | undefined)?.sessionId;+ if (method === 'Target.attachedToTarget' && childSessionId)+ tabSession.childSessions.add(childSessionId);+ else if (method === 'Target.detachedFromTarget' && childSessionId)+ tabSession.childSessions.delete(childSessionId);+ // Top-level CDP events for the tab use the tab's relay sessionId.+ // Child CDP sessions (workers, oopifs) keep their own sessionId.+ const sessionId = source.sessionId || tabSession.sessionId;+ this._emit({ sessionId, method, params });+ }++ onDebuggerDetach(source: Debuggee): void {+ if (source.tabId !== undefined)+ this._detachTab(source.tabId);+ }++ // ─── Playwright → model commands ──────────────────────────────────────++ // Turn auto-attach on and attach to every tab we already know about.+ // Called in response to Playwright's `Target.setAutoAttach` on the root session.+ async enableAutoAttach(): Promise<void> {+ this._autoAttach = true;+ const tabIds = [...this._knownTabs.keys()];+ await Promise.all(tabIds.map(tabId => this._attachTab(tabId).catch(logUnhandledError)));+ }++ async createTarget(url: string | undefined): Promise<{ targetId: string | undefined }> {+ const tab = await this._sendToExtension('chrome.tabs.create', [{ url }]);+ if (tab?.id === undefined)+ throw new Error('Failed to create tab');+ this._knownTabs.set(tab.id, tab);+ const tabSession = await this._attachTab(tab.id);+ return { targetId: tabSession.targetInfo?.targetId };+ }++ async closeTarget(targetId: string | undefined): Promise<{ success: boolean }> {+ const tabSession = targetId ? this._findTabSession(s => s.targetInfo?.targetId === targetId) : undefined;+ if (!tabSession)+ return { success: false };+ await this._sendToExtension('chrome.tabs.remove', [tabSession.tabId]);+ return { success: true };+ }++ getTargetInfo(sessionId: string | undefined): any {+ if (!sessionId)+ return undefined;+ return this._findTabSession(s => s.sessionId === sessionId)?.targetInfo;+ }++ // Forward a CDP command from Playwright to the tab its sessionId resolves to.+ async sendCommand(sessionId: string, method: string, params: any): Promise<any> {+ // Two cases:+ // 1. sessionId is a relay-level tab session (pw-tab-N) → strip and route by tabId.+ // 2. sessionId is a child CDP session (worker, oopif) → route to its owning tab,+ // keep the sessionId so the extension forwards it to chrome.debugger.+ let tabSession = this._findTabSession(s => s.sessionId === sessionId);+ let cdpSessionId: string | undefined;+ if (!tabSession) {+ tabSession = this._findTabSession(s => s.childSessions.has(sessionId));+ cdpSessionId = sessionId;+ }+ if (!tabSession)+ throw new Error(`No tab found for sessionId: ${sessionId}`);+ return await this._sendToExtension('chrome.debugger.sendCommand', [+ { tabId: tabSession.tabId, sessionId: cdpSessionId },+ method,+ params,+ ]);+ }++ // ─── Internals ────────────────────────────────────────────────────────++ private async _attachTab(tabId: number): Promise<TabSession> {+ const existing = this._tabSessions.get(tabId);+ if (existing)+ return existing;+ await this._sendToExtension('chrome.debugger.attach', [{ tabId }, '1.3']);+ const result = await this._sendToExtension('chrome.debugger.sendCommand', [+ { tabId },+ 'Target.getTargetInfo',+ ]);+ const targetInfo = result?.targetInfo;+ const sessionId = `pw-tab-${this._nextSessionId++}`;+ const tabSession: TabSession = { tabId, sessionId, targetInfo, childSessions: new Set() };+ this._tabSessions.set(tabId, tabSession);+ this._emit({+ method: 'Target.attachedToTarget',+ params: {+ sessionId,+ targetInfo: { ...targetInfo, attached: true },+ waitingForDebugger: false,+ },+ });+ return tabSession;+ }++ private _detachTab(tabId: number): void {+ const tabSession = this._tabSessions.get(tabId);+ if (!tabSession)+ return;+ this._tabSessions.delete(tabId);+ this._emit({+ method: 'Target.detachedFromTarget',+ params: {+ sessionId: tabSession.sessionId,+ targetId: tabSession.targetInfo?.targetId,+ },+ });+ }++ private _findTabSession(predicate: (session: TabSession) => boolean): TabSession | undefined {+ for (const session of this._tabSessions.values()) {+ if (predicate(session))+ return session;+ }+ return undefined;+ }+}diff --git a/packages/playwright-core/src/tools/mcp/cdpRelay.ts b/packages/playwright-core/src/tools/mcp/cdpRelay.tsindex eeb568ab33..738163825f 100644--- a/packages/playwright-core/src/tools/mcp/cdpRelay.ts+++ b/packages/playwright-core/src/tools/mcp/cdpRelay.ts@@ -85,12 +85,11 @@ export class CDPRelayServer {throw new Error('Extension not connected');return this._extensionConnection.send(method as keyof ExtensionCommand, params);};- const sendToPlaywright = (message: CDPResponse) => this._sendToPlaywright(message);if (this._protocolVersion >= 2)- this._handler = new ExtensionProtocolV2(sendCommand, sendToPlaywright);+ this._handler = new ExtensionProtocolV2(sendCommand);else- this._handler = new ExtensionProtocolV1(sendCommand, sendToPlaywright);+ this._handler = new ExtensionProtocolV1(sendCommand);const uuid = crypto.randomUUID();this._cdpPath = `/cdp/${uuid}`;@@ -114,6 +113,7 @@ export class CDPRelayServer {this._openConnectPageInBrowser(clientName);debugLogger('Waiting for incoming extension connection');await this._extensionConnectionPromise;+ await this._handler.ready();debugLogger('Extension connection established');}@@ -193,10 +193,10 @@ export class CDPRelayServer {return;}this._cdpConnection = ws;+ this._handler.connectOverCDP(msg => this._sendToCDPClient(msg));ws.on('message', async data => {try {- const message = JSON.parse(data.toString());- await this._handlePlaywrightMessage(message);+ await this._handlePlaywrightMessage(JSON.parse(data.toString()));} catch (error: any) {debugLogger(`Error while handling Playwright message\n${data.toString()}\n`, error);}@@ -230,6 +230,7 @@ export class CDPRelayServer {this._extensionConnection = new ExtensionConnection(ws);this._extensionConnection.onclose = reason => {debugLogger('Extension WebSocket closed:', reason);+ this._handler.onExtensionDisconnect(reason);this._closeCDPConnection(`Extension disconnected: ${reason}`);};this._extensionConnection.onmessage = (method, params) => this._handler.handleExtensionEvent(method, params);@@ -241,10 +242,10 @@ export class CDPRelayServer {const { id, sessionId, method, params } = message;try {const result = await this._handleCDPCommand(method, params, sessionId);- this._sendToPlaywright({ id, sessionId, result });+ this._sendToCDPClient({ id, sessionId, result });} catch (e) {debugLogger('Error in the extension:', e);- this._sendToPlaywright({+ this._sendToCDPClient({id,sessionId,error: { message: (e as Error).message }@@ -271,7 +272,7 @@ export class CDPRelayServer {return await this._handler.forwardToExtension(method, params, sessionId);}- private _sendToPlaywright(message: CDPResponse): void {+ private _sendToCDPClient(message: CDPResponse): void {debugLogger('→ Playwright:', `${message.method ?? `response(id=${message.id})`}`);this._cdpConnection?.send(JSON.stringify(message));}diff --git a/packages/playwright-core/src/tools/mcp/cdpRelayHandler.ts b/packages/playwright-core/src/tools/mcp/cdpRelayHandler.tsindex fa70ed8a43..f6310e65d9 100644--- a/packages/playwright-core/src/tools/mcp/cdpRelayHandler.ts+++ b/packages/playwright-core/src/tools/mcp/cdpRelayHandler.ts@@ -24,7 +24,7 @@ export type CDPMessage = {};export type SendCommand = (method: string, params: any) => Promise<any>;-export type SendToPlaywright = (message: CDPMessage) => void;+export type SendToCDPClient = (message: CDPMessage) => void;export interface ExtensionProtocolHandler {// Handle an event from the extension. Sends CDP events to Playwright as needed.@@ -34,4 +34,15 @@ export interface ExtensionProtocolHandler {handleCDPCommand(method: string, params: any, sessionId: string | undefined): Promise<{ result: any } | undefined>;// Forward a CDP command to the extension.forwardToExtension(method: string, params: any, sessionId: string | undefined): Promise<any>;+ // Resolves once the extension has completed its initial handshake and the+ // relay may start processing CDP commands from Playwright.+ ready(): Promise<void>;+ // Wires up the sink through which the handler emits CDP events back to+ // Playwright. Called once `ready()` has resolved and the Playwright ws is+ // about to start draining — before this call the handler is a silent sink.+ connectOverCDP(sendToCDPClient: SendToCDPClient): void;+ // Called when the extension WebSocket closes. Handlers should reject any+ // pending `ready()` promise so a blocked `establishExtensionConnection`+ // bails out instead of hanging forever.+ onExtensionDisconnect(reason: string): void;}diff --git a/packages/playwright-core/src/tools/mcp/cdpRelayV1.ts b/packages/playwright-core/src/tools/mcp/cdpRelayV1.tsindex c953639916..0926aba871 100644--- a/packages/playwright-core/src/tools/mcp/cdpRelayV1.ts+++ b/packages/playwright-core/src/tools/mcp/cdpRelayV1.ts@@ -19,18 +19,21 @@* attachment and forwards CDP events/commands through a thin wrapper.*/-import type { ExtensionProtocolHandler, SendCommand, SendToPlaywright } from './cdpRelayHandler';+import type { ExtensionProtocolHandler, SendCommand, SendToCDPClient } from './cdpRelayHandler';import type { ExtensionEventsV1 } from './protocol';export class ExtensionProtocolV1 implements ExtensionProtocolHandler {private _sendCommand: SendCommand;- private _sendToPlaywright: SendToPlaywright;+ private _sendToCDPClient: SendToCDPClient | null = null;private _connectedTabInfo: { targetInfo: any; sessionId: string } | undefined;private _nextSessionId = 1;- constructor(sendCommand: SendCommand, sendToPlaywright: SendToPlaywright) {+ constructor(sendCommand: SendCommand) {this._sendCommand = sendCommand;- this._sendToPlaywright = sendToPlaywright;+ }++ connectOverCDP(sendToCDPClient: SendToCDPClient): void {+ this._sendToCDPClient = sendToCDPClient;}handleExtensionEvent(method: string, params: any): void {@@ -38,7 +41,7 @@ export class ExtensionProtocolV1 implements ExtensionProtocolHandler {case 'forwardCDPEvent': {const p = params as ExtensionEventsV1['forwardCDPEvent']['params'];const sessionId = p.sessionId || this._connectedTabInfo?.sessionId;- this._sendToPlaywright({+ this._sendToCDPClient?.({sessionId,method: p.method,params: p.params,@@ -58,7 +61,7 @@ export class ExtensionProtocolV1 implements ExtensionProtocolHandler {targetInfo,sessionId: `pw-tab-${this._nextSessionId++}`,};- this._sendToPlaywright({+ this._sendToCDPClient?.({method: 'Target.attachedToTarget',params: {sessionId: this._connectedTabInfo.sessionId,@@ -87,4 +90,13 @@ export class ExtensionProtocolV1 implements ExtensionProtocolHandler {sessionId = undefined;return await this._sendCommand('forwardCDPCommand', { sessionId, method, params });}++ ready(): Promise<void> {+ // v1 has no initial handshake; messages from Playwright are processed immediately.+ return Promise.resolve();+ }++ onExtensionDisconnect(_reason: string): void {+ // v1 has no pending ready() promise to reject.+ }}diff --git a/packages/playwright-core/src/tools/mcp/cdpRelayV2.ts b/packages/playwright-core/src/tools/mcp/cdpRelayV2.tsindex eb69160a23..90ed24a60f 100644--- a/packages/playwright-core/src/tools/mcp/cdpRelayV2.ts+++ b/packages/playwright-core/src/tools/mcp/cdpRelayV2.ts@@ -15,83 +15,73 @@*//**- * Protocol v2: multi-tab interface. The relay owns CDP session management —- * it asks the extension for the user's tab pick (extension.selectTab), then- * attaches the debugger and dispatches Target.attachedToTarget events to- * Playwright. Additional tabs are created either by Playwright- * (Target.createTarget → chrome.tabs.create) or by the controlled tabs- * themselves (chrome.tabs.onCreated event from the extension).+ * Protocol v2: thin adapter between the extension wire protocol and the+ * CDP wire protocol. All tab-model state lives in `BrowserModel`; this file+ * only demultiplexes incoming extension events and dispatches CDP commands+ * to the model.+ *+ * Handshake: the extension pushes `chrome.tabs.onCreated` for each initial+ * tab, then `extension.initialized`. The relay does not process CDP+ * commands until `ready()` resolves, so `Target.setAutoAttach` is always+ * answered from a populated model.*/+import { ManualPromise } from '@isomorphic/manualPromise';+import { logUnhandledError } from './log';+import { BrowserModel } from './browserModel';-import type { ExtensionProtocolHandler, SendCommand, SendToPlaywright } from './cdpRelayHandler';+import type { ExtensionProtocolHandler, SendCommand, SendToCDPClient } from './cdpRelayHandler';import type { ExtensionEventsV2 } from './protocol';-type TabSession = {- tabId: number;- sessionId: string;- targetInfo: any;- // Child CDP sessionIds (workers, oopifs, ...) belonging to this tab,- // tracked via Target.attachedToTarget / Target.detachedFromTarget events.- childSessions: Set<string>;-};-export class ExtensionProtocolV2 implements ExtensionProtocolHandler {- private _sendCommand: SendCommand;- private _sendToPlaywright: SendToPlaywright;- private _tabSessions = new Map<number, TabSession>();- private _nextSessionId = 1;+ private _model: BrowserModel;+ // Resolved by `extension.initialized`. Purely a handshake signal for the+ // relay — the model itself is oblivious to this phase.+ private _ready = new ManualPromise<void>();++ constructor(sendCommand: SendCommand) {+ this._model = new BrowserModel(sendCommand);+ void this._ready.catch(logUnhandledError);+ }++ ready(): Promise<void> {+ return this._ready;+ }++ connectOverCDP(sendToCDPClient: SendToCDPClient): void {+ this._model.connectOverCDP(sendToCDPClient);+ }- constructor(sendCommand: SendCommand, sendToPlaywright: SendToPlaywright) {- this._sendCommand = sendCommand;- this._sendToPlaywright = sendToPlaywright;+ onExtensionDisconnect(reason: string): void {+ if (!this._ready.isDone())+ this._ready.reject(new Error(`Extension disconnected before initialization: ${reason}`));}handleExtensionEvent(method: string, params: any): void {switch (method) {case 'chrome.debugger.onEvent': {const [source, cdpMethod, cdpParams] = params as ExtensionEventsV2['chrome.debugger.onEvent']['params'];- if (source.tabId === undefined)- return;- const tabSession = this._tabSessions.get(source.tabId);- if (!tabSession)- return;- // Track child CDP sessions so we can route subsequent commands for- // them to the correct tab. Target.attachedToTarget introduces a new- // sessionId belonging to the same tab; Target.detachedFromTarget- // releases it.- const childSessionId = (cdpParams as { sessionId?: string } | undefined)?.sessionId;- if (cdpMethod === 'Target.attachedToTarget' && childSessionId)- tabSession.childSessions.add(childSessionId);- else if (cdpMethod === 'Target.detachedFromTarget' && childSessionId)- tabSession.childSessions.delete(childSessionId);- // Top-level CDP events for the tab use the tab's relay sessionId.- // Child CDP sessions (workers, oopifs) keep their own sessionId.- const sessionId = source.sessionId || tabSession.sessionId;- this._sendToPlaywright({- sessionId,- method: cdpMethod,- params: cdpParams,- });+ this._model.onDebuggerEvent(source, cdpMethod, cdpParams);break;}case 'chrome.debugger.onDetach': {const [source] = params as ExtensionEventsV2['chrome.debugger.onDetach']['params'];- if (source.tabId !== undefined)- this._detachTab(source.tabId);+ this._model.onDebuggerDetach(source);break;}case 'chrome.tabs.onCreated': {const [tab] = params as ExtensionEventsV2['chrome.tabs.onCreated']['params'];- // A controlled tab opened a popup. Attach to it.- if (tab.id !== undefined)- void this._attachTab(tab.id).catch(logUnhandledError);+ this._model.onTabCreated(tab);break;}case 'chrome.tabs.onRemoved': {const [tabId] = params as ExtensionEventsV2['chrome.tabs.onRemoved']['params'];- this._detachTab(tabId);+ this._model.onTabRemoved(tabId);+ break;+ }+ case 'extension.initialized': {+ this._ready.resolve();break;}}@@ -102,31 +92,15 @@ export class ExtensionProtocolV2 implements ExtensionProtocolHandler {case 'Target.setAutoAttach': {if (sessionId)return undefined;- // Ask the user to pick the initial tab via the connect UI, then attach.- const { tabId } = await this._sendCommand('extension.selectTab', []);- await this._attachTab(tabId);+ await this._model.enableAutoAttach();return { result: {} };}- case 'Target.createTarget': {- const tab = await this._sendCommand('chrome.tabs.create', [{ url: params?.url }]);- if (tab?.id === undefined)- throw new Error('Failed to create tab');- const tabSession = await this._attachTab(tab.id);- return { result: { targetId: tabSession.targetInfo?.targetId } };- }- case 'Target.closeTarget': {- const targetId = params?.targetId;- const tabSession = targetId ? this._findTabSession(s => s.targetInfo?.targetId === targetId) : undefined;- if (!tabSession)- return { result: { success: false } };- await this._sendCommand('chrome.tabs.remove', [tabSession.tabId]);- return { result: { success: true } };- }- case 'Target.getTargetInfo': {- if (!sessionId)- return { result: undefined };- return { result: this._findTabSession(s => s.sessionId === sessionId)?.targetInfo };- }+ case 'Target.createTarget':+ return { result: await this._model.createTarget(params?.url) };+ case 'Target.closeTarget':+ return { result: await this._model.closeTarget(params?.targetId) };+ case 'Target.getTargetInfo':+ return { result: this._model.getTargetInfo(sessionId) };}return undefined;}@@ -134,68 +108,6 @@ export class ExtensionProtocolV2 implements ExtensionProtocolHandler {async forwardToExtension(method: string, params: any, sessionId: string | undefined): Promise<any> {if (!sessionId)throw new Error(`Unsupported command without sessionId: ${method}`);- // Resolve the sessionId to a tab session. Two cases:- // 1. sessionId is a relay-level tab session (pw-tab-N) → strip and route by tabId.- // 2. sessionId is a child CDP session (worker, oopif) → route to its owning tab,- // keep the sessionId so the extension forwards it to chrome.debugger.- let tabSession = this._findTabSession(s => s.sessionId === sessionId);- let cdpSessionId: string | undefined;- if (!tabSession) {- tabSession = this._findTabSession(s => s.childSessions.has(sessionId));- cdpSessionId = sessionId;- }- if (!tabSession)- throw new Error(`No tab found for sessionId: ${sessionId}`);- return await this._sendCommand('chrome.debugger.sendCommand', [- { tabId: tabSession.tabId, sessionId: cdpSessionId },- method,- params,- ]);- }-- private async _attachTab(tabId: number): Promise<TabSession> {- const existing = this._tabSessions.get(tabId);- if (existing)- return existing;- await this._sendCommand('chrome.debugger.attach', [{ tabId }, '1.3']);- const result = await this._sendCommand('chrome.debugger.sendCommand', [- { tabId },- 'Target.getTargetInfo',- ]);- const targetInfo = result?.targetInfo;- const sessionId = `pw-tab-${this._nextSessionId++}`;- const tabSession: TabSession = { tabId, sessionId, targetInfo, childSessions: new Set() };- this._tabSessions.set(tabId, tabSession);- this._sendToPlaywright({- method: 'Target.attachedToTarget',- params: {- sessionId,- targetInfo: { ...targetInfo, attached: true },- waitingForDebugger: false,- },- });- return tabSession;- }-- private _detachTab(tabId: number): void {- const tabSession = this._tabSessions.get(tabId);- if (!tabSession)- return;- this._tabSessions.delete(tabId);- this._sendToPlaywright({- method: 'Target.detachedFromTarget',- params: {- sessionId: tabSession.sessionId,- targetId: tabSession.targetInfo?.targetId,- },- });- }-- private _findTabSession(predicate: (session: TabSession) => boolean): TabSession | undefined {- for (const session of this._tabSessions.values()) {- if (predicate(session))- return session;- }- return undefined;+ return await this._model.sendCommand(sessionId, method, params);}}diff --git a/packages/playwright-core/src/tools/mcp/protocol.ts b/packages/playwright-core/src/tools/mcp/protocol.tsindex 9cf074f3e8..8a79958c4d 100644--- a/packages/playwright-core/src/tools/mcp/protocol.ts+++ b/packages/playwright-core/src/tools/mcp/protocol.ts@@ -75,11 +75,6 @@ export type ExtensionCommandV2 = {params: [tabIds: number | number[]];result: void;};- // Playwright-specific: ask the user to pick a tab via the connect UI.- 'extension.selectTab': {- params: [];- result: { tabId: number };- };};// Protocol v2 events mirror chrome.<api>.<event>.addListener callback signatures.@@ -100,6 +95,13 @@ export type ExtensionEventsV2 = {'chrome.tabs.onRemoved': {params: [tabId: number, removeInfo: TabRemoveInfo];};+ // Playwright-specific: signals end of the initial tab handshake. The relay+ // withholds Playwright-side CDP messages until this event arrives, so that+ // `Target.setAutoAttach` can be answered from a fully-populated tab model+ // rather than blocking on a user pick.+ 'extension.initialized': {+ params: [];+ };};// Protocol v1: legacy single-tab interface.diff --git a/tests/extension/cli.spec.ts b/tests/extension/cli.spec.tsindex e6814ac94e..2eb7a08209 100644--- a/tests/extension/cli.spec.ts+++ b/tests/extension/cli.spec.ts@@ -58,13 +58,18 @@ async function expectDaemonExited(cliPromise: Promise<CliResult>): Promise<void>await expect.poll(() => isAlive(pid)).toBe(false);}-test('daemon exits when user rejects the extension connection', async ({ startAttach }) => {+test('daemon exits when user rejects the extension connection', async ({ startAttach, protocolVersion }) => {+ // v2 defers opening the relay WS until the user clicks Allow, so a Reject+ // without a prior connection leaves the daemon waiting — intentionally.+ test.skip(protocolVersion === 2, 'v2 defers the relay connection until Allow');const { confirmationPage, cliPromise } = await startAttach();await confirmationPage.getByRole('button', { name: 'Reject' }).click();await expectDaemonExited(cliPromise);});-test('daemon exits when user closes the connect tab', async ({ startAttach }) => {+test('daemon exits when user closes the connect tab', async ({ startAttach, protocolVersion }) => {+ // Same as above — closing the tab before Allow never opens a relay WS in v2.+ test.skip(protocolVersion === 2, 'v2 defers the relay connection until Allow');const { confirmationPage, cliPromise } = await startAttach();// Wait for the page to fully load and the connection to the relay to be established before closing it.await expect(confirmationPage.getByRole('button', { name: 'Reject' })).toBeVisible();diff --git a/tests/extension/extension.spec.ts b/tests/extension/extension.spec.tsindex 48faa26fb7..0c2430b4d2 100644--- a/tests/extension/extension.spec.ts+++ b/tests/extension/extension.spec.ts@@ -304,7 +304,10 @@ test(`bypass connection dialog with token`, async ({ browserWithExtension, start});});-test(`pending connection closed when client disconnects`, async ({ startExtensionClient, server }) => {+test(`pending connection closed when client disconnects`, async ({ startExtensionClient, server, protocolVersion }) => {+ // v2 does not open a WS to the relay before the user clicks Allow, so there+ // is no pending connection to tear down when the client dies pre-Allow.+ test.skip(protocolVersion === 2, 'v2 defers the relay connection until Allow');const { browserContext, client } = await startExtensionClient();const confirmationPagePromise = browserContext.waitForEvent('page', page => {