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): rehaul connect page and fix tab group management (#40321)
Yury Semikhatsky1112f6e3752b
diff --git a/packages/extension/src/background.ts b/packages/extension/src/background.tsindex 901734b9e1..27dc4b262d 100644--- a/packages/extension/src/background.ts+++ b/packages/extension/src/background.ts@@ -37,7 +37,9 @@ class TabShareExtension {private _activeConnection: RelayConnection | undefined;private _connectedTabIds: Set<number> = new Set();private _groupId: number | null = null;+ private _groupQueue: Promise<void> = Promise.resolve();private _pendingTabSelection = new Map<number, RelayConnection>();+ private _selectorTabId: number | undefined;constructor() {chrome.tabs.onRemoved.addListener(this._onTabRemoved.bind(this));@@ -94,13 +96,10 @@ class TabShareExtension {connection.onclose = () => {debugLog('Pending connection closed');const existed = this._pendingTabSelection.delete(selectorTabId);- if (existed) {+ if (existed)chrome.tabs.sendMessage(selectorTabId, { type: 'pendingConnectionClosed' }).catch(() => {});- chrome.tabs.ungroup(selectorTabId).catch(() => {});- }};this._pendingTabSelection.set(selectorTabId, connection);- await this._addTabToGroup(selectorTabId);debugLog(`Connected to MCP relay`);} catch (error: any) {const message = `Failed to connect to MCP relay: ${error.message}`;@@ -129,15 +128,20 @@ class TabShareExtension {this._activeConnection.onclose = () => {debugLog('MCP connection closed');this._activeConnection = undefined;+ this._selectorTabId = undefined;const allTabIds = [...this._connectedTabIds];this._connectedTabIds.clear();allTabIds.map(id => this._updateBadge(id, { text: '' }));- chrome.tabs.ungroup(allTabIds).catch(() => {});+ if (allTabIds.length)+ chrome.tabs.ungroup(allTabIds).catch(() => {});};this._activeConnection.ontabattached = (newTabId: number) => {this._connectedTabIds.add(newTabId);void this._updateBadge(newTabId, { text: '✓', color: '#4CAF50', title: 'Connected to Playwright client' });- void this._addTabToGroup(newTabId);+ void this._addTabToGroup(newTabId).then(() => {+ if (this._selectorTabId)+ return this._addTabToGroup(this._selectorTabId);+ });};this._activeConnection.ontabdetached = (removedTabId: number) => {this._connectedTabIds.delete(removedTabId);@@ -149,6 +153,7 @@ class TabShareExtension {chrome.tabs.update(tabId, { active: true }),chrome.windows.update(windowId, { focused: true }),]);+ this._selectorTabId = selectorTabId;debugLog(`Connected to Playwright client`);} catch (error: any) {this._connectedTabIds.clear();@@ -183,14 +188,9 @@ class TabShareExtension {private _onTabUpdated(tabId: number, changeInfo: chrome.tabs.TabChangeInfo, tab: chrome.tabs.Tab) {if (this._connectedTabIds.has(tabId))void this._updateBadge(tabId, { text: '✓', color: '#4CAF50', title: 'Connected to MCP client' });-- if (!this._activeConnection || changeInfo.groupId === undefined)+ if (!this._activeConnection || this._groupId === null || changeInfo.groupId === undefined)return;- // Ignore the extension's own UI tabs (connect/status pages) — those get added- // to the group for visual grouping, not because they should be controlled.- if (tab.url?.startsWith(chrome.runtime.getURL('')))- return;- const inOurGroup = this._groupId !== null && changeInfo.groupId === this._groupId;+ const inOurGroup = changeInfo.groupId === this._groupId;const isConnected = this._connectedTabIds.has(tabId);if (inOurGroup && !isConnected)void this._activeConnection.attachTab(tabId);@@ -203,24 +203,43 @@ class TabShareExtension {return tabs.filter(tab => tab.url && !['chrome:', 'edge:', 'devtools:'].some(scheme => tab.url!.startsWith(scheme)));}- private async _addTabToGroup(tabId: number): Promise<void> {+ private _addTabToGroup(tabId: number): Promise<void> {+ const result = this._groupQueue.then(() => this._addTabToGroupImpl(tabId));+ this._groupQueue = result.catch(() => {});+ return result;+ }++ private async _addTabToGroupImpl(tabId: number, retries = 3): Promise<void> {try {if (this._groupId !== null) {try {await chrome.tabs.group({ groupId: this._groupId, tabIds: [tabId] });await chrome.tabGroups.update(this._groupId, { color: 'green', title: 'Playwright' });return;- } catch {- this._groupId = null;+ } catch (e: any) {+ if (this._isDragError(e) && retries > 0)+ return this._retryAfterDelay(tabId, retries);+ debugLog('Error adding tab to group:', e);}}this._groupId = await chrome.tabs.group({ tabIds: [tabId] });await chrome.tabGroups.update(this._groupId, { color: 'green', title: 'Playwright' });} catch (error: any) {- debugLog('Error adding tab to group:', error);+ if (this._isDragError(error) && retries > 0)+ return this._retryAfterDelay(tabId, retries);+ debugLog('Error creating tab group:', error);}}+ private _isDragError(e: any): boolean {+ return e?.message?.includes('user may be dragging a tab');+ }++ private async _retryAfterDelay(tabId: number, retries: number): Promise<void> {+ await new Promise(resolve => setTimeout(resolve, 200));+ return this._addTabToGroupImpl(tabId, retries - 1);+ }+private async _onActionClicked(): Promise<void> {await chrome.tabs.create({url: chrome.runtime.getURL('status.html'),diff --git a/packages/extension/src/ui/connect.css b/packages/extension/src/ui/connect.cssindex dd0081a28f..e173fac5a0 100644--- a/packages/extension/src/ui/connect.css+++ b/packages/extension/src/ui/connect.css@@ -41,7 +41,6 @@ body {align-items: center;justify-content: space-between;margin-bottom: 16px;- padding-right: 12px;}.status-banner {@@ -74,7 +73,7 @@ body {/* Warning banner */.warning-banner {- margin: 0 12px 16px 12px;+ margin: 0 0 16px 0;padding: 12px;background-color: #fff8e1;border: 1px solid #f0c674;@@ -90,10 +89,9 @@ body {/* Buttons */.button-container {- margin-bottom: 16px;display: flex;justify-content: flex-end;- padding-right: 12px;+ gap: 8px;}.button {@@ -107,7 +105,6 @@ body {align-items: center;justify-content: center;text-decoration: none;- margin-right: 8px;min-width: 90px;}@@ -155,7 +152,7 @@ body {.tab-item {display: flex;align-items: center;- padding: 12px;+ padding: 12px 0 12px 12px;margin-bottom: 8px;background-color: #ffffff;cursor: pointer;@@ -224,7 +221,7 @@ body {/* Auth token section */.auth-token-section {margin: 16px 0;- padding: 16px;+ padding: 12px;background-color: #f6f8fa;border-radius: 6px;}diff --git a/packages/extension/src/ui/connect.tsx b/packages/extension/src/ui/connect.tsxindex beecffe26a..8c248328a8 100644--- a/packages/extension/src/ui/connect.tsx+++ b/packages/extension/src/ui/connect.tsx@@ -36,7 +36,6 @@ const ConnectApp: React.FC = () => {const [showTabList, setShowTabList] = useState(true);const [clientInfo, setClientInfo] = useState('unknown');const [mcpRelayUrl, setMcpRelayUrl] = useState('');- const [newTab, setNewTab] = useState<boolean>(false);useEffect(() => {const runAsync = async () => {@@ -104,12 +103,10 @@ const ConnectApp: React.FC = () => {await connectToMCPRelay(relayUrl, requestedVersion);// If this is a browser_navigate command, hide the tab list and show simple allow/reject- if (params.get('newTab') === 'true') {- setNewTab(true);+ if (params.get('newTab') === 'true')setShowTabList(false);- } else {+ elseawait loadTabs();- }};void runAsync();}, []);@@ -183,20 +180,12 @@ const ConnectApp: React.FC = () => {<StatusBanner status={status} />{showButtons && (<div className='button-container'>- {newTab ? (- <>- <Button variant='primary' onClick={() => handleConnectToTab()}>- Allow- </Button>- <Button variant='reject' onClick={() => handleReject('Connection rejected. This tab can be closed.')}>- Reject- </Button>- </>- ) : (- <Button variant='reject' onClick={() => handleReject('Connection rejected. This tab can be closed.')}>- Reject- </Button>- )}+ <Button variant='primary' onClick={() => handleConnectToTab()}>+ Allow+ </Button>+ <Button variant='reject' onClick={() => handleReject('Connection rejected. This tab can be closed.')}>+ Reject+ </Button></div>)}</div>@@ -218,7 +207,8 @@ const ConnectApp: React.FC = () => {{showTabList && (<div><div className='tab-section-title'>- Select the default tab for this connection:+ You can drag tabs into the Playwright group later to make them accessible to the client.+ Optionally, select a tab to allow and immediately switch to it:</div><div>{tabs.map(tab => (@@ -227,7 +217,7 @@ const ConnectApp: React.FC = () => {tab={tab}button={<Button variant='primary' onClick={() => handleConnectToTab(tab)}>- Connect+ Allow & select</Button>}/>diff --git a/tests/extension/cli.spec.ts b/tests/extension/cli.spec.tsindex a103776135..a90a540812 100644--- a/tests/extension/cli.spec.ts+++ b/tests/extension/cli.spec.ts@@ -39,7 +39,7 @@ test('attach <url> --extension', async ({ browserWithExtension, cli, server }, tconst confirmationPage = await confirmationPagePromise;// Click the Connect button- await confirmationPage.locator('.tab-item', { hasText: 'Welcome' }).getByRole('button', { name: 'Connect' }).click();+ await confirmationPage.locator('.tab-item', { hasText: 'Welcome' }).getByRole('button', { name: 'Allow & select' }).click();{// Wait for the CLI command to completediff --git a/tests/extension/extension-fixtures.ts b/tests/extension/extension-fixtures.tsindex 5ff605939e..666c83cd1e 100644--- a/tests/extension/extension-fixtures.ts+++ b/tests/extension/extension-fixtures.ts@@ -222,6 +222,6 @@ export async function connectAndNavigate();const navigatePromise = client.callTool({ name: 'browser_navigate', arguments: { url } });const selectorPage = await confirmationPagePromise;- await selectorPage.locator('.tab-item', { hasText: tabTitle }).getByRole('button', { name: 'Connect' }).click();+ await selectorPage.locator('.tab-item', { hasText: tabTitle }).getByRole('button', { name: 'Allow & select' }).click();return await navigatePromise;}diff --git a/tests/extension/extension.spec.ts b/tests/extension/extension.spec.tsindex 230386bc9a..2dd5f5ce4e 100644--- a/tests/extension/extension.spec.ts+++ b/tests/extension/extension.spec.ts@@ -30,7 +30,7 @@ test(`navigate with extension`, async ({ startExtensionClient, server }) => {});const selectorPage = await confirmationPagePromise;- await selectorPage.locator('.tab-item', { hasText: 'Welcome' }).getByRole('button', { name: 'Connect' }).click();+ await selectorPage.locator('.tab-item', { hasText: 'Welcome' }).getByRole('button', { name: 'Allow & select' }).click();expect(await navigateResponse).toHaveResponse({snapshot: expect.stringContaining(`- generic [active] [ref=e1]: Hello, world!`),@@ -104,7 +104,7 @@ test(`browser_run_code can evaluate in a web worker`, async ({ startExtensionCli});const selectorPage = await confirmationPagePromise;- await selectorPage.locator('.tab-item', { hasText: 'Welcome' }).getByRole('button', { name: 'Connect' }).click();+ await selectorPage.locator('.tab-item', { hasText: 'Welcome' }).getByRole('button', { name: 'Allow & select' }).click();await navigateResponse;@@ -183,7 +183,7 @@ test(`snapshot of an existing page`, async ({ browserWithExtension, startClient,const selectorPage = await confirmationPagePromise;expect(browserContext.pages()).toHaveLength(4);- await selectorPage.locator('.tab-item', { hasText: 'Title' }).getByRole('button', { name: 'Connect' }).click();+ await selectorPage.locator('.tab-item', { hasText: 'Title' }).getByRole('button', { name: 'Allow & select' }).click();expect(await navigateResponse).toHaveResponse({inlineSnapshot: expect.stringContaining(`- generic [active] [ref=e1]: Hello, world!`),@@ -224,7 +224,7 @@ testWithOldExtensionVersion(`works with old extension version`, async ({ startEx});const selectorPage = await confirmationPagePromise;- await selectorPage.locator('.tab-item', { hasText: 'Welcome' }).getByRole('button', { name: 'Connect' }).click();+ await selectorPage.locator('.tab-item', { hasText: 'Welcome' }).getByRole('button', { name: 'Allow & select' }).click();expect(await navigateResponse).toHaveResponse({snapshot: expect.stringContaining(`- generic [active] [ref=e1]: Hello, world!`),diff --git a/tests/extension/tab-grouping.spec.ts b/tests/extension/tab-grouping.spec.tsindex 62f860f488..e27113e8fc 100644--- a/tests/extension/tab-grouping.spec.ts+++ b/tests/extension/tab-grouping.spec.ts@@ -16,7 +16,7 @@import { test, expect, extensionId, startWithExtensionFlag } from './extension-fixtures';-test('connect page is added to green Playwright group on relay connect', async ({ startExtensionClient, server }) => {+test('connect page is not in group before selection', async ({ startExtensionClient, server }) => {const { browserContext, client } = await startExtensionClient();const connectPagePromise = browserContext.waitForEvent('page', page =>@@ -26,26 +26,21 @@ test('connect page is added to green Playwright group on relay connect', async (const navigatePromise = client.callTool({ name: 'browser_navigate', arguments: { url: server.HELLO_WORLD } });const connectPage = await connectPagePromise;- // Wait for the tab list to appear — this means connectToMCPRelay was processed- // by the background and _addTabToGroup has been called.+ // Wait for the tab list to appear — this means connectToMCPRelay was processed.await expect(connectPage.locator('.tab-item').first()).toBeVisible();- const group = await connectPage.evaluate(async () => {+ const groupId = await connectPage.evaluate(async () => {const chrome = (window as any).chrome;const tab = await chrome.tabs.getCurrent();- if (!tab || tab.groupId === -1)- return null;- const g = await chrome.tabGroups.get(tab.groupId);- return { color: g.color, title: g.title };+ return tab?.groupId ?? -1;});+ expect(groupId).toBe(-1);- expect(group).toEqual({ color: 'green', title: 'Playwright' });-- await connectPage.locator('.tab-item', { hasText: 'Welcome' }).getByRole('button', { name: 'Connect' }).click();+ await connectPage.locator('.tab-item', { hasText: 'Welcome' }).getByRole('button', { name: 'Allow & select' }).click();await navigatePromise;});-test('connected tab is added to same Playwright group', async ({ browserWithExtension, startClient, server }) => {+test('connected tab and connect page are in green Playwright group', async ({ browserWithExtension, startClient, server }) => {const browserContext = await browserWithExtension.launch();const page = await browserContext.newPage();@@ -60,21 +55,30 @@ test('connected tab is added to same Playwright group', async ({ browserWithExteconst navigatePromise = client.callTool({ name: 'browser_navigate', arguments: { url: server.HELLO_WORLD } });const connectPage = await connectPagePromise;- await connectPage.locator('.tab-item', { hasText: 'Title' }).getByRole('button', { name: 'Connect' }).click();+ await connectPage.locator('.tab-item', { hasText: 'Title' }).getByRole('button', { name: 'Allow & select' }).click();await navigatePromise;- const { connectGroupId, connectedGroupId } = await connectPage.evaluate(async () => {- const chrome = (window as any).chrome;- const connectTab = await chrome.tabs.getCurrent();- const [connectedTab] = await chrome.tabs.query({ title: 'Title' });- return {- connectGroupId: connectTab?.groupId,- connectedGroupId: connectedTab?.groupId,- };- });+ // Connected tab should be in the Playwright group.+ await expect.poll(async () => {+ return connectPage.evaluate(async () => {+ const chrome = (window as any).chrome;+ const [connectedTab] = await chrome.tabs.query({ title: 'Title' });+ if (!connectedTab || connectedTab.groupId === -1)+ return null;+ const g = await chrome.tabGroups.get(connectedTab.groupId);+ return { color: g.color, title: g.title };+ });+ }).toEqual({ color: 'green', title: 'Playwright' });- expect(connectGroupId).not.toBe(-1);- expect(connectedGroupId).toBe(connectGroupId);+ // Connect page should also be in the same group.+ await expect.poll(async () => {+ return connectPage.evaluate(async () => {+ const chrome = (window as any).chrome;+ const connectTab = await chrome.tabs.getCurrent();+ const [connectedTab] = await chrome.tabs.query({ title: 'Title' });+ return connectTab?.groupId === connectedTab?.groupId;+ });+ }).toBe(true);});test('tab added to group gets auto-attached', async ({ browserWithExtension, startClient, server, protocolVersion }) => {@@ -99,15 +103,24 @@ test('tab added to group gets auto-attached', async ({ browserWithExtension, staconst navigatePromise = client.callTool({ name: 'browser_navigate', arguments: { url: server.HELLO_WORLD } });const connectPage = await connectPagePromise;- await connectPage.locator('.tab-item', { hasText: 'Title' }).getByRole('button', { name: 'Connect' }).click();+ await connectPage.locator('.tab-item', { hasText: 'Title' }).getByRole('button', { name: 'Allow & select' }).click();await navigatePromise;+ // Wait for the connected tab to be added to the group.+ await expect.poll(async () => {+ return connectPage.evaluate(async () => {+ const chrome = (window as any).chrome;+ const [connectedTab] = await chrome.tabs.query({ title: 'Title' });+ return connectedTab?.groupId ?? -1;+ });+ }).toBeGreaterThan(-1);+// Drag the extra tab into the Playwright group — this should auto-attach it.await connectPage.evaluate(async (targetUrl: string) => {const chrome = (window as any).chrome;- const connectTab = await chrome.tabs.getCurrent();+ const [connectedTab] = await chrome.tabs.query({ title: 'Title' });const [extra] = await chrome.tabs.query({ url: targetUrl });- await chrome.tabs.group({ groupId: connectTab.groupId, tabIds: [extra.id] });+ await chrome.tabs.group({ groupId: connectedTab.groupId, tabIds: [extra.id] });}, server.PREFIX + '/extra');await expect.poll(async () => {@@ -134,7 +147,7 @@ test('tab removed from group gets auto-detached', async ({ browserWithExtension,const navigatePromise = client.callTool({ name: 'browser_navigate', arguments: { url: server.HELLO_WORLD } });const connectPage = await connectPagePromise;- await connectPage.locator('.tab-item', { hasText: 'Title' }).getByRole('button', { name: 'Connect' }).click();+ await connectPage.locator('.tab-item', { hasText: 'Title' }).getByRole('button', { name: 'Allow & select' }).click();await navigatePromise;// Create a second tab via the client — it will be attached and added to the group.@@ -185,7 +198,7 @@ test('connected tab is removed from group on disconnect', async ({ browserWithExconst navigatePromise = client.callTool({ name: 'browser_navigate', arguments: { url: server.HELLO_WORLD } });const connectPage = await connectPagePromise;- await connectPage.locator('.tab-item', { hasText: 'Title' }).getByRole('button', { name: 'Connect' }).click();+ await connectPage.locator('.tab-item', { hasText: 'Title' }).getByRole('button', { name: 'Allow & select' }).click();await navigatePromise;await client.close();