What an agent is, and how it differs from a code generator
If you have tried an agent-based testing tool in the last year, you have probably seen both ends of the distribution: a scenario drafted in thirty seconds that you would have written yourself in twenty minutes, and a “self-healing” locator that quietly adapted to a button the product team had accidentally deleted. Both come from the same property, and that property decides where an agent belongs in your pipeline.
An agent is a model plus tool access — a browser, a file system, a terminal — plus a loop that keeps running until it decides the goal is met. A code generator produces one artifact in one shot; Playwright’s codegen records your clicks and emits a file. An agent runs its own output, reads the failure, and tries again. That loop is the whole value proposition and the whole problem: a loop means unbounded time, unbounded cost, and a non-reproducible result. Everything below follows from that sentence.
Break QA into steps: the debate only makes sense here
“Will AI take over testing” is an unanswerable question because QA is not one job. Split it into steps and the question becomes tractable: reading requirements and analysing risk, designing scenarios, preparing test data, writing locators, defining assertions, executing, triaging failures, maintaining the suite, reporting.
There is exactly one criterion that decides whether a step is a good fit for an agent: can someone verify the output cheaply? Not “is it hard” — hard is fine. Verifiable is what matters. A wrong locator breaks the test and you find out in one run. A wrong assertion keeps the test green and you never find out at all. One mistake costs minutes; the other costs a production incident and a suite you no longer trust.

