TestPilot in Your Own Playwright or Selenium Suite
Why This Matters
So far TestPilot has triaged a fixture. The real pay-off comes when it reads your failures: the Playwright or Selenium suite your team already runs every night. This lesson shows where TestPilot fits in an existing suite, how to wire it in, and, just as important, where it does not belong.
The one rule: no AI inside your tests
Your tests decide pass or fail. That decision must stay fast, deterministic and free. So TestPilot never runs inside a test. It runs after the run, on the failures only, and its verdict is advice next to the result, never a change to it.
| Inside a test | After the run | |
|---|---|---|
| Speed | Every test waits for the model | No impact on test time |
| Determinism | Pass/fail could depend on a model answer | Pass/fail untouched |
| Cost | Calls for passing tests too | Only failures, capped |
| Without an API key | Suite breaks | Suite runs; triage is skipped |
Where to use it
TestPilot earns its place where failures pile up and someone has to make sense of them:
- The nightly regression run. The report opens with “6 failed: 2 product bugs, 3 flaky, 1 environment”, not six stack traces.
- Pull request pipelines. A comment on the PR says whether the red test is likely caused by this change, or flaky noise the author can ignore.
- Big end-to-end suites against shared environments, where environment problems (a sandbox down, a slow service) are a large share of failures and should not be filed as bugs.
- Teams with a known flaky backlog. Intermittent failures get recognised and grouped instead of triggering “rerun until green”.
And where it adds little:
- Fast unit test suites. A failing unit test usually points straight at the problem.
- Runs with dozens of identical failures. Group them in code first (lesson 36); triage the group, not every copy.
Playwright: a custom reporter
Playwright gives a reporter everything TestPilot needs: the error and stack, stdout, retries, duration and attachments such as the failure screenshot.
// testpilot-reporter.ts
import type { Reporter, TestCase, TestResult } from "@playwright/test/reporter";
import Anthropic from "@anthropic-ai/sdk";
import { triageFailure } from "./testpilot/triage"; // TestPilot's triage function
import type { TestRun } from "./testpilot/types";
const MAX_TRIAGE = 20;
export default class TestPilotReporter implements Reporter {
private failures: { test: TestCase; result: TestResult }[] = [];
onTestEnd(test: TestCase, result: TestResult) {
if (result.status === "failed" || result.status === "timedOut") this.failures.push({ test, result });
}
async onEnd() {
if (!process.env.ANTHROPIC_API_KEY || this.failures.length === 0) return; // no key: skip quietly
const client = new Anthropic();
const run: TestRun = {
id: process.env.GITHUB_RUN_ID ?? "local", pipeline: "e2e",
branch: process.env.GITHUB_REF_NAME ?? "local", commit: process.env.GITHUB_SHA ?? "local",
startedAt: new Date().toISOString(), environment: process.env.TEST_ENV ?? "local", results: [],
};
const lines = ["## TestPilot triage", ""];
for (const { test, result } of this.failures.slice(0, MAX_TRIAGE)) {
const verdict = await triageFailure(client, run, {
id: test.id,
file: test.location.file,
name: test.titlePath().slice(1).join(" › "),
status: "failed",
durationMs: result.duration,
retries: result.retry,
history: [], // fill from your CI results store (lesson 24) when you have one
error: { message: result.error?.message ?? "", stack: result.error?.stack },
log: result.stdout.map(String).slice(-30),
});
lines.push(`- **${test.title}**: \`${verdict.category}\` (${verdict.confidence.toFixed(2)}): ${verdict.summary}`);
}
if (this.failures.length > MAX_TRIAGE) lines.push(`- …and ${this.failures.length - MAX_TRIAGE} more, not triaged (limit)`);
console.log(lines.join("\n"));
}
}
// playwright.config.ts
reporter: [["html"], ["./testpilot-reporter.ts"]],
The try/catch around each triage call from lesson 13 belongs here too: one API error must cost you one verdict, not the reporter.
Selenium: the same idea in your test framework’s hook
Selenium itself has no reporter; the test framework does. The pattern is identical: collect failures during the run, triage after the run.
pytest
# conftest.py
failures = []
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == "call" and report.failed:
driver = item.funcargs.get("driver")
failures.append({
"id": item.nodeid, "name": item.name, "error": str(call.excinfo.value),
"log": report.capstdout.splitlines()[-30:],
"screenshot": driver.get_screenshot_as_png() if driver else None, # capture now, the page is gone later
})
def pytest_sessionfinish(session, exitstatus):
if failures and os.environ.get("ANTHROPIC_API_KEY"):
triage_and_write_summary(failures) # calls the API like src/triage.ts, writes Markdown
Java (JUnit 5 or TestNG): a TestWatcher extension (JUnit) or an ITestListener (TestNG) collects the failure and takes the screenshot in testFailed / onTestFailure; an after-suite step sends the collected failures for triage.
The one Selenium-specific point: take the screenshot at the moment of failure. By the time the run is over, the browser session is gone.
Show it where people look
- GitHub Actions: append the Markdown to
$GITHUB_STEP_SUMMARY, so the triage is the first thing on the run page. - Pull requests: post it as a comment, updated on each run instead of adding a new one.
- Playwright HTML report: add the verdict as an annotation or text attachment on the failed test, so it sits right next to the trace.
Keep it safe and cheap
- Advisory only. The verdict never changes a test’s status, never retries a test and never files a bug by itself (module 7 adds controlled proposals).
- Only failures, capped.
MAX_TRIAGEstops a broken environment from turning into 300 API calls. Group identical failures first. - Cache the stable part of the prompt (lesson 14): the system prompt and definitions are the same for every failure.
- Secrets in CI secrets. The key comes from the CI secret store; with no key the reporter skips triage and the suite still runs.
- Mind what you send. Logs and screenshots from test environments can contain data that must not leave the company (lesson 12).
Exercise
Add the reporter to a small Playwright project (or to TestPilot’s own example tests), make one test fail on purpose with a wrong expected text, and run it with and without an API key. Check that:
- without a key, the suite result is exactly the same and no triage runs
- with a key, the summary shows a
test_bugverdict with the wrong text as evidence - a passing test never triggers a triage call