# Browser Agents with Chrome DevTools MCP & Playwright

> Pair live Chrome DevTools MCP diagnostics (accessibility uid snapshots, LCP subpart traces, HttpOnly cookie forensics, and heap leak diffs) with deterministic Playwright E2E regression gates.

- **Topic:** [Agent Engineering](https://twelve-pages.com/topics/agent-engineering)
- **Web Edition:** https://twelve-pages.com/guides/agent-engineering/chrome-devtools-and-playwright-agents
- **Printable 12-Page PDF:** https://twelve-pages.com/guides/agent-engineering/chrome-devtools-and-playwright-agents/Chrome_DevTools_and_Playwright_Agents_Complete_How_To_Guide.pdf (3.9 MB)
- **Version:** v1.0 (Updated 2026-11)
- **Reading Time:** 12 minutes (12 pages)
- **Authorship:** AI-authored under human editorial direction & print QA (https://twelve-pages.com/editorial)
- **Tags:** chrome-devtools-mcp · Accessibility uid Snapshots · LCP & CWV Traces · Cookie & Auth Forensics · Heap Leak Diffing · Playwright CI Specs

## Core Takeaways

- **Live DevTools Telemetry:** Inspect accessibility uid nodes, authoritative CSS cascades, network headers, and 4-part LCP breakdowns in real time.
- **Zero-Flake E2E Gates:** Lock every verified bug fix into resilient Playwright specs with user-facing locators, auto-waiting assertions, and trace bundles.
- **Safe Auth & Security:** Diagnose HttpOnly sessions via network headers, run clean-slate GDPR checks in isolatedContext, and respect bot gates.

## 1. Live Telemetry Diagnosis vs. Deterministic Regression Gates

Traditional browser automation asks an agent to guess pixel coordinates from heavy screenshots. Modern browser engineering splits the job in two: Chrome DevTools MCP acts as your agent's live diagnostic microscope, while Playwright locks each verified fix into a repeatable CI regression gate.

### Quick Navigation

### Why Every Browser Agent Needs Both Surfaces

#### 1 DevTools MCP (Microscope)

Excels at **open-ended investigation**: reading accessibility `uid` trees, `get_css_styles` cascades, LCP waterfalls, `Set-Cookie` headers, and V8 heap retainers.

#### 2 Agent Edit Loop (Surgeon)

Turns telemetry receipts into targeted patches—removing `loading="lazy"` on hero images, fixing `SameSite` flags, or clearing leaked listeners.

#### 3 Playwright (Guardrail)

Encodes the proven fix into headless `.spec.ts` assertions with `getByRole` locators, visual diffs, and failure traces on every PR.

### Architecture: Closed-Loop Browser Agent Telemetry & Verification

#### The Token-Saving Golden Rule: Snapshots for Structure, Screenshots Only for Pixels

Passing a full-page PNG screenshot on every click wastes thousands of vision tokens and still hides ARIA names, computed CSS variables, and `HttpOnly` cookie headers. Start with text-based `take_snapshot` trees and targeted MCP queries, then reserve `take_screenshot` for visual layout checks.

## 2. Setup, Capability Flags & Tool Selection Matrix

By default, chrome-devtools-mcp launches automatically on the first tool call using a persistent Chrome profile. Unlock extension and memory forensics with opt-in CLI flags, then pair them with headless Playwright in your repo.

### 1. MCP Server Config & Opt-In Capability Flags

```
<code>{
  "mcpServers": {
    "chrome-devtools": {
      "command": "npx",
      "args": [
        "chrome-devtools-mcp@latest",
        "--categoryExtensions",
        "--memoryDebugging"
      ]
    }
  }
}</code>
```

**Restart required:** After adding `--categoryExtensions` (MV3 extension tools) or `--memoryDebugging` (heap diff tools), restart your MCP server or AI client. Note: `--slim` mode disables standard automation tools.

### 2. Isolated Contexts vs. Persistent Profile & Playwright

- **Persistent Profile (Default):** Great for reusing active developer logins, local dev servers, and live 401/403 session debugging via `list_pages` and `pageId`.
- **Clean-Slate `isolatedContext`:** Call `new_page` with `isolatedContext: "audit-1"` for zero-cookie GDPR banner checks or fresh auth flows; always call `close_page` afterward.
- **Playwright Setup:** Install `npm i -D @playwright/test` and run `npx playwright install chromium`. Tests execute headless by default.

```
<code>npx playwright test -g "checkout flow" --trace on</code>
```

### Tool Selection Matrix: Choosing the Right Browser Signal

| Tool / Surface | Primary Signal | Best Used For | Token Cost & Caveats |
| --- | --- | --- | --- |
| `take_snapshot` | Accessibility tree with unique element `uid`s | Navigating UI, clicking/filling controls, checking heading hierarchy, ARIA labels, and focus state. | **Lowest cost.** Stale `uid`s expire after DOM mutations; take a fresh snapshot after transitions. |
| `take_screenshot` | Rendered raster pixels (PNG/JPEG) | Visual layout checks, overlapping elements, gradient text legibility, and user-facing proof. | **High vision tokens.** Pass `filePath` to save large images to disk rather than inline payloads. |
| `get_css_styles` | Matched CSS rules, cascade & custom properties | Authoritative inspection of computed spacing, specificity conflicts, and theme variables. | **Targeted & exact.** Treat output as complete and authoritative before calling raw JS. |
| `evaluate_script` | Live JS execution in page or service worker | `PerformanceObserver` LCP entries, `cookieStore` checks, tap-target bounding boxes, or MV3 `serviceWorkerId`. | Pass `pageId` for tabs, OR `serviceWorkerId` (omitting `pageId`) for extensions. Fails on `HttpOnly` cookies. |
| **Playwright** `npx playwright test` | Deterministic assertions, visual diffs & traces | CI regression suites, `getByRole` auto-wait flows, `toHaveScreenshot()`, and Next.js `instant()` checks. | Run headless by default; target single files or `-g` filters during fast agent edit loops. |

#### Always Target Explicitly with `pageId`

Multi-tab sessions break when tools guess the active tab. Always capture `pageId` from `new_page` or `list_pages` and pass it explicitly to every page-scoped tool (`take_snapshot`, `press_key`, `performance_start_trace`, `lighthouse_audit`).

## 3. Annotated Tour: The Dual-Mode Browser Agent Cockpit

Effective browser agents correlate live DevTools MCP telemetry with repeatable Playwright test verdicts. Below is the unified mental workspace your agent inspects across accessibility trees, CSS cascades, LCP waterfalls, network headers, and CI traces.

Dual-Mode Browser Agent Cockpit • Target: http://localhost:3000/checkout

pageId: 4 • isolatedContext: "audit-checkout"

**ACCESSIBILITY SNAPSHOT TREE (`take_snapshot`)**

RootWebArea "Checkout • Acme" [uid=1_0]

banner -> heading[level=1] "Complete Order" [uid=1_4]

img "Hero Bundle" [uid=1_9] (LCP candidate)

textbox "Promo code" [uid=1_14] [focused]

button "Apply Coupon" [uid=1_15]

button "" [uid=1_19] <- missing accessible name!

**STYLE CASCADE (`get_css_styles`)**

.hero-img { width: 100%; height: var(--hero-h, 360px); }
 Matched: globals.css:42 • Computed: 1180&times;360px

**LCP SUBPART TRACE (`LCPBreakdown`)**

TTFB 0.4s

Load Delay 1.6s (!)

DL 0.3s

R

**NETWORK HEADERS (`get_network_request`)**

GET /api/orders -> 401 Unauthorized [reqid=48]

Req `Cookie`: (omitted — Domain=api.acme.test mismatch)

Res `Set-Cookie`: sid=9f2a; HttpOnly; Secure; SameSite=Lax

**NATIVE ISSUES (`types: ["issue"]`)**

[CookieIssue] SameSiteNoneInsecure • [A11y] FormFieldNoLabel

**PLAYWRIGHT CI GATE (`--trace on`)**

await page.getByLabel("Promo code").fill("SAVE20");

await page.getByRole("button", { name: "Apply Coupon" }).click();

await expect(page.getByText("-$20.00")).toBeVisible();

PASS 3/3 (1.4s headless) • trace.zip saved

### Numbered Cockpit Legend

**`pageId` & `isolatedContext` Bar:** Pins the exact browser tab ID and clean-slate session namespace so multi-tab audits never collide.

**Accessibility `uid` Tree:** Exposes screen-reader semantics, focus state, and missing accessible names in crisp text instead of raw DOM noise.

**Authoritative CSS Cascade:** Shows matched selectors, file lines, and CSS variables directly from DevTools without guessing computed styles.

**`LCPBreakdown` 4-Subpart Timeline:** Pinpoints whether latency sits in TTFB, resource load delay, download duration, or render blocking.

**`Cookie` / `Set-Cookie` Forensics:** Reveals `HttpOnly` values, `SameSite` rules, and domain/path mismatches invisible to client JS.

**Native Console Issue Stream:** Surfaces Chrome's built-in `CookieIssue`, contrast, and ARIA diagnostics via `types: ["issue"]`.

**Playwright `--trace on` Runner:** Turns verified discoveries into headless user-facing locator specs with downloadable time-travel traces.

#### Why This Dual View Eliminates Guesswork

When a Playwright assertion times out on `getByRole("button", { name: "Close" })`, DevTools MCP's `take_snapshot` immediately proves why: the icon button rendered as `button ""` with no `aria-label`. Fix the label, re-snapshot, and watch Playwright turn green.

## 4. Token-Lean Navigation, uid Snapshots & A11y Audits

Disciplined browser agents follow one strict sequence: navigate → wait → snapshot → interact. Because take_snapshot returns the browser's accessibility tree rather than raw HTML, it serves double duty as your fastest interaction map and your semantic screen-reader truth.

*[Illustration: Architectural Prism Distilling a Glowing Web Interface Plane Into a Clean Semantic Accessibility Node Tree]*

**1. NAVIGATE & WAIT:**
`navigate_page` then `wait_for` target text before reading.

**2. SNAPSHOT & ACT BY `uid`:**
`click`/`fill` with `includeSnapshot: false` to save tokens.

**3. OFFLOAD HEAVY OUTPUT:**
Save screenshots/reports with `filePath` & `outputDirPath`.

#### 1 Lighthouse + Native Issues First

Run `lighthouse_audit` with `mode: "navigation"` and `outputDirPath: "/tmp/lh-report"`. **Never** read the multi-megabyte JSON file into context—filter failing audits with Node:

```
<code>node -e "const r=require('/tmp/lh-report/report.json');
Object.values(r.audits).filter(a=>a.score!==null&&a.score<1)
.forEach(a=>console.log(a.id, a.details?.items?.length))"</code>
```

Pair with `list_console_messages` using `types: ["issue"]` and `includePreservedMessages: true` to catch missing labels and invalid ARIA emitted at load time.

#### 2 Keyboard, Labels & 48&times;48px Targets

- **Focus Traps:** Call `press_key("Tab")` or `"Shift+Tab"`, then `take_snapshot` to confirm the focused node moved cleanly inside open modals.
- **DOM vs. Visual Order:** Compare heading hierarchy (`h1` -> `h2`, no skipped levels) in `take_snapshot` against `take_screenshot` to spot CSS float/order mismatches.
- **Tap Targets (48&times;48px):** Pass an interactive element's `uid` to `evaluate_script`: `el => el.getBoundingClientRect()` to verify mobile target sizing.
- **Orphaned Inputs:** Query inputs missing `label[for]`, wrapping `<label>`, or `aria-label`.

#### Hiding Rules Matter: `opacity: 0` vs. `display: none` vs. `aria-hidden`

Visually hiding a control with `opacity: 0` leaves it exposed to keyboard focus and screen readers, whereas `display: none` or `aria-hidden="true"` removes it from the accessibility tree. When pixels and assistive tech disagree, trust `take_snapshot`.

## 5. Core Web Vitals, LCP Forensics & Diagnostic Prompt Anatomy

Good Largest Contentful Paint (LCP) stays at or below 2.5 seconds (2.5–4.0s needs improvement; >4.0s is poor). Because compressing an image will not fix a slow server or blocked stylesheet, always decompose LCP into its four sequential subparts first.

*[Illustration: Dark Emerald Telemetry Visualization Showing Four Sequential Luminous LCP Timing Bars Above a Glassy Memory Retainer Graph]*

**1. TTFB (~40%):**
Edge cache HTML; cut server redirects.

**2. LOAD DELAY (<10%):**
Drop `loading="lazy"`; add `fetchpriority="high"`.

**3. LOAD DURATION (~40%):**
Serve AVIF/WebP + `srcset` on CDN.

**4. RENDER DELAY (<10%):**
Defer head scripts; inline critical CSS; SSR.

#### 1 5-Step LCP Trace Workflow

1. **Record:** `navigate_page(pageId)` -> `performance_start_trace(pageId, reload: true, autoStop: true)`.
2. **Analyze Insights:** Call `performance_analyze_insight` with the insight set ID for `LCPBreakdown`, `DocumentLatency`, `RenderBlocking`, and `LCPDiscovery`.
3. **Identify Element:** Query `PerformanceObserver` (`largest-contentful-paint`, `buffered: true`) via `evaluate_script` to grab tag & `url`.
4. **Waterfall & HTML:** Check `list_network_requests(resourceTypes: ["Image", "Font"])`, spot viewport `img[loading="lazy"]`, and add `<link rel="preload" fetchpriority="high">` when needed.
5. **Stress-Test:** Re-verify under `emulate(pageId, networkConditions: "Fast 3G", cpuThrottlingRate: 4)`.

#### 2 Color-Coded Browser Agent Prompt Anatomy

Every color block encodes one essential constraint so the agent gathers hard telemetry without burning tokens or touching restricted gates:

Open http://localhost:3000/pricing in a fresh isolatedContext and pin its pageId. Run performance_start_trace (reload: true, autoStop: true) then LCPBreakdown + RenderBlocking. Identify the LCP image URL and cut Resource Load Delay under 10%. Never read raw JSON dumps or bypass auth/CAPTCHA walls; use includeSnapshot: false on actions. After patching, re-run the trace and lock the check into Playwright.

Target URL Context & pageId MCP Sequence Metric Goal Token/Safety Guard CI Verification

## 6. Auth Cookies, Consent Conformance & Memory Leak Hunting

Two browser bugs fool naive agents every week: trying to read or delete HttpOnly session cookies from client JavaScript, and reading raw multi-megabyte .heapsnapshot JSON files instead of letting Chrome DevTools MCP compute retainer diffs.

#### 1 Why Client JS Fails on `HttpOnly` Cookies

Browsers hide `HttpOnly` cookies from `cookieStore` and `document.cookie`. Calling `cookieStore.delete()` on an `HttpOnly` token **silently fails**! Always inspect the network layer instead:

- **401/403 Auth Triage:** Call `list_network_requests(includePreservedRequests: true)`, then `get_network_request(reqid)` to check the outgoing `Cookie` header and login `Set-Cookie` flags (`Path`, `Domain`, `Secure`, `SameSite`, `Expires`).
- **Native Warnings:** Run `list_console_messages(types: ["issue"], includePreservedMessages: true)` for `SameSiteNoneInsecure`, `SchemefulSameSite`, or CHIPS `PartitionedCookies` alerts.
- **Client Cookies Only:** Use `async () => await cookieStore.getAll()` on Secure Contexts (`https://` or `localhost`).

#### 2 Clean-Slate GDPR & Consent Revocation

Never test cookie consent banners inside a dirty default tab full of cached analytics tokens. Run a repeatable 6-step clean-slate audit:

1. Spawn `new_page(url, isolatedContext: "consent-test-1")`.
2. Record baseline via `cookieStore.getAll()` and confirm zero premature tracking beacons in `list_network_requests`.
3. Snapshot & click **Reject All**; verify only strictly necessary cookies remain.
4. Test **Revocation:** Open privacy settings, revoke consent, and confirm non-essential cookies clear and beacons stop firing.
5. Always finish with `close_page` so residual cookies never leak into later tests.

### 3. The 3-Snapshot Memory Leak Workflow (Requires `--memoryDebugging`)

| Phase | Exact MCP Tool Sequence | What to Inspect & Why |
| --- | --- | --- |
| **1. Capture 3 States** | `take_heapsnapshot` at **Baseline** -> repeat suspect user action **10&times;** -> capture **Target** -> revert UI -> capture **Final**. | Repeating an open/close or route change 10&times; amplifies tiny leaks into unmistakable delta spikes. |
| **2. Diff & Drill** | `get_heapsnapshot_summary` -> `compare_heapsnapshots` (summary first, then suspicious `classIndex`). | Find object classes whose retained size and count keep growing even after reverting the UI. |
| **3. Trace Retainers** | `get_heapsnapshot_details` / `get_heapsnapshot_class_nodes` with `filterName`; then `get_heapsnapshot_retaining_paths` & `get_heapsnapshot_dominators`. | Filter directly for `objectsRetainedByDetachedDomNodes`, `objectsRetainedByEventHandlers`, `objectsRetainedByContexts`, or `objectsRetainedByConsole`. |
| **4. Teardown** | Call `close_heapsnapshot` for every loaded snapshot once root cause is traced. | Releases gigabytes of parsed heap graph memory held inside the MCP server process. |

#### Before Nulling Detached DOM Nodes: Check If Caching Is Intentional

Detached DOM trees are not always bugs—some apps intentionally cache off-screen route views for instant back navigation. Flag detached node retainer paths to the user and confirm before stripping cached references.

## 7. Playwright Agent Mastery: Locators, Traces, MV3 & Instant UI

Once DevTools MCP proves what is broken and verifies your patch, encode the behavior in Playwright so it can never silently regress. Follow five strict rules to keep agent-written specs fast, readable, and completely flake-free.

#### 1 Five Non-Negotiable Playwright Rules

1. **Headless by default:** Run `npx playwright test` headless; pass `--headed` only when explicitly requested.
2. **Targeted runs:** Iterate fast with a file path or `-g "user logs in"` instead of running the whole suite on small edits.
3. **Trace on failure:** Run with `--trace on` or inspect `test-results/` artifacts when a spec fails.
4. **User-facing locators:** Prefer `getByRole`, `getByLabel`, `getByText`, and `getByTestId` over brittle CSS or XPath.
5. **Zero arbitrary sleeps:** Use web-first auto-waiting assertions like `await expect(locator).toBeVisible()`—never `page.waitForTimeout()`.

#### 2 Visual Snapshots & Next.js `instant()`

```
<code>// Resilient locator + visual regression + instant shell gate
await page.getByRole("button", { name: "Publish" }).click();
await expect(page.getByRole("status")).toContainText("Live");
await expect(page.getByTestId("hero-card")).toHaveScreenshot();

// Refresh golden PNGs intentionally after UI changes:
// npx playwright test -u</code>
```

In Next.js apps using Cache Components or Partial Prefetching, pair Playwright with `@next/playwright` `instant()` checks to verify that critical static shell UI renders immediately on both hard loads and soft client navigations without blocking Suspense stalls.

### Testing Chrome MV3 Extensions with DevTools MCP (`--categoryExtensions`)

**Step 1 • Install & Trigger**

Call `install_extension` with the unpacked build directory, grab the ID from the response or `list_extensions`, and open popups or side panels via `trigger_extension_action`.

**Step 2 • Service Worker Eval**

With `--categoryExtensions` active, call `evaluate_script` passing `serviceWorkerId` while **omitting `pageId` and `args`** to inspect MV3 background storage or alarms.

**Step 3 • Content Script Check**

Navigate a regular page tab with `pageId` and call `take_snapshot` to confirm injected badges, buttons, or overlays appear cleanly in the accessibility tree.

#### Service Worker vs. Page Context Rule

Never pass both `pageId` and `serviceWorkerId` in the same `evaluate_script` call. Pass `pageId` when inspecting a tab's DOM, and pass `serviceWorkerId` (omitting `pageId`) when inspecting extension background state.

## 8. 5 Real-World Copy-Paste Browser Agent Recipes

Drop these five battle-tested workflows directly into your agent instructions or repository test suite to eliminate performance bottlenecks, auth cookie mysteries, consent leaks, detached DOM bloat, and flaky E2E runs.

| Scenario & Goal | Copy-Paste MCP Sequence / Playwright Snippet | Verification Outcome |
| --- | --- | --- |
| **1. LCP Subpart Bottleneck Audit** Pinpoint why hero paint > 2.5s | `navigate_page(pageId, url)` -> `performance_start_trace(pageId, reload: true, autoStop: true)` -> `performance_analyze_insight(pageId, insightSetId, "LCPBreakdown")` -> `evaluate_script` audit for viewport `img[loading="lazy"]` -> patch with `fetchpriority="high"`. | Confirm Resource Load Delay drops below `10%` and total LCP clears `≤ 2.5s` on re-trace and `Fast 3G` emulation. |
| **2. 401/403 `HttpOnly` Cookie Forensics** Debug missing auth headers | `list_network_requests(pageId, includePreservedRequests: true)` -> `get_network_request(pageId, reqid)` on failing `401`/`302` -> inspect request `Cookie` and login response `Set-Cookie` + `list_console_messages(types: ["issue"])`. | Pinpoint exact `Domain`, `Path`, `SameSite`, or `Secure` mismatch without touching client JS `cookieStore`. |
| **3. Clean-Slate GDPR Consent Audit** Prove zero tracking before/after opt-out | `new_page(url, isolatedContext: "consent-test-1")` -> `evaluate_script("async () => await cookieStore.getAll()")` -> `take_snapshot` -> `click` Reject All -> re-check `cookieStore.getAll()` & beacons -> test Revoke -> `close_page`. | Zero non-essential cookies or tracking beacons before accept, after decline, and after preference revocation. |
| **4. 10&times; Repeat Heap Leak Diff** Isolate detached DOM & listener leaks | `take_heapsnapshot(pageId, filePath: "/tmp/base.heapsnapshot")` -> repeat open/close 10&times; -> take `target` & `reverted` -> `compare_heapsnapshots` -> `get_heapsnapshot_details(filterName: "objectsRetainedByDetachedDomNodes")` -> `close_heapsnapshot`. | Exact retaining chain identifies unremoved listeners or closures; memory stabilizes after patching and re-diffing. |
| **5. Flake-Free Playwright Spec** Lock verified behavior into CI | `test("saves profile", async ({ page }) => { await page.goto("/settings"); await page.getByLabel("Display name").fill("Ada"); await page.getByRole("button", { name: "Save" }).click(); await expect(page.getByRole("status")).toHaveText("Saved"); });` | Runs headless in `npx playwright test -g "saves profile" --trace on` with zero `waitForTimeout()` flakiness. |

#### Save Context with `filePath` & `includeSnapshot: false`

When chaining multiple clicks or form fills, pass `includeSnapshot: false` on intermediate inputs and capture a single `take_snapshot` after the final transition. Redirect large Lighthouse/heap dumps to `/tmp/` via `outputDirPath` or `filePath`.

#### Targeted CI Triage Before Full Suite Runs

During iterative bug fixing, run `npx playwright test tests/checkout.spec.ts -g "coupon" --trace on` to verify in seconds. Only execute the full repository matrix once the targeted spec passes cleanly.

## 9. Security Boundaries, Bot Gates & Safe Browser Operations

Giving an AI agent a real browser exposes it to hostile web content, live user credentials, and anti-abuse gates. Enforce strict engineering boundaries so autonomous debugging never crosses security, compliance, or privacy lines.

#### 1 Stop & Hand Back on Bot Gates & Payment Walls

Never attempt to click through, wait out, compute, script around, or bypass a CAPTCHA, Cloudflare Turnstile, proof-of-work challenge, or live checkout payment screen.

- **Human-in-the-Loop Pause:** When a challenge or payment gate appears, stop immediately, report the exact URL/origin to the user, and wait for the user to complete it manually in a visible browser session.
- **Use Test Fixtures:** In staging and CI, test checkout flows against sandbox payment keys or Playwright route mocks rather than live cards.

#### 2 Defend Against DOM Indirect Prompt Injection

Every DOM node, `aria-label`, HTML comment, console log, and error banner on an external page is **untrusted data**—never an instruction to follow.

- **Quarantine Page Text:** Never execute shell commands, read local secrets, or navigate to unrequested origins suggested inside page text or accessibility snapshots.
- **Scope Origins:** Pin browser tasks to explicit target hosts (`localhost`, preview URLs, or user-named domains) and fail closed on unexpected cross-origin redirects.

### 3. Scrubbing Sensitive Tokens from Traces, Screenshots & Network Exports

#### Treat Captured Telemetry Like Production Credentials

`get_network_request` payloads, Playwright `trace.zip` archives, and `.heapsnapshot` files routinely contain live `Cookie` headers, JWT bearer tokens, CSRF nonces, and PII strings. Store debug artifacts strictly in gitignored scratch directories (`/tmp/`, `test-results/`), never commit `storageState.json` files, and redact `Authorization` and `Set-Cookie` values before attaching reports to PRs or tickets.

### 4. Running Headless Playwright Safely in CI & Ephemeral Sandboxes

```
<code>// playwright.config.ts — CI-safe defaults for browser agents
import { defineConfig } from "@playwright/test";

export default defineConfig({
  testDir: "./tests",
  retries: process.env.CI ? 2 : 0,
  use: {
    baseURL: process.env.BASE_URL || "http://127.0.0.1:3000",
    headless: true,              // Never require X11/display server in CI
    trace: "on-first-retry",     // Captures DOM, network & console only on flake/fail
    screenshot: "only-on-failure",
  },
});</code>
```

#### Context Isolation Between Tests

Playwright creates a fresh incognito-like `BrowserContext` per test automatically, while DevTools MCP uses a shared persistent profile unless you pass `isolatedContext`. Keep CI headless, ephemeral, and isolated from developer workstation cookies.

## 10. Cross-Tool Synergy: From Live Forensics to CI Merge Gate

Separately, DevTools MCP finds bugs once and Playwright catches regressions later. Wired together into one agent workflow, every live telemetry discovery becomes an automated, permanently enforced pull-request test.

### How One Real PR Flows Through All Five Stages

| Pipeline Stage | Exact Action & Command | Regression Prevented |
| --- | --- | --- |
| **1. Preview Boot** | Start local dev server or target deployment preview URL with clean `isolatedContext`. | Prevents testing stale build artifacts or polluted browser profile state. |
| **2. MCP Forensics** | Verify ARIA tree (`take_snapshot`), CSS variables (`get_css_styles`), `LCPBreakdown`, and zero `CookieIssue` warnings. | Catches root causes invisible to simple HTTP `200` checks or pixel screenshots. |
| **3. Surgical Code Fix** | Apply minimal patch (add `aria-label`, `fetchpriority="high"`, or cleanup hook) and re-run MCP check. | Proves the live browser telemetry improved before writing any test code. |
| **4. Playwright Lock** | Write `getByRole` + `toHaveScreenshot()` + `instant()` tests; verify with `npx playwright test -g ... --trace on`. | Prevents future commits from reintroducing the exact layout, auth, or timing bug. |
| **5. CI Merge Gate** | GitHub Actions runs full headless Playwright suite with `trace: "on-first-retry"` and uploads failure traces only. | Blocks regressions automatically on every pull request without manual QA click-throughs. |

#### Pair Playwright with Isolated Git Worktrees for Parallel Fixes

Assign each browser bug to its own `git worktree` with a dedicated port (e.g., `3001`, `3002`) and unique `isolatedContext` name so parallel coding agents never collide on cookies, ports, or test artifacts.

## 11. Troubleshooting Clinic & Pre-Flight Checklist

Keep this cheat sheet beside your MCP config and CI pipeline. Almost every browser-agent stall, token explosion, or flaky test failure maps directly to one of these seven root causes.

### Top 7 Browser-Agent Pitfalls & 10-Second Fixes

| Symptom You Observe | Root Cause & 10-Second Engineering Fix |
| --- | --- |
| **1. Element not found or stale `uid` on `click`** | DOM re-rendered or navigated since the last snapshot. Call `wait_for` then `take_snapshot(pageId)` to refresh `uid`s before interacting. |
| **2. Extension or heap tools missing from MCP** | Server started without `--categoryExtensions` or `--memoryDebugging`. Add the flag in MCP JSON config and **restart the MCP server/client**. |
| **3. `cookieStore.delete()` fails to log out** | Target session cookie is `HttpOnly`, so client JS silently fails. Inspect via `get_network_request` and spawn `new_page(isolatedContext: ...)` for clean state. |
| **4. Agent context blows up on Lighthouse/heap dumps** | Reading raw multi-MB `report.json` or `.heapsnapshot` files directly. Filter Lighthouse with `node -e` and inspect heaps strictly via MCP diff tools. |
| **5. Playwright tests flake on slow CI runners** | Hardcoded `page.waitForTimeout()` or brittle CSS/XPath selectors. Switch to `getByRole`/`getByLabel` and auto-waiting `await expect(loc).toBeVisible()`. |
| **6. MCP server bloats RAM or cookies leak across audits** | Forgot cleanup after forensics. Always call `close_heapsnapshot` on every loaded snapshot and `close_page` when an `isolatedContext` audit ends. |
| **7. Playwright crashes in CI with missing X server** | Running `--headed` inside a headless Linux container or sandbox. Keep default headless execution and debug failures via `--trace on` artifacts. |

#### 6-Point Pre-Flight Checklist: Before Declaring Any Web Fix Complete

☐ **1. Explicit Targeting & Hygiene:** Pinned `pageId` (or `serviceWorkerId`), set `includeSnapshot: false` on intermediate inputs, and closed any `isolatedContext` or heap snapshot.

☐ **4. Clean Auth & Consent Verified:** Verified `HttpOnly` `Cookie`/`Set-Cookie` headers via network tools and zero `CookieIssue` console warnings.

☐ **2. Accessibility Tree Verified:** Checked `take_snapshot` headings, `Tab` focus flow, 48&times;48px tap targets, and zero native `types: ["issue"]` errors.

☐ **5. Security & Bot Boundaries Kept:** Stopped cleanly for human input on any CAPTCHA/payment wall and scrubbed tokens from saved traces or HARs.

☐ **3. LCP Subparts Checked:** Confirmed hero LCP stays &le;2.5s via `LCPBreakdown`, no viewport `loading="lazy"`, and `fetchpriority="high"` applied.

☐ **6. Headless Playwright Locked:** Added targeted `getByRole` + `expect()` regression test and verified green headless run with `--trace on`.

---

## Edition Note & Attribution

This 12-page handbook, its topic structure, and its illustrations were generated with AI under human editorial direction and print-layout QA. Verify commands, pricing tiers, and security settings against official vendor documentation before production use.

- AI & Editorial Disclosure: https://twelve-pages.com/editorial
- Terms & Licensing: https://twelve-pages.com/terms
- Privacy & Cookie Notice: https://twelve-pages.com/privacy
