---
title: "Playwright Self-Healing Tests: What to Heal, What to Fail"
description: "Run Playwright self-healing tests in CI with the healer agent as a failure-only job, a locator-only review gate, and runtime heals as annotations."
canonical: "https://currents.dev/posts/playwright-self-healing-tests-what-to-heal-what-to-fail"
updated: "2026-11-23"
---

# Playwright Self-Healing Tests: What to Heal, What to Fail

Published 2026-11-23 by Walter Galvão.

Canonical URL: https://currents.dev/posts/playwright-self-healing-tests-what-to-heal-what-to-fail

Run Playwright self-healing tests in CI with the healer agent as a failure-only job, a locator-only review gate, and runtime heals as annotations.

---


> **TL;DR**
>
> This article covers self-healing Playwright tests in CI. It explains the three layers of self-healing, how the Playwright healer agent works and how to tell locator drift from a real failure. It then walks through a failure-only healer step, a review gate that accepts only locator changes, runtime heals recorded as annotations and heal history across runs.
>
> Gate the build on the unhealed run, and let healing only propose changes. Accept a heal when the same user flow still exists on the same commit, and fail it when the patch changes what the test means.
>
> 1. Re-run only the failures with `--last-failed`. If they pass on their own, they were flaky, and there's nothing to heal.
> 2. Run the full suite on the healed code, and only then open a draft PR for a person to review.
> 3. Record runtime fallback heals in `test.info().annotations`, and treat the second heal of the same test as a bug in the test.

A locator that stops matching fails the build the same way whether a designer renamed the button or a regression removed the checkout step. The red test is the only signal that something changed, and it can't say which of the two happened. A tool that turns both green throws that signal away.