The left column is where agents earn their keep. The right column is where they create debt you discover six months later.
The steps agents genuinely take over today
Three steps produce measurable benefit right now. Their shared property is not that they are easy — it is that a human can check the answer in seconds.
Exploration passes and scenario drafts
Point an agent at a screen it has never seen and ask it to enumerate the states that exist: empty state, error state, unauthorised user, expired session, 300-character input in a field designed for 20, slow network. The output is not a test suite. It is a list, and a human crosses out two thirds of it.
This works because scanning a UI for edge cases is creative but tedious work — exactly the category where humans stop being thorough after the fourth screen and an agent does not. Keep the output as a list, not as code. The moment you let it emit expect() calls, you have moved into the right column of the diagram above.
Locator generation and repairing broken locators
Deriving a durable locator from a DOM tree is pattern work, and verification is free: the locator either resolves to exactly one element or it does not. You know within a second.
Two constraints make this useful instead of dangerous. First, force the agent toward getByRole and getByLabel rather than CSS chains — this is a system-prompt and lint-rule job, not a hope. Second, never let repair happen at run time. A locator that silently heals itself hides the fact that the product changed. If the “Checkout” button lost its accessible name, that is a bug you want to see in red, not a problem for the agent to route around. Repairs belong in a pull request a human reads, with the old and new locator side by side.
Failure triage: hypotheses from traces, logs and screenshots
This is the clearest win. A red test in CI costs an engineer fifteen minutes before they even form a first hypothesis: open the trace, scrub the timeline, read the network log, look at the last screenshot. An agent can do that pass and hand you a classification — product bug, test bug, or infrastructure — plus the one check that would confirm it.
The economics work because the cost of being wrong is near zero. A bad hypothesis is visible in seconds, and you were going to open the trace anyway. Typically the classification is strongest on the obvious shapes — a 500 from the API, a timeout on a locator that no longer exists — and weakest on timing-sensitive races, where the trace shows a symptom that looks identical to a product bug. That is also exactly where root-cause analysis of flaky tests needs a human who knows the system.
// scripts/triage.mjs
// Usage: node scripts/triage.mjs playwright-report/report.json
// Requires: npx playwright test --reporter=json,html + OPENAI_API_KEY
import { readFileSync } from "node:fs";
import OpenAI from "openai";
const reportPath = process.argv[2] ?? "playwright-report/report.json";
const report = JSON.parse(readFileSync(reportPath, "utf8"));
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
function collectFailures(suite, out = []) {
for (const spec of suite.specs ?? []) {
for (const test of spec.tests ?? []) {
for (const result of test.results ?? []) {
if (result.status !== "failed" && result.status !== "timedOut") continue;
out.push({
title: `${spec.file} > ${spec.title}`,
status: result.status,
error: (result.error?.message ?? "").slice(0, 2000),
steps: (result.steps ?? []).slice(-10).map((s) => `${s.title} (${s.duration}ms)`),
stdout: (result.stdout ?? []).map((c) => c.text ?? "").join("").slice(-1500),
screenshot: (result.attachments ?? []).find((a) => a.name === "screenshot")?.path,
});
}
}
}
for (const child of suite.suites ?? []) collectFailures(child, out);
return out;
}
const SYSTEM = `You triage Playwright failures. Reply with JSON only:
{"category":"product|test|infrastructure","confidence":0..1,
"hypothesis":"one sentence","next_check":"one concrete action"}
Your category is a hypothesis for a human to confirm, never a verdict.
If the evidence does not separate the categories, say so and lower confidence.`;
const failures = (report.suites ?? []).flatMap((s) => collectFailures(s));
for (const f of failures) {
const content = [
{
type: "text",
text: [
`TEST: ${f.title}`,
`STATUS: ${f.status}`,
`ERROR:\n${f.error}`,
`LAST STEPS:\n${f.steps.join("\n")}`,
`STDOUT:\n${f.stdout}`,
].join("\n\n"),
},
];
if (f.screenshot) {
const b64 = readFileSync(f.screenshot).toString("base64");
content.push({ type: "image_url", image_url: { url: `data:image/png;base64,${b64}` } });
}
const res = await client.chat.completions.create({
model: "gpt-4o-mini",
temperature: 0,
response_format: { type: "json_object" },
messages: [
{ role: "system", content: SYSTEM },
{ role: "user", content },
],
});
const v = JSON.parse(res.choices[0].message.content);
console.log(
`\n${f.title}\n category: ${v.category} (confidence ${v.confidence})\n` +
` hypothesis: ${v.hypothesis}\n next check: ${v.next_check}`
);
}
Run this as a post-step on red CI builds and post the output as a PR comment. Note temperature: 0 and the explicit “hypothesis, never a verdict” instruction — triage output is an input to a human, not a gate.
The step it cannot take over: the oracle problem
An agent can read what is on the screen. It cannot know what should be on the screen. The distance between “the total reads €1,248.00” and “the total is correct” is a business rule, and that rule does not live in the product — it lives in the acceptance criteria and in the head of whoever wrote them.
This is why agent-generated assertions are structurally dangerous. The agent observes the current behaviour and encodes it as the expectation. If the discount is applied before tax when it should be applied after, the generated test asserts the wrong number and turns a live bug into a protected invariant. Every future engineer who touches that code sees a green suite and assumes the rule is intentional. You have not tested the product; you have taken a photograph of it and called the photograph a specification.
Observation is not specification. That sentence is the whole argument for keeping assertions human-owned, or at minimum human-approved line by line. Turning acceptance criteria into tests is the one part of the job where the source of truth is outside the system under test, and no amount of tool access closes that gap.
Agents at run time: the determinism and cost bill
An agent that re-plans its steps on every run breaks the basic contract of a regression suite: the same input must produce the same result. If a run is green today and red tomorrow with no code change, you cannot tell whether the product regressed or the planner took a different path. You have lost the signal that justifies the suite’s existence.
Then add the bill. A deterministic Playwright step resolves in milliseconds; a planning round trip takes seconds, so a test that ran in seconds now takes tens of seconds. Multiply by the number of tests, then by the number of runs per pull request, then by the number of pull requests per day. Add token cost per run and a hard dependency on an external API that can rate-limit you at 2 a.m. In exchange, you get nondeterminism — deliberately injected into a system where you spend real engineering hours hunting nondeterminism out.

There is one defensible exception: an exploratory nightly job whose output is a report, not a gate. It may not block a merge.
The right placement: agent at write time, output frozen as code
The model that actually works is boring. The agent runs on a developer machine or in a nightly job. Its output is reviewed by a human and lands in the repository as a deterministic Playwright spec. CI only ever runs frozen code. The agent drafts scenarios, the human owns the assertions, and the repo stays the single source of truth.

