Skip to content

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

feat(cli): channel-named attach sessions and detach command (#40408)

Pavel Feldmanbc82f031a87c
diff --git a/packages/playwright-core/src/tools/cli-client/channelSessions.ts b/packages/playwright-core/src/tools/cli-client/channelSessions.ts
index 9c222f2123..4f1d764870 100644
--- a/packages/playwright-core/src/tools/cli-client/channelSessions.ts
+++ b/packages/playwright-core/src/tools/cli-client/channelSessions.ts
@@ -28,6 +28,10 @@ export type ChannelSession = {
extensionInstalled: boolean;
};
+export function isKnownChannel(name: string): boolean {
+ return channelToUserDataDir.has(name);
+}
+
export async function listChannelSessions(): Promise<ChannelSession[]> {
if (process.env.PWTEST_CLI_CHANNEL_SCAN_DISABLED_FOR_TEST)
return [];
diff --git a/packages/playwright-core/src/tools/cli-client/output.ts b/packages/playwright-core/src/tools/cli-client/output.ts
index b188e4965a..562041b263 100644
--- a/packages/playwright-core/src/tools/cli-client/output.ts
+++ b/packages/playwright-core/src/tools/cli-client/output.ts
@@ -53,6 +53,7 @@ export interface Output {
errorUnknownCommand(name: string | undefined, globalHelp: string): never;
errorUnknownOption(opts: string[], commandHelp: string): never;
errorAttachConflict(): never;
+ errorDetachNotAttached(session: string): never;
errorBrowserNotOpenForTool(session: string): never;
list(data: ListData): void;
@@ -62,6 +63,7 @@ export interface Output {
open(session: string, pid: number | undefined, toolResult: string): void;
attach(session: string, pid: number | undefined, endpoint: string | undefined, toolResult: string): void;
close(session: string, wasOpen: boolean): void;
+ detach(session: string, wasAttached: boolean): void;
installed(): void;
show(session: string, pid: number | undefined): void;
toolResult(text: string): void;
@@ -98,6 +100,11 @@ export class TextOutput implements Output {
return process.exit(1);
}
+ errorDetachNotAttached(session: string): never {
+ console.error(`Error: session '${session}' was not attached; use \`playwright-cli${session !== 'default' ? ` -s=${session}` : ''} close\` to stop it.`);
+ return process.exit(1);
+ }
+
errorBrowserNotOpenForTool(session: string): never {
console.log(`The browser '${session}' is not open, please run open first`);
console.log('');
@@ -213,6 +220,14 @@ export class TextOutput implements Output {
console.log(`Browser '${session}' closed\n`);
}
+ detach(session: string, wasAttached: boolean): void {
+ if (!wasAttached) {
+ console.log(`Browser '${session}' is not attached.`);
+ return;
+ }
+ console.log(`Browser '${session}' detached\n`);
+ }
+
installed(): void {
// The spawned install subprocess handles its own output.
}
@@ -257,6 +272,11 @@ export class JsonOutput implements Output {
return process.exit(1);
}
+ errorDetachNotAttached(session: string): never {
+ this._emit({ isError: true, error: `session '${session}' was not attached; use close to stop it.` });
+ return process.exit(1);
+ }
+
errorBrowserNotOpenForTool(session: string): never {
this._emit({ isError: true, error: `The browser '${session}' is not open, please run open first` });
return process.exit(1);
@@ -300,6 +320,10 @@ export class JsonOutput implements Output {
this._emit({ session, status: wasOpen ? 'closed' : 'not-open' });
}
+ detach(session: string, wasAttached: boolean): void {
+ this._emit({ session, status: wasAttached ? 'detached' : 'not-attached' });
+ }
+
installed(): void {
this._emit({ installed: true });
}
diff --git a/packages/playwright-core/src/tools/cli-client/program.ts b/packages/playwright-core/src/tools/cli-client/program.ts
index 9865f53fd4..cf9817e0b5 100644
--- a/packages/playwright-core/src/tools/cli-client/program.ts
+++ b/packages/playwright-core/src/tools/cli-client/program.ts
@@ -22,7 +22,7 @@ import crypto from 'crypto';
import os from 'os';
import path from 'path';
-import { listChannelSessions } from './channelSessions';
+import { isKnownChannel, listChannelSessions } from './channelSessions';
import { JsonOutput, TextOutput } from './output';
import { clientKey, createClientInfo, explicitSessionName, Registry, resolveSessionName } from './registry';
import { Session } from './session';
@@ -160,11 +160,13 @@ export async function program(options?: { embedderVersion?: string}) {
output.errorAttachConflict();
if (attachTarget)
args.endpoint = attachTarget;
+ const extensionChannel = typeof args.extension === 'string' && isKnownChannel(args.extension) ? args.extension : undefined;
if (typeof args.extension === 'string') {
args.browser = args.extension;
args.extension = true;
}
- const attachSessionName = explicitSessionName(args.session as string) ?? attachTarget ?? sessionName;
+ const cdpChannel = typeof args.cdp === 'string' && isKnownChannel(args.cdp) ? args.cdp : undefined;
+ const attachSessionName = explicitSessionName(args.session as string) ?? attachTarget ?? cdpChannel ?? extensionChannel ?? sessionName;
args.session = attachSessionName;
const { pid, endpoint } = await startSession(attachSessionName, registry, clientInfo, args, 'attach');
const newEntry = await registry.loadEntry(clientInfo, attachSessionName);
@@ -178,6 +180,14 @@ export async function program(options?: { embedderVersion?: string}) {
output.close(sessionName, wasOpen);
return;
}
+ case 'detach': {
+ const detachEntry = registry.entry(clientInfo, sessionName);
+ if (detachEntry && !detachEntry.config.attached)
+ output.errorDetachNotAttached(sessionName);
+ const { wasOpen } = detachEntry ? await new Session(detachEntry).stop() : { wasOpen: false };
+ output.detach(sessionName, wasOpen);
+ return;
+ }
case 'install':
await runInitWorkspace(args, output);
output.installed();
diff --git a/packages/playwright-core/src/tools/cli-client/skill/SKILL.md b/packages/playwright-core/src/tools/cli-client/skill/SKILL.md
index 9e70ca9322..7d1fddbbc2 100644
--- a/packages/playwright-core/src/tools/cli-client/skill/SKILL.md
+++ b/packages/playwright-core/src/tools/cli-client/skill/SKILL.md
@@ -224,6 +224,8 @@ playwright-cli open --config=my-config.json
# Close the browser
playwright-cli close
+# Detach from an attached browser (leaves the external browser running)
+playwright-cli -s=msedge detach
# Delete user data for the default session
playwright-cli delete-data
```
diff --git a/packages/playwright-core/src/tools/cli-client/skill/references/session-management.md b/packages/playwright-core/src/tools/cli-client/skill/references/session-management.md
index d1650ef005..bf39acd5f4 100644
--- a/packages/playwright-core/src/tools/cli-client/skill/references/session-management.md
+++ b/packages/playwright-core/src/tools/cli-client/skill/references/session-management.md
@@ -129,6 +129,8 @@ playwright-cli attach --cdp=msedge-dev
Supported channels: `chrome`, `chrome-beta`, `chrome-dev`, `chrome-canary`, `msedge`, `msedge-beta`, `msedge-dev`, `msedge-canary`.
+When `--session` is not provided, the session is named after the channel (e.g. `--cdp=msedge` creates a session called `msedge`), so parallel attaches to Chrome and Edge don't collide on `default`. Pass `--session=<name>` to override.
+
### Attach via CDP endpoint
Connect to a browser that exposes a Chrome DevTools Protocol endpoint:
@@ -145,6 +147,20 @@ Connect to a browser with the Playwright extension installed:
playwright-cli attach --extension
```
+### Detach
+
+Tear down an attached session without affecting the external browser:
+
+```bash
+# Detach the default attached session
+playwright-cli detach
+
+# Detach a specific attached session
+playwright-cli -s=msedge detach
+```
+
+`detach` only works on sessions created via `attach`. For sessions created via `open`, use `close`.
+
## Default Browser Session
When `-s` is omitted, commands use the default browser session:
diff --git a/packages/playwright-core/src/tools/cli-daemon/commands.ts b/packages/playwright-core/src/tools/cli-daemon/commands.ts
index 594778e874..5e55b3bce9 100644
--- a/packages/playwright-core/src/tools/cli-daemon/commands.ts
+++ b/packages/playwright-core/src/tools/cli-daemon/commands.ts
@@ -80,6 +80,15 @@ const close = declareCommand({
toolParams: () => ({}),
});
+const detach = declareCommand({
+ name: 'detach',
+ description: 'Detach from an attached browser',
+ category: 'core',
+ args: z.object({}),
+ toolName: '',
+ toolParams: () => ({}),
+});
+
const goto = declareCommand({
name: 'goto',
description: 'Navigate to a URL',
@@ -1015,6 +1024,7 @@ const commandsArray: AnyCommandSchema[] = [
open,
attach,
close,
+ detach,
goto,
type,
click,
diff --git a/tests/mcp/cli-cdp.spec.ts b/tests/mcp/cli-cdp.spec.ts
index 86e35717ba..8d32e88437 100644
--- a/tests/mcp/cli-cdp.spec.ts
+++ b/tests/mcp/cli-cdp.spec.ts
@@ -15,7 +15,7 @@
*/
import fs from 'fs';
-import { test, expect } from './cli-fixtures';
+import { test, expect, daemonFolder } from './cli-fixtures';
test.describe.configure({
retries: 1,
@@ -27,6 +27,65 @@ test('connect by channel name error', async ({ cli }) => {
expect(error).toContain('chrome://inspect/#remote-debugging');
});
+test('attach --cdp=<channel> defaults session name to the channel', async ({ cli }) => {
+ // Connection fails, but the daemon writes its err log under the resolved session name.
+ await cli('attach', '--cdp=chrome-canary');
+ const folder = await daemonFolder();
+ expect(folder).toBeTruthy();
+ const files = await fs.promises.readdir(folder!);
+ expect(files).toContain('chrome-canary.err');
+ expect(files).not.toContain('default.err');
+});
+
+test('explicit --session wins over --cdp=<channel>', async ({ cli }) => {
+ await cli('attach', '--cdp=chrome-canary', '-s=explicit');
+ const folder = await daemonFolder();
+ expect(folder).toBeTruthy();
+ const files = await fs.promises.readdir(folder!);
+ expect(files).toContain('explicit.err');
+ expect(files).not.toContain('chrome-canary.err');
+});
+
+test('attach via cdp URL keeps the default session', async ({ cdpServer, cli, server }) => {
+ const browserContext = await cdpServer.start();
+ const [page] = browserContext.pages();
+ await page.goto(server.HELLO_WORLD);
+
+ await cli('attach', `--cdp=${cdpServer.endpoint}`);
+ const { output: listOutput } = await cli('list');
+ expect(listOutput).toContain('- default:');
+ expect(listOutput).toContain('(attached)');
+});
+
+test('detach tears down an attached session', async ({ cdpServer, cli }) => {
+ await cdpServer.start();
+
+ await cli('attach', `--cdp=${cdpServer.endpoint}`, '-s=mine');
+ const { output: listBefore } = await cli('list');
+ expect(listBefore).toContain('- mine:');
+ expect(listBefore).toContain('(attached)');
+
+ const { output: detachOutput } = await cli('-s=mine', 'detach');
+ expect(detachOutput).toContain(`Browser 'mine' detached`);
+
+ const { output: listAfter } = await cli('list');
+ expect(listAfter).not.toContain('- mine:');
+});
+
+test('detach rejects sessions opened via open', async ({ cli, server }) => {
+ await cli('open', server.HELLO_WORLD);
+
+ const { error, exitCode } = await cli('detach');
+ expect(exitCode).toBe(1);
+ expect(error).toContain(`session 'default' was not attached`);
+ expect(error).toContain('close');
+});
+
+test('detach on unknown session reports not attached', async ({ cli }) => {
+ const { output } = await cli('-s=nobody', 'detach');
+ expect(output).toContain(`Browser 'nobody' is not attached.`);
+});
+
test('cdp server', async ({ cdpServer, cli, server }) => {
const browserContext = await cdpServer.start();
const [page] = browserContext.pages();