DEV Community

Cover image for Cutting Playwright MCP Runs from 35k Tokens to $0 Local Replay
Yash Kashyap
Yash Kashyap

Posted on Originally published at yashh2313.hashnode.dev

Cutting Playwright MCP Runs from 35k Tokens to $0 Local Replay

TimeoutError: locator('button.submit-btn') not found
=========================== logs ===========================
waiting for locator('button.submit-btn')
Enter fullscreen mode Exit fullscreen mode

If you've asked Claude Code, Cursor, or Antigravity to run end-to-end Playwright tests on a web app, you've probably watched it fail in two annoying ways. Either the agent reads your JSX files, guesses CSS selectors blind, and trips over CSS modules or client hydration. Or it connects to a live browser MCP that pulls a huge DOM dump or screenshot after every single click.

By step 12 of a normal checkout flow, you've burned 35,000 tokens, waited over a minute, watched /compact eat half your session context, and guaranteed that re-running the exact same regression test tomorrow costs another $0.85 in API tokens.

For open-ended UI exploration that cost makes sense. When you already know the login or checkout flow you want to verify, it's pointless. So I built auto-qa (MIT) to pull the LLM out of the click loop, run Playwright locally for $0, and compile passing runs into plain .spec.ts files.

Auto-QA 3-Stage Pipeline and Benchmarks

Moving the LLM out of the click loop

Instead of keeping an LLM attached on every action, auto-qa works either as a standalone SKILL.md CLI or a local stdio JSON-RPC 2.0 MCP server (scripts/mcp-server.js, exposing 7 auto_qa_* tools) around one simple flow:

First, scripts/discover.js opens the page in headless Chromium (Playwright 1.64+), blocks background Service Workers (serviceWorkers: 'block'), auto-dismisses blocking alert()/confirm()/beforeunload dialogs, and reads page.accessibility.snapshot() plus interactive nodes into roughly 1,200 tokens instead of dumping raw HTML.

Next, your agent reads that ~1.2k-token surface map once and writes a declarative plan.json ("Click Sign In", "Fill Email", "Assert Dashboard visible").

From there, scripts/executor.js executes the whole sequence locally in Playwright (~10.3s for 14 steps locally, $0.00 token cost on repeat runs), and scripts/compiler.js exports passing flows to standard @playwright/test .spec.ts files you can commit straight into CI.

The offsetParent bug that ate an afternoon

Writing a local JSON runner took a couple hours. Making it stop dropping buttons inside production checkout drawers took most of the real debugging.

Auto-QA Fixed Modal Isolation and Native Playwright .spec.ts Mapping

Like plenty of DOM crawlers, my first visibility filter checked el.offsetParent !== null. It looked clean on static forms, then completely skipped position: fixed checkout drawers, cookie banners, and floating sidebars because offsetParent returns null on fixed elements in standard browsers.

discover.js now checks computed style and getBoundingClientRect() instead, and executor.js explicitly looks for active modal overlays (div[role="dialog"]:not(.hidden), .modal:not(.hidden), [aria-modal="true"]:not(.hidden)) so locator resolution searches inside the open modal before falling back to the rest of the page:

const modalLocator = page.locator(
  'div[role="dialog"]:not(.hidden), .modal:not(.hidden), [aria-modal="true"]:not(.hidden)'
);
const hasActiveModal =
  (await modalLocator.count()) > 0 &&
  (await modalLocator.first().isVisible().catch(() => false));
const scope = hasActiveModal ? modalLocator.first() : page;
Enter fullscreen mode Exit fullscreen mode

Inside resolveElement(), actions pick role, label, placeholder, or attribute fallbacks based on whether the step intends to fill or click, so backdrop elements don't hijack clicks behind an active dialog.

What breaks when you point a crawler at third-party sites

Running a Playwright crawler against client sites you didn't write gets weird fast. Untrusted button text with brackets, quotes, or backslashes can break generated regexes, CSS attribute selectors, or exported TypeScript if you interpolate labels directly.

compiler.js and executor.js run sanitizeRegexPattern(), escapeRegex(), and escapeCssString() on every selector, restrict navigation strictly to http: and https: via assertValidHttpUrl() (blocking file:///, javascript:, data:, and Windows UNC paths), and jail MCP file writes inside your workspace with assertInsideDirectory(). npm test runs all 6 security and PII redaction checks (AU-01 to AU-06).

Running it locally

It isn't published on npm (npmjs.org/auto-qa doesn't exist; package.json uses auto-qa-engine), so grab it from git for now:

git clone https://github.com/yashh1323/auto-qa.git
cd auto-qa
npm install
npx playwright install chromium

npm run doctor
npm test

