Skip to content

fix(browser): surface CDP recovery errors#1736

Merged
zerob13 merged 1 commit into
devfrom
codex/issue-1734-cdp-graceful-degradation
Jun 4, 2026
Merged

fix(browser): surface CDP recovery errors#1736
zerob13 merged 1 commit into
devfrom
codex/issue-1734-cdp-graceful-degradation

Conversation

@zerob13
Copy link
Copy Markdown
Collaborator

@zerob13 zerob13 commented Jun 4, 2026

Summary

Closes #1734

Validation

  • pnpm run format
  • pnpm run i18n
  • pnpm run lint
  • pnpm run typecheck
  • pnpm vitest run test/main/presenter/browser/YoBrowserToolHandler.test.ts test/main/presenter/toolPresenter/agentTools/agentToolManagerYoBrowser.test.ts test/main/presenter/toolPresenter/toolPresenter.test.ts test/main/presenter/agentRuntimePresenter/dispatch.test.ts
  • git diff --check

Summary by CodeRabbit

  • New Features

    • YoBrowser now gracefully handles panel unavailability (closed/detached/hidden), providing agents with structured, recoverable error information
    • Agents receive clear recovery guidance: check browser status and reload target URLs when available
  • Documentation

    • Added implementation specifications and planning documentation for YoBrowser graceful degradation

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 4, 2026

Review Change Stack

📝 Walkthrough

Walkthrough

This PR implements graceful degradation for YoBrowser CDP failures when the browser panel becomes unavailable mid-session. It introduces a recoverable error type, detection logic in the tool handler, structured error transformation in the agent tool manager, and recovery instructions in the tool system prompt.

Changes

YoBrowser CDP Graceful Degradation

Layer / File(s) Summary
Documentation and planning
docs/issues/yobrowser-cdp-graceful-degradation/spec.md, plan.md, tasks.md
Specification, implementation plan, and task checklist documenting the graceful degradation feature, error payload structure, detection and propagation strategy, test approach, and identified risks.
Recoverable error contract and type guards
src/main/presenter/browser/YoBrowserErrors.ts
Defines YoBrowserUnavailableError class, YoBrowserUnavailableErrorPayload interface, error code constant, type-guard predicate, and payload builder that standardize the error shape with code, recoverability flag, session/method context, browser status, and suggested recovery actions.
Handler browser availability detection and error throwing
src/main/presenter/browser/YoBrowserToolHandler.ts, test/main/presenter/browser/YoBrowserToolHandler.test.ts
YoBrowserToolHandler checks getBrowserStatus() for initialization and page attachment before executing cdp_send; constructs and throws YoBrowserUnavailableError when unavailable. Maps YoBrowserNotReadyError exceptions to the recoverable error format. Updates catch logging to distinguish unavailability errors. Unit tests verify error detection and payload structure.
Tool manager error transformation to structured result
src/main/presenter/toolPresenter/agentTools/agentToolManager.ts, test/main/presenter/toolPresenter/agentTools/agentToolManagerYoBrowser.test.ts
AgentToolManager wraps YoBrowser tool invocation in try/catch, transforming non-unavailability errors into structured responses with stringified payload content and rawData.toolResult envelope via createAgentToolErrorResult, while rethrown unavailability errors propagate upward. Unit tests verify structured error transformation.
Tool system prompt recovery instructions and tests
src/main/presenter/toolPresenter/index.ts, test/main/presenter/toolPresenter/toolPresenter.test.ts
Updates cdp_send tool prompt to include explicit fallback guidance: when yobrowser_unavailable is returned, call get_browser_status and then use load_url with target URL when available. Verifies prompt text in system tests.
Integration test for full error propagation through agent execution
test/main/presenter/agentRuntimePresenter/dispatch.test.ts
Verifies that recoverable yobrowser_unavailable error payloads returned by cdp_send are correctly treated as tool errors: tool message contains error code, tool_call response contains error code, and block status is marked 'error'.

Sequence Diagram(s)

sequenceDiagram
  participant Agent
  participant AgentToolManager
  participant YoBrowserHandler
  participant Presenter
  participant ErrorPayload
  Agent->>AgentToolManager: callTool('cdp_send', args)
  AgentToolManager->>YoBrowserHandler: callTool('cdp_send', args)
  YoBrowserHandler->>Presenter: getBrowserStatus(sessionId)
  Presenter-->>YoBrowserHandler: {initialized: false, page: null, ...}
  alt Browser unavailable
    YoBrowserHandler->>ErrorPayload: buildYoBrowserUnavailablePayload(sessionId, method, status)
    ErrorPayload-->>YoBrowserHandler: {error: {code, recoverable, nextActions}, ...}
    YoBrowserHandler->>YoBrowserHandler: throw YoBrowserUnavailableError(payload)
    YoBrowserHandler-->>AgentToolManager: YoBrowserUnavailableError
    AgentToolManager-->>AgentToolManager: rethrow (propagate upward)
  else Browser ready
    YoBrowserHandler->>Presenter: sendCdpCommand(...)
    Presenter-->>YoBrowserHandler: result
    YoBrowserHandler-->>AgentToolManager: success response
    AgentToolManager-->>Agent: tool result
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • ThinkInAIXYZ/deepchat#1357: Refactors YoBrowser tools to use session-based get_browser_status, load_url, and cdp_send patterns; this PR's error handling layer builds upon that tool execution path.

