Skip to content

Commit fb10ea7

Browse files
authored
feat(cli): detach --close-tabs for extension sessions (#44084)
1 parent 188c63e commit fb10ea7

10 files changed

Lines changed: 82 additions & 13 deletions

File tree

‎packages/extension/README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,12 @@ playwright-cli attach --extension=msedge --session="my session" --session-color=
5454

5555
When a client disconnects, its tab group stays and turns gray. Select that group on the connect page of the next client to continue with the same tabs.
5656

57+
With the CLI, `detach --close-tabs` closes the tabs of the session before it disconnects, so no group stays:
58+
59+
```bash
60+
playwright-cli --session="my session" detach --close-tabs
61+
```
62+
5763
To disable automatic grouping, pass `--no-tab-group` alongside `--extension`, or set `PLAYWRIGHT_MCP_NO_TAB_GROUP=1`. With the CLI, pass `--no-tab-group` to `attach`. Grouping stays enabled by default. With grouping disabled, the selected tabs and tabs opened by the client stay in their existing groups, if any. This does not grant access to all existing tabs or change connection approval; each controlled tab still belongs to only one client. Use the status page to see controlled tabs and disconnect clients.
5864

5965
### Bypassing the Connection Approval Dialog

‎packages/extension/design.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ The relay starts the browser with `connect.html` and these parameters:
135135
| `tabGroupColor` | Optional color: `green`, `blue`, `purple`, `orange`, `pink`, `cyan`, `yellow` or `red`. The default is the first of these, in this order, that no other client group has. `grey` is refused, because it marks a group that its client left. |
136136
| `background` | `true` if the tabs of the client must not become active |
137137

138-
The MCP server has the options `--session-name`, `--session-color`, `--no-tab-group` and `--background`. The session name is the title of the group, and the session color is its color. The CLI gives the name of its session as the title, and `attach` has the options `--session-color` and `--no-tab-group`.
138+
The MCP server has the options `--session-name`, `--session-color`, `--no-tab-group` and `--background`. The session name is the title of the group, and the session color is its color. The CLI gives the name of its session as the title, and `attach` has the options `--session-color` and `--no-tab-group`. `detach --close-tabs` closes each page of the session with `chrome.tabs.remove` before the client stops, so the session leaves no gray group.
139139

140140
### Runtime messages
141141

‎packages/playwright-core/src/tools/cli-client/program.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ export async function program(options?: { args?: MinimistArgs, embedderVersion?:
204204
const detachEntry = registry.entry(clientInfo, sessionName);
205205
if (detachEntry && !detachEntry.config.attached)
206206
output.errorDetachNotAttached(sessionName);
207-
const { wasOpen } = detachEntry ? await new Session(detachEntry).stop() : { wasOpen: false };
207+
const { wasOpen } = detachEntry ? await new Session(detachEntry).stop({ closeTabs: !!args['close-tabs'] }) : { wasOpen: false };
208208
output.detach(sessionName, wasOpen);
209209
return;
210210
}

‎packages/playwright-core/src/tools/cli-client/session.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,10 @@ export class Session {
5252
return await SocketConnectionClient.sendAndClose(socket, 'run', { args, cwd: process.cwd(), raw: options?.raw, json: options?.json });
5353
}
5454

55-
async stop(): Promise<{ wasOpen: boolean }> {
55+
async stop(options: { closeTabs?: boolean } = {}): Promise<{ wasOpen: boolean }> {
5656
if (!await this.canConnect())
5757
return { wasOpen: false };
58-
await this._stopDaemon();
58+
await this._stopDaemon(options);
5959
return { wasOpen: true };
6060
}
6161

@@ -195,13 +195,13 @@ export class Session {
195195
return { pid: child.pid, sessionName, endpoint: cliArgs.endpoint as string | undefined };
196196
}
197197

198-
private async _stopDaemon(): Promise<void> {
198+
private async _stopDaemon(options: { closeTabs?: boolean }): Promise<void> {
199199
const { socket } = await this._connect();
200200
if (!socket)
201201
return;
202202

203203
let error: Error | undefined;
204-
await SocketConnectionClient.sendAndClose(socket, 'stop', {}).catch(e => error = e);
204+
await SocketConnectionClient.sendAndClose(socket, 'stop', options).catch(e => error = e);
205205
if (error && !error?.message?.includes('Session closed'))
206206
throw error;
207207
}

‎packages/playwright-core/src/tools/cli-daemon/commands.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,9 @@ const detach = declareCommand({
9494
description: 'Detach from an attached browser',
9595
category: 'core',
9696
args: z.object({}),
97+
options: z.object({
98+
['close-tabs']: z.boolean().optional().describe('With --extension, close the tabs of the session before detaching.'),
99+
}),
97100
toolName: '',
98101
toolParams: () => ({}),
99102
});

‎packages/playwright-core/src/tools/cli-daemon/daemon.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ export async function startCliDaemonServer(
8080
ownership?: 'attached' | 'own',
8181
persistent?: boolean,
8282
idleTimer?: IdleTimer,
83+
extension?: boolean,
8384
}
8485
): Promise<string> {
8586
const sessionConfig = createSessionConfig(clientInfo, sessionName, browserInfo, options);
@@ -108,6 +109,11 @@ export async function startCliDaemonServer(
108109
const { id, method, params } = message;
109110
try {
110111
if (method === 'stop') {
112+
if (params?.closeTabs) {
113+
if (!options.extension)
114+
throw new Error(`--close-tabs works only for a session attached with --extension.`);
115+
await Promise.all(browserContext.pages().map(page => page.close()));
116+
}
111117
await exit(async () => connection.send({ id, result: 'ok' }).catch(() => {}));
112118
} else if (method === 'run') {
113119
const { toolName, toolParams } = parseCliCommand(params.args);

‎packages/playwright-core/src/tools/cli-daemon/program.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ export function decorateProgram(program: Command) {
7171
if (!browserContext)
7272
throw new Error('Error: unable to connect to a browser that does not have any contexts');
7373
const persistent = options.persistent || options.profile || mcpConfig.browser.userDataDir ? true : undefined;
74-
const socketPath = await startCliDaemonServer(sessionName, browserContext, browserInfo, mcpConfig, clientInfo, mcpClientInfo, { persistent, ownership, idleTimer });
74+
const socketPath = await startCliDaemonServer(sessionName, browserContext, browserInfo, mcpConfig, clientInfo, mcpClientInfo, { persistent, ownership, idleTimer, extension: !!options.extension });
7575
console.log(`Daemon listening on ${socketPath}\n`);
7676
} catch (error) {
7777
console.log(error);

‎packages/playwright-core/src/tools/skills/playwright-cli/SKILL.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -285,8 +285,12 @@ playwright-cli open --persistent
285285
# Use persistent profile with custom directory
286286
playwright-cli open --profile=/path/to/profile
287287
288-
# Connect to browser via Playwright Extension
289-
playwright-cli attach --extension=chrome
288+
# Connect to the browser profile of the user via Playwright Extension (chrome, msedge, ...).
289+
# The session name is the title of the tab group; pick a color to tell sessions apart.
290+
playwright-cli attach --extension=chrome --session=finance --session-color=blue
291+
playwright-cli -s=finance goto https://example.com
292+
# Detach and close the tabs of the session, when the user does not need them
293+
playwright-cli -s=finance detach --close-tabs
290294
291295
# Connect to a running Chrome or Edge by channel name
292296
playwright-cli attach --cdp=chrome
@@ -484,7 +488,7 @@ See [references/pr-attachments.md](references/pr-attachments.md) for alt text, i
484488
* **Running and Debugging Playwright tests** [references/playwright-tests.md](references/playwright-tests.md)
485489
* **Request mocking** [references/request-mocking.md](references/request-mocking.md)
486490
* **Running Playwright code** [references/running-code.md](references/running-code.md)
487-
* **Browser session management** [references/session-management.md](references/session-management.md)
491+
* **Browser session management, attaching to the browser of the user** [references/session-management.md](references/session-management.md)
488492
* **Storage state (cookies, localStorage)** [references/storage-state.md](references/storage-state.md)
489493
* **Test generation (plan / generate / heal)** [references/test-generation.md](references/test-generation.md)
490494
* **Tracing** [references/tracing.md](references/tracing.md)

‎packages/playwright-core/src/tools/skills/playwright-cli/references/session-management.md‎

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -143,12 +143,41 @@ playwright-cli attach --cdp=http://localhost:9222
143143

144144
### Attach via browser extension
145145

146-
Connect to a browser with the Playwright extension installed:
146+
Connect to the everyday browser profile of the user: their tabs, logins and cookies. The browser must have the Playwright Extension installed. Name the browser, because the extension can be in Edge and not in Chrome:
147147

148148
```bash
149-
playwright-cli attach --extension
149+
playwright-cli attach --extension=chrome
150+
playwright-cli attach --extension=msedge
150151
```
151152

153+
When the extension is not installed in that browser, `attach` fails with `Playwright Extension not found in "<profile path>"`. Try the other browser, or ask the user to install the extension.
154+
155+
The session controls only its own tabs: the tabs that the user picked on the connect page, and the tabs that the session opened. The extension puts them into a tab group. Give the session a name for the task, and optionally a color:
156+
157+
```bash
158+
# The tab group has the title "finance" and the color blue.
159+
# Colors: blue, red, yellow, green, pink, purple, cyan, orange.
160+
playwright-cli attach --extension=msedge --session=finance --session-color=blue
161+
162+
# Each next command names the session
163+
playwright-cli -s=finance goto https://example.com
164+
playwright-cli -s=finance snapshot
165+
```
166+
167+
Without `--session`, the session has the name of the browser (`chrome`, `msedge`). Without `--session-color`, the group takes the first color that no other session uses. Pass `--no-tab-group` to leave the tabs where the user has them.
168+
169+
When the work is done, detach. The browser of the user keeps running:
170+
171+
```bash
172+
# Leave the tabs open. The tab group stays and turns gray, and the user can continue in it.
173+
playwright-cli -s=finance detach
174+
175+
# Close the tabs of the session. Use it to clean up tabs that the user does not need any more.
176+
playwright-cli -s=finance detach --close-tabs
177+
```
178+
179+
`--close-tabs` closes all tabs of the session, also the tabs that the user picked for it. It never closes other tabs of the user.
180+
152181
### Detach
153182

154183
Tear down an attached session without affecting the external browser:
@@ -161,7 +190,7 @@ playwright-cli detach
161190
playwright-cli -s=msedge detach
162191
```
163192

164-
`detach` only works on sessions created via `attach`. For sessions created via `open`, use `close`.
193+
`detach` only works on sessions created via `attach`. For sessions created via `open`, use `close`. `detach --close-tabs` only works on sessions created via `attach --extension`.
165194

166195
## Default Browser Session
167196

‎tests/extension/cli.spec.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,27 @@ test('attach --extension gives the name and the color of the session to the tab
4848
await expect.poll(user.groups).toEqual([{ title: 'my session', color: 'red', tabs: ['Alpha'] }]);
4949
});
5050

51+
test('detach --close-tabs closes the tabs of the session', async ({ user, cli, browserWithExtension }) => {
52+
await user.openTab('Alpha');
53+
const userTabs = await user.tabs();
54+
55+
const connectPage = user.waitForConnectPage();
56+
const attached = cli(['attach', '--extension=chromium', '--session=work'], {
57+
env: { PWTEST_EXTENSION_USER_DATA_DIR: browserWithExtension.userDataDir },
58+
});
59+
await user.allow(await connectPage);
60+
await attached;
61+
62+
await cli(['--session=work', 'goto', user.urlOf('Beta')]);
63+
await cli(['--session=work', 'tab-new', user.urlOf('Gamma')]);
64+
await expect.poll(user.groups).toEqual([{ title: 'work', color: 'green', tabs: ['Beta', 'Gamma'] }]);
65+
66+
const { output } = await cli(['--session=work', 'detach', '--close-tabs']);
67+
expect(output).toContain(`Browser 'work' detached`);
68+
await expect.poll(() => user.tabs()).toEqual(userTabs);
69+
expect(await user.groups()).toEqual([]);
70+
});
71+
5172
test('attach --extension --no-tab-group leaves the tab where the user has it', async ({ user, cli, browserWithExtension }) => {
5273
await user.openTab('Alpha');
5374
await user.dragIntoNewGroup('Alpha', 'My tabs');

0 commit comments

Comments
 (0)