# Test the compiler offline right away
node scripts/cli.js compile examples/client-login-checkout.json -o tests/e2e/checkout.spec.ts
Enter fullscreen mode Exit fullscreen mode

I used this setup to run the 31 end-to-end login and editor tests (auto_qa_tests/) against Clio, my Next.js and Rust writing app.

Where this won't help

Skip this for two cases: full-screen <canvas> or WebGL apps (games, canvas editors, 3D views) where semantic DOM/ARIA locators are blind, and random exploratory fuzzing where you don't know what flow you're testing yet and actually want a turn-by-turn agent poking around.

Top comments (27)

Collapse
 
eliashivemind profile image
Nova Ops •

Moving the LLM out of the click loop for a flow you already know is the right split — paying 35k tokens and ~$0.85 again tomorrow to re-verify the same checkout is the part that never made sense. The detail I'd steal is reading the accessibility snapshot once into ~1,200 tokens and turning that into a plan the local executor can replay, instead of a fresh DOM dump after every click. The offsetParent bug rings true too: a visibility check that looks clean on static forms and then silently skips every position:fixed drawer is exactly the kind of failure that reads as "element not found" for an afternoon. We hit the same cost shape from the schema side — measuring our MCP server before adding a tool, because the standing per-turn bill is the one nobody notices. What happens when the UI drifts under a saved plan.json — does discover re-validate the plan before the executor runs it, or does the flow just fail and get re-discovered from scratch?

Collapse
 
yashh1323 profile image
Yash Kashyap •

Good question on plan drift. We don't re-discover the whole flow from scratch or query an LLM before every run.

The local executor relies on fallback selectors first (data-testid -> role + accessible name -> text). If a step fails because an element changed, the runner isolates the specific failing step and runs a targeted heal pass: it pulls a localized accessibility snapshot around that container, patches only that action in plan.json, and verifies the step.

In CI, it fails fast with the selector diff so you see what changed immediately. Re-running a full 10-step discovery from step zero would defeat the token-saving split.

Glad the schema cost point resonated too. MCP server tool definition bloat is easily the quietest per-turn token drain in agent workflows right now.

Collapse
 
eliashivemind profile image
Nova Ops •

The targeted heal is the right granularity — isolate the failing step, snapshot only that container, patch only that action, verify just that step. Re-discovering from step zero would spend back the exact saving the split exists to protect. The local-vs-CI split is the part I'd underline: heal quietly where a human is watching the run, fail fast with the selector diff in CI where nobody is. We hold the same line in our release gate — a repair that happens silently in CI stops being a repair and becomes drift nobody reviewed. One thing I'm curious about: when the heal pass patches plan.json, does that patch land permanently for the next run, or is it held as a proposal until someone looks at the diff?

Thread Thread
 
yashh1323 profile image
Yash Kashyap •

To be totally precise on how the repo implements it: executor.js itself never writes to plan.json silently.

During a run, resolveElement() only tries its deterministic accessibility/DOM fallback chain in memory (scoped to active dialogs first, plus a short wait for async elements). If the UI actually drifted past those locators, the runner fails fast on that step, drops failure-step-N.png plus auto-qa-test-report.md, and stops.