Poem

🐰 When panels close and browsers fade away,
A graceful error shows the agent the way—
"Browser unavailable," structured and clear,
Recover with get_status, no need to fear!
From silence to signal, from crash into grace, 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix(browser): surface CDP recovery errors' directly describes the main change—introducing recoverable error handling for CDP failures when the YoBrowser is unavailable, enabling the agent to adapt.
Linked Issues check ✅ Passed The PR implements graceful degradation (suggested fix direction #2) by returning meaningful, recoverable errors from CDP calls so the agent can adjust strategy, directly addressing issue #1734's expected behavior.
Out of Scope Changes check ✅ Passed All changes are narrowly scoped to implementing the graceful degradation pattern: error contract definition, CDP failure detection/mapping, structured error propagation, agent prompt guidance, and focused testing—no auto-recovery or state synchronization changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/issue-1734-cdp-graceful-degradation

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
docs/issues/yobrowser-cdp-graceful-degradation/tasks.md (1)

16-19: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add typecheck to the validation checklist for consistency.

The task list omits pnpm run typecheck, which is part of this PR’s stated validation steps. Adding it keeps the checklist auditable.

Suggested diff
 - [x] Run `pnpm run format`.
 - [x] Run `pnpm run i18n`.
 - [x] Run `pnpm run lint`.
+- [x] Run `pnpm run typecheck`.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/issues/yobrowser-cdp-graceful-degradation/tasks.md` around lines 16 -
19, Add the missing checklist entry for typechecking in the tasks checklist by
inserting an item for "Run `pnpm run typecheck`" alongside the existing
format/i18n/lint lines in the tasks block (the checklist items in
docs/issues/yobrowser-cdp-graceful-degradation/tasks.md), ensuring it matches
the same checked-box style ("- [x] Run `pnpm run typecheck`.") so the validation
steps are auditable and consistent.
src/main/presenter/browser/YoBrowserToolHandler.ts (1)

67-77: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Refresh browserStatus before wrapping YoBrowserNotReadyError.

Line 76 reuses the preflight status, so if the page detaches after Line 51 the emitted payload.error.browserStatus can still say the session is initialized/visible. That makes the new recoverable error contract report the wrong state right when the agent needs it for recovery. Build this branch from a fresh status lookup instead of the stale snapshot.

Proposed fix
-              throw await this.createUnavailableError(sessionId, method, status, error)
+              throw await this.createUnavailableError(sessionId, method, undefined, error)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main/presenter/browser/YoBrowserToolHandler.ts` around lines 67 - 77, The
branch handling YoBrowserNotReadyError in YoBrowserToolHandler currently reuses
the stale preflight status snapshot; before calling createUnavailableError (and
before logging the final payload), refresh the page/browser status by invoking
the same status lookup used earlier (e.g., the method or helper that produced
`status` for the preflight check) to obtain an up-to-date `browserStatus`/page
status, then use that fresh status in the logger and when calling
this.createUnavailableError(sessionId, method, freshStatus, error) so the
wrapped recoverable error reports current state rather than the stale snapshot.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@docs/issues/yobrowser-cdp-graceful-degradation/tasks.md`:
- Around line 16-19: Add the missing checklist entry for typechecking in the
tasks checklist by inserting an item for "Run `pnpm run typecheck`" alongside
the existing format/i18n/lint lines in the tasks block (the checklist items in
docs/issues/yobrowser-cdp-graceful-degradation/tasks.md), ensuring it matches
the same checked-box style ("- [x] Run `pnpm run typecheck`.") so the validation
steps are auditable and consistent.

In `@src/main/presenter/browser/YoBrowserToolHandler.ts`:
- Around line 67-77: The branch handling YoBrowserNotReadyError in
YoBrowserToolHandler currently reuses the stale preflight status snapshot;
before calling createUnavailableError (and before logging the final payload),
refresh the page/browser status by invoking the same status lookup used earlier
(e.g., the method or helper that produced `status` for the preflight check) to
obtain an up-to-date `browserStatus`/page status, then use that fresh status in
the logger and when calling this.createUnavailableError(sessionId, method,
freshStatus, error) so the wrapped recoverable error reports current state
rather than the stale snapshot.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: aa0ee280-1d94-4282-a3df-2539c910e99e

📥 Commits

Reviewing files that changed from the base of the PR and between c59e32d and bbfad09.

📒 Files selected for processing (11)
  • docs/issues/yobrowser-cdp-graceful-degradation/plan.md
  • docs/issues/yobrowser-cdp-graceful-degradation/spec.md
  • docs/issues/yobrowser-cdp-graceful-degradation/tasks.md
  • src/main/presenter/browser/YoBrowserErrors.ts
  • src/main/presenter/browser/YoBrowserToolHandler.ts
  • src/main/presenter/toolPresenter/agentTools/agentToolManager.ts
  • src/main/presenter/toolPresenter/index.ts
  • test/main/presenter/agentRuntimePresenter/dispatch.test.ts
  • test/main/presenter/browser/YoBrowserToolHandler.test.ts
  • test/main/presenter/toolPresenter/agentTools/agentToolManagerYoBrowser.test.ts
  • test/main/presenter/toolPresenter/toolPresenter.test.ts

@zerob13 zerob13 merged commit d566c6a into dev Jun 4, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(browser): YoBrowser panel closed mid-session breaks subsequent agent CDP calls

1 participant