A frozen spec looks like ordinary code, because that is the point:
// tests/checkout/discount.spec.ts
// Drafted by agent run 2026-02-11. Assertions reviewed and owned by QA.
// Business rule: percentage discount applies AFTER tax (ACC-412).
import { test, expect } from "@playwright/test";
import { randomUUID } from "node:crypto";
test.describe("Checkout discount", () => {
let orderId: string | undefined;
test.afterEach(async ({ request }) => {
if (orderId) {
await request.delete(`/api/orders/${orderId}`);
orderId = undefined;
}
});
test("applies a 10% discount after tax", async ({ page, request }) => {
const email = `qa-${randomUUID()}@example.test`;
const created = await request.post("/api/test-fixtures/cart", {
data: { email, items: [{ sku: "SKU-100", qty: 2, unitPrice: 500 }], taxRate: 0.2 },
});
expect(created.ok()).toBeTruthy();
orderId = (await created.json()).orderId;
await page.goto(`/checkout/${orderId}`);
await page.getByLabel("Discount code").fill("SAVE10");
await page.getByRole("button", { name: "Apply" }).click();
// 2 x 500 = 1000; +20% tax = 1200; -10% = 1080. Human-derived from ACC-412.
await expect(page.getByTestId("order-total")).toHaveText("€1,080.00");
await expect(page.getByTestId("tax-line")).toHaveText("€200.00");
});
});
The comment linking the assertion to an acceptance criterion is not decoration. It is the record of who owns the oracle. Note also that the test creates and deletes its own data — every test owning its data matters more, not less, when a machine is drafting the setup code.
Gates an agent’s output must pass before you accept it
Reviewing generated tests by hand does not scale, and reviewer fatigue is real: by the tenth near-identical spec, nobody is reading carefully. Push the mechanical checks down to a script that runs in CI on changed spec files.
// scripts/check-specs.mjs
// Usage: node scripts/check-specs.mjs tests
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
const RULES = [
{
id: "no-assertion",
message: "spec contains no expect() assertion",
violated: (src) => !/\bexpect\s*\(/.test(src),
},
{
id: "hard-wait",
message: "uses waitForTimeout/sleep instead of a web-first assertion",
violated: (src) => /waitForTimeout\s*\(|\bsleep\s*\(/.test(src),
},
{
id: "brittle-locator",
message: "raw CSS/XPath locator; use getByRole, getByLabel or getByTestId",
violated: (src) => /page\.locator\(\s*['"`](?!\[data-testid)/.test(src) || /xpath=/.test(src),
},
{
id: "uncleaned-data",
message: "creates data via API but has no afterEach/afterAll cleanup",
violated: (src) =>
/request\.(post|put)\s*\(/.test(src) && !/afterEach|afterAll/.test(src),
},
{
id: "shared-state",
message: "module-level mutable state leaks between tests",
violated: (src) => /^let\s+\w+\s*=/m.test(src),
},
{
id: "serial-without-reason",
message: "describe.serial without a // reason: comment",
violated: (src) => /describe\.serial/.test(src) && !/\/\/\s*reason:/i.test(src),
},
];
function walk(dir, out = []) {
for (const entry of readdirSync(dir)) {
const full = join(dir, entry);
if (statSync(full).isDirectory()) walk(full, out);
else if (full.endsWith(".spec.ts") || full.endsWith(".spec.js")) out.push(full);
}
return out;
}
const root = process.argv[2] ?? "tests";
let failures = 0;
for (const file of walk(root)) {
const src = readFileSync(file, "utf8");
for (const rule of RULES) {
if (rule.violated(src)) {
console.error(`${file}: [${rule.id}] ${rule.message}`);
failures++;
}
}
}
console.log(failures ? `\n${failures} violation(s).` : "All specs passed the gates.");
process.exit(failures ? 1 : 0);
eslint-plugin-playwright covers part of this; the data-ownership and shared-state rules are project-specific and worth owning yourself. Once these gates are automated, human review shrinks to the only question that matters: is this assertion the right assertion?
How to measure an agent
Do not decide from a demo. Demos are run on applications the tool vendor chose. Track four numbers on your own codebase:
- Merge-without-edit rate — of the generated tests, how many landed with zero lines changed. Tests that needed a rewrite cost more than writing from scratch.
- Flake rate in the first two weeks — generated tests often pass once and then destabilise. Two weeks is the minimum honest window.
- Triage hit rate — how often the hypothesis matched the eventual root cause, broken down by category, so you learn where it misleads.
- Time and token cost per test — including review time, which is the cost people forget.
Compare each against the same work done by hand. A tool stays only if it lowers total cost of ownership, and the same discipline applies here as when you compare automation frameworks on real criteria: measure on your repo, not on the vendor’s.
Where to start
Start with triage. It is the lowest-risk, fastest-return placement: wire the script above into your red-build path and let it post a hypothesis as a PR comment for two weeks. Nothing is blocked, nothing is merged, and you get hit-rate data for free.
Second, connect locator repair — as a pull request suggestion only, never as run-time healing. Require the diff to show old and new locator so the reviewer can ask whether the product broke.
Leave assertion and test-data generation for last, keep both behind human approval, and never enable auto-merge on an agent-authored branch. Collect your four numbers for two weeks before expanding scope. If the merge-without-edit rate is low, the problem is usually your codebase conventions, not the model — fix the conventions first and re-measure.