openqa icon indicating copy to clipboard operation
openqa copied to clipboard

Revisit Claude Code Hooks implementation for improved error handling and reporting

Open gurvinder-dhillon opened this issue 7 months ago • 1 comments

Problem Statement

Currently, OpenQA implements a hard-coded logic in Orchestrator.js to handle tool errors. Specifically, when a Playwright MCP verification or assertion tool (browser_verify_*) returns an error, the Orchestrator abruptly kills the Claude Code subprocess and rejects the promise.

While this ensures that failing assertions cause the test to fail, it has several drawbacks:

  1. Lack of Meaningful Output: The agent ends abruptly, so we lose any summary or reasoning the agent might have provided after the failure.
  2. Poor Reporting: The Playwright test report only shows the rejection error from the Orchestrator, rather than a cohesive explanation from the AI agent.
  3. Inflexibility: The decision to fail is hard-coded based on tool names rather than an intelligent evaluation of the situation.

Current Behavior Example

When an assertion fails, the process is killed immediately:

Error: Assertion failed: ### Error
Text not found
### Page
- Page URL: https://demo.playwright.dev/todomvc/#/
- Page Title: React • TodoMVC
- Console: 1 errors, 0 warnings
### Events
- New console entries: .playwright-mcp/console-2026-05-03T02-13-10-785Z.log#L1-L2

   at ../../src/agent/Orchestrator.js:167

  165 |                                 if (lastToolName.includes('browser_verify_')) {
  166 |                                     // Assertion tool failed → definitive test failure
> 167 |                                     const err = new Error(`Assertion failed: ${event.error}`);
      |                                                 ^
  168 |                                     child.kill();
  169 |                                     reject(err);
  170 |                                 }

Research & Exploration

We want to explore alternative ways to implement hooks using Claude Code's native capabilities. Instead of hard-coding failure logic in the bridge, we want the agent to evaluate its own progress and decide whether to continue or terminate gracefully with a report.

Documentation to Review

Please read the following Claude Code documentation on hooks:

Considerations for Brainstorming

  • Session Resumption: Every step in our feature file is executed by Claude Code one at a time, resuming the session.
  • Intelligent Evaluation: Claude should be able to evaluate the situation and decide if a failure is a real test failure (to be reported) or a transient agent error that can be retried.
  • Generic Hooks: Explore using generic hooks (e.g., triggered on each prompt start or post-tool) that can run a prompt to decide the next action.
  • Graceful Termination: The agent should be able to summarize the test result and exit gracefully.
  • Reporting to Playwright: We need a mechanism to ensure that if the agent decides the test has failed, it still triggers a Playwright failure (perhaps by executing a final failing assertion tool call) so the Playwright results are accurate and contain the agent's summary.

gurvinder-dhillon avatar May 03 '26 04:05 gurvinder-dhillon

Resolved in v0.0.7 — PR #10

All items in this issue have been addressed. Here's what was implemented:

1. Graceful Assertion Failure (replaces child.kill())

Removed the hard-coded child.kill() + immediate reject(). The Orchestrator now sets an assertionFailed flag and waits for the subprocess to exit naturally. Claude writes its own failure summary before stopping.

2. Native Claude Code Hooks (PostToolUseFailure + Stop)

Two prompt-based hooks are now scaffolded into .openqa/.claude/settings.json via openqa init:

  • PostToolUseFailure (matcher: browser_verify_*) — fires the moment a verification tool fails. Returns decision: "block" to prevent any further tool calls, and injects additionalContext instructing Claude to write a 1–2 sentence failure report then stop.
  • Stop — quality gate that fires when Claude finishes its turn. Checks if a browser_verify_* tool was called and, if so, validates that Claude's output contains a proper failure summary. Returns ok: false with guidance if the report is missing or vague.

3. Meaningful Failure Reports

Claude now writes its own failure summary (e.g. "Expected 'Buy fruits' to be visible but the todo list only contained 'Buy groceries'") which appears in the Playwright test report instead of the raw ### Error string.

4. Provider Decoupling

tool_error events now carry toolName (correlated from tool_use_id). The Orchestrator no longer tracks lastToolName state across events — each event is self-describing, and the architecture is ready for additional providers beyond Claude Code.

5. Token Optimizations

  • outputMode: 'file' — console/network/snapshot logs go to .playwright-mcp/ files instead of the agent context window
  • saveSession: true — MCP session persisted across steps
  • Action responses include [Snapshot](path.yml) links; agent reuses those refs instead of calling browser_snapshot before every action

Key files changed

  • src/agent/Orchestrator.js — graceful failure, updated system prompt
  • src/agent/providers/claudeCode.js — toolName on tool_error events, per-instance Map closure
  • src/cli/init.js — generates .openqa/.claude/settings.json with hooks during openqa init

gurvinder-dhillon avatar May 03 '26 17:05 gurvinder-dhillon