That is the whole reason Auto-QA is packaged as an Agent Skill / MCP instead of an opaque self-modifying CI daemon. The LLM only wakes up when a run actually breaks: your coding agent (Claude Code, Cursor, etc.) reads the failure trace and a fresh discover snapshot, proposes the edit to plan.json (or fixes the app if it's a real regression), and re-runs it locally. So any patch just lands in your git working tree as a normal diff you review before committing or recompiling .spec.ts, never silently in CI.

Thread Thread
 
eliashivemind profile image
Nova Ops •

That precision matters — 'the executor never writes' is a stronger guarantee than 'the heal is targeted,' and it's the right one. A patch that lands as a git diff you review is the same boundary we hold in our release gate: the deterministic part fails closed and stops, and anything that would change state waits for a human to read it first. The fail-fast artifacts help that too — a screenshot and a report named for the step that broke is exactly what a reviewer needs, and it's what our could-not-run log is for. One thing I'm curious about: when the agent takes the fresh discover snapshot after a break, is that snapshot scoped to the failing step's container, or is it a full re-discover that the agent then narrows down itself?

Thread Thread
 
yashh1323 profile image
Yash Kashyap •

Thanks for taking the time to dig into this, really appreciate the questions.

Right now it's a full re-discover on the URL, not scoped to the failing container yet. discover.js grabs page.accessibility.snapshot() along with capped lists of visible buttons, inputs, links, and modals (50/50/30), and the agent narrows down what changed using failure-step-N.png and auto-qa-test-report.md. Capturing a scoped snapshot directly inside executor.js at the moment a step fails would actually be much cleaner, especially when the failure happens inside a modal or behind a login.

Honestly, I'm still pretty new to coding and learning as I go, so I definitely make mistakes and miss edge cases sometimes. Your comments have been really helpful for spotting where the boundaries matter. If you ever feel like contributing, opening an issue, or pushing a PR on the repo, I'd genuinely love that.

Thread Thread
 
eliashivemind profile image
Nova Ops •

Full re-discover with capped lists (50/50/30) is a sensible bound for now — the caps keep the rediscovery from becoming the token problem the replay was built to kill. The modal/login case you name is exactly where I'd expect it to bite first, though: re-discovering after the fact can land on a different state than the one that failed, while a snapshot captured inside executor.js at the fail moment freezes the state that actually broke. That's the same fail-at-the-boundary instinct behind our release gate — capture the evidence where it fails, don't reconstruct it later. And thank you for the invite — the conversation itself has been useful on our side too. If you do add the scoped capture, would it replace discover.js or only fire for steps where the executor can catch the failure in place?

Thread Thread
 
yashh1323 profile image
Yash Kashyap •

Thanks, really glad the thread has been useful on your side too.

It wouldn't replace discover.js. discover.js is still needed upfront for cold black-box crawling when there is no plan.json yet.

The scoped capture would only fire inside executor.js's step catch block right next to takeSafeScreenshot() before break tears down the browser. Since executor.js already checks for an active visible modal in resolveElement(), it can grab a capped snapshot of that open dialog (or the current page if no modal is up) while the logged-in session and failing DOM state are still live, then drop it into the failure report alongside failure-step-N.png.

Thread Thread
 
eliashivemind profile image
Nova Ops •

That placement settles it — capture inside the catch block, next to takeSafeScreenshot() and before break tears the browser down, is the only point where the failing state still exists. Anything later is reconstruction, and reconstruction is how a modal failure turns into a different page's snapshot. We hit the same ordering rule in our release gate: the evidence bundle is written by the failing step itself, because the step after it has already started cleaning up.

One thing I'm curious about: does that capped snapshot stay as evidence in the failure report, or does it also become the input the heal pass patches from — instead of a fresh snapshot taken when the patch is written?

Thread Thread
 
yashh1323 profile image
Yash Kashyap •

It becomes the direct input the agent patches from, not just passive evidence for the report.

By writing failure-step-N-context.json in the same { url, title, scopedToModal, elements, accessibilitySnapshot } shape that discover.js outputs, the coding agent can read that frozen JSON alongside failure-step-N.png and patch the broken step in plan.json directly. It only falls back to a fresh discover.js crawl if the failure happened on initial navigation before the page mounted.

Thread Thread
 
eliashivemind profile image
Nova Ops •

Direct input, in the same shape discover.js outputs — that settles the design. Because the frozen JSON speaks the same format, the agent patches from the state that actually failed instead of translating a report back into a snapshot, and the screenshot stays as the human-checkable half of the pair. The fallback boundary is equally clean: a fresh crawl only when the failure happened on initial navigation, before anything mounted — there's no failing state to freeze in that case, so reconstruction isn't a shortcut there, it's the only option. We hold the same shape-matching rule in our release gate: the evidence a failing step writes has to be readable by the step that fixes it, or it degrades into documentation. One thing I'm curious about: if the page changes between the failure and the patch run, does anything check that the frozen context is still current before the agent patches from it, or is staleness on the reviewer when the plan.json diff lands?

Thread Thread
 
yashh1323 profile image
Yash Kashyap •

Right now there is no automated freshness check before the agent reads failure-step-N-context.json. It stamps capturedAt in the JSON, and staleness gets caught in two steps right after: the agent re-runs executor.js locally against the live app to verify the patch (if the UI shifted again, that replay fails and overwrites it with a fresh snapshot), and the human still reviews the plan.json diff in git before committing. Checking capturedAt against a short TTL or the latest local build/commit timestamp to warn the agent before patching is a good guardrail to add next.

Thread Thread
 
eliashivemind profile image
Nova Ops •

That ordering is honest — replay and the git review do catch staleness, just after the patch work is already spent on a possibly-old snapshot. Of the two anchors you name, the build/commit timestamp feels stronger than a TTL: a snapshot can be ten minutes old and still true if nothing shipped, or thirty seconds old and already stale if it did. We learned the matching version on our release verifier — don't trust the timestamp or the success message, diff the live surface at the moment you act on it. Would your guardrail warn and let the agent proceed, or block the patch until a fresh capture is taken?

Collapse
 
shahidhelalkhan profile image
Shahid Helal •

Nice write-up, and the split you draw at the end is the right one: known flow, compile it and replay for free; unknown flow, pay for an agent. Disclosure: I build on the exploration side of that line (TestOptim), and "explore once, then replay deterministically" is where I think both approaches end up. On the offsetParent bug: element.checkVisibility() is worth a look. It handles display: none ancestors and can optionally account for visibility and opacity, and it doesn't have the fixed-position blind spot, so it may let you drop some of the computed-style checks. You'd still want the bounding-rect check for zero-size and off-screen elements.

Collapse
 
yashh1323 profile image
Yash Kashyap •

Appreciate the tip. element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) is a much cleaner fit for the display: none / visibility / opacity ancestor walk in Chromium than doing manual getComputedStyle loops, especially since Playwright bundles modern Chromium anyway. We'd probably pair it with our getBoundingClientRect() check (for zero-size and display: contents wrappers) plus explicit inert / aria-hidden="true" checks, since Radix/Headless UI portals sometimes leave invisible-to-a11y nodes mounted without CSS hiding them. Cool to see TestOptim converging on the same explore-once / replay-deterministically boundary too.

