Skip to content

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

chore(cli): provide skills (#39069)

Pavel Feldman98769e3832d8
diff --git a/packages/playwright/src/mcp/terminal/commands.ts b/packages/playwright/src/mcp/terminal/commands.ts
index 62d04df115..a76392a8f2 100644
--- a/packages/playwright/src/mcp/terminal/commands.ts
+++ b/packages/playwright/src/mcp/terminal/commands.ts
@@ -391,6 +391,30 @@ const tabSelect = declareCommand({
toolParams: ({ index }) => ({ action: 'select', index }),
});
+// Storage
+
+const stateLoad = declareCommand({
+ name: 'state-load',
+ description: 'Loads storage (authentication) state from a file',
+ category: 'storage',
+ args: z.object({
+ filename: z.string().describe('File name to load the storage state from.'),
+ }),
+ toolName: 'browser_set_storage_state',
+ toolParams: ({ filename }) => ({ filename }),
+});
+
+const stateSave = declareCommand({
+ name: 'state-save',
+ description: 'Saves the current storage (authentication) state to a file',
+ category: 'storage',
+ args: z.object({
+ filename: z.string().optional().describe('File name to save the storage state to.'),
+ }),
+ toolName: 'browser_storage_state',
+ toolParams: ({ filename }) => ({ filename }),
+});
+
// Export
const screenshot = declareCommand({
@@ -612,6 +636,10 @@ const commandsArray: AnyCommandSchema[] = [
tabClose,
tabSelect,
+ // storage category
+ stateLoad,
+ stateSave,
+
// config category
config,
diff --git a/packages/playwright/src/mcp/terminal/program.ts b/packages/playwright/src/mcp/terminal/program.ts
index 0394252432..ca70a095f4 100644
--- a/packages/playwright/src/mcp/terminal/program.ts
+++ b/packages/playwright/src/mcp/terminal/program.ts
@@ -452,7 +452,7 @@ const booleanOptions = [
'extension',
'headed',
'help',
- 'isolated',
+ 'in-memory',
'version',
];
@@ -534,7 +534,7 @@ function sessionConfigFromArgs(version: string, sessionName: string, args: Minim
headed: args.headed,
extension: args.extension,
browser: args.browser,
- isolated: args.isolated,
+ isolated: args['in-memory'],
config,
},
userDataDirPrefix: path.resolve(daemonProfilesDir, `ud-${sessionName}`),
diff --git a/packages/playwright/src/mcp/terminal/SKILL.md b/packages/playwright/src/skill/SKILL.md
similarity index 73%
rename from packages/playwright/src/mcp/terminal/SKILL.md
rename to packages/playwright/src/skill/SKILL.md
index 0600464be3..24e060e893 100644
--- a/packages/playwright/src/mcp/terminal/SKILL.md
+++ b/packages/playwright/src/skill/SKILL.md
@@ -94,6 +94,14 @@ playwright-cli tab-close 2
playwright-cli tab-select 0
```
+### Storage
+
+```bash
+playwright-cli state-save
+playwright-cli state-save auth.json
+playwright-cli state-load auth.json
+```
+
### DevTools
```bash
@@ -109,8 +117,9 @@ playwright-cli video-stop video.webm
### Configuration
```bash
-# configure the session
-playwright-cli config my-config.json
+# Configure the session
+playwright-cli config --config my-config.json
+playwright-cli config --headed --in-memory --browser=firefox
# Configure named session
playwright-cli --session=mysession config my-config.json
# Start with configured session
@@ -168,3 +177,29 @@ playwright-cli click e4
playwright-cli fill e7 "test"
playwright-cli tracing-stop
```
+
+## Example: Authentication state reuse
+
+```bash
+# Login and save auth state
+playwright-cli open https://app.example.com/login
+playwright-cli snapshot
+playwright-cli fill e1 "[email protected]"
+playwright-cli fill e2 "password123"
+playwright-cli click e3
+playwright-cli state-save auth.json
+
+# Later, restore state and skip login
+playwright-cli state-load auth.json
+playwright-cli open https://app.example.com/dashboard
+```
+
+## Specific tasks
+
+* **Request mocking** [references/request-mocking.md](references/request-mocking.md)
+* **Running Playwright code** [references/running-code.md](references/running-code.md)
+* **Session management** [references/session-management.md](references/session-management.md)
+* **Storage state (cookies, localStorage)** [references/storage-state.md](references/storage-state.md)
+* **Test generation** [references/test-generation.md](references/test-generation.md)
+* **Tracing** [references/tracing.md](references/tracin.md`)
+* **Video recording** [references/video-recording.md](references/video-recording.md)
diff --git a/packages/playwright/src/skill/references/request-mocking.md b/packages/playwright/src/skill/references/request-mocking.md
new file mode 100644
index 0000000000..f6e25c342e
--- /dev/null
+++ b/packages/playwright/src/skill/references/request-mocking.md
@@ -0,0 +1,452 @@
+# Request Mocking
+
+Intercept, mock, modify, and block network requests using `page.route()`.
+
+## Basic Syntax
+
+```bash
+playwright-cli run-code "async page => {
+ await page.route('**/api/endpoint', route => {
+ // Handle the route
+ });
+}"
+```
+
+## URL Patterns
+
+```
+**/api/users - Exact path match
+**/api/*/details - Wildcard in path
+**/*.{png,jpg,jpeg} - Match file extensions
+**/search?q=* - Match query parameters
+/\/api\/v\d+\/users/ - Regex pattern (passed as RegExp)
+```
+
+## Mock API Responses
+
+### Return Static JSON
+
+```bash
+playwright-cli run-code "async page => {
+ await page.route('**/api/users', route => {
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify([
+ { id: 1, name: 'Alice' },
+ { id: 2, name: 'Bob' }
+ ])
+ });
+ });
+}"
+```
+
+### Return with Custom Headers
+
+```bash
+playwright-cli run-code "async page => {
+ await page.route('**/api/data', route => {
+ route.fulfill({
+ status: 200,
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-Custom-Header': 'custom-value',
+ 'Cache-Control': 'no-cache'
+ },
+ body: JSON.stringify({ success: true })
+ });
+ });
+}"
+```
+
+### Return HTML
+
+```bash
+playwright-cli run-code "async page => {
+ await page.route('**/page.html', route => {
+ route.fulfill({
+ status: 200,
+ contentType: 'text/html',
+ body: '<html><body><h1>Mocked Page</h1></body></html>'
+ });
+ });
+}"
+```
+
+### Return Based on Request Data
+
+```bash
+playwright-cli run-code "async page => {
+ await page.route('**/api/search', async route => {
+ const request = route.request();
+ const postData = request.postDataJSON();
+
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ query: postData.query,
+ results: ['mock result 1', 'mock result 2']
+ })
+ });
+ });
+}"
+```
+
+## Modify Real Responses
+
+### Intercept and Transform
+
+```bash
+playwright-cli run-code "async page => {
+ await page.route('**/api/products', async route => {
+ // Fetch the real response
+ const response = await route.fetch();
+ const json = await response.json();
+
+ // Modify it
+ json.products = json.products.map(p => ({
+ ...p,
+ price: 0,
+ discount: '100%'
+ }));
+
+ // Return modified response
+ await route.fulfill({ response, json });
+ });
+}"
+```
+
+### Add Fields to Response
+
+```bash
+playwright-cli run-code "async page => {
+ await page.route('**/api/user/profile', async route => {
+ const response = await route.fetch();
+ const json = await response.json();
+
+ // Add mock fields
+ json.isPremium = true;
+ json.credits = 9999;
+
+ await route.fulfill({ response, json });
+ });
+}"
+```
+
+### Filter Response Data
+
+```bash
+playwright-cli run-code "async page => {
+ await page.route('**/api/items', async route => {
+ const response = await route.fetch();
+ const json = await response.json();
+
+ // Filter to only active items
+ json.items = json.items.filter(item => item.active);
+
+ await route.fulfill({ response, json });
+ });
+}"
+```
+
+## Modify Request Headers
+
+### Add Authorization
+
+```bash
+playwright-cli run-code "async page => {
+ await page.route('**/api/**', async route => {
+ const headers = {
+ ...route.request().headers(),
+ 'Authorization': 'Bearer my-secret-token'
+ };
+ await route.continue({ headers });
+ });
+}"
+```
+
+### Add Custom Headers
+
+```bash
+playwright-cli run-code "async page => {
+ await page.route('**/*', async route => {
+ const headers = {
+ ...route.request().headers(),
+ 'X-Test-Mode': 'true',
+ 'X-Request-Id': Date.now().toString()
+ };
+ await route.continue({ headers });
+ });
+}"
+```
+
+### Remove Headers
+
+```bash
+playwright-cli run-code "async page => {
+ await page.route('**/*', async route => {
+ const headers = { ...route.request().headers() };
+ delete headers['cookie'];
+ delete headers['authorization'];
+ await route.continue({ headers });
+ });
+}"
+```
+
+## Block Requests
+
+### Block by URL Pattern
+
+```bash
+# Block images
+playwright-cli run-code "async page => {
+ await page.route('**/*.{png,jpg,jpeg,gif,webp,svg}', route => route.abort());
+}"
+
+# Block fonts
+playwright-cli run-code "async page => {
+ await page.route('**/*.{woff,woff2,ttf,otf}', route => route.abort());
+}"
+
+# Block CSS
+playwright-cli run-code "async page => {
+ await page.route('**/*.css', route => route.abort());
+}"
+```
+
+### Block Third-Party Scripts
+
+```bash
+playwright-cli run-code "async page => {
+ await page.route('**/*google-analytics*/**', route => route.abort());
+ await page.route('**/*googletagmanager*/**', route => route.abort());
+ await page.route('**/*facebook*/**', route => route.abort());
+ await page.route('**/*hotjar*/**', route => route.abort());
+ await page.route('**/*intercom*/**', route => route.abort());
+}"
+```
+
+### Block All External Requests
+
+```bash
+playwright-cli run-code "async page => {
+ const allowedDomain = 'example.com';
+ await page.route('**/*', route => {
+ const url = new URL(route.request().url());
+ if (url.hostname.includes(allowedDomain)) {
+ route.continue();
+ } else {
+ route.abort();
+ }
+ });
+}"
+```
+
+## Simulate Errors
+
+### HTTP Error Codes
+
+```bash
+# 404 Not Found
+playwright-cli run-code "async page => {
+ await page.route('**/api/missing', route => {
+ route.fulfill({ status: 404, body: 'Not Found' });
+ });
+}"
+
+# 500 Internal Server Error
+playwright-cli run-code "async page => {
+ await page.route('**/api/broken', route => {
+ route.fulfill({
+ status: 500,
+ contentType: 'application/json',
+ body: JSON.stringify({ error: 'Internal Server Error' })
+ });
+ });
+}"
+
+# 401 Unauthorized
+playwright-cli run-code "async page => {
+ await page.route('**/api/protected', route => {
+ route.fulfill({
+ status: 401,
+ body: JSON.stringify({ error: 'Unauthorized' })
+ });
+ });
+}"
+
+# 429 Rate Limited
+playwright-cli run-code "async page => {
+ await page.route('**/api/limited', route => {
+ route.fulfill({
+ status: 429,
+ headers: { 'Retry-After': '60' },
+ body: JSON.stringify({ error: 'Too Many Requests' })
+ });
+ });
+}"
+```
+
+### Network Failures
+
+```bash
+# Connection refused
+playwright-cli run-code "async page => {
+ await page.route('**/api/unreachable', route => route.abort('connectionrefused'));
+}"
+
+# Timeout
+playwright-cli run-code "async page => {
+ await page.route('**/api/slow', route => route.abort('timedout'));
+}"
+
+# Connection reset
+playwright-cli run-code "async page => {
+ await page.route('**/api/reset', route => route.abort('connectionreset'));
+}"
+
+# Internet disconnected
+playwright-cli run-code "async page => {
+ await page.route('**/api/offline', route => route.abort('internetdisconnected'));
+}"
+```
+
+## Delayed Responses
+
+```bash
+# Simulate slow API
+playwright-cli run-code "async page => {
+ await page.route('**/api/slow-endpoint', async route => {
+ await new Promise(r => setTimeout(r, 3000)); // 3 second delay
+ route.fulfill({
+ status: 200,
+ body: JSON.stringify({ data: 'finally loaded' })
+ });
+ });
+}"
+```
+
+## Conditional Mocking
+
+### Based on Request Method
+
+```bash
+playwright-cli run-code "async page => {
+ await page.route('**/api/resource', route => {
+ const method = route.request().method();
+
+ if (method === 'GET') {
+ route.fulfill({
+ body: JSON.stringify({ items: [] })
+ });
+ } else if (method === 'POST') {
+ route.fulfill({
+ status: 201,
+ body: JSON.stringify({ id: 123, created: true })
+ });
+ } else if (method === 'DELETE') {
+ route.fulfill({ status: 204 });
+ } else {
+ route.continue();
+ }
+ });
+}"
+```
+
+### Based on Request Body
+
+```bash
+playwright-cli run-code "async page => {
+ await page.route('**/api/login', route => {
+ const body = route.request().postDataJSON();
+
+ if (body.username === 'admin' && body.password === 'secret') {
+ route.fulfill({
+ body: JSON.stringify({ token: 'mock-jwt-token' })
+ });
+ } else {
+ route.fulfill({
+ status: 401,
+ body: JSON.stringify({ error: 'Invalid credentials' })
+ });
+ }
+ });
+}"
+```
+
+## Remove Routes
+
+```bash
+# Remove specific route
+playwright-cli run-code "async page => {
+ const handler = route => route.abort();
+ await page.route('**/api/blocked', handler);
+
+ // Later, remove the route
+ await page.unroute('**/api/blocked', handler);
+}"
+
+# Remove all routes for a pattern
+playwright-cli run-code "async page => {
+ await page.unroute('**/api/**');
+}"
+```
+
+## Logging Requests
+
+```bash
+# Log all requests and responses
+playwright-cli run-code "async page => {
+ page.on('request', request => {
+ console.log('>>', request.method(), request.url());
+ });
+ page.on('response', response => {
+ console.log('<<', response.status(), response.url());
+ });
+}"
+
+# Log only failed requests
+playwright-cli run-code "async page => {
+ page.on('requestfailed', request => {
+ console.log('FAILED:', request.url(), request.failure().errorText);
+ });
+}"
+```
+
+## Wait for Requests
+
+```bash
+# Wait for specific request after action
+playwright-cli run-code "async page => {
+ const [response] = await Promise.all([
+ page.waitForResponse('**/api/submit'),
+ page.click('button[type=submit]')
+ ]);
+ return { status: response.status(), ok: response.ok() };
+}"
+
+# Wait for request with custom condition
+playwright-cli run-code "async page => {
+ const response = await page.waitForResponse(
+ response => response.url().includes('/api/') && response.status() === 200
+ );
+ return await response.json();
+}"
+```
+
+## HAR File Mocking
+
+```bash
+# Record network to HAR
+playwright-cli run-code "async page => {
+ await page.routeFromHAR('network.har', { update: true });
+ // Navigate and interact - requests are recorded
+}"
+
+# Replay from HAR
+playwright-cli run-code "async page => {
+ await page.routeFromHAR('network.har');
+ // Requests matching HAR entries return recorded responses
+}"
+```
diff --git a/packages/playwright/src/skill/references/running-code.md b/packages/playwright/src/skill/references/running-code.md
new file mode 100644
index 0000000000..53fdcff76a
--- /dev/null
+++ b/packages/playwright/src/skill/references/running-code.md
@@ -0,0 +1,249 @@
+# Running Custom Playwright Code
+
+Use `run-code` to execute arbitrary Playwright code for advanced scenarios not covered by CLI commands.
+
+## Syntax
+
+```bash
+playwright-cli run-code "async page => {
+ // Your Playwright code here
+ // Access page.context() for browser context operations
+}"
+```
+
+## Geolocation
+
+```bash
+# Grant geolocation permission and set location
+playwright-cli run-code "async page => {
+ await page.context().grantPermissions(['geolocation']);
+ await page.context().setGeolocation({ latitude: 37.7749, longitude: -122.4194 });
+}"
+
+# Set location to London
+playwright-cli run-code "async page => {
+ await page.context().grantPermissions(['geolocation']);
+ await page.context().setGeolocation({ latitude: 51.5074, longitude: -0.1278 });
+}"
+
+# Clear geolocation override
+playwright-cli run-code "async page => {
+ await page.context().clearPermissions();
+}"
+```
+
+## Permissions
+
+```bash
+# Grant multiple permissions
+playwright-cli run-code "async page => {
+ await page.context().grantPermissions([
+ 'geolocation',
+ 'notifications',
+ 'camera',
+ 'microphone'
+ ]);
+}"
+
+# Grant permissions for specific origin
+playwright-cli run-code "async page => {
+ await page.context().grantPermissions(['clipboard-read'], {
+ origin: 'https://example.com'
+ });
+}"
+```
+
+## Media Emulation
+
+```bash
+# Emulate dark color scheme
+playwright-cli run-code "async page => {
+ await page.emulateMedia({ colorScheme: 'dark' });
+}"
+
+# Emulate light color scheme
+playwright-cli run-code "async page => {
+ await page.emulateMedia({ colorScheme: 'light' });
+}"
+
+# Emulate reduced motion
+playwright-cli run-code "async page => {
+ await page.emulateMedia({ reducedMotion: 'reduce' });
+}"
+
+# Emulate print media
+playwright-cli run-code "async page => {
+ await page.emulateMedia({ media: 'print' });
+}"
+```
+
+## Wait Strategies
+
+```bash
+# Wait for network idle
+playwright-cli run-code "async page => {
+ await page.waitForLoadState('networkidle');
+}"
+
+# Wait for specific element
+playwright-cli run-code "async page => {
+ await page.waitForSelector('.loading', { state: 'hidden' });
+}"
+
+# Wait for function to return true
+playwright-cli run-code "async page => {
+ await page.waitForFunction(() => window.appReady === true);
+}"
+
+# Wait with timeout
+playwright-cli run-code "async page => {
+ await page.waitForSelector('.result', { timeout: 10000 });
+}"
+```
+
+## Frames and Iframes
+
+```bash
+# Work with iframe
+playwright-cli run-code "async page => {
+ const frame = page.frameLocator('iframe#my-iframe');
+ await frame.locator('button').click();
+}"
+
+# Get all frames
+playwright-cli run-code "async page => {
+ const frames = page.frames();
+ return frames.map(f => f.url());
+}"
+```
+
+## File Downloads
+
+```bash
+# Handle file download
+playwright-cli run-code "async page => {
+ const [download] = await Promise.all([
+ page.waitForEvent('download'),
+ page.click('a.download-link')
+ ]);
+ await download.saveAs('./downloaded-file.pdf');
+ return download.suggestedFilename();
+}"
+```
+
+## Clipboard
+
+```bash
+# Read clipboard (requires permission)
+playwright-cli run-code "async page => {
+ await page.context().grantPermissions(['clipboard-read']);
+ return await page.evaluate(() => navigator.clipboard.readText());
+}"
+
+# Write to clipboard
+playwright-cli run-code "async page => {
+ await page.evaluate(text => navigator.clipboard.writeText(text), 'Hello clipboard!');
+}"
+```
+
+## Accessibility
+
+```bash
+# Get accessibility tree
+playwright-cli run-code "async page => {
+ const snapshot = await page.accessibility.snapshot();
+ return snapshot;
+}"
+
+# Get accessibility info for element
+playwright-cli run-code "async page => {
+ const button = page.getByRole('button', { name: 'Submit' });
+ const snapshot = await page.accessibility.snapshot({ root: button });
+ return snapshot;
+}"
+```
+
+## Page Information
+
+```bash
+# Get page title
+playwright-cli run-code "async page => {
+ return await page.title();
+}"
+
+# Get current URL
+playwright-cli run-code "async page => {
+ return page.url();
+}"
+
+# Get page content
+playwright-cli run-code "async page => {
+ return await page.content();
+}"
+
+# Get viewport size
+playwright-cli run-code "async page => {
+ return page.viewportSize();
+}"
+```
+
+## JavaScript Execution
+
+```bash
+# Execute JavaScript and return result
+playwright-cli run-code "async page => {
+ return await page.evaluate(() => {
+ return {
+ userAgent: navigator.userAgent,
+ language: navigator.language,
+ cookiesEnabled: navigator.cookieEnabled
+ };
+ });
+}"
+
+# Pass arguments to evaluate
+playwright-cli run-code "async page => {
+ const multiplier = 5;
+ return await page.evaluate(m => document.querySelectorAll('li').length * m, multiplier);
+}"
+```
+
+## Error Handling
+
+```bash
+# Try-catch in run-code
+playwright-cli run-code "async page => {
+ try {
+ await page.click('.maybe-missing', { timeout: 1000 });
+ return 'clicked';
+ } catch (e) {
+ return 'element not found';
+ }
+}"
+```
+
+## Complex Workflows
+
+```bash
+# Login and save state
+playwright-cli run-code "async page => {
+ await page.goto('https://example.com/login');
+ await page.fill('input[name=email]', '[email protected]');
+ await page.fill('input[name=password]', 'secret');
+ await page.click('button[type=submit]');
+ await page.waitForURL('**/dashboard');
+ await page.context().storageState({ path: 'auth.json' });
+ return 'Login successful';
+}"
+
+# Scrape data from multiple pages
+playwright-cli run-code "async page => {
+ const results = [];
+ for (let i = 1; i <= 3; i++) {
+ await page.goto(\`https://example.com/page/\${i}\`);
+ const items = await page.locator('.item').allTextContents();
+ results.push(...items);
+ }
+ return results;
+}"
+```
diff --git a/packages/playwright/src/skill/references/session-management.md b/packages/playwright/src/skill/references/session-management.md
new file mode 100644
index 0000000000..99ce2a833d
--- /dev/null
+++ b/packages/playwright/src/skill/references/session-management.md
@@ -0,0 +1,163 @@
+# Session Management
+
+Run multiple isolated browser sessions concurrently with state persistence.
+
+## Named Sessions
+
+Use `--session` flag to isolate browser contexts:
+
+```bash
+# Session 1: Authentication flow
+playwright-cli --session=auth open https://app.example.com/login
+
+# Session 2: Public browsing (separate cookies, storage)
+playwright-cli --session=public open https://example.com
+
+# Commands are isolated by session
+playwright-cli --session=auth fill e1 "[email protected]"
+playwright-cli --session=public snapshot
+```
+
+## Session Isolation Properties
+
+Each session has independent:
+- Cookies
+- LocalStorage / SessionStorage
+- IndexedDB
+- Cache
+- Browsing history
+- Open tabs
+
+## Session Commands
+
+```bash
+# List all sessions
+playwright-cli session-list
+
+# Stop a specific session
+playwright-cli session-stop mysession
+
+# Stop all sessions
+playwright-cli session-stop-all
+
+# Restart a session (useful after version updates)
+playwright-cli session-restart mysession
+
+# Delete session data (cookies, storage, etc.)
+playwright-cli session-delete mysession
+```
+
+## Environment Variable
+
+Set a default session name via environment variable:
+
+```bash
+export PLAYWRIGHT_CLI_SESSION="mysession"
+playwright-cli open example.com # Uses "mysession" automatically
+```
+
+## Common Patterns
+
+### Concurrent Scraping
+
+```bash
+#!/bin/bash
+# Scrape multiple sites concurrently
+
+# Start all sessions
+playwright-cli --session=site1 open https://site1.com &
+playwright-cli --session=site2 open https://site2.com &
+playwright-cli --session=site3 open https://site3.com &
+wait
+
+# Take snapshots from each
+playwright-cli --session=site1 snapshot
+playwright-cli --session=site2 snapshot
+playwright-cli --session=site3 snapshot
+
+# Cleanup
+playwright-cli --session=site1 close
+playwright-cli --session=site2 close
+playwright-cli --session=site3 close
+```
+
+### A/B Testing Sessions
+
+```bash
+# Test different user experiences
+playwright-cli --session=variant-a open "https://app.com?variant=a"
+playwright-cli --session=variant-b open "https://app.com?variant=b"
+
+# Compare
+playwright-cli --session=variant-a screenshot
+playwright-cli --session=variant-b screenshot
+```
+
+### Testing without persistent profile
+
+Use `--in-memory` flag to keep the browser profile in memory only:
+
+```bash
+# Session data won't persist to disk
+playwright-cli --in-memory open https://example.com
+```
+
+## Default Session
+
+When `--session` is omitted, commands use the default session:
+
+```bash
+# These use the same default session
+playwright-cli open https://example.com
+playwright-cli snapshot
+playwright-cli close # Closes default session
+```
+
+## Session Configuration
+
+Configure a session with specific settings:
+
+```bash
+# Configure session with config file
+playwright-cli --session=mysession config --config=playwright-cli.json
+
+# Configure session with specific browser
+playwright-cli --session=mysession config --browser=firefox
+
+# Configure session in headed mode
+playwright-cli --session=mysession config --headed
+
+# Restart session to apply changes
+playwright-cli session-restart mysession
+```
+
+## Best Practices
+
+### 1. Name Sessions Semantically
+
+```bash
+# GOOD: Clear purpose
+playwright-cli --session=github-auth open https://github.com
+playwright-cli --session=docs-scrape open https://docs.example.com
+
+# AVOID: Generic names
+playwright-cli --session=s1 open https://github.com
+```
+
+### 2. Always Clean Up
+
+```bash
+# Stop sessions when done
+playwright-cli session-stop auth
+playwright-cli session-stop scrape
+
+# Or stop all at once
+playwright-cli session-stop-all
+```
+
+### 3. Delete Stale Session Data
+
+```bash
+# Remove old session data to free disk space
+playwright-cli session-delete oldsession
+```
diff --git a/packages/playwright/src/skill/references/storage-state.md b/packages/playwright/src/skill/references/storage-state.md
new file mode 100644
index 0000000000..7cf83e8c4c
--- /dev/null
+++ b/packages/playwright/src/skill/references/storage-state.md
@@ -0,0 +1,373 @@
+# Storage Management
+
+Manage cookies, localStorage, sessionStorage, and browser storage state.
+
+## Storage State
+
+Save and restore complete browser state including cookies and storage.
+
+### Save Storage State
+
+```bash
+# Save to auto-generated filename (storage-state-{timestamp}.json)
+playwright-cli state-save
+
+# Save to specific filename
+playwright-cli state-save my-auth-state.json
+```
+
+### Restore Storage State
+
+```bash
+# Load storage state from file
+playwright-cli state-load my-auth-state.json
+
+# Reload page to apply cookies
+playwright-cli open https://example.com
+```
+
+### Storage State File Format
+
+The saved file contains:
+
+```json
+{
+ "cookies": [
+ {
+ "name": "session_id",
+ "value": "abc123",
+ "domain": "example.com",
+ "path": "/",
+ "expires": 1735689600,
+ "httpOnly": true,
+ "secure": true,
+ "sameSite": "Lax"
+ }
+ ],
+ "origins": [
+ {
+ "origin": "https://example.com",
+ "localStorage": [
+ { "name": "theme", "value": "dark" },
+ { "name": "user_id", "value": "12345" }
+ ]
+ }
+ ]
+}
+```
+
+## Cookies
+
+### Get All Cookies
+
+```bash
+playwright-cli run-code "async page => {
+ const cookies = await page.context().cookies();
+ return cookies;
+}"
+```
+
+### Get Cookies for Specific URL
+
+```bash
+playwright-cli run-code "async page => {
+ const cookies = await page.context().cookies('https://example.com');
+ return cookies;
+}"
+```
+
+### Add a Single Cookie
+
+```bash
+playwright-cli run-code "async page => {
+ await page.context().addCookies([{
+ name: 'session',
+ value: 'abc123',
+ domain: 'example.com',
+ path: '/'
+ }]);
+}"
+```
+
+### Add Multiple Cookies
+
+```bash
+playwright-cli run-code "async page => {
+ await page.context().addCookies([
+ {
+ name: 'session_id',
+ value: 'sess_abc123',
+ domain: 'example.com',
+ path: '/',
+ httpOnly: true,
+ secure: true
+ },
+ {
+ name: 'preferences',
+ value: JSON.stringify({ theme: 'dark', lang: 'en' }),
+ domain: 'example.com',
+ path: '/'
+ },
+ {
+ name: 'tracking_opt_out',
+ value: 'true',
+ domain: '.example.com',
+ path: '/'
+ }
+ ]);
+}"
+```
+
+### Add Cookie with Expiration
+
+```bash
+playwright-cli run-code "async page => {
+ const oneWeekFromNow = Date.now() / 1000 + 7 * 24 * 60 * 60;
+ await page.context().addCookies([{
+ name: 'remember_me',
+ value: 'token123',
+ domain: 'example.com',
+ path: '/',
+ expires: oneWeekFromNow
+ }]);
+}"
+```
+
+### Clear All Cookies
+
+```bash
+playwright-cli run-code "async page => {
+ await page.context().clearCookies();
+}"
+```
+
+### Clear Cookies by Name
+
+```bash
+playwright-cli run-code "async page => {
+ await page.context().clearCookies({ name: 'session_id' });
+}"
+```
+
+### Clear Cookies by Domain
+
+```bash
+playwright-cli run-code "async page => {
+ await page.context().clearCookies({ domain: 'example.com' });
+}"
+```
+
+### Clear Cookies by Path
+
+```bash
+playwright-cli run-code "async page => {
+ await page.context().clearCookies({ path: '/api' });
+}"
+```
+
+### Find Specific Cookie
+
+```bash
+playwright-cli run-code "async page => {
+ const cookies = await page.context().cookies();
+ const session = cookies.find(c => c.name === 'session_id');
+ return session ? session.value : null;
+}"
+```
+
+## Local Storage
+
+### Get All localStorage
+
+```bash
+playwright-cli run-code "async page => {
+ return await page.evaluate(() => {
+ const items = {};
+ for (let i = 0; i < localStorage.length; i++) {
+ const key = localStorage.key(i);
+ items[key] = localStorage.getItem(key);
+ }
+ return items;
+ });
+}"
+```
+
+### Get Single Value
+
+```bash
+playwright-cli run-code "async page => {
+ return await page.evaluate(() => localStorage.getItem('token'));
+}"
+```
+
+### Get and Parse JSON Value
+
+```bash
+playwright-cli run-code "async page => {
+ return await page.evaluate(() => {
+ const data = localStorage.getItem('user_settings');
+ return data ? JSON.parse(data) : null;
+ });
+}"
+```
+
+### Set Value
+
+```bash
+playwright-cli run-code "async page => {
+ await page.evaluate(() => localStorage.setItem('theme', 'dark'));
+}"
+```
+
+### Set JSON Value
+
+```bash
+playwright-cli run-code "async page => {
+ await page.evaluate(() => {
+ localStorage.setItem('user_settings', JSON.stringify({
+ theme: 'dark',
+ language: 'en',
+ notifications: true
+ }));
+ });
+}"
+```
+
+### Set Multiple Values
+
+```bash
+playwright-cli run-code "async page => {
+ await page.evaluate(() => {
+ localStorage.setItem('token', 'jwt_abc123');
+ localStorage.setItem('user_id', '12345');
+ localStorage.setItem('expires_at', Date.now() + 3600000);
+ });
+}"
+```
+
+### Remove Single Item
+
+```bash
+playwright-cli run-code "async page => {
+ await page.evaluate(() => localStorage.removeItem('token'));
+}"
+```
+
+### Clear All localStorage
+
+```bash
+playwright-cli run-code "async page => {
+ await page.evaluate(() => localStorage.clear());
+}"
+```
+
+## Session Storage
+
+### Get All sessionStorage
+
+```bash
+playwright-cli run-code "async page => {
+ return await page.evaluate(() => {
+ const items = {};
+ for (let i = 0; i < sessionStorage.length; i++) {
+ const key = sessionStorage.key(i);
+ items[key] = sessionStorage.getItem(key);
+ }
+ return items;
+ });
+}"
+```
+
+### Get Single Value
+
+```bash
+playwright-cli run-code "async page => {
+ return await page.evaluate(() => sessionStorage.getItem('form_data'));
+}"
+```
+
+### Set Value
+
+```bash
+playwright-cli run-code "async page => {
+ await page.evaluate(() => sessionStorage.setItem('step', '3'));
+}"
+```
+
+### Clear sessionStorage
+
+```bash
+playwright-cli run-code "async page => {
+ await page.evaluate(() => sessionStorage.clear());
+}"
+```
+
+## IndexedDB
+
+### List Databases
+
+```bash
+playwright-cli run-code "async page => {
+ return await page.evaluate(async () => {
+ const databases = await indexedDB.databases();
+ return databases;
+ });
+}"
+```
+
+### Delete Database
+
+```bash
+playwright-cli run-code "async page => {
+ await page.evaluate(() => {
+ indexedDB.deleteDatabase('myDatabase');
+ });
+}"
+```
+
+## Common Patterns
+
+### Authentication State Reuse
+
+```bash
+# Step 1: Login and save state
+playwright-cli open https://app.example.com/login
+playwright-cli snapshot
+playwright-cli fill e1 "[email protected]"
+playwright-cli fill e2 "password123"
+playwright-cli click e3
+
+# Save the authenticated state
+playwright-cli state-save auth.json
+
+# Step 2: Later, restore state and skip login
+playwright-cli state-load auth.json
+playwright-cli open https://app.example.com/dashboard
+# Already logged in!
+```
+
+### Save and Restore Roundtrip
+
+```bash
+# Set up authentication state
+playwright-cli open https://example.com
+playwright-cli eval "() => { document.cookie = 'session=abc123'; localStorage.setItem('user', 'john'); }"
+
+# Save state to file
+playwright-cli state-save my-session.json
+
+# ... later, in a new session ...
+
+# Restore state
+playwright-cli state-load my-session.json
+playwright-cli open https://example.com
+# Cookies and localStorage are restored!
+```
+
+## Security Notes
+
+- Never commit storage state files containing auth tokens
+- Add `*.auth-state.json` to `.gitignore`
+- Delete state files after automation completes
+- Use environment variables for sensitive data
+- Consider using `--in-memory` mode for sensitive operations
diff --git a/packages/playwright/src/skill/references/test-generation.md b/packages/playwright/src/skill/references/test-generation.md
new file mode 100644
index 0000000000..7a09df387f
--- /dev/null
+++ b/packages/playwright/src/skill/references/test-generation.md
@@ -0,0 +1,88 @@
+# Test Generation
+
+Generate Playwright test code automatically as you interact with the browser.
+
+## How It Works
+
+Every action you perform with `playwright-cli` generates corresponding Playwright TypeScript code.
+This code appears in the output and can be copied directly into your test files.
+
+## Example Workflow
+
+```bash
+# Start a session
+playwright-cli open https://example.com/login
+
+# Take a snapshot to see elements
+playwright-cli snapshot
+# Output shows: e1 [textbox "Email"], e2 [textbox "Password"], e3 [button "Sign In"]
+
+# Fill form fields - generates code automatically
+playwright-cli fill e1 "[email protected]"
+# Ran Playwright code:
+# await page.getByRole('textbox', { name: 'Email' }).fill('[email protected]');
+
+playwright-cli fill e2 "password123"
+# Ran Playwright code:
+# await page.getByRole('textbox', { name: 'Password' }).fill('password123');
+
+playwright-cli click e3
+# Ran Playwright code:
+# await page.getByRole('button', { name: 'Sign In' }).click();
+```
+
+## Building a Test File
+
+Collect the generated code into a Playwright test:
+
+```typescript
+import { test, expect } from '@playwright/test';
+
+test('login flow', async ({ page }) => {
+ // Generated code from playwright-cli session:
+ await page.goto('https://example.com/login');
+ await page.getByRole('textbox', { name: 'Email' }).fill('[email protected]');
+ await page.getByRole('textbox', { name: 'Password' }).fill('password123');
+ await page.getByRole('button', { name: 'Sign In' }).click();
+
+ // Add assertions
+ await expect(page).toHaveURL(/.*dashboard/);
+});
+```
+
+## Best Practices
+
+### 1. Use Semantic Locators
+
+The generated code uses role-based locators when possible, which are more resilient:
+
+```typescript
+// Generated (good - semantic)
+await page.getByRole('button', { name: 'Submit' }).click();
+
+// Avoid (fragile - CSS selectors)
+await page.locator('#submit-btn').click();
+```
+
+### 2. Explore Before Recording
+
+Take snapshots to understand the page structure before recording actions:
+
+```bash
+playwright-cli open https://example.com
+playwright-cli snapshot
+# Review the element structure
+playwright-cli click e5
+```
+
+### 3. Add Assertions Manually
+
+Generated code captures actions but not assertions. Add expectations in your test:
+
+```typescript
+// Generated action
+await page.getByRole('button', { name: 'Submit' }).click();
+
+// Manual assertion
+await expect(page.getByText('Success')).toBeVisible();
+```
diff --git a/packages/playwright/src/skill/references/tracing.md b/packages/playwright/src/skill/references/tracing.md
new file mode 100644
index 0000000000..7ce7babbdf
--- /dev/null
+++ b/packages/playwright/src/skill/references/tracing.md
@@ -0,0 +1,139 @@
+# Tracing
+
+Capture detailed execution traces for debugging and analysis. Traces include DOM snapshots, screenshots, network activity, and console logs.
+
+## Basic Usage
+
+```bash
+# Start trace recording
+playwright-cli tracing-start
+
+# Perform actions
+playwright-cli open https://example.com
+playwright-cli click e1
+playwright-cli fill e2 "test"
+
+# Stop trace recording
+playwright-cli tracing-stop
+```
+
+## Trace Output Files
+
+When you start tracing, Playwright creates a `traces/` directory with several files:
+
+### `trace-{timestamp}.trace`
+
+**Action log** - The main trace file containing:
+- Every action performed (clicks, fills, navigations)
+- DOM snapshots before and after each action
+- Screenshots at each step
+- Timing information
+- Console messages
+- Source locations
+
+### `trace-{timestamp}.network`
+
+**Network log** - Complete network activity:
+- All HTTP requests and responses
+- Request headers and bodies
+- Response headers and bodies
+- Timing (DNS, connect, TLS, TTFB, download)
+- Resource sizes
+- Failed requests and errors
+
+### `resources/`
+
+**Resources directory** - Cached resources:
+- Images, fonts, stylesheets, scripts
+- Response bodies for replay
+- Assets needed to reconstruct page state
+
+## What Traces Capture
+
+| Category | Details |
+|----------|---------|
+| **Actions** | Clicks, fills, hovers, keyboard input, navigations |
+| **DOM** | Full DOM snapshot before/after each action |
+| **Screenshots** | Visual state at each step |
+| **Network** | All requests, responses, headers, bodies, timing |
+| **Console** | All console.log, warn, error messages |
+| **Timing** | Precise timing for each operation |
+
+## Use Cases
+
+### Debugging Failed Actions
+
+```bash
+playwright-cli tracing-start
+playwright-cli open https://app.example.com
+
+# This click fails - why?
+playwright-cli click e5
+
+playwright-cli tracing-stop
+# Open trace to see DOM state when click was attempted
+```
+
+### Analyzing Performance
+
+```bash
+playwright-cli tracing-start
+playwright-cli open https://slow-site.com
+playwright-cli tracing-stop
+
+# View network waterfall to identify slow resources
+```
+
+### Capturing Evidence
+
+```bash
+# Record a complete user flow for documentation
+playwright-cli tracing-start
+
+playwright-cli open https://app.example.com/checkout
+playwright-cli fill e1 "4111111111111111"
+playwright-cli fill e2 "12/25"
+playwright-cli fill e3 "123"
+playwright-cli click e4
+
+playwright-cli tracing-stop
+# Trace shows exact sequence of events
+```
+
+## Trace vs Video vs Screenshot
+
+| Feature | Trace | Video | Screenshot |
+|---------|-------|-------|------------|
+| **Format** | .trace file | .webm video | .png/.jpeg image |
+| **DOM inspection** | Yes | No | No |
+| **Network details** | Yes | No | No |
+| **Step-by-step replay** | Yes | Continuous | Single frame |
+| **File size** | Medium | Large | Small |
+| **Best for** | Debugging | Demos | Quick capture |
+
+## Best Practices
+
+### 1. Start Tracing Before the Problem
+
+```bash
+# Trace the entire flow, not just the failing step
+playwright-cli tracing-start
+playwright-cli open https://example.com
+# ... all steps leading to the issue ...
+playwright-cli tracing-stop
+```
+
+### 2. Clean Up Old Traces
+
+Traces can consume significant disk space:
+
+```bash
+# Remove traces older than 7 days
+find .playwright-cli/traces -mtime +7 -delete
+```
+
+## Limitations
+
+- Traces add overhead to automation
+- Large traces can consume significant disk space
+- Some dynamic content may not replay perfectly
diff --git a/packages/playwright/src/skill/references/video-recording.md b/packages/playwright/src/skill/references/video-recording.md
new file mode 100644
index 0000000000..38391b37ad
--- /dev/null
+++ b/packages/playwright/src/skill/references/video-recording.md
@@ -0,0 +1,43 @@
+# Video Recording
+
+Capture browser automation sessions as video for debugging, documentation, or verification. Produces WebM (VP8/VP9 codec).
+
+## Basic Recording
+
+```bash
+# Start recording
+playwright-cli video-start
+
+# Perform actions
+playwright-cli open https://example.com
+playwright-cli snapshot
+playwright-cli click e1
+playwright-cli fill e2 "test input"
+
+# Stop and save
+playwright-cli video-stop demo.webm
+```
+
+## Best Practices
+
+### 1. Use Descriptive Filenames
+
+```bash
+# Include context in filename
+playwright-cli video-stop recordings/login-flow-2024-01-15.webm
+playwright-cli video-stop recordings/checkout-test-run-42.webm
+```
+
+## Tracing vs Video
+
+| Feature | Video | Tracing |
+|---------|-------|---------|
+| Output | WebM file | Trace file (viewable in Trace Viewer) |
+| Shows | Visual recording | DOM snapshots, network, console, actions |
+| Use case | Demos, documentation | Debugging, analysis |
+| Size | Larger | Smaller |
+
+## Limitations
+
+- Recording adds slight overhead to automation
+- Large recordings can consume significant disk space
diff --git a/tests/mcp/cli-config.spec.ts b/tests/mcp/cli-config.spec.ts
new file mode 100644
index 0000000000..75dc8a70de
--- /dev/null
+++ b/tests/mcp/cli-config.spec.ts
@@ -0,0 +1,54 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import fs from 'fs';
+import { test, expect } from './cli-fixtures';
+
+test('user-data-dir', async ({ cli, server }, testInfo) => {
+ const config = {
+ browser: {
+ userDataDir: testInfo.outputPath('my-data-dir'),
+ },
+ };
+ await fs.promises.writeFile(testInfo.outputPath('config.json'), JSON.stringify(config, null, 2));
+ await cli('open', `--config=config.json`, server.PREFIX);
+ expect(fs.existsSync(testInfo.outputPath('my-data-dir'))).toBe(true);
+});
+
+test('context options', async ({ cli, server }, testInfo) => {
+ const config = {
+ browser: {
+ contextOptions: {
+ viewport: { width: 800, height: 600 },
+ },
+ },
+ };
+ await fs.promises.writeFile(testInfo.outputPath('playwright-cli.json'), JSON.stringify(config, null, 2));
+ await cli('open', server.PREFIX);
+ const { output } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight');
+ expect(output).toContain('800x600');
+});
+
+test('isolated', async ({ cli, server }, testInfo) => {
+ const config = {
+ browser: {
+ isolated: true,
+ },
+ };
+ await fs.promises.writeFile(testInfo.outputPath('playwright-cli.json'), JSON.stringify(config, null, 2));
+ await cli('open', server.PREFIX);
+ expect(fs.existsSync(testInfo.outputPath('daemon', 'default-user-data'))).toBe(false);
+});
diff --git a/tests/mcp/cli-core.spec.ts b/tests/mcp/cli-core.spec.ts
new file mode 100644
index 0000000000..e8a483eb6c
--- /dev/null
+++ b/tests/mcp/cli-core.spec.ts
@@ -0,0 +1,190 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import fs from 'fs';
+import path from 'path';
+
+import { test, expect, eventsPage } from './cli-fixtures';
+
+test('open', async ({ cli, server }) => {
+ const { output, snapshot } = await cli('open', server.HELLO_WORLD);
+ expect(output).toContain(`### Page
+- Page URL: ${server.HELLO_WORLD}
+- Page Title: Title`);
+
+ expect(snapshot).toContain(`- generic [active] [ref=e1]: Hello, world!`);
+});
+
+test('close', async ({ cli, server }) => {
+ await cli('open', server.HELLO_WORLD);
+ const { output } = await cli('close');
+ expect(output).toContain(`Session 'default' stopped.`);
+});
+
+test('click button', async ({ cli, server }) => {
+ server.setContent('/', `<button>Submit</button>`, 'text/html');
+
+ const { snapshot } = await cli('open', server.PREFIX);
+ expect(snapshot).toContain(`- button "Submit" [ref=e2]`);
+
+ const { output, snapshot: clickSnapshot } = await cli('click', 'e2');
+ expect(clickSnapshot).toBeTruthy();
+ expect(output).toContain(`### Ran Playwright code
+\`\`\`js
+await page.getByRole('button', { name: 'Submit' }).click();
+\`\`\``);
+});
+
+test('click link', async ({ cli, server }) => {
+ server.setContent('/', `<a href="/hello-world">Hello, world!</a>`, 'text/html');
+
+ const { snapshot } = await cli('open', server.PREFIX);
+ expect(snapshot).toContain(`- link \"Hello, world!\" [ref=e2]`);
+
+ const { output: clickOutput, snapshot: clickSnapshot } = await cli('click', 'e2');
+ expect(clickOutput).toContain(`### Page
+- Page URL: ${server.HELLO_WORLD}
+- Page Title: Title`);
+ expect(clickSnapshot).toContain('Hello, world!');
+});
+
+test('dblclick', async ({ cli, server }) => {
+ server.setContent('/', eventsPage, 'text/html');
+ await cli('open', server.PREFIX);
+ const { snapshot } = await cli('dblclick', 'e2');
+ expect(snapshot).toContain('dblclick 0');
+});
+
+test('type', async ({ cli, server }) => {
+ server.setContent('/', `<input type=text>`, 'text/html');
+ const { snapshot } = await cli('open', server.PREFIX);
+ expect(snapshot).toContain(`- textbox [ref=e2]`);
+
+ const { snapshot: typeSnapshot } = await cli('type', 'Hello, world!', '--submit');
+ expect(typeSnapshot).toBe(`- textbox [ref=e2]`);
+});
+
+test('fill', async ({ cli, server }) => {
+ server.setContent('/', `<input type=text>`, 'text/html');
+ const { snapshot } = await cli('open', server.PREFIX);
+ expect(snapshot).toContain(`- textbox [ref=e2]`);
+
+ const { snapshot: fillSnapshot } = await cli('fill', 'e2', 'Hello, world!', '--submit');
+ expect(fillSnapshot).toBe(`- textbox [active] [ref=e2]: Hello, world!`);
+});
+
+test('hover', async ({ cli, server }) => {
+ server.setContent('/', eventsPage, 'text/html');
+ await cli('open', server.PREFIX);
+ await cli('hover', 'e2');
+ const { snapshot } = await cli('snapshot');
+ expect(snapshot).toContain('mouse move 50 50');
+});
+
+test('select', async ({ cli, server }) => {
+ server.setContent('/', `<select><option value="1">One</option><option value="2">Two</option></select>`, 'text/html');
+ await cli('open', server.PREFIX);
+ await cli('select', 'e2', 'Two');
+ const { snapshot } = await cli('snapshot');
+ expect(snapshot).toContain('- option "Two" [selected]');
+});
+
+test('check', async ({ cli, server, mcpBrowser }) => {
+ const active = mcpBrowser === 'webkit' && process.platform !== 'linux' ? '' : '[active] ';
+ server.setContent('/', `<input type="checkbox">`, 'text/html');
+ await cli('open', server.PREFIX);
+ await cli('check', 'e2');
+ const { snapshot } = await cli('snapshot');
+ expect(snapshot).toContain(`- checkbox [checked] ${active}[ref=e2]`);
+});
+
+test('uncheck', async ({ cli, server, mcpBrowser }) => {
+ const active = mcpBrowser === 'webkit' && process.platform !== 'linux' ? '' : '[active] ';
+ server.setContent('/', `<input type="checkbox" checked>`, 'text/html');
+ await cli('open', server.PREFIX);
+ await cli('uncheck', 'e2');
+ const { snapshot } = await cli('snapshot');
+ expect(snapshot).toContain(`- checkbox ${active}[ref=e2]`);
+});
+
+test('eval', async ({ cli, server }) => {
+ await cli('open', server.HELLO_WORLD);
+ const { output } = await cli('eval', '() => document.title');
+ expect(output).toContain('"Title"');
+});
+
+test('eval no arrow', async ({ cli, server }) => {
+ await cli('open', server.HELLO_WORLD);
+ const { output } = await cli('eval', 'document.title');
+ expect(output).toContain('"Title"');
+});
+
+test('eval <ref>', async ({ cli, server }) => {
+ server.setContent('/', `<button>Submit</button>`, 'text/html');
+ await cli('open', server.PREFIX);
+ const { output } = await cli('eval', 'element => element.nodeName', 'e2');
+ expect(output).toContain('"BUTTON"');
+});
+
+test('dialog-accept', async ({ cli, server }) => {
+ server.setContent('/', `<button onclick="alert('MyAlert')">Button</button>`, 'text/html');
+ await cli('open', server.PREFIX);
+ const { output } = await cli('click', 'e2');
+ expect(output).toContain('MyAlert');
+ expect(output).toContain('["alert" dialog with message "MyAlert"]: can be handled by dialog-accept or dialog-dismiss');
+ await cli('dialog-accept');
+ const { snapshot } = await cli('snapshot');
+ expect(snapshot).not.toContain('MyAlert');
+});
+
+test('dialog-dismiss', async ({ cli, server }) => {
+ server.setContent('/', `<button onclick="alert('MyAlert')">Button</button>`, 'text/html');
+ await cli('open', server.PREFIX);
+ const { output } = await cli('click', 'e2');
+ expect(output).toContain('MyAlert');
+ await cli('dialog-dismiss');
+ const { snapshot } = await cli('snapshot');
+ expect(snapshot).not.toContain('MyAlert');
+});
+
+test('dialog-accept <prompt>', async ({ cli, server }) => {
+ server.setContent('/', `<button onclick="document.body.textContent = prompt('MyAlert')">Button</button>`, 'text/html');
+ await cli('open', server.PREFIX);
+ await cli('click', 'e2');
+ await cli('dialog-accept', 'my reply');
+ const { snapshot } = await cli('snapshot');
+ expect(snapshot).toContain('my reply');
+});
+
+test('resize', async ({ cli, server }) => {
+ await cli('open', server.PREFIX);
+ await cli('resize', '480', '320');
+ const { output } = await cli('eval', '() => window.innerWidth + "x" + window.innerHeight');
+ expect(output).toContain('480x320');
+});
+
+test('snapshot', async ({ cli, server }, testInfo) => {
+ {
+ const { output } = await cli('open', server.HELLO_WORLD);
+ expect(output).toContain('.playwright-cli' + path.sep + 'page-');
+ }
+ {
+ const nested = testInfo.outputPath('nested');
+ await fs.promises.mkdir(nested, { recursive: true });
+ const { output } = await cli('open', server.HELLO_WORLD, { cwd: nested });
+ expect(output).toContain('..' + path.sep + '.playwright-cli' + path.sep + 'page-');
+ }
+});
diff --git a/tests/mcp/cli-devtools.spec.ts b/tests/mcp/cli-devtools.spec.ts
new file mode 100644
index 0000000000..09c60dcdac
--- /dev/null
+++ b/tests/mcp/cli-devtools.spec.ts
@@ -0,0 +1,95 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import path from 'path';
+import { test, expect } from './cli-fixtures';
+
+test('console', async ({ cli, server }) => {
+ await cli('open', server.PREFIX);
+ await cli('eval', 'console.log("Hello, world!")');
+ const { attachments } = await cli('console');
+ expect(attachments[0].name).toEqual('Console');
+ expect(attachments[0].data.toString()).toContain('Hello, world!');
+});
+
+test('console error', async ({ cli, server }) => {
+ await cli('open', server.PREFIX);
+ await cli('eval', 'console.log("log-level")');
+ await cli('eval', 'console.error("error-level")');
+ const { attachments } = await cli('console', 'error');
+ expect(attachments[0].name).toEqual('Console');
+ expect(attachments[0].data.toString()).not.toContain('log-level');
+ expect(attachments[0].data.toString()).toContain('error-level');
+});
+
+test('console --clear', async ({ cli, server }) => {
+ await cli('open', server.PREFIX);
+ await cli('eval', 'console.log("log-level")');
+ await cli('console', '--clear');
+ const { attachments } = await cli('console');
+ expect(attachments[0].name).toEqual('Console');
+ expect(attachments[0].data.toString()).not.toContain('log-level');
+});
+
+test('network', async ({ cli, server }) => {
+ await cli('open', server.PREFIX);
+ await cli('eval', '() => fetch("/hello-world")');
+ const { attachments } = await cli('network');
+ expect(attachments[0].name).toEqual('Network');
+ expect(attachments[0].data.toString()).not.toContain(`[GET] ${`${server.PREFIX}/`} => [200] OK`);
+ expect(attachments[0].data.toString()).toContain(`[GET] ${`${server.PREFIX}/hello-world`} => [200] OK`);
+});
+
+test('network --static', async ({ cli, server }) => {
+ await cli('open', server.PREFIX);
+ const { attachments } = await cli('network', '--static');
+ expect(attachments[0].name).toEqual('Network');
+ expect(attachments[0].data.toString()).toContain(`[GET] ${`${server.PREFIX}/`} => [200] OK`);
+});
+
+test('network --clear', async ({ cli, server }) => {
+ await cli('open', server.PREFIX);
+ await cli('eval', '() => fetch("/hello-world")');
+ await cli('network', '--clear');
+ const { attachments } = await cli('network');
+ expect(attachments[0].name).toEqual('Network');
+ expect(attachments[0].data.toString()).not.toContain(`[GET] ${`${server.PREFIX}/hello-world`} => [200] OK`);
+});
+
+test('tracing-start-stop', async ({ cli, server }) => {
+ await cli('open', server.HELLO_WORLD);
+ const { output } = await cli('tracing-start');
+ expect(output).toContain('Trace recording started');
+ await cli('eval', '() => fetch("/hello-world")');
+ const { output: tracingStopOutput } = await cli('tracing-stop');
+ expect(tracingStopOutput).toContain('Trace recording stopped');
+});
+
+test('video-start-stop', async ({ cli, server }) => {
+ await cli('open', server.HELLO_WORLD);
+ const { output: videoStartOutput } = await cli('video-start');
+ expect(videoStartOutput).toContain('Video recording started.');
+ await cli('open', server.HELLO_WORLD);
+ await cli('eval', `
+ async () => {
+ document.body.style.backgroundColor = "red";
+ for (let i = 0; i < 100; i++)
+ await new Promise(f => requestAnimationFrame(() => requestAnimationFrame(f)));
+ }
+ `);
+ const { output: videoStopOutput } = await cli('video-stop', '--filename=video.webm');
+ expect(videoStopOutput).toContain(`### Result\n- [Video](.playwright-cli${path.sep}video.webm)`);
+});
diff --git a/tests/mcp/cli-help.spec.ts b/tests/mcp/cli-help.spec.ts
new file mode 100644
index 0000000000..abb502a5e6
--- /dev/null
+++ b/tests/mcp/cli-help.spec.ts
@@ -0,0 +1,27 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { test, expect } from './cli-fixtures';
+
+test('prints help by default', async ({ cli }) => {
+ const { output } = await cli('--help');
+ expect(output).toContain('Usage: playwright-cli <command>');
+});
+
+test('prints command help', async ({ cli }) => {
+ const { output } = await cli('click', '--help');
+ expect(output).toContain('playwright-cli click <ref> [button]');
+});
diff --git a/tests/mcp/cli-isolated.spec.ts b/tests/mcp/cli-isolated.spec.ts
new file mode 100644
index 0000000000..67acfbdb64
--- /dev/null
+++ b/tests/mcp/cli-isolated.spec.ts
@@ -0,0 +1,39 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import fs from 'fs';
+import { test, expect } from './cli-fixtures';
+
+test('should not save user data', async ({ cli, server, mcpBrowser }, testInfo) => {
+ await cli('open', server.HELLO_WORLD, '--in-memory');
+ const dataDir = testInfo.outputPath('daemon', 'ud-default-' + mcpBrowser);
+ expect(fs.existsSync(dataDir)).toBe(false);
+ const sessionFile = testInfo.outputPath('daemon', 'default.session');
+ expect(fs.existsSync(sessionFile)).toBe(true);
+ const sessionOptions = JSON.parse(await fs.promises.readFile(sessionFile, 'utf-8'));
+ expect(sessionOptions).toEqual({
+ cli: {
+ isolated: true,
+ },
+ socketPath: expect.any(String),
+ userDataDirPrefix: expect.any(String),
+ version: expect.any(String),
+ });
+
+ const { output: listOutput } = await cli('session-list');
+ expect(listOutput).toContain('Sessions:');
+ expect(listOutput).toContain(' [running] default');
+});
diff --git a/tests/mcp/cli-keyboard.spec.ts b/tests/mcp/cli-keyboard.spec.ts
new file mode 100644
index 0000000000..c13137c8c4
--- /dev/null
+++ b/tests/mcp/cli-keyboard.spec.ts
@@ -0,0 +1,36 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { test, expect } from './cli-fixtures';
+
+test('press', async ({ cli, server }) => {
+ server.setContent('/', `<input type=text>`, 'text/html');
+ await cli('open', server.PREFIX);
+ await cli('click', 'e2');
+ await cli('press', 'h');
+ const { snapshot } = await cli('snapshot');
+ expect(snapshot).toBe(`- textbox [active] [ref=e2]: h`);
+});
+
+test('keydown keyup', async ({ cli, server }) => {
+ server.setContent('/', `<input type=text>`, 'text/html');
+ await cli('open', server.PREFIX);
+ await cli('click', 'e2');
+ await cli('keydown', 'h');
+ await cli('keyup', 'h');
+ const { snapshot } = await cli('snapshot');
+ expect(snapshot).toBe(`- textbox [active] [ref=e2]: h`);
+});
diff --git a/tests/mcp/cli-misc.spec.ts b/tests/mcp/cli-misc.spec.ts
new file mode 100644
index 0000000000..d0d9988bc2
--- /dev/null
+++ b/tests/mcp/cli-misc.spec.ts
@@ -0,0 +1,46 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { test, expect } from './cli-fixtures';
+
+test('daemon shuts down on browser launch failure', async ({ cli, server }) => {
+ const first = await cli('open', server.PREFIX, { env: { PLAYWRIGHT_MCP_EXECUTABLE_PATH: '/nonexistent/browser/path' } });
+ expect(first.output).toContain('Failed to launch');
+
+ const second = await cli('open', server.PREFIX);
+ expect(second.exitCode).toBe(0);
+ expect(second.output).toContain('Page URL');
+});
+
+test('old client', async ({ cli }) => {
+ await cli('open', { env: { PLAYWRIGHT_CLI_VERSION_FOR_TEST: '2.0.0' } });
+ const { output: output1 } = await cli('session-list');
+ expect(output1).toContain(' [running] default - v2.0.0, needs restart');
+
+ await cli('session-stop');
+ const { output: output2 } = await cli('session-list');
+ expect(output2).toContain(' [stopped] default - v2.0.0, needs restart');
+ await cli('session-delete');
+ const { output: output3 } = await cli('session-list');
+ expect(output3).toContain(' (no sessions)');
+});
+
+test('install', async ({ cli, server, mcpBrowser }) => {
+ test.skip(mcpBrowser !== 'chromium', 'Test only chromium');
+ await cli('open', server.HELLO_WORLD);
+ const { output } = await cli('install');
+ expect(output).toContain(`Browser ${mcpBrowser} installed.`);
+});
diff --git a/tests/mcp/cli-mouse.spec.ts b/tests/mcp/cli-mouse.spec.ts
new file mode 100644
index 0000000000..5ce183c07e
--- /dev/null
+++ b/tests/mcp/cli-mouse.spec.ts
@@ -0,0 +1,49 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { test, expect, eventsPage } from './cli-fixtures';
+
+test('mousemove', async ({ cli, server }) => {
+ server.setContent('/', eventsPage, 'text/html');
+ await cli('open', server.PREFIX);
+ await cli('mousemove', '45', '35');
+ const { snapshot } = await cli('snapshot');
+ expect(snapshot).toContain('mouse move 45 35');
+});
+
+test('mousedown mouseup', async ({ cli, server }) => {
+ server.setContent('/', eventsPage, 'text/html');
+ await cli('open', server.PREFIX);
+ await cli('mousemove', '45', '35');
+ await cli('mousedown');
+ await cli('mouseup');
+ const { snapshot } = await cli('snapshot');
+ expect(snapshot).toContain('mouse down');
+ expect(snapshot).toContain('mouse up');
+});
+
+test('mousewheel', async ({ cli, server }) => {
+ server.setContent('/', eventsPage, 'text/html');
+ await cli('open', server.PREFIX);
+ // click to focus
+ await cli('mousemove', '50', '50');
+ await cli('mousedown');
+ await cli('mouseup');
+
+ await cli('mousewheel', '10', '5');
+
+ await expect.poll(() => cli('snapshot').then(result => result.snapshot)).toContain('wheel 5 10');
+});
diff --git a/tests/mcp/cli-navigation.spec.ts b/tests/mcp/cli-navigation.spec.ts
new file mode 100644
index 0000000000..90141ffeb1
--- /dev/null
+++ b/tests/mcp/cli-navigation.spec.ts
@@ -0,0 +1,42 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { test, expect } from './cli-fixtures';
+
+test('go-back', async ({ cli, server }) => {
+ await cli('open', server.HELLO_WORLD);
+ await cli('open', server.PREFIX);
+ const { output } = await cli('go-back');
+ expect(output).toContain(`### Page
+- Page URL: ${server.HELLO_WORLD}
+- Page Title: Title`);
+});
+
+test('go-forward', async ({ cli, server }) => {
+ await cli('open', server.PREFIX);
+ await cli('open', server.HELLO_WORLD);
+ await cli('go-back');
+ const { output } = await cli('go-forward');
+ expect(output).toContain(`### Page
+- Page URL: ${server.HELLO_WORLD}
+- Page Title: Title`);
+});
+
+test('run-code', async ({ cli, server }) => {
+ await cli('open', server.HELLO_WORLD);
+ const { output } = await cli('run-code', '() => page.title()');
+ expect(output).toContain('"Title"');
+});
diff --git a/tests/mcp/cli-parsing.spec.ts b/tests/mcp/cli-parsing.spec.ts
new file mode 100644
index 0000000000..3b8a8c954e
--- /dev/null
+++ b/tests/mcp/cli-parsing.spec.ts
@@ -0,0 +1,47 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { test, expect } from './cli-fixtures';
+
+test('unknown option', async ({ cli, server }) => {
+ const { error, exitCode } = await cli('open', '--some-option', 'value', 'about:blank');
+ expect(exitCode).toBe(1);
+ expect(error).toContain(`error: unknown '--some-option' option`);
+});
+
+test('too many arguments', async ({ cli, server }) => {
+ const { error, exitCode } = await cli('open', 'foo', 'bar');
+ expect(exitCode).toBe(1);
+ expect(error).toContain(`error: too many arguments: expected 1, received 2`);
+});
+
+test('wrong option type', async ({ cli, server }) => {
+ const { error, exitCode } = await cli('type', 'foo', '--submit=bar');
+ expect(exitCode).toBe(1);
+ expect(error).toContain(`error: '--submit' option: expected boolean, received string`);
+});
+
+test('missing argument', async ({ cli, server }) => {
+ const { error, exitCode } = await cli('keyup');
+ expect(exitCode).toBe(1);
+ expect(error).toContain(`error: 'key' argument: expected string, received undefined`);
+});
+
+test('wrong argument type', async ({ cli, server }) => {
+ const { error, exitCode } = await cli('mousemove', '12', 'foo');
+ expect(exitCode).toBe(1);
+ expect(error).toContain(`error: 'y' argument: expected number, received string`);
+});
diff --git a/tests/mcp/cli-save-as.spec.ts b/tests/mcp/cli-save-as.spec.ts
new file mode 100644
index 0000000000..9e0bd0efbc
--- /dev/null
+++ b/tests/mcp/cli-save-as.spec.ts
@@ -0,0 +1,65 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import path from 'path';
+import { test, expect } from './cli-fixtures';
+
+test('screenshot', async ({ cli, server, mcpBrowser }) => {
+ await cli('open', server.HELLO_WORLD);
+ const { attachments } = await cli('screenshot');
+ expect(attachments[0].name).toEqual('Screenshot of viewport');
+ expect(attachments[0].data).toEqual(expect.any(Buffer));
+});
+
+test('screenshot <ref>', async ({ cli, server, mcpBrowser }) => {
+ server.setContent('/', `<div id="square" style="width: 100px; height: 100px; background-color: red;"></div>`, 'text/html');
+ await cli('open', server.PREFIX);
+ const { attachments } = await cli('screenshot', 'e2');
+ expect(attachments[0].name).toEqual('Screenshot of element');
+ expect(attachments[0].data).toEqual(expect.any(Buffer));
+});
+
+test('screenshot --full-page', async ({ cli, server, mcpBrowser }) => {
+ await cli('open', server.HELLO_WORLD);
+ const { attachments } = await cli('screenshot', '--full-page');
+ expect(attachments[0].name).toEqual('Screenshot of full page');
+ expect(attachments[0].data).toEqual(expect.any(Buffer));
+});
+
+test('screenshot --filename', async ({ cli, server, mcpBrowser }) => {
+ await cli('open', server.HELLO_WORLD);
+ const { output, attachments } = await cli('screenshot', '--filename=screenshot.png');
+ expect(output).toContain('.playwright-cli' + path.sep + 'screenshot.png');
+ expect(attachments[0].name).toEqual('Screenshot of viewport');
+ expect(attachments[0].data).toEqual(expect.any(Buffer));
+});
+
+test('pdf', async ({ cli, server, mcpBrowser }) => {
+ test.skip(mcpBrowser !== 'chromium' && mcpBrowser !== 'chrome', 'PDF is only supported in Chromium and Chrome');
+ await cli('open', server.HELLO_WORLD);
+ const { attachments } = await cli('pdf');
+ expect(attachments[0].name).toEqual('Page as pdf');
+ expect(attachments[0].data).toEqual(expect.any(Buffer));
+});
+
+test('pdf --filename', async ({ cli, server, mcpBrowser }) => {
+ test.skip(mcpBrowser !== 'chromium' && mcpBrowser !== 'chrome', 'PDF is only supported in Chromium and Chrome');
+ await cli('open', server.HELLO_WORLD);
+ const { output, attachments } = await cli('pdf', '--filename=pdf.pdf');
+ expect(output).toContain('.playwright-cli' + path.sep + 'pdf.pdf');
+ expect(attachments[0].name).toEqual('Page as pdf');
+ expect(attachments[0].data).toEqual(expect.any(Buffer));
+});
diff --git a/tests/mcp/cli-session.spec.ts b/tests/mcp/cli-session.spec.ts
new file mode 100644
index 0000000000..dbe8c07ab7
--- /dev/null
+++ b/tests/mcp/cli-session.spec.ts
@@ -0,0 +1,148 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import fs from 'fs';
+import { test, expect } from './cli-fixtures';
+
+test('session-list', async ({ cli, server }) => {
+ const { output: emptyOutput } = await cli('session-list');
+ expect(emptyOutput).toContain('Sessions:');
+ expect(emptyOutput).toContain(' (no sessions)');
+
+ await cli('open', server.HELLO_WORLD);
+
+ const { output: listOutput } = await cli('session-list');
+ expect(listOutput).toContain('Sessions:');
+ expect(listOutput).toContain(' [running] default');
+});
+
+test('session-stop', async ({ cli, server }) => {
+ await cli('open', server.HELLO_WORLD);
+
+ const { output } = await cli('session-stop');
+ expect(output).toContain(`Session 'default' stopped.`);
+
+ const { output: listOutput } = await cli('session-list');
+ expect(listOutput).toContain('[stopped] default');
+});
+
+test('session-stop named session', async ({ cli, server }) => {
+ await cli('open', '--session=mysession', server.HELLO_WORLD);
+
+ const { output } = await cli('session-stop', 'mysession');
+ expect(output).toContain(`Session 'mysession' stopped.`);
+});
+
+test('session-stop non-running session', async ({ cli }) => {
+ const { output } = await cli('session-stop', 'nonexistent');
+ expect(output).toContain(`Session 'nonexistent' is not running.`);
+});
+
+test('session-stop-all', async ({ cli, server }) => {
+ await cli('open', '--session=session1', server.HELLO_WORLD);
+ await cli('open', '--session=session2', server.HELLO_WORLD);
+
+ const { output: listBefore } = await cli('session-list');
+ expect(listBefore).toContain('[running] session1');
+ expect(listBefore).toContain('[running] session2');
+
+ await cli('session-stop-all');
+
+ const { output: listAfter } = await cli('session-list');
+ expect(listAfter).not.toContain('[running]');
+});
+
+test('session-delete', async ({ cli, server, mcpBrowser }, testInfo) => {
+ await cli('open', server.HELLO_WORLD);
+
+ const dataDir = testInfo.outputPath('daemon', 'ud-default-' + mcpBrowser);
+ expect(fs.existsSync(dataDir)).toBe(true);
+
+ const { output } = await cli('session-delete');
+ expect(output).toContain(`Deleted user data for session 'default'.`);
+
+ expect(fs.existsSync(dataDir)).toBe(false);
+});
+
+test('session-delete named session', async ({ cli, server, mcpBrowser }, testInfo) => {
+ await cli('open', '--session=mysession', server.HELLO_WORLD);
+
+ const dataDir = testInfo.outputPath('daemon', 'ud-mysession-' + mcpBrowser);
+ expect(fs.existsSync(dataDir)).toBe(true);
+
+ const { output } = await cli('session-delete', 'mysession');
+ expect(output).toContain(`Deleted user data for session 'mysession'.`);
+
+ expect(fs.existsSync(dataDir)).toBe(false);
+});
+
+test('session-delete non-existent session', async ({ cli }) => {
+ const { output } = await cli('session-delete', 'nonexistent');
+ expect(output).toContain(`No user data found for session 'nonexistent'.`);
+});
+
+test('session stops when browser exits', async ({ cli, server }) => {
+ await cli('open', server.HELLO_WORLD);
+
+ const { output: listBefore } = await cli('session-list');
+ expect(listBefore).toContain('[running] default');
+
+ // Close the browser - this will cause the daemon to exit so the command may fail
+ await cli('run-code', '() => page.context().browser().close()').catch(() => {});
+
+ await expect.poll(() => cli('session-list').then(r => r.output)).toContain('[stopped]');
+});
+
+test('session restart', async ({ cli, server }, testInfo) => {
+ const config = { browser: { contextOptions: { viewport: { width: 700, height: 500 } } } };
+ const configPath = testInfo.outputPath('config.json');
+ await fs.promises.writeFile(configPath, JSON.stringify(config, null, 2));
+ {
+ await cli('open', server.HELLO_WORLD, '--config=' + configPath);
+ const { output } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight');
+ expect(output).toContain('700x500');
+ await cli('close');
+ }
+ {
+ await cli('open', server.HELLO_WORLD);
+ const { output } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight');
+ expect(output).toContain('700x500');
+ }
+});
+
+test('config should work', async ({ cli, server }, testInfo) => {
+ // Start a session with default config
+ await cli('open', server.PREFIX);
+ const { output: beforeOutput } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight');
+ expect(beforeOutput).toContain('1280x720');
+
+ const config = {
+ browser: {
+ contextOptions: {
+ viewport: { width: 700, height: 500 },
+ },
+ },
+ };
+ const configPath = testInfo.outputPath('session-config.json');
+ await fs.promises.writeFile(configPath, JSON.stringify(config, null, 2));
+
+ const { output: configureOutput } = await cli('config', '--config=' + configPath);
+ expect(configureOutput).toContain(`- Using config file at \`session-config.json\`.`);
+
+ await cli('open', server.PREFIX);
+ const { output: afterOutput } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight');
+ expect(afterOutput).toContain('700x500');
+});
diff --git a/tests/mcp/cli-storage.spec.ts b/tests/mcp/cli-storage.spec.ts
new file mode 100644
index 0000000000..3b8aff3a3e
--- /dev/null
+++ b/tests/mcp/cli-storage.spec.ts
@@ -0,0 +1,135 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import fs from 'fs';
+import path from 'path';
+import { test, expect } from './cli-fixtures';
+
+test('state-save saves storage state to file', async ({ cli, server }, testInfo) => {
+ const config = { capabilities: ['storage'] };
+ await fs.promises.writeFile(testInfo.outputPath('playwright-cli.json'), JSON.stringify(config, null, 2));
+
+ await cli('open', server.EMPTY_PAGE);
+
+ // Set some cookies and localStorage
+ await cli('eval', '() => { document.cookie = "testCookie=testValue"; localStorage.setItem("testKey", "testValue"); }');
+
+ // Save storage state
+ const { output } = await cli('state-save');
+ expect(output).toContain('storage-state-');
+ expect(output).toContain('.json');
+
+ // Verify the file was created and contains the cookie
+ const outputDir = testInfo.outputPath('.playwright-cli');
+ const files = await fs.promises.readdir(outputDir);
+ const storageStateFile = files.find(f => f.startsWith('storage-state-'));
+ expect(storageStateFile).toBeDefined();
+
+ const content = JSON.parse(await fs.promises.readFile(path.join(outputDir, storageStateFile!), 'utf-8'));
+ expect(content.cookies).toContainEqual(expect.objectContaining({
+ name: 'testCookie',
+ value: 'testValue',
+ }));
+});
+
+test('state-save saves to custom filename', async ({ cli, server }, testInfo) => {
+ const config = { capabilities: ['storage'] };
+ await fs.promises.writeFile(testInfo.outputPath('playwright-cli.json'), JSON.stringify(config, null, 2));
+
+ await cli('open', server.EMPTY_PAGE);
+
+ const { output } = await cli('state-save', 'my-state.json');
+ expect(output).toContain('my-state.json');
+
+ const stateFile = testInfo.outputPath('.playwright-cli', 'my-state.json');
+ expect(await fs.promises.stat(stateFile).catch(() => null)).not.toBeNull();
+});
+
+test('state-load restores storage state from file', async ({ cli, server, mcpBrowser }, testInfo) => {
+ test.fixme(mcpBrowser === 'webkit', 'setStorageState is failing');
+
+ const config = { capabilities: ['storage'] };
+ await fs.promises.writeFile(testInfo.outputPath('playwright-cli.json'), JSON.stringify(config, null, 2));
+
+ const outputDir = testInfo.outputPath('.playwright-cli');
+ await fs.promises.mkdir(outputDir, { recursive: true });
+
+ // Create a storage state file
+ const storageState = {
+ cookies: [{
+ name: 'restoredCookie',
+ value: 'restoredValue',
+ domain: 'localhost',
+ path: '/',
+ }],
+ origins: [{
+ origin: server.PREFIX,
+ localStorage: [{
+ name: 'restoredKey',
+ value: 'restoredValue',
+ }],
+ }],
+ };
+
+ const stateFile = path.join(outputDir, 'state.json');
+ await fs.promises.writeFile(stateFile, JSON.stringify(storageState));
+
+ await cli('open', server.EMPTY_PAGE);
+
+ // Restore storage state
+ const { output } = await cli('state-load', stateFile);
+ expect(output).toContain('Storage state restored');
+
+ // Verify the cookie was restored
+ const { output: cookieResult } = await cli('eval', '() => document.cookie');
+ expect(cookieResult).toContain('restoredCookie=restoredValue');
+
+ // Verify localStorage was restored
+ const { output: localStorageResult } = await cli('eval', '() => localStorage.getItem("restoredKey")');
+ expect(localStorageResult).toContain('restoredValue');
+});
+
+test('state-save and state-load roundtrip', async ({ cli, server, mcpBrowser }, testInfo) => {
+ test.fixme(mcpBrowser === 'webkit', 'setStorageState is failing');
+
+ const config = { capabilities: ['storage'] };
+ await fs.promises.writeFile(testInfo.outputPath('playwright-cli.json'), JSON.stringify(config, null, 2));
+
+ await cli('open', server.EMPTY_PAGE);
+
+ // Set data
+ await cli('eval', '() => { document.cookie = "roundtripCookie=roundtripValue"; localStorage.setItem("roundtripKey", "roundtripValue"); }');
+
+ // Save storage state
+ await cli('state-save', 'roundtrip-state.json');
+
+ // Clear storage
+ await cli('eval', '() => { document.cookie = "roundtripCookie=; expires=Thu, 01 Jan 1970 00:00:00 GMT"; localStorage.clear(); }');
+
+ // Verify storage is cleared
+ const { output: clearedResult } = await cli('eval', '() => document.cookie + "|" + localStorage.getItem("roundtripKey")');
+ expect(clearedResult).toContain('|null');
+
+ // Restore storage state
+ await cli('state-load', testInfo.outputPath('.playwright-cli', 'roundtrip-state.json'));
+
+ // Reload to pick up cookies
+ await cli('open', server.EMPTY_PAGE);
+
+ // Verify storage was restored
+ const { output: restoredResult } = await cli('eval', '() => document.cookie + "|" + localStorage.getItem("roundtripKey")');
+ expect(restoredResult).toContain('roundtripCookie=roundtripValue');
+});
diff --git a/tests/mcp/cli.spec.ts b/tests/mcp/cli.spec.ts
deleted file mode 100644
index 92630db7dd..0000000000
--- a/tests/mcp/cli.spec.ts
+++ /dev/null
@@ -1,676 +0,0 @@
-/**
- * Copyright (c) Microsoft Corporation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import fs from 'fs';
-import path from 'path';
-import { test, expect, eventsPage } from './cli-fixtures';
-
-test.describe('help', () => {
- test('prints help by default', async ({ cli }) => {
- const { output } = await cli('--help');
- expect(output).toContain('Usage: playwright-cli <command>');
- });
-
- test('prints command help', async ({ cli }) => {
- const { output } = await cli('click', '--help');
- expect(output).toContain('playwright-cli click <ref> [button]');
- });
-});
-
-test.describe('core', () => {
- test('open', async ({ cli, server }) => {
- const { output, snapshot } = await cli('open', server.HELLO_WORLD);
- expect(output).toContain(`### Page
-- Page URL: ${server.HELLO_WORLD}
-- Page Title: Title`);
-
- expect(snapshot).toContain(`- generic [active] [ref=e1]: Hello, world!`);
- });
-
- test('close', async ({ cli, server }) => {
- await cli('open', server.HELLO_WORLD);
- const { output } = await cli('close');
- expect(output).toContain(`Session 'default' stopped.`);
- });
-
- test('click button', async ({ cli, server }) => {
- server.setContent('/', `<button>Submit</button>`, 'text/html');
-
- const { snapshot } = await cli('open', server.PREFIX);
- expect(snapshot).toContain(`- button "Submit" [ref=e2]`);
-
- const { output, snapshot: clickSnapshot } = await cli('click', 'e2');
- expect(clickSnapshot).toBeTruthy();
- expect(output).toContain(`### Ran Playwright code
-\`\`\`js
-await page.getByRole('button', { name: 'Submit' }).click();
-\`\`\``);
- });
-
- test('click link', async ({ cli, server }) => {
- server.setContent('/', `<a href="/hello-world">Hello, world!</a>`, 'text/html');
-
- const { snapshot } = await cli('open', server.PREFIX);
- expect(snapshot).toContain(`- link \"Hello, world!\" [ref=e2]`);
-
- const { output: clickOutput, snapshot: clickSnapshot } = await cli('click', 'e2');
- expect(clickOutput).toContain(`### Page
-- Page URL: ${server.HELLO_WORLD}
-- Page Title: Title`);
- expect(clickSnapshot).toContain('Hello, world!');
- });
-
- test('dblclick', async ({ cli, server }) => {
- server.setContent('/', eventsPage, 'text/html');
- await cli('open', server.PREFIX);
- const { snapshot } = await cli('dblclick', 'e2');
- expect(snapshot).toContain('dblclick 0');
- });
-
- test('type', async ({ cli, server }) => {
- server.setContent('/', `<input type=text>`, 'text/html');
- const { snapshot } = await cli('open', server.PREFIX);
- expect(snapshot).toContain(`- textbox [ref=e2]`);
-
- const { snapshot: typeSnapshot } = await cli('type', 'Hello, world!', '--submit');
- expect(typeSnapshot).toBe(`- textbox [ref=e2]`);
- });
-
- test('fill', async ({ cli, server }) => {
- server.setContent('/', `<input type=text>`, 'text/html');
- const { snapshot } = await cli('open', server.PREFIX);
- expect(snapshot).toContain(`- textbox [ref=e2]`);
-
- const { snapshot: fillSnapshot } = await cli('fill', 'e2', 'Hello, world!', '--submit');
- expect(fillSnapshot).toBe(`- textbox [active] [ref=e2]: Hello, world!`);
- });
-
- test('hover', async ({ cli, server }) => {
- server.setContent('/', eventsPage, 'text/html');
- await cli('open', server.PREFIX);
- await cli('hover', 'e2');
- const { snapshot } = await cli('snapshot');
- expect(snapshot).toContain('mouse move 50 50');
- });
-
- test('select', async ({ cli, server }) => {
- server.setContent('/', `<select><option value="1">One</option><option value="2">Two</option></select>`, 'text/html');
- await cli('open', server.PREFIX);
- await cli('select', 'e2', 'Two');
- const { snapshot } = await cli('snapshot');
- expect(snapshot).toContain('- option "Two" [selected]');
- });
-
- test('check', async ({ cli, server, mcpBrowser }) => {
- const active = mcpBrowser === 'webkit' && process.platform !== 'linux' ? '' : '[active] ';
- server.setContent('/', `<input type="checkbox">`, 'text/html');
- await cli('open', server.PREFIX);
- await cli('check', 'e2');
- const { snapshot } = await cli('snapshot');
- expect(snapshot).toContain(`- checkbox [checked] ${active}[ref=e2]`);
- });
-
- test('uncheck', async ({ cli, server, mcpBrowser }) => {
- const active = mcpBrowser === 'webkit' && process.platform !== 'linux' ? '' : '[active] ';
- server.setContent('/', `<input type="checkbox" checked>`, 'text/html');
- await cli('open', server.PREFIX);
- await cli('uncheck', 'e2');
- const { snapshot } = await cli('snapshot');
- expect(snapshot).toContain(`- checkbox ${active}[ref=e2]`);
- });
-
- test('eval', async ({ cli, server }) => {
- await cli('open', server.HELLO_WORLD);
- const { output } = await cli('eval', '() => document.title');
- expect(output).toContain('"Title"');
- });
-
- test('eval no arrow', async ({ cli, server }) => {
- await cli('open', server.HELLO_WORLD);
- const { output } = await cli('eval', 'document.title');
- expect(output).toContain('"Title"');
- });
-
- test('eval <ref>', async ({ cli, server }) => {
- server.setContent('/', `<button>Submit</button>`, 'text/html');
- await cli('open', server.PREFIX);
- const { output } = await cli('eval', 'element => element.nodeName', 'e2');
- expect(output).toContain('"BUTTON"');
- });
-
- test('dialog-accept', async ({ cli, server }) => {
- server.setContent('/', `<button onclick="alert('MyAlert')">Button</button>`, 'text/html');
- await cli('open', server.PREFIX);
- const { output } = await cli('click', 'e2');
- expect(output).toContain('MyAlert');
- expect(output).toContain('["alert" dialog with message "MyAlert"]: can be handled by dialog-accept or dialog-dismiss');
- await cli('dialog-accept');
- const { snapshot } = await cli('snapshot');
- expect(snapshot).not.toContain('MyAlert');
- });
-
- test('dialog-dismiss', async ({ cli, server }) => {
- server.setContent('/', `<button onclick="alert('MyAlert')">Button</button>`, 'text/html');
- await cli('open', server.PREFIX);
- const { output } = await cli('click', 'e2');
- expect(output).toContain('MyAlert');
- await cli('dialog-dismiss');
- const { snapshot } = await cli('snapshot');
- expect(snapshot).not.toContain('MyAlert');
- });
-
- test('dialog-accept <prompt>', async ({ cli, server }) => {
- server.setContent('/', `<button onclick="document.body.textContent = prompt('MyAlert')">Button</button>`, 'text/html');
- await cli('open', server.PREFIX);
- await cli('click', 'e2');
- await cli('dialog-accept', 'my reply');
- const { snapshot } = await cli('snapshot');
- expect(snapshot).toContain('my reply');
- });
-
- test('resize', async ({ cli, server }) => {
- await cli('open', server.PREFIX);
- await cli('resize', '480', '320');
- const { output } = await cli('eval', '() => window.innerWidth + "x" + window.innerHeight');
- expect(output).toContain('480x320');
- });
-});
-
-test.describe('navigation', () => {
- test('go-back', async ({ cli, server }) => {
- await cli('open', server.HELLO_WORLD);
- await cli('open', server.PREFIX);
- const { output } = await cli('go-back');
- expect(output).toContain(`### Page
-- Page URL: ${server.HELLO_WORLD}
-- Page Title: Title`);
- });
-
- test('go-forward', async ({ cli, server }) => {
- await cli('open', server.PREFIX);
- await cli('open', server.HELLO_WORLD);
- await cli('go-back');
- const { output } = await cli('go-forward');
- expect(output).toContain(`### Page
-- Page URL: ${server.HELLO_WORLD}
-- Page Title: Title`);
- });
-
- test('run-code', async ({ cli, server }) => {
- await cli('open', server.HELLO_WORLD);
- const { output } = await cli('run-code', '() => page.title()');
- expect(output).toContain('"Title"');
- });
-});
-
-test.describe('keyboard', () => {
- test('press', async ({ cli, server }) => {
- server.setContent('/', `<input type=text>`, 'text/html');
- await cli('open', server.PREFIX);
- await cli('click', 'e2');
- await cli('press', 'h');
- const { snapshot } = await cli('snapshot');
- expect(snapshot).toBe(`- textbox [active] [ref=e2]: h`);
- });
-
- test('keydown keyup', async ({ cli, server }) => {
- server.setContent('/', `<input type=text>`, 'text/html');
- await cli('open', server.PREFIX);
- await cli('click', 'e2');
- await cli('keydown', 'h');
- await cli('keyup', 'h');
- const { snapshot } = await cli('snapshot');
- expect(snapshot).toBe(`- textbox [active] [ref=e2]: h`);
- });
-});
-
-test.describe('mouse', () => {
- test('mousemove', async ({ cli, server }) => {
- server.setContent('/', eventsPage, 'text/html');
- await cli('open', server.PREFIX);
- await cli('mousemove', '45', '35');
- const { snapshot } = await cli('snapshot');
- expect(snapshot).toContain('mouse move 45 35');
- });
-
- test('mousedown mouseup', async ({ cli, server }) => {
- server.setContent('/', eventsPage, 'text/html');
- await cli('open', server.PREFIX);
- await cli('mousemove', '45', '35');
- await cli('mousedown');
- await cli('mouseup');
- const { snapshot } = await cli('snapshot');
- expect(snapshot).toContain('mouse down');
- expect(snapshot).toContain('mouse up');
- });
-
- test('mousewheel', async ({ cli, server }) => {
- server.setContent('/', eventsPage, 'text/html');
- await cli('open', server.PREFIX);
- // click to focus
- await cli('mousemove', '50', '50');
- await cli('mousedown');
- await cli('mouseup');
-
- await cli('mousewheel', '10', '5');
-
- await expect.poll(() => cli('snapshot').then(result => result.snapshot)).toContain('wheel 5 10');
- });
-});
-
-
-test.describe('save as', () => {
- test('screenshot', async ({ cli, server, mcpBrowser }) => {
- await cli('open', server.HELLO_WORLD);
- const { attachments } = await cli('screenshot');
- expect(attachments[0].name).toEqual('Screenshot of viewport');
- expect(attachments[0].data).toEqual(expect.any(Buffer));
- });
-
- test('screenshot <ref>', async ({ cli, server, mcpBrowser }) => {
- server.setContent('/', `<div id="square" style="width: 100px; height: 100px; background-color: red;"></div>`, 'text/html');
- await cli('open', server.PREFIX);
- const { attachments } = await cli('screenshot', 'e2');
- expect(attachments[0].name).toEqual('Screenshot of element');
- expect(attachments[0].data).toEqual(expect.any(Buffer));
- });
-
- test('screenshot --full-page', async ({ cli, server, mcpBrowser }) => {
- await cli('open', server.HELLO_WORLD);
- const { attachments } = await cli('screenshot', '--full-page');
- expect(attachments[0].name).toEqual('Screenshot of full page');
- expect(attachments[0].data).toEqual(expect.any(Buffer));
- });
-
- test('screenshot --filename', async ({ cli, server, mcpBrowser }) => {
- await cli('open', server.HELLO_WORLD);
- const { output, attachments } = await cli('screenshot', '--filename=screenshot.png');
- expect(output).toContain('.playwright-cli' + path.sep + 'screenshot.png');
- expect(attachments[0].name).toEqual('Screenshot of viewport');
- expect(attachments[0].data).toEqual(expect.any(Buffer));
- });
-
- test('pdf', async ({ cli, server, mcpBrowser }) => {
- test.skip(mcpBrowser !== 'chromium' && mcpBrowser !== 'chrome', 'PDF is only supported in Chromium and Chrome');
- await cli('open', server.HELLO_WORLD);
- const { attachments } = await cli('pdf');
- expect(attachments[0].name).toEqual('Page as pdf');
- expect(attachments[0].data).toEqual(expect.any(Buffer));
- });
-
- test('pdf --filename', async ({ cli, server, mcpBrowser }) => {
- test.skip(mcpBrowser !== 'chromium' && mcpBrowser !== 'chrome', 'PDF is only supported in Chromium and Chrome');
- await cli('open', server.HELLO_WORLD);
- const { output, attachments } = await cli('pdf', '--filename=pdf.pdf');
- expect(output).toContain('.playwright-cli' + path.sep + 'pdf.pdf');
- expect(attachments[0].name).toEqual('Page as pdf');
- expect(attachments[0].data).toEqual(expect.any(Buffer));
- });
-});
-
-test.describe('devtools', () => {
- test('console', async ({ cli, server }) => {
- await cli('open', server.PREFIX);
- await cli('eval', 'console.log("Hello, world!")');
- const { attachments } = await cli('console');
- expect(attachments[0].name).toEqual('Console');
- expect(attachments[0].data.toString()).toContain('Hello, world!');
- });
-
- test('console error', async ({ cli, server }) => {
- await cli('open', server.PREFIX);
- await cli('eval', 'console.log("log-level")');
- await cli('eval', 'console.error("error-level")');
- const { attachments } = await cli('console', 'error');
- expect(attachments[0].name).toEqual('Console');
- expect(attachments[0].data.toString()).not.toContain('log-level');
- expect(attachments[0].data.toString()).toContain('error-level');
- });
-
- test('console --clear', async ({ cli, server }) => {
- await cli('open', server.PREFIX);
- await cli('eval', 'console.log("log-level")');
- await cli('console', '--clear');
- const { attachments } = await cli('console');
- expect(attachments[0].name).toEqual('Console');
- expect(attachments[0].data.toString()).not.toContain('log-level');
- });
-
- test('network', async ({ cli, server }) => {
- await cli('open', server.PREFIX);
- await cli('eval', '() => fetch("/hello-world")');
- const { attachments } = await cli('network');
- expect(attachments[0].name).toEqual('Network');
- expect(attachments[0].data.toString()).not.toContain(`[GET] ${`${server.PREFIX}/`} => [200] OK`);
- expect(attachments[0].data.toString()).toContain(`[GET] ${`${server.PREFIX}/hello-world`} => [200] OK`);
- });
-
- test('network --static', async ({ cli, server }) => {
- await cli('open', server.PREFIX);
- const { attachments } = await cli('network', '--static');
- expect(attachments[0].name).toEqual('Network');
- expect(attachments[0].data.toString()).toContain(`[GET] ${`${server.PREFIX}/`} => [200] OK`);
- });
-
- test('network --clear', async ({ cli, server }) => {
- await cli('open', server.PREFIX);
- await cli('eval', '() => fetch("/hello-world")');
- await cli('network', '--clear');
- const { attachments } = await cli('network');
- expect(attachments[0].name).toEqual('Network');
- expect(attachments[0].data.toString()).not.toContain(`[GET] ${`${server.PREFIX}/hello-world`} => [200] OK`);
- });
-
- test('tracing-start-stop', async ({ cli, server }) => {
- await cli('open', server.HELLO_WORLD);
- const { output } = await cli('tracing-start');
- expect(output).toContain('Trace recording started');
- await cli('eval', '() => fetch("/hello-world")');
- const { output: tracingStopOutput } = await cli('tracing-stop');
- expect(tracingStopOutput).toContain('Trace recording stopped');
- });
-
- test('video-start-stop', async ({ cli, server }) => {
- await cli('open', server.HELLO_WORLD);
- const { output: videoStartOutput } = await cli('video-start');
- expect(videoStartOutput).toContain('Video recording started.');
- await cli('open', server.HELLO_WORLD);
- await cli('eval', `
- async () => {
- document.body.style.backgroundColor = "red";
- for (let i = 0; i < 100; i++)
- await new Promise(f => requestAnimationFrame(() => requestAnimationFrame(f)));
- }
- `);
- const { output: videoStopOutput } = await cli('video-stop', '--filename=video.webm');
- expect(videoStopOutput).toContain(`### Result\n- [Video](.playwright-cli${path.sep}video.webm)`);
- });
-});
-
-test.describe('config', () => {
- test('user-data-dir', async ({ cli, server }, testInfo) => {
- const config = {
- browser: {
- userDataDir: testInfo.outputPath('my-data-dir'),
- },
- };
- await fs.promises.writeFile(testInfo.outputPath('config.json'), JSON.stringify(config, null, 2));
- await cli('open', `--config=config.json`, server.PREFIX);
- expect(fs.existsSync(testInfo.outputPath('my-data-dir'))).toBe(true);
- });
-
- test('context options', async ({ cli, server }, testInfo) => {
- const config = {
- browser: {
- contextOptions: {
- viewport: { width: 800, height: 600 },
- },
- },
- };
- await fs.promises.writeFile(testInfo.outputPath('playwright-cli.json'), JSON.stringify(config, null, 2));
- await cli('open', server.PREFIX);
- const { output } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight');
- expect(output).toContain('800x600');
- });
-
- test('isolated', async ({ cli, server }, testInfo) => {
- const config = {
- browser: {
- isolated: true,
- },
- };
- await fs.promises.writeFile(testInfo.outputPath('playwright-cli.json'), JSON.stringify(config, null, 2));
- await cli('open', server.PREFIX);
- expect(fs.existsSync(testInfo.outputPath('daemon', 'default-user-data'))).toBe(false);
- });
-});
-
-test.describe('session', () => {
- test('session-list', async ({ cli, server }) => {
- const { output: emptyOutput } = await cli('session-list');
- expect(emptyOutput).toContain('Sessions:');
- expect(emptyOutput).toContain(' (no sessions)');
-
- await cli('open', server.HELLO_WORLD);
-
- const { output: listOutput } = await cli('session-list');
- expect(listOutput).toContain('Sessions:');
- expect(listOutput).toContain(' [running] default');
- });
-
- test('session-stop', async ({ cli, server }) => {
- await cli('open', server.HELLO_WORLD);
-
- const { output } = await cli('session-stop');
- expect(output).toContain(`Session 'default' stopped.`);
-
- const { output: listOutput } = await cli('session-list');
- expect(listOutput).toContain('[stopped] default');
- });
-
- test('session-stop named session', async ({ cli, server }) => {
- await cli('open', '--session=mysession', server.HELLO_WORLD);
-
- const { output } = await cli('session-stop', 'mysession');
- expect(output).toContain(`Session 'mysession' stopped.`);
- });
-
- test('session-stop non-running session', async ({ cli }) => {
- const { output } = await cli('session-stop', 'nonexistent');
- expect(output).toContain(`Session 'nonexistent' is not running.`);
- });
-
- test('session-stop-all', async ({ cli, server }) => {
- await cli('open', '--session=session1', server.HELLO_WORLD);
- await cli('open', '--session=session2', server.HELLO_WORLD);
-
- const { output: listBefore } = await cli('session-list');
- expect(listBefore).toContain('[running] session1');
- expect(listBefore).toContain('[running] session2');
-
- await cli('session-stop-all');
-
- const { output: listAfter } = await cli('session-list');
- expect(listAfter).not.toContain('[running]');
- });
-
- test('session-delete', async ({ cli, server, mcpBrowser }, testInfo) => {
- await cli('open', server.HELLO_WORLD);
-
- const dataDir = testInfo.outputPath('daemon', 'ud-default-' + mcpBrowser);
- expect(fs.existsSync(dataDir)).toBe(true);
-
- const { output } = await cli('session-delete');
- expect(output).toContain(`Deleted user data for session 'default'.`);
-
- expect(fs.existsSync(dataDir)).toBe(false);
- });
-
- test('session-delete named session', async ({ cli, server, mcpBrowser }, testInfo) => {
- await cli('open', '--session=mysession', server.HELLO_WORLD);
-
- const dataDir = testInfo.outputPath('daemon', 'ud-mysession-' + mcpBrowser);
- expect(fs.existsSync(dataDir)).toBe(true);
-
- const { output } = await cli('session-delete', 'mysession');
- expect(output).toContain(`Deleted user data for session 'mysession'.`);
-
- expect(fs.existsSync(dataDir)).toBe(false);
- });
-
- test('session-delete non-existent session', async ({ cli }) => {
- const { output } = await cli('session-delete', 'nonexistent');
- expect(output).toContain(`No user data found for session 'nonexistent'.`);
- });
-
- test('session stops when browser exits', async ({ cli, server }) => {
- await cli('open', server.HELLO_WORLD);
-
- const { output: listBefore } = await cli('session-list');
- expect(listBefore).toContain('[running] default');
-
- // Close the browser - this will cause the daemon to exit so the command may fail
- await cli('run-code', '() => page.context().browser().close()').catch(() => {});
-
- await expect.poll(() => cli('session-list').then(r => r.output)).toContain('[stopped]');
- });
-
- test('session restart', async ({ cli, server }, testInfo) => {
- const config = { browser: { contextOptions: { viewport: { width: 700, height: 500 } } } };
- const configPath = testInfo.outputPath('config.json');
- await fs.promises.writeFile(configPath, JSON.stringify(config, null, 2));
- {
- await cli('open', server.HELLO_WORLD, '--config=' + configPath);
- const { output } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight');
- expect(output).toContain('700x500');
- await cli('close');
- }
- {
- await cli('open', server.HELLO_WORLD);
- const { output } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight');
- expect(output).toContain('700x500');
- }
- });
-
- test('config should work', async ({ cli, server }, testInfo) => {
- // Start a session with default config
- await cli('open', server.PREFIX);
- const { output: beforeOutput } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight');
- expect(beforeOutput).toContain('1280x720');
-
- const config = {
- browser: {
- contextOptions: {
- viewport: { width: 700, height: 500 },
- },
- },
- };
- const configPath = testInfo.outputPath('session-config.json');
- await fs.promises.writeFile(configPath, JSON.stringify(config, null, 2));
-
- const { output: configureOutput } = await cli('config', '--config=' + configPath);
- expect(configureOutput).toContain(`- Using config file at \`session-config.json\`.`);
-
- await cli('open', server.PREFIX);
- const { output: afterOutput } = await cli('eval', 'window.innerWidth + "x" + window.innerHeight');
- expect(afterOutput).toContain('700x500');
- });
-});
-
-test.describe('versions', () => {
- test('old client', async ({ cli }) => {
- await cli('open', { env: { PLAYWRIGHT_CLI_VERSION_FOR_TEST: '2.0.0' } });
- const { output: output1 } = await cli('session-list');
- expect(output1).toContain(' [running] default - v2.0.0, needs restart');
-
- await cli('session-stop');
- const { output: output2 } = await cli('session-list');
- expect(output2).toContain(' [stopped] default - v2.0.0, needs restart');
- await cli('session-delete');
- const { output: output3 } = await cli('session-list');
- expect(output3).toContain(' (no sessions)');
- });
-});
-
-test.describe('parsing', () => {
- test('unknown option', async ({ cli, server }) => {
- const { error, exitCode } = await cli('open', '--some-option', 'value', 'about:blank');
- expect(exitCode).toBe(1);
- expect(error).toContain(`error: unknown '--some-option' option`);
- });
-
- test('too many arguments', async ({ cli, server }) => {
- const { error, exitCode } = await cli('open', 'foo', 'bar');
- expect(exitCode).toBe(1);
- expect(error).toContain(`error: too many arguments: expected 1, received 2`);
- });
-
- test('wrong option type', async ({ cli, server }) => {
- const { error, exitCode } = await cli('type', 'foo', '--submit=bar');
- expect(exitCode).toBe(1);
- expect(error).toContain(`error: '--submit' option: expected boolean, received string`);
- });
-
- test('missing argument', async ({ cli, server }) => {
- const { error, exitCode } = await cli('keyup');
- expect(exitCode).toBe(1);
- expect(error).toContain(`error: 'key' argument: expected string, received undefined`);
- });
-
- test('wrong argument type', async ({ cli, server }) => {
- const { error, exitCode } = await cli('mousemove', '12', 'foo');
- expect(exitCode).toBe(1);
- expect(error).toContain(`error: 'y' argument: expected number, received string`);
- });
-});
-
-test.describe('folders', () => {
- test('snapshot', async ({ cli, server }, testInfo) => {
- {
- const { output } = await cli('open', server.HELLO_WORLD);
- expect(output).toContain('.playwright-cli' + path.sep + 'page-');
- }
- {
- const nested = testInfo.outputPath('nested');
- await fs.promises.mkdir(nested, { recursive: true });
- const { output } = await cli('open', server.HELLO_WORLD, { cwd: nested });
- expect(output).toContain('..' + path.sep + '.playwright-cli' + path.sep + 'page-');
- }
- });
-});
-
-test.describe('isolated', () => {
- test('should not save user data', async ({ cli, server, mcpBrowser }, testInfo) => {
- await cli('open', server.HELLO_WORLD, '--isolated');
- const dataDir = testInfo.outputPath('daemon', 'ud-default-' + mcpBrowser);
- expect(fs.existsSync(dataDir)).toBe(false);
- const sessionFile = testInfo.outputPath('daemon', 'default.session');
- expect(fs.existsSync(sessionFile)).toBe(true);
- const sessionOptions = JSON.parse(await fs.promises.readFile(sessionFile, 'utf-8'));
- expect(sessionOptions).toEqual({
- cli: {
- isolated: true,
- },
- socketPath: expect.any(String),
- userDataDirPrefix: expect.any(String),
- version: expect.any(String),
- });
-
- const { output: listOutput } = await cli('session-list');
- expect(listOutput).toContain('Sessions:');
- expect(listOutput).toContain(' [running] default');
- });
-});
-
-test.describe('browser launch failure', () => {
- test('daemon shuts down on browser launch failure', async ({ cli, server }) => {
- const first = await cli('open', server.PREFIX, { env: { PLAYWRIGHT_MCP_EXECUTABLE_PATH: '/nonexistent/browser/path' } });
- expect(first.output).toContain('Failed to launch');
-
- const second = await cli('open', server.PREFIX);
- expect(second.exitCode).toBe(0);
- expect(second.output).toContain('Page URL');
- });
-});
-
-test.describe('install', () => {
- test('install', async ({ cli, server, mcpBrowser }) => {
- test.skip(mcpBrowser !== 'chromium', 'Test only chromium');
- await cli('open', server.HELLO_WORLD);
- const { output } = await cli('install');
- expect(output).toContain(`Browser ${mcpBrowser} installed.`);
- });
-});
diff --git a/utils/build/build.js b/utils/build/build.js
index 6a71fa3225..605ebb7d55 100644
--- a/utils/build/build.js
+++ b/utils/build/build.js
@@ -647,7 +647,7 @@ copyFiles.push({
});
copyFiles.push({
- files: 'packages/playwright/src/mcp/terminal/*.md',
+ files: 'packages/playwright/src/skill/**/*.md',
from: 'packages/playwright/src',
to: 'packages/playwright/lib',
});