Playwright comes with a healer agent out of the box. Since [version 1.56](https://playwright.dev/docs/release-notes), Playwright includes Test Agents, three custom agent definitions that guide LLMs through building a Playwright test. One of them, the healer, executes the test suite and automatically repairs failing tests. For a CI team, the question is no longer whether to heal. It's which heals to accept.

A heal that only makes a test pass is invisible. The healer's output is a passing test, or a skipped test if the healer believes that functionality is broken.

So treat every heal as a CI event: something that passes, warns or fails the build on a rule you set, and leaves a record you can count across runs.

## Three layers of self-healing

Three different mechanisms go by the name self-healing, and only one of them leaves you something to review.

- Prevention keeps the heal from being needed. Playwright's [best practices](https://playwright.dev/docs/best-practices) recommend prioritizing user-facing attributes and explicit contracts in locators to make tests resilient. Playwright's best practices warn that a button selected by its CSS classes can break when a designer changes the class, and recommend locators that are resilient to changes in the DOM, such as `page.getByRole('button', { name: 'submit' })`.
- Runtime fallback happens inside the run. A helper, a library or a grid feature tries a substitute element when the original locator fails, and the action runs on whatever it finds. The test passes on this commit and nobody edits the code, so the next run hits the same broken locator and falls back again.
- Code-level repair happens after the run. Playwright's healer agent executes the test suite and automatically repairs failing tests, and when a test fails it suggests a patch, such as a locator update, a wait adjustment or a data fix, that you can read before you trust it.

Playwright's built-in healer sits in the third layer. When a test fails, the healer suggests a patch, such as a locator update, a wait adjustment or a data fix.

| Layer | When it acts | What changes in the repo | What CI sees |
|---|---|---|---|
| Prevention | Before anything breaks | The locators you write | A pass |
| Runtime fallback | During the run, after a locator fails | Nothing | A pass, unless the fallback records itself |
| Healer agent | After a failure | A patch to the test, such as a locator update, wait adjustment or data fix | A diff to review |

Invest in prevention first. Use the healer for repairs a person reviews. Allow runtime fallback only where every fallback leaves a record in the report, and nowhere else.

<AntiPattern title="Auto-heal over brittle locators" id="anti-pattern-auto-heal-over-brittle-locators">

The suite still finds elements by CSS class and XPath, and someone turns on runtime healing to stop the red builds. Every class rename can break those locators, as Playwright's best practices warn for a button selected by its CSS classes. The healing layer becomes the place where the suite's brittleness hides, and nobody can see how much of it there is.

<AntiPattern.Fix>

Fix the locators before you heal them. Rewrite the ones that break on user-facing attributes and explicit contracts, following a [selector hierarchy that survives UI refactors](/posts/designing-playwright-tests-that-survive-ui-refactors#the-selector-hierarchy-what-to-use-and-when), then watch what still breaks. What's left is the drift worth healing.

</AntiPattern.Fix>

</AntiPattern>

## How the healer agent works

The healer lives in your repo as files, and those files go stale.

Add the agent definitions with the `init-agents` command. Its `--loop` option picks the agent client, and `--loop=claude` sets them up for Claude Code:

```bash
npx playwright init-agents --loop=claude
```

Under the hood, an agent definition is a collection of instructions and MCP tools, both provided by Playwright. If you drive the agents from VS Code, the [Test Agents docs](https://playwright.dev/docs/test-agents) say the agentic experience needs VS Code v1.105.

When a test fails, the healer works in a loop:

1. It replays the failing steps.
2. It inspects the current UI to locate equivalent elements or flows.
3. It suggests a patch, such as a locator update, a wait adjustment or a data fix.
4. It re-runs the test until it passes or until guardrails stop the loop.

Read the third step twice. The healer's patches aren't limited to locators. A wait adjustment can cover for a page that got slower, and a data fix can change what the test checks, which is why every patch in the pipeline below goes through a gate.

The healer's output is a passing test, or a skipped test if it believes the functionality is broken. That skip is the most useful thing the healer produces. CI should treat it as a failure on that commit, never as a quieter green.

The healer runs the test suite itself and repairs failing tests automatically. Don't plan on it rescuing a run in progress. A user asked Playwright to expose a public instrumentation API for monitoring and self-healing ([#37308](https://github.com/microsoft/playwright/issues/37308)). A maintainer recommended Playwright Agents instead. The reporter answered that the healer agent is for healing tests at the maintenance phase, not when an element lookup fails during a pipeline run. The issue was closed as completed, with no release attached.

<AntiPattern title="Stale agent definitions" id="anti-pattern-stale-agent-definitions">

A dependency bot bumps `@playwright/test`, the PR goes green, and nobody runs `init-agents` again. The agent definitions are provided by Playwright, and they should be regenerated whenever Playwright is updated.

<AntiPattern.Fix>

The docs say to regenerate the definitions whenever Playwright is updated, to pick up new tools and instructions. Do it in the same PR that bumps the version: run `npx playwright init-agents --loop=claude` again and commit the result. The heal job below regenerates the definitions too and fails if anything changes, so a stale set can't slip through.

</AntiPattern.Fix>

</AntiPattern>

## Locator drift vs real failures

The error text can't tell drift from a bug. A locator that matches nothing, or an action that times out, looks the same whether the button was renamed or the feature behind it is gone. So the decision has to come from what the patch changes, not from the error.

Heal it when the same user flow still exists on the same commit:

- A label, role name or test attribute changed, and the element still does the same job.
- A button moved, and the healer found the equivalent element in the current UI.

Fail it when the patch changes what the test means:

- It changes an assertion's expected value.
- It adds a wait that only hides slowness.
- The healer skipped the test, which it does when it believes that functionality is broken.

The line between the two lists is whether the test still checks the same thing. A new locator for the same button keeps the test's meaning. A new expected value replaces it, which is the [intent-weakening heal](/posts/reviewing-ai-generated-playwright-tests-before-they-reach-ci#failure-mode-2-intent-weakening-heals) a human review exists to catch.

<AntiPattern title="Accepting an assertion rewrite" id="anti-pattern-accepting-an-assertion-rewrite">

A checkout test expects an order total of $42.00, and a pricing bug makes the page show $0.00. The healer re-runs the test until it passes or until guardrails stop the loop, so if its patch edits the expected value, accepting the heal makes the test agree with the bug. A feature request for a triage agent warned that the healer can end up adjusting the assertion until the test passes, so a test is quietly adjusted to match the bug ([#43675](https://github.com/microsoft/playwright/issues/43675)). The request was closed as not planned. A maintainer replied that it's unlikely they can provide anything useful on top of modern models, and to ask your agent to classify things directly.

<AntiPattern.Fix>

Send every patch that touches an expectation to a human, and never let one merge on its own. A healer allowed to rewrite expectations can make any test agree with any bug. The review gate below turns that rule into a script the heal job runs on every patch.

</AntiPattern.Fix>

</AntiPattern>

## Retries are not healing

A retry pass is not a heal. Playwright categorizes a test that failed on the first run but passed when retried as flaky, and a runtime heal on that retry has to stay visible too.

By default, Playwright doesn't retry failing tests. With [retries](https://playwright.dev/docs/test-retries) enabled, it retries a failing test until the test passes or hits the maximum.

<AntiPattern title="Retries until green" id="anti-pattern-retries-until-green">

The suite flickers, so the retry count goes up until CI stays green, and the team calls the result self-healing. Every extra retry gives a flaky test, or a heal hiding inside one, another chance to pass while the build reports success.

<AntiPattern.Fix>

Keep retries low on CI. Then set `failOnFlakyTests`: the docs describe it as making the run exit with an error if any test is marked flaky, and call it useful on CI.

```ts
// playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  // One retry on CI is enough to tell a flake from a hard failure
  retries: process.env.CI ? 1 : 0,
  // A pass on retry is flaky, and a flaky test fails the run
  failOnFlakyTests: !!process.env.CI,
});
```

The retry still earns its place: it tells you, in the same run, that a failure is flaky, which makes it [a flake detector rather than a fix](/posts/playwright-flaky-tests-detect-them-in-ci-with-retries#retries-are-a-flake-detector-not-a-fix). It doesn't get to turn the build green. Never count a retry pass as a healed test.

</AntiPattern.Fix>

</AntiPattern>

## A failure-only healer step

The run that gates the build has to be one that nobody healed. If the healer runs inside the gating job, a failure and its repair collapse into one green check, and the commit that broke the test never shows red.

<AntiPattern title="Healer inside the gating job" id="anti-pattern-healer-inside-the-gating-job">

The pipeline has one job. It runs the suite and, when that fails, runs the healer and the suite again in the same step. A heal makes the second run pass, the step exits zero, and the build goes green on a test nobody has reviewed.

```yaml
# Anti-pattern: the healer runs inside the gating job, so a healed test turns the build green unreviewed
# .github/workflows/e2e.yml
name: e2e
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm ci
      - run: npx playwright install --with-deps
      - run: npx playwright test || (./scripts/run-healer.sh && npx playwright test)
```

<AntiPattern.Fix>

Split the work into two jobs on the same commit. The `test` job runs with no healing of any kind and doesn't set `continue-on-error`, the option that prevents a workflow run from failing when a job fails. The `heal` job runs only when `test` fails.

```yaml
# .github/workflows/e2e.yml
name: e2e
on:
  push:
    branches: [main]
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      # Check out the PR head, the same commit the heal job pins
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.sha || github.sha }}
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm ci
      - run: npx playwright install --with-deps
      # The gate: no healing of any kind
      - run: npx playwright test
      # The heal job's --last-failed re-run starts from these results
      - if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: test-results
          path: test-results/
          include-hidden-files: true

  heal:
    needs: test
    if: failure()
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
    env:
      FAILING_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
      TARGET_BRANCH: ${{ github.head_ref || github.ref_name }}
    steps:
      # Pin the exact commit that failed, not the branch tip
      - uses: actions/checkout@v4
        with:
          ref: ${{ env.FAILING_SHA }}
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm ci
      - run: npx playwright install --with-deps
      # Committed agent definitions must match the installed Playwright
      - run: |
          npx playwright init-agents --loop=claude
          test -z "$(git status --porcelain)"
      - uses: actions/download-artifact@v4
        with:
          name: test-results
          path: test-results/
      # Failures that pass on their own are flakes: nothing to heal
      - id: rerun
        continue-on-error: true
        run: npx playwright test --last-failed
      # The one agent-specific step
      - if: steps.rerun.outcome == 'failure'
        run: ./scripts/run-healer.sh
      - if: steps.rerun.outcome == 'failure'
        run: |
          git add -A
          node scripts/heal-gate.mjs "$FAILING_SHA"
      - if: steps.rerun.outcome == 'failure'
        run: npx playwright test
      - if: steps.rerun.outcome == 'failure'
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          git config user.name "heal-bot"
          git config user.email "heal-bot@users.noreply.github.com"
          git switch -c "heal/$FAILING_SHA"
          git commit -m "Heal locators failing on $FAILING_SHA"
          git push origin "heal/$FAILING_SHA"
          gh pr create --draft --base "$TARGET_BRANCH" --head "heal/$FAILING_SHA" \
            --title "Heal locators failing on ${FAILING_SHA:0:7}" \
            --body "Locator-only healer patch for $FAILING_SHA. Review gate and full re-run passed."
```

The heal job checks out the exact commit the `test` job ran, not the branch tip, so the healer sees the code that broke. It downloads the failing run's results as an artifact, and `--last-failed` then re-runs only the failures. That re-run is a cheap filter: if the failures pass on their own, they were flaky, and there's nothing to heal.

If they fail again, the healer runs, the gate script from the next section checks its diff, and the full suite runs on the healed code. Only then does the job open a draft PR against the branch that failed. The workflow's only push goes to the new `heal/` branch, and a reviewer sees the diff and the re-run before anything merges. Add a `schedule` trigger and the same two jobs cover a nightly regression run too.

</AntiPattern.Fix>

</AntiPattern>

### One healer per job

When several commits fail at once, each workflow run gets its own heal job on its own runner, and each heal job starts its own healer. Keep it that way. In one report, several healer agents sharing one playwright-test MCP server hung, with only one finishing ([#39235](https://github.com/microsoft/playwright/issues/39235)). A maintainer replied that this is not a supported scenario. Don't point two healers at one server to save a runner.

### The agent step

`./scripts/run-healer.sh` and the `--loop` value of `init-agents` are the only parts that depend on your agent client. Keep the script a single step that starts your client with the healer definitions from `init-agents` and lets the healer work on the failing tests. Swap the client and its `--loop` value, and the rest stays: the unhealed gate, the commit pin, the review gate, the full re-run and the draft PR.

## A locator-only review gate

A passing re-run proves the healed test passes. It doesn't prove the patch is safe, because the healer's patches can include wait adjustments and data fixes as well as locator updates.

<AntiPattern title="Auto-merging passing heals" id="anti-pattern-auto-merging-passing-heals">

The heal job opens a PR, the re-run is green, and an auto-merge rule takes it. This patch passes that check:

```ts
// Anti-pattern: the heal changes a locator and an expected value, and auto-merge accepts both
// tests/checkout.spec.ts after the healer's patch
import { test, expect } from '@playwright/test';

test('order total includes shipping', async ({ page }) => {
  // Assumes use.baseURL in playwright.config.ts
  await page.goto('/checkout');
  // Healed: was getByRole('button', { name: 'Place order' })
  await page.getByRole('button', { name: 'Complete purchase' }).click();
  // Healed: was toHaveText('$42.00')
  await expect(page.getByTestId('order-total')).toHaveText('$0.00');
});
```

The new locator is drift. The new expected total makes the test agree with the pricing bug, and an auto-merge rule can't tell the two lines apart.

<AntiPattern.Fix>

Put a script between the healer and the PR. It reads the healer's staged changes against the failing commit and accepts only changed locator lines in page object files. It rejects:

- any file outside `pages/`, which covers specs, config, CI files and agent definitions
- any added, deleted or renamed file, a renamed spec file included
- any changed line that contains `expect`, `expect.soft(` included
- any added `.skip(` or `.fixme(`
- any other changed line that isn't a locator

A test title lives in a spec file, so a renamed title fails the first rule.

```js
// scripts/heal-gate.mjs
// Accepts a staged healer patch only if it changes locator lines in page objects.
import { execFileSync } from 'node:child_process';

const base = process.argv[2];
if (!base) {
  console.error('Usage: node scripts/heal-gate.mjs <failing-commit-sha>');
  process.exit(2);
}

const git = (...args) => execFileSync('git', args, { encoding: 'utf8' });
const problems = [];

// Scope: only edits to existing page object files
for (const entry of git('diff', '--cached', '--name-status', base).split('\n').filter(Boolean)) {
  const [status, ...paths] = entry.split('\t');
  if (status !== 'M') {
    problems.push(`${paths.join(' -> ')}: added, deleted or renamed (${status})`);
  } else if (!/^pages\/.+\.ts$/.test(paths[0])) {
    problems.push(`${paths[0]}: outside pages/`);
  }
}

// Content: every changed line must be a locator line
const LOCATOR = /\bgetBy(Role|Label|Text|TestId|Placeholder|AltText|Title)\(|\.locator\(/;
const SKIP = /\.(skip|fixme)\(/;

for (const line of git('diff', '--cached', '--unified=0', base).split('\n')) {
  if (!/^[+-]/.test(line) || /^(\+\+\+|---) /.test(line)) continue;
  const code = line.slice(1).trim();
  if (code === '' || code.startsWith('//')) continue;
  if (line.startsWith('+') && SKIP.test(code)) {
    problems.push(`skip added, so the healer believes the feature is broken: ${code}`);
  } else if (/\bexpect\b/.test(code)) {
    problems.push(`assertion changed: ${code}`);
  } else if (!LOCATOR.test(code)) {
    problems.push(`not a locator line: ${code}`);
  }
}

if (problems.length > 0) {
  console.error(`Heal rejected:\n${problems.map((p) => `  - ${p}`).join('\n')}`);
  process.exit(1);
}
console.log('Heal accepted: locator-only changes in pages/.');
```

The heal job stages the healer's changes with `git add -A` before it runs the script, so new files show up in the diff. In GitHub Actions, a non-zero exit fails the gate step, since the runner reports a step's status from its exit code. Keep each locator on one line so the line check can see it.

Treat a healer skip as a confirmed failure on that commit. The script reports a skip on its own line because it carries different news from a bad patch: a healer skip means it believes the feature is broken. Fail the job and put a person on the regression.

</AntiPattern.Fix>

</AntiPattern>

### Why page objects matter

The gate stays this simple only if your locators live in page objects. Then a locator-only heal changes files under `pages/` and nothing else, and any diff that reaches a spec file is suspect. The Test Agents docs describe the static agent definitions and generated files as following a simple, auditable structure; a diff check on every heal is how you do the auditing.

## Runtime heals as annotations

A runtime heal that only writes to the console never happened, as far as the report is concerned. The test passes, and the fallback's warning is written to standard error, which Playwright keeps in `testResult.stderr`.

<AntiPattern title="Heals logged to the console" id="anti-pattern-heals-logged-to-the-console">

A fallback helper tries a list of candidate locators and warns when it uses any but the first. A JSON side file has the same problem: the record exists, but not on the test result where reviewers look.

```ts
// Anti-pattern: the heal is only written to stderr, never to test.info().annotations, so the result shows a pass with no heal annotation
// tests/helpers/fallback.ts
import type { Locator } from '@playwright/test';

export type Candidate = { label: string; locator: Locator };

export async function firstMatch(name: string, candidates: Candidate[]): Promise<Locator> {
  // Give the primary locator a chance to appear before falling back
  await candidates[0].locator.waitFor({ timeout: 5_000 }).catch(() => {});
  for (const [i, { label, locator }] of candidates.entries()) {
    if ((await locator.count()) === 1) {
      if (i > 0) console.warn(`[heal] ${name}: ${candidates[0].label} -> ${label}`);
      return locator;
    }
  }
  throw new Error(`${name}: no candidate matched`);
}
```

<AntiPattern.Fix>

Record the heal on the test result. While a test is running, you can add annotations to `test.info().annotations`, and `testResult.annotations` includes the annotations appended during the test, so every reporter sees the heal. Playwright's built-in HTML reporter shows all annotations except those whose type starts with `_`, so the helper below records each heal under a plain type:

```ts
// tests/helpers/fallback.ts
import { test, type Locator } from '@playwright/test';

export type Candidate = { label: string; locator: Locator };

export async function firstMatch(name: string, candidates: Candidate[]): Promise<Locator> {
  // Give the primary locator a chance to appear before falling back
  await candidates[0].locator.waitFor({ timeout: 5_000 }).catch(() => {});
  for (const [i, { label, locator }] of candidates.entries()) {
    if ((await locator.count()) === 1) {
      if (i > 0) {
        // Lands in testResult.annotations, where every reporter can read it
        test.info().annotations.push({
          type: 'heal',
          description: `${name}: ${candidates[0].label} -> ${label}`,
        });
      }
      return locator;
    }
  }
  throw new Error(`${name}: no candidate matched`);
}
```

Pass a label with each locator so the annotation reads as the old locator and the new one:

```ts
// tests/settings.spec.ts
import { test, expect } from '@playwright/test';
import { firstMatch } from './helpers/fallback';

test('saves display preferences', async ({ page }) => {
  // Relies on use: { baseURL } in playwright.config.ts
  await page.goto('/settings');
  const save = await firstMatch('save preferences', [
    {
      label: "getByRole('button', { name: 'Save' })",
      locator: page.getByRole('button', { name: 'Save' }),
    },
    {
      label: "getByTestId('save-preferences')",
      locator: page.getByTestId('save-preferences'),
    },
  ]);
  await save.click();
  await expect(page.getByText('Preferences saved')).toBeVisible();
});
```

Currents shows a test's annotations in its dashboard, including ones added at runtime with `testInfo.annotations.push`, so a heal stays on the result reviewers already open ([annotations guide](https://docs.currents.dev/guides/playwright-annotations)).

If a library or a grid heals outside your code, find out where it records each heal, and keep that setup out of the gating run until the record reaches the test result.

</AntiPattern.Fix>

</AntiPattern>

### Warn and fail modes

Once heals are annotations, you can count them. A small custom reporter reads the heal annotations from each test result and prints them at the end of the run, and in fail mode the reporter fails a run that needed more heals than you allow:

```ts
// reporters/heal-reporter.ts
import type { FullResult, Reporter, TestCase, TestResult } from '@playwright/test/reporter';

const mode = process.env.HEAL_MODE === 'fail' ? 'fail' : 'warn';
const maxHeals = Number(process.env.MAX_HEALS ?? 0);

class HealReporter implements Reporter {
  private heals: string[] = [];

  onTestEnd(test: TestCase, result: TestResult) {
    for (const annotation of result.annotations) {
      if (annotation.type === 'heal') {
        this.heals.push(`${test.titlePath().join(' > ')}: ${annotation.description}`);
      }
    }
  }

  async onEnd(result: FullResult) {
    console.log(`Runtime heals in this run: ${this.heals.length}`);
    for (const heal of this.heals) console.log(`  ${heal}`);
    // In fail mode, a run that passed on too many heals is a failed run
    if (mode === 'fail' && this.heals.length > maxHeals && result.status === 'passed') {
      return { status: 'failed' as const };
    }
  }
}

export default HealReporter;
```

Register it in the `reporter` option, the list of reporters to use, next to the HTML reporter. Start in warn mode, where every heal prints, and switch to `HEAL_MODE=fail` once the suite's locators are clean; with `MAX_HEALS` unset, any heal then fails the run.

## Heal history across runs

One heal is drift. The same test healing run after run means a locator that belongs in code or a feature that is changing a little at a time, and that pattern only shows up across runs.

To trace it back, every run needs its commit. By default, Playwright captures git information when tests run as part of CI where it is safe to obtain it, and not otherwise. With the commit on every run, the first run that needed a heal names the first commit that needed it.

In Currents, [Test History](https://docs.currents.dev/dashboard/tests/test-history) shows how one test performed across runs and branches, as a chart or a list, and clicking a run's bar opens the recorded test instance, heal annotation included. Renaming a test or its spec file detaches it from that history, because instances with the same spec file, project and title count as the same test. That is one more reason the review gate rejects every change outside `pages/`.

Watch three things for each test:

- how often it heals
- the first commit that needed a heal
- whether it heals again after the code fix

<AntiPattern title="Every heal as a one-off" id="anti-pattern-every-heal-as-a-one-off">

Each heal gets looked at alone, if at all. A test that heals every day reads as a string of unrelated drift, and the slow change behind it, a button that keeps moving or a flow that keeps losing a step, never gets a name.

<AntiPattern.Fix>

Treat the second heal of the same test as a bug in the test. Send it through the healer PR flow so the locator changes in code, and let the runtime fallback cover it only until that PR merges. A test that heals again after the code fix isn't drifting: look at the feature.

</AntiPattern.Fix>

</AntiPattern>

## When not to self-heal

A runtime heal that picks a look-alike element hides a moved button on a settings page, and a broken purchase on checkout. The second is the one the suite exists to catch, so some tests get no healing at all:

- Keep runtime fallback out of login, checkout and payment, and let those tests fail.
- Read fresh generator output yourself. Generated tests may include initial errors that the healer can heal automatically, and the docs present that as a use. A healed generated test still needs a human read before it joins the suite, because two agents agreeing is not a review.
- Stop healing a locator that keeps breaking, and rewrite it on user-facing attributes. [`locator.normalize()`](https://playwright.dev/docs/api/class-locator) is useful for converting implementation-detail selectors into more resilient, human-readable locators.
- Skip the healer for failures in assertions or data. The healer suggests a patch such as a locator update, a wait adjustment or a data fix.

<AntiPattern title="Healing the whole suite" id="anti-pattern-healing-the-whole-suite">

Runtime healing goes on for every spec, critical flows included, as the answer to brittle locators. Now the payment test can pass on a substitute element, and the only record of which element it clicked is an annotation, if anyone added one.

<AntiPattern.Fix>

Scope healing to the specs that can afford it. Import the fallback helper only in non-critical specs, keep critical flows on strict locators, and let them fail loudly when a locator breaks.

</AntiPattern.Fix>

</AntiPattern>

## The setup we recommend

With the pieces in place, every heal has a place in the pipeline and a record. This is what CI does with each event:

| Event | What CI does |
|---|---|
| The unhealed run passes | The build passes |
| The unhealed run fails | The build fails, and the heal job starts on the failing commit |
| A test passes only on retry | The build fails, through `failOnFlakyTests` |
| The failures pass on the `--last-failed` re-run | Nothing to heal: fix the flake |
| The healer's diff changes only locators in `pages/` | Full re-run, then a draft PR |
| The healer's diff touches an assertion, adds a skip or edits another file | The heal job fails, and a person looks for the regression |
| A runtime fallback fires | A `heal` annotation on the result, and a warning or a failure past the threshold |
| The same test heals twice | Fix the locator in code |

Gate the build on the unhealed run and let healing only propose. A test that needs a heal twice was never on the right locator: rewrite it, and leave the healer for the next real drift.

## Frequently asked questions


### Does Playwright have self-healing tests?

Yes. Playwright's healer agent runs the test suite and automatically repairs failing tests. When a test fails, the healer suggests a patch, such as a locator update, a wait adjustment or a data fix, which sits in the code-level repair layer described in [Three layers of self-healing](#three-layers-of-self-healing).


### How do I set up the Playwright healer agent?

Add the agent definitions with the `init-agents` command, for example `npx playwright init-agents --loop=claude` for Claude Code. The `--loop` option picks the agent client. Regenerate the definitions whenever Playwright is updated, as [How the healer agent works](#how-the-healer-agent-works) explains.


### Can the Playwright healer agent fix a test during a CI run?

Don't plan on it rescuing a run in progress. The healer runs the test suite itself and repairs failing tests automatically.


### How do I tell locator drift from a real test failure?

Heal it when the same user flow still exists on the same commit, and fail it when the patch changes what the test means. A new locator for the same button keeps the test's meaning, and a new expected value replaces it, as [Locator drift vs real failures](#locator-drift-vs-real-failures) explains.


### Should I auto-merge self-healing patches that pass?

No. A passing re-run proves the healed test passes, but it doesn't prove the patch is safe, because the healer's patches can include wait adjustments and data fixes as well as locator updates. Put a script between the healer and the PR that accepts only changed locator lines in page object files, as [A locator-only review gate](#a-locator-only-review-gate) shows.


### How do I see runtime self-healing in Playwright reports?

Record each heal on the test result instead of writing it to the console. While a test is running, you can add annotations to `test.info().annotations`, and `testResult.annotations` includes the annotations appended during the test, so every reporter sees the heal. [Runtime heals as annotations](#runtime-heals-as-annotations) has the helper.


### Are Playwright retries the same as self-healing?

No, a retry pass is not a heal. Playwright categorizes a test that failed on the first run but passed when retried as flaky. As [Retries are not healing](#retries-are-not-healing) recommends, keep retries low on CI and set `failOnFlakyTests` so the run exits with an error if any test is marked flaky.


### When should you not use self-healing in Playwright?

Keep runtime fallback out of login, checkout and payment, and let those tests fail. [When not to self-heal](#when-not-to-self-heal) lists the other cases.




---

## About the author

**Walter Galvão**, Software Engineer. Walter Galvão is a software engineer at Currents. He writes about Playwright in practice: debugging flaky tests, structuring suites for CI, and the engineering workflows that keep large test suites reliable.

LinkedIn: https://www.linkedin.com/in/waltergalvao/
