Skip to main content

browser_control/
errors.rs

1//! Shared error types.
2
3use thiserror::Error;
4
5/// Typed errors raised from the page-session layer so callers (and tests) can
6/// pattern-match on the failure category — in particular, `TabHung` is the
7/// catch-all for the alive-but-unresponsive renderer case that has no
8/// protocol event signal.
9#[derive(Debug, Error)]
10pub enum SessionError {
11    /// Op exceeded its per-call timeout without a reply and without a crash
12    /// event. The most likely cause is a wedged renderer (service-worker
13    /// suspended page, infinite loop, modal dialog, etc.). The agent should
14    /// treat the tab as unusable until reloaded or recreated.
15    #[error("tab hung: op exceeded {timeout_ms}ms without reply ({hint}) [target={target_id:?} url={url:?}]")]
16    TabHung {
17        target_id: Option<String>,
18        url: Option<String>,
19        timeout_ms: u64,
20        hint: &'static str,
21    },
22    /// Renderer crashed mid-op (observed via `Target.targetCrashed` /
23    /// `Inspector.targetCrashed`). Distinct from `TabHung` so callers can
24    /// distinguish "definitely dead" from "presumed wedged."
25    #[error("tab crashed: {reason} [target={target_id:?}]")]
26    TabCrashed { target_id: String, reason: String },
27    /// `<browser>/<name>` referenced a tab that doesn't exist in the
28    /// `tabs` registry. Agents see this when they reference a tab they
29    /// haven't `tab open`'d yet — the recovery is to open it first.
30    /// Distinct from `TabHung` because the tab was never there to wedge.
31    #[error("no tab `{name}` registered for browser `{browser}` — run `browser-control tab open {browser}/{name}` first")]
32    TabNotFound { browser: String, name: String },
33    /// Protocol-level error indicating the underlying target/session/context
34    /// referenced by the request no longer exists in the browser. Raised by
35    /// the CDP/BiDi client layer when the server returns a recognised
36    /// "gone" code (e.g. `no target with given id`, `no such frame`). The
37    /// recover-once wrappers treat this as a signal to recreate the tab
38    /// and retry; otherwise it would surface as a generic protocol error.
39    #[error("{kind:?} target gone: {details}")]
40    TargetGone { kind: TargetKind, details: String },
41    /// The requested operation cannot run against the currently selected
42    /// browser engine. Used by the Playwright sidecar tools (snapshot,
43    /// click, type, etc.) when the active browser is BiDi (Firefox) —
44    /// Playwright can't drive a user-launched Firefox. The agent's
45    /// recovery is to `browser_select` a Chromium-family browser, or
46    /// to use the engine-agnostic tools (`browser_get_html`,
47    /// `browser_fetch`, `browser_navigate`, etc.) which work on both engines.
48    #[error("tool `{tool}` requires {required_engine} engine; current browser uses {current_engine} ({hint})")]
49    EngineUnsupported {
50        tool: String,
51        required_engine: String,
52        current_engine: String,
53        hint: &'static str,
54    },
55}
56
57/// Which protocol surfaced a `TargetGone`. Useful for diagnostics; the
58/// recovery path treats both kinds identically.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum TargetKind {
61    Cdp,
62    Bidi,
63}
64
65/// Substrings that, when found in a CDP error `message`, indicate the
66/// target/session referenced by the call no longer exists. Centralised so
67/// the client-layer classifier and the recovery-wrapper fallback agree.
68pub const CDP_TARGET_GONE_NEEDLES: &[&str] = &[
69    "no target with given id",
70    "session is gone",
71    "no session with given id",
72    "target closed",
73];
74
75/// Substrings that indicate a BiDi context/frame/session is gone. BiDi
76/// also surfaces context-gone via the dedicated error codes
77/// `no such frame` / `no such context` etc.; we match on message text so
78/// we catch both shapes.
79pub const BIDI_TARGET_GONE_NEEDLES: &[&str] = &[
80    "no such frame",
81    "no such node",
82    "no such context",
83    "invalid session id",
84];
85
86/// Returns true if `message` matches any CDP "target gone" indicator.
87pub fn is_cdp_target_gone(message: &str) -> bool {
88    let m = message.to_ascii_lowercase();
89    CDP_TARGET_GONE_NEEDLES.iter().any(|n| m.contains(n))
90}
91
92/// Returns true if `code` or `message` indicates a BiDi context is gone.
93/// BiDi codes are stable per spec (`no such frame`, etc.), but we also
94/// scan the message in case the code is generic.
95pub fn is_bidi_target_gone(code: &str, message: &str) -> bool {
96    let c = code.to_ascii_lowercase();
97    if BIDI_TARGET_GONE_NEEDLES.iter().any(|n| c.contains(n)) {
98        return true;
99    }
100    let m = message.to_ascii_lowercase();
101    BIDI_TARGET_GONE_NEEDLES.iter().any(|n| m.contains(n))
102}
103
104/// Single shared predicate for "the tab the op targeted is dead; one
105/// recover-and-retry round is appropriate." Used by `with_scratch_recovery`,
106/// `with_named_tab_recovery`, and the origin-bound evaluate helper.
107/// Keeping these in one place avoids the call
108/// sites drifting apart on what counts as recoverable.
109pub fn is_recoverable_tab_failure(err: &anyhow::Error) -> bool {
110    if let Some(se) = err.downcast_ref::<SessionError>() {
111        return matches!(
112            se,
113            SessionError::TabHung { .. }
114                | SessionError::TabCrashed { .. }
115                | SessionError::TargetGone { .. }
116        );
117    }
118    let msg = format!("{err:#}").to_ascii_lowercase();
119    CDP_TARGET_GONE_NEEDLES.iter().any(|n| msg.contains(n))
120        || BIDI_TARGET_GONE_NEEDLES.iter().any(|n| msg.contains(n))
121}