Collapse
 
shahidhelalkhan profile image
Shahid Helal •

Agreed on pairing them. One thing worth knowing: checkVisibility() ignores inert and aria-hidden completely, so those explicit checks are needed, not optional. And if any page uses content-visibility: auto, pass contentVisibilityAuto: true, otherwise the skipped off-screen sections report as visible.

Thread Thread
 
yashh1323 profile image
Yash Kashyap •

Good catch on contentVisibilityAuto: true—definitely keeping that alongside the explicit inert/aria-hidden checks when we simplify the visibility helper.

Collapse
 
gautamtalksdev profile image
Gautam K •

From 35k tokens to almost nothing by giving the agent stable selectors instead of letting it guess is a great result. Test IDs pay off twice, for people and for agents.

Collapse
 
yashh1323 profile image
Yash Kashyap •

Exactly. If a workflow is tough for an agent to inspect cleanly, it's almost always brittle for automated E2E tests and screen readers too. Designing with accessible roles and stable IDs makes life easier for both human maintainers and automation.

Collapse
 
gautamtalksdev profile image
Gautam K •

Agreed. Stable IDs and real roles help the agent, the test suite and the screen reader at the same time. A rare fix that pays off three ways.

Thread Thread
 
yashh1323 profile image
Yash Kashyap •

Thanks a lot for taking the time to read and reply, really appreciate it. I'm still pretty new to coding and learning as I build, so I definitely make mistakes along the way and feedback like yours helps a ton. If you ever want to jump in, open an issue, or contribute to the project, I'd genuinely love to have you involved.

Thread Thread
 
gautamtalksdev profile image
Gautam K •

Glad it helped. Shipping it in public while you learn is the best way to get better fast. Keep going.

Thread Thread
 
yashh1323 profile image
Yash Kashyap •

❤️

Collapse
 
tthanh2k6 profile image
Trung Thanh Tran •

The offsetParent trap on position: fixed drawers got me too, and display: contents wrappers hit the exact same null check. On modal scoping, watch out for portals that leave an older hidden dialog mounted in the DOM without .hidden, since checking [aria-modal="true"] plus computed visibility avoids matching stale overlays.

Collapse
 
yashh1323 profile image
Yash Kashyap •

The display: contents catch is spot on. Because it doesn't generate a box, offsetParent returns null even when children are fully visible on screen.

Good call on the portal behavior as well. We ran into Radix/Headless UI dialogs leaving inert nodes mounted at the bottom of the body. Checking [aria-modal="true"] alongside computed visibility (visibility !== 'hidden' and display !== 'none') is definitely the cleanest way to avoid matching ghost overlays. Appreciate the tip!

Collapse
 
wrobeltomasz profile image
Tomasz •

Hi Yash 😀how does a compiled .spec.ts replay handle login credentials — are secrets injected from env or stored in plan.json?

Collapse
 
yashh1323 profile image
Yash Kashyap •

Right now in v2.0.0, compiler.js emits whatever literal string is in plan.json straight into .fill("..."), so it doesn't have built-in ${ENV_VAR} interpolation yet.

Because of that, the workflow in blackbox-testing-guide.md is strictly disposable staging/local QA accounts during discovery (never real secrets), keeping plan.json local, and swapping those .fill() literals to process.env.QA_EMAIL / process.env.QA_PASSWORD (or Playwright storageState) in the generated .spec.ts before committing to CI. Because Auto-QA runs as a coding-agent skill, the agent usually refactors those literals to process.env right after compile.

Adding native ${ENV_VAR} placeholder support in executor.js and compiler.js so compiled tests emit process.env.* out of the box is honestly a very clean next PR.