Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(browser): prevent concurrent browser actions from corrupting state

Steven Enamakeladce4600fb4e
diff --git a/crates/openhuman-core/src/tools/impl/browser/browser_computer_use.rs b/crates/openhuman-core/src/tools/impl/browser/browser_computer_use.rs
index d11bb05a4d..db162a95ac 100644
--- a/crates/openhuman-core/src/tools/impl/browser/browser_computer_use.rs
+++ b/crates/openhuman-core/src/tools/impl/browser/browser_computer_use.rs
@@ -160,5 +160,4 @@ impl BrowserTool {
body.trim()
)))
}
-
}
diff --git a/crates/openhuman-core/src/tools/impl/browser/browser_construction.rs b/crates/openhuman-core/src/tools/impl/browser/browser_construction.rs
index bc5700c2b0..d20920d1e4 100644
--- a/crates/openhuman-core/src/tools/impl/browser/browser_construction.rs
+++ b/crates/openhuman-core/src/tools/impl/browser/browser_construction.rs
@@ -92,5 +92,4 @@ impl BrowserTool {
false
}
}
-
}
diff --git a/crates/openhuman-core/src/tools/impl/browser/browser_part_01.rs b/crates/openhuman-core/src/tools/impl/browser/browser_part_01.rs
deleted file mode 100644
index a16e8b5ae9..0000000000
--- a/crates/openhuman-core/src/tools/impl/browser/browser_part_01.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-
-use super::playwright_backend;
-#[allow(unused_imports)]
-pub(super) use action_parser::{
- backend_name, is_computer_use_only_action, is_supported_browser_action, parse_browser_action,
- unavailable_action_for_backend_error,
-};
-pub(super) use security::{
- allow_all_browser_domains, endpoint_reachable, extract_host, host_matches_allowlist,
- is_private_host, normalize_domains,
-};
-pub(super) use types::{
- AgentBrowserResponse, BrowserBackendKind, ComputerUseResponse, ResolvedBackend,
-};
-pub use types::{BrowserAction, ComputerUseConfig};
-
-use crate::security::SecurityPolicy;
-use crate::tools::traits::{Tool, ToolResult};
-use anyhow::Context;
-use async_trait::async_trait;
-use serde_json::{json, Value};
-use std::process::Stdio;
-use std::sync::Arc;
-use std::time::Duration;
-use tokio::process::Command;
-use tracing::debug;
-
-/// Browser automation tool using pluggable backends.
-pub struct BrowserTool {
- security: Arc<SecurityPolicy>,
- allowed_domains: Vec<String>,
- session_name: Option<String>,
- backend: String,
- native_headless: bool,
- native_webdriver_url: String,
- native_chrome_path: Option<String>,
- computer_use: ComputerUseConfig,
- playwright_state: tokio::sync::Mutex<playwright_backend::PlaywrightBrowserState>,
- #[cfg(feature = "browser-native")]
- native_state: tokio::sync::Mutex<native_backend::NativeBrowserState>,
-}
diff --git a/crates/openhuman-core/src/tools/impl/browser/browser_part_02.rs b/crates/openhuman-core/src/tools/impl/browser/browser_part_02.rs
deleted file mode 100644
index 7a426d5e97..0000000000
--- a/crates/openhuman-core/src/tools/impl/browser/browser_part_02.rs
+++ /dev/null
@@ -1,679 +0,0 @@
-
-impl BrowserTool {
- pub fn new(
- security: Arc<SecurityPolicy>,
- allowed_domains: Vec<String>,
- session_name: Option<String>,
- ) -> Self {
- Self::new_with_backend(
- security,
- allowed_domains,
- session_name,
- "agent_browser".into(),
- true,
- "http://127.0.0.1:9515".into(),
- None,
- ComputerUseConfig::default(),
- )
- }
-
- #[allow(clippy::too_many_arguments)]
- pub fn new_with_backend(
- security: Arc<SecurityPolicy>,
- allowed_domains: Vec<String>,
- session_name: Option<String>,
- backend: String,
- native_headless: bool,
- native_webdriver_url: String,
- native_chrome_path: Option<String>,
- computer_use: ComputerUseConfig,
- ) -> Self {
- Self {
- security,
- allowed_domains: normalize_domains(allowed_domains),
- session_name,
- backend,
- native_headless,
- native_webdriver_url,
- native_chrome_path,
- computer_use,
- playwright_state: tokio::sync::Mutex::new(
- playwright_backend::PlaywrightBrowserState::default(),
- ),
- #[cfg(feature = "browser-native")]
- native_state: tokio::sync::Mutex::new(native_backend::NativeBrowserState::default()),
- }
- }
-
- /// Check if agent-browser tool is available
- pub async fn is_agent_browser_available() -> bool {
- Command::new("agent-browser")
- .arg("--version")
- .stdout(Stdio::null())
- .stderr(Stdio::null())
- .status()
- .await
- .map(|s| s.success())
- .unwrap_or(false)
- }
-
- /// Backward-compatible alias.
- pub async fn is_available() -> bool {
- Self::is_agent_browser_available().await
- }
-
- /// Check if the local Playwright package is available to Node.js.
- pub async fn is_playwright_available() -> bool {
- playwright_backend::PlaywrightBrowserState::is_available().await
- }
-
- fn configured_backend(&self) -> anyhow::Result<BrowserBackendKind> {
- BrowserBackendKind::parse(&self.backend)
- }
-
- fn rust_native_compiled() -> bool {
- cfg!(feature = "browser-native")
- }
-
- fn rust_native_available(&self) -> bool {
- #[cfg(feature = "browser-native")]
- {
- native_backend::NativeBrowserState::is_available(
- self.native_headless,
- &self.native_webdriver_url,
- self.native_chrome_path.as_deref(),
- )
- }
- #[cfg(not(feature = "browser-native"))]
- {
- false
- }
- }
-
- fn computer_use_endpoint_url(&self) -> anyhow::Result<reqwest::Url> {
- if self.computer_use.timeout_ms == 0 {
- anyhow::bail!("browser.computer_use.timeout_ms must be > 0");
- }
-
- let endpoint = self.computer_use.endpoint.trim();
- if endpoint.is_empty() {
- anyhow::bail!("browser.computer_use.endpoint cannot be empty");
- }
-
- let parsed = reqwest::Url::parse(endpoint).map_err(|_| {
- anyhow::anyhow!(
- "Invalid browser.computer_use.endpoint: '{endpoint}'. Expected http(s) URL"
- )
- })?;
-
- let scheme = parsed.scheme();
- if scheme != "http" && scheme != "https" {
- anyhow::bail!("browser.computer_use.endpoint must use http:// or https://");
- }
-
- let host = parsed
- .host_str()
- .ok_or_else(|| anyhow::anyhow!("browser.computer_use.endpoint must include host"))?;
-
- let host_is_private = is_private_host(host);
- if !self.computer_use.allow_remote_endpoint && !host_is_private {
- anyhow::bail!(
- "browser.computer_use.endpoint host '{host}' is public. Set browser.computer_use.allow_remote_endpoint=true to allow it"
- );
- }
-
- if self.computer_use.allow_remote_endpoint && !host_is_private && scheme != "https" {
- anyhow::bail!(
- "browser.computer_use.endpoint must use https:// when allow_remote_endpoint=true and host is public"
- );
- }
-
- Ok(parsed)
- }
-
- fn computer_use_available(&self) -> anyhow::Result<bool> {
- let endpoint = self.computer_use_endpoint_url()?;
- Ok(endpoint_reachable(&endpoint, Duration::from_millis(500)))
- }
-
- async fn resolve_backend(&self) -> anyhow::Result<ResolvedBackend> {
- let configured = self.configured_backend()?;
-
- match configured {
- BrowserBackendKind::AgentBrowser => {
- if Self::is_agent_browser_available().await {
- Ok(ResolvedBackend::AgentBrowser)
- } else {
- anyhow::bail!(
- "browser.backend='{}' but agent-browser is unavailable. Install it in your environment.",
- configured.as_str()
- )
- }
- }
- BrowserBackendKind::Playwright => {
- if Self::is_playwright_available().await {
- Ok(ResolvedBackend::Playwright)
- } else {
- anyhow::bail!(
- "browser.backend='playwright' but Playwright is unavailable. Ensure app/node_modules is installed, run `pnpm --filter openhuman-app exec playwright install chromium-headless-shell`, or set OPENHUMAN_PLAYWRIGHT_CWD."
- )
- }
- }
- BrowserBackendKind::RustNative => {
- if !Self::rust_native_compiled() {
- anyhow::bail!(
- "browser.backend='rust_native' requires build feature 'browser-native'"
- );
- }
- if !self.rust_native_available() {
- anyhow::bail!(
- "Rust-native browser backend is enabled but WebDriver endpoint is unreachable. Set browser.native_webdriver_url and start a compatible driver"
- );
- }
- Ok(ResolvedBackend::RustNative)
- }
- BrowserBackendKind::ComputerUse => {
- if !self.computer_use_available()? {
- anyhow::bail!(
- "browser.backend='computer_use' but sidecar endpoint is unreachable. Check browser.computer_use.endpoint and sidecar status"
- );
- }
- Ok(ResolvedBackend::ComputerUse)
- }
- BrowserBackendKind::Auto => {
- if Self::rust_native_compiled() && self.rust_native_available() {
- return Ok(ResolvedBackend::RustNative);
- }
- if Self::is_playwright_available().await {
- return Ok(ResolvedBackend::Playwright);
- }
- if Self::is_agent_browser_available().await {
- return Ok(ResolvedBackend::AgentBrowser);
- }
-
- let computer_use_err = match self.computer_use_available() {
- Ok(true) => return Ok(ResolvedBackend::ComputerUse),
- Ok(false) => None,
- Err(err) => Some(err.to_string()),
- };
-
- if Self::rust_native_compiled() {
- if let Some(err) = computer_use_err {
- anyhow::bail!(
- "browser.backend='auto' found no usable backend (playwright missing, agent-browser missing, rust-native unavailable, computer-use invalid: {err})"
- );
- }
- anyhow::bail!(
- "browser.backend='auto' found no usable backend (playwright missing, agent-browser missing, rust-native unavailable, computer-use sidecar unreachable)"
- )
- }
-
- if let Some(err) = computer_use_err {
- anyhow::bail!(
- "browser.backend='auto' needs Playwright, agent-browser tool, browser-native, or valid computer-use sidecar (error: {err})"
- );
- }
-
- anyhow::bail!(
- "browser.backend='auto' needs Playwright, agent-browser tool, browser-native, or computer-use sidecar"
- )
- }
- }
- }
-
- /// Validate URL against allowlist
- fn validate_url(&self, url: &str) -> anyhow::Result<()> {
- let url = url.trim();
-
- if url.is_empty() {
- anyhow::bail!("URL cannot be empty");
- }
-
- // Block file:// URLs — browser file access bypasses all SSRF and
- // domain-allowlist controls and can exfiltrate arbitrary local files.
- if url.starts_with("file://") {
- anyhow::bail!("file:// URLs are not allowed in browser automation");
- }
-
- if !url.starts_with("https://") && !url.starts_with("http://") {
- anyhow::bail!("Only http:// and https:// URLs are allowed");
- }
-
- if self.allowed_domains.is_empty() && !allow_all_browser_domains() {
- anyhow::bail!(
- "Browser tool enabled but no allowed_domains configured. \
- Add [browser].allowed_domains in config.toml or set OPENHUMAN_BROWSER_ALLOW_ALL=1"
- );
- }
-
- let host = extract_host(url)?;
-
- if is_private_host(&host) {
- anyhow::bail!("Blocked local/private host: {host}");
- }
-
- if !self.allowed_domains.is_empty() && !host_matches_allowlist(&host, &self.allowed_domains)
- {
- anyhow::bail!("Host '{host}' not in browser.allowed_domains");
- }
-
- Ok(())
- }
-
- /// Execute an agent-browser command
- async fn run_command(&self, args: &[&str]) -> anyhow::Result<AgentBrowserResponse> {
- let mut cmd = Command::new("agent-browser");
-
- // Add session if configured
- if let Some(ref session) = self.session_name {
- cmd.arg("--session").arg(session);
- }
-
- // Add --json for machine-readable output
- cmd.args(args).arg("--json");
-
- debug!("Running: agent-browser {} --json", args.join(" "));
-
- let output = cmd
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .output()
- .await?;
-
- let stdout = String::from_utf8_lossy(&output.stdout);
- let stderr = String::from_utf8_lossy(&output.stderr);
-
- if !stderr.is_empty() {
- debug!("agent-browser stderr: {}", stderr);
- }
-
- // Parse JSON response
- if let Ok(resp) = serde_json::from_str::<AgentBrowserResponse>(&stdout) {
- return Ok(resp);
- }
-
- // Fallback for non-JSON output
- if output.status.success() {
- Ok(AgentBrowserResponse {
- success: true,
- data: Some(json!({ "output": stdout.trim() })),
- error: None,
- })
- } else {
- Ok(AgentBrowserResponse {
- success: false,
- data: None,
- error: Some(stderr.trim().to_string()),
- })
- }
- }
-
- /// Execute a browser action via agent-browser tool
- #[allow(clippy::too_many_lines)]
- async fn execute_agent_browser_action(
- &self,
- action: BrowserAction,
- ) -> anyhow::Result<ToolResult> {
- match action {
- BrowserAction::Open { url } => {
- self.validate_url(&url)?;
- let resp = self.run_command(&["open", &url]).await?;
- self.to_result(resp)
- }
-
- BrowserAction::Snapshot {
- interactive_only,
- compact,
- depth,
- } => {
- let mut args = vec!["snapshot"];
- if interactive_only {
- args.push("-i");
- }
- if compact {
- args.push("-c");
- }
- let depth_str;
- if let Some(d) = depth {
- args.push("-d");
- depth_str = d.to_string();
- args.push(&depth_str);
- }
- let resp = self.run_command(&args).await?;
- self.to_result(resp)
- }
-
- BrowserAction::Click { selector } => {
- let resp = self.run_command(&["click", &selector]).await?;
- self.to_result(resp)
- }
-
- BrowserAction::Fill { selector, value } => {
- let resp = self.run_command(&["fill", &selector, &value]).await?;
- self.to_result(resp)
- }
-
- BrowserAction::Type { selector, text } => {
- let resp = self.run_command(&["type", &selector, &text]).await?;
- self.to_result(resp)
- }
-
- BrowserAction::GetText { selector } => {
- let resp = self.run_command(&["get", "text", &selector]).await?;
- self.to_result(resp)
- }
-
- BrowserAction::GetTitle => {
- let resp = self.run_command(&["get", "title"]).await?;
- self.to_result(resp)
- }
-
- BrowserAction::GetUrl => {
- let resp = self.run_command(&["get", "url"]).await?;
- self.to_result(resp)
- }
-
- BrowserAction::Wait { selector, ms, text } => {
- let mut args = vec!["wait"];
- let ms_str;
- if let Some(sel) = selector.as_ref() {
- args.push(sel);
- } else if let Some(millis) = ms {
- ms_str = millis.to_string();
- args.push(&ms_str);
- } else if let Some(ref t) = text {
- args.push("--text");
- args.push(t);
- }
- let resp = self.run_command(&args).await?;
- self.to_result(resp)
- }
-
- BrowserAction::Press { key } => {
- let resp = self.run_command(&["press", &key]).await?;
- self.to_result(resp)
- }
-
- BrowserAction::Hover { selector } => {
- let resp = self.run_command(&["hover", &selector]).await?;
- self.to_result(resp)
- }
-
- BrowserAction::Scroll { direction, pixels } => {
- let mut args = vec!["scroll", &direction];
- let px_str;
- if let Some(px) = pixels {
- px_str = px.to_string();
- args.push(&px_str);
- }
- let resp = self.run_command(&args).await?;
- self.to_result(resp)
- }
-
- BrowserAction::IsVisible { selector } => {
- let resp = self.run_command(&["is", "visible", &selector]).await?;
- self.to_result(resp)
- }
-
- BrowserAction::Close => {
- let resp = self.run_command(&["close"]).await?;
- self.to_result(resp)
- }
-
- BrowserAction::Find {
- by,
- value,
- action,
- fill_value,
- } => {
- let mut args = vec!["find", &by, &value, &action];
- if let Some(ref fv) = fill_value {
- args.push(fv);
- }
- let resp = self.run_command(&args).await?;
- self.to_result(resp)
- }
- }
- }
-
- #[allow(clippy::unused_async)]
- async fn execute_rust_native_action(
- &self,
- action: BrowserAction,
- ) -> anyhow::Result<ToolResult> {
- #[cfg(feature = "browser-native")]
- {
- let mut state = self.native_state.lock().await;
-
- let output = state
- .execute_action(
- action,
- self.native_headless,
- &self.native_webdriver_url,
- self.native_chrome_path.as_deref(),
- )
- .await?;
-
- Ok(ToolResult::success(
- serde_json::to_string_pretty(&output).unwrap_or_default(),
- ))
- }
-
- #[cfg(not(feature = "browser-native"))]
- {
- let _ = action;
- anyhow::bail!(
- "Rust-native browser backend is not compiled. Rebuild with --features browser-native"
- )
- }
- }
-
- async fn execute_playwright_action(&self, action: BrowserAction) -> anyhow::Result<ToolResult> {
- if let BrowserAction::Open { url } = &action {
- debug!("[browser] validating playwright open url before dispatch");
- self.validate_url(url)?;
- }
-
- let mut state = self.playwright_state.lock().await;
- let output = state
- .execute_action(
- action,
- self.native_headless,
- Some(playwright_backend::BrowserUrlPolicy {
- allowed_domains: self.allowed_domains.clone(),
- allow_all: allow_all_browser_domains(),
- }),
- )
- .await
- .context("Playwright browser action failed")?;
-
- Ok(ToolResult::success(
- serde_json::to_string_pretty(&output).unwrap_or_default(),
- ))
- }
-
- fn validate_coordinate(&self, key: &str, value: i64, max: Option<i64>) -> anyhow::Result<()> {
- if value < 0 {
- anyhow::bail!("'{key}' must be >= 0")
- }
- if let Some(limit) = max {
- if limit < 0 {
- anyhow::bail!("Configured coordinate limit for '{key}' must be >= 0")
- }
- if value > limit {
- anyhow::bail!("'{key}'={value} exceeds configured limit {limit}")
- }
- }
- Ok(())
- }
-
- fn read_required_i64(
- &self,
- params: &serde_json::Map<String, Value>,
- key: &str,
- ) -> anyhow::Result<i64> {
- params
- .get(key)
- .and_then(Value::as_i64)
- .ok_or_else(|| anyhow::anyhow!("Missing or invalid '{key}' parameter"))
- }
-
- fn validate_computer_use_action(
- &self,
- action: &str,
- params: &serde_json::Map<String, Value>,
- ) -> anyhow::Result<()> {
- match action {
- "open" => {
- let url = params
- .get("url")
- .and_then(Value::as_str)
- .ok_or_else(|| anyhow::anyhow!("Missing 'url' for open action"))?;
- self.validate_url(url)?;
- }
- "mouse_move" | "mouse_click" => {
- let x = self.read_required_i64(params, "x")?;
- let y = self.read_required_i64(params, "y")?;
- self.validate_coordinate("x", x, self.computer_use.max_coordinate_x)?;
- self.validate_coordinate("y", y, self.computer_use.max_coordinate_y)?;
- }
- "mouse_drag" => {
- let from_x = self.read_required_i64(params, "from_x")?;
- let from_y = self.read_required_i64(params, "from_y")?;
- let to_x = self.read_required_i64(params, "to_x")?;
- let to_y = self.read_required_i64(params, "to_y")?;
- self.validate_coordinate("from_x", from_x, self.computer_use.max_coordinate_x)?;
- self.validate_coordinate("to_x", to_x, self.computer_use.max_coordinate_x)?;
- self.validate_coordinate("from_y", from_y, self.computer_use.max_coordinate_y)?;
- self.validate_coordinate("to_y", to_y, self.computer_use.max_coordinate_y)?;
- }
- _ => {}
- }
- Ok(())
- }
-
- async fn execute_computer_use_action(
- &self,
- action: &str,
- args: &Value,
- ) -> anyhow::Result<ToolResult> {
- let endpoint = self.computer_use_endpoint_url()?;
-
- let mut params = args
- .as_object()
- .cloned()
- .ok_or_else(|| anyhow::anyhow!("browser args must be a JSON object"))?;
- params.remove("action");
-
- self.validate_computer_use_action(action, &params)?;
-
- let payload = json!({
- "action": action,
- "params": params,
- "policy": {
- "allowed_domains": self.allowed_domains,
- "window_allowlist": self.computer_use.window_allowlist,
- "max_coordinate_x": self.computer_use.max_coordinate_x,
- "max_coordinate_y": self.computer_use.max_coordinate_y,
- },
- "metadata": {
- "session_name": self.session_name,
- "source": "openhuman.browser",
- "version": env!("CARGO_PKG_VERSION"),
- }
- });
-
- let client = crate::config::build_runtime_proxy_client("tool.browser");
- let mut request = client
- .post(endpoint)
- .timeout(Duration::from_millis(self.computer_use.timeout_ms))
- .json(&payload);
-
- if let Some(api_key) = self.computer_use.api_key.as_deref() {
- let token = api_key.trim();
- if !token.is_empty() {
- request = request.bearer_auth(token);
- }
- }
-
- let response = request.send().await.with_context(|| {
- format!(
- "Failed to call computer-use sidecar at {}",
- self.computer_use.endpoint
- )
- })?;
-
- let status = response.status();
- let body = response
- .text()
- .await
- .context("Failed to read computer-use sidecar response body")?;
-
- if let Ok(parsed) = serde_json::from_str::<ComputerUseResponse>(&body) {
- if status.is_success() && parsed.success.unwrap_or(true) {
- let output = parsed
- .data
- .map(|data| serde_json::to_string_pretty(&data).unwrap_or_default())
- .unwrap_or_else(|| {
- serde_json::to_string_pretty(&json!({
- "backend": "computer_use",
- "action": action,
- "ok": true,
- }))
- .unwrap_or_default()
- });
-
- return Ok(ToolResult::success(output));
- }
-
- let error = parsed.error.or_else(|| {
- if status.is_success() && parsed.success == Some(false) {
- Some("computer-use sidecar returned success=false".to_string())
- } else {
- Some(format!(
- "computer-use sidecar request failed with status {status}"
- ))
- }
- });
-
- return Ok(ToolResult::error(error.unwrap_or_default()));
- }
-
- if status.is_success() {
- return Ok(ToolResult::success(body));
- }
-
- Ok(ToolResult::error(format!(
- "computer-use sidecar request failed with status {status}: {}",
- body.trim()
- )))
- }
-
- async fn execute_action(
- &self,
- action: BrowserAction,
- backend: ResolvedBackend,
- ) -> anyhow::Result<ToolResult> {
- match backend {
- ResolvedBackend::AgentBrowser => self.execute_agent_browser_action(action).await,
- ResolvedBackend::Playwright => self.execute_playwright_action(action).await,
- ResolvedBackend::RustNative => self.execute_rust_native_action(action).await,
- ResolvedBackend::ComputerUse => anyhow::bail!(
- "Internal error: computer_use backend must be handled before BrowserAction parsing"
- ),
- }
- }
-
- #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
- fn to_result(&self, resp: AgentBrowserResponse) -> anyhow::Result<ToolResult> {
- if resp.success {
- let output = resp
- .data
- .map(|d| serde_json::to_string_pretty(&d).unwrap_or_default())
- .unwrap_or_default();
- Ok(ToolResult::success(output))
- } else {
- Ok(ToolResult::error(resp.error.unwrap_or_default()))
- }
- }
-}
diff --git a/crates/openhuman-core/src/tools/impl/browser/browser_part_03.rs b/crates/openhuman-core/src/tools/impl/browser/browser_part_03.rs
deleted file mode 100644
index acf9496d71..0000000000
--- a/crates/openhuman-core/src/tools/impl/browser/browser_part_03.rs
+++ /dev/null
@@ -1,171 +0,0 @@
-
-#[async_trait]
-impl Tool for BrowserTool {
- fn name(&self) -> &str {
- "browser"
- }
-
- fn description(&self) -> &str {
- concat!(
- "Web/browser automation with pluggable backends (playwright, agent-browser, rust-native, computer_use). ",
- "Supports DOM actions plus optional OS-level actions (mouse_move, mouse_click, mouse_drag, ",
- "key_type, key_press) through a computer-use sidecar. Use 'snapshot' to map ",
- "interactive elements to refs (@e1, @e2). Enforces browser.allowed_domains for open actions."
- )
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "action": {
- "type": "string",
- "enum": ["open", "snapshot", "click", "fill", "type", "get_text",
- "get_title", "get_url", "wait", "press",
- "hover", "scroll", "is_visible", "close", "find",
- "mouse_move", "mouse_click", "mouse_drag", "key_type",
- "key_press"],
- "description": "Browser action to perform (OS-level actions require backend=computer_use)"
- },
- "url": {
- "type": "string",
- "description": "URL to navigate to (for 'open' action)"
- },
- "selector": {
- "type": "string",
- "description": "Element selector: @ref (e.g. @e1), CSS (#id, .class), or text=..."
- },
- "value": {
- "type": "string",
- "description": "Value to fill or type"
- },
- "text": {
- "type": "string",
- "description": "Text to type or wait for"
- },
- "key": {
- "type": "string",
- "description": "Key to press (Enter, Tab, Escape, etc.)"
- },
- "x": {
- "type": "integer",
- "description": "Screen X coordinate (computer_use: mouse_move/mouse_click)"
- },
- "y": {
- "type": "integer",
- "description": "Screen Y coordinate (computer_use: mouse_move/mouse_click)"
- },
- "from_x": {
- "type": "integer",
- "description": "Drag source X coordinate (computer_use: mouse_drag)"
- },
- "from_y": {
- "type": "integer",
- "description": "Drag source Y coordinate (computer_use: mouse_drag)"
- },
- "to_x": {
- "type": "integer",
- "description": "Drag target X coordinate (computer_use: mouse_drag)"
- },
- "to_y": {
- "type": "integer",
- "description": "Drag target Y coordinate (computer_use: mouse_drag)"
- },
- "button": {
- "type": "string",
- "enum": ["left", "right", "middle"],
- "description": "Mouse button for computer_use mouse_click"
- },
- "direction": {
- "type": "string",
- "enum": ["up", "down", "left", "right"],
- "description": "Scroll direction"
- },
- "pixels": {
- "type": "integer",
- "description": "Pixels to scroll"
- },
- "interactive_only": {
- "type": "boolean",
- "description": "For snapshot: only show interactive elements"
- },
- "compact": {
- "type": "boolean",
- "description": "For snapshot: remove empty structural elements"
- },
- "depth": {
- "type": "integer",
- "description": "For snapshot: limit tree depth"
- },
- "ms": {
- "type": "integer",
- "description": "Milliseconds to wait"
- },
- "by": {
- "type": "string",
- "enum": ["role", "text", "label", "placeholder", "testid"],
- "description": "For find: semantic locator type"
- },
- "find_action": {
- "type": "string",
- "enum": ["click", "fill", "text", "hover", "check"],
- "description": "For find: action to perform on found element"
- },
- "fill_value": {
- "type": "string",
- "description": "For find with fill action: value to fill"
- }
- },
- "required": ["action"]
- })
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- // Security checks
- if !self.security.can_act() {
- return Ok(ToolResult::error(
- "[policy-blocked] Action blocked: autonomy is read-only",
- ));
- }
-
- if !self.security.record_action() {
- return Ok(ToolResult::error("Action blocked: rate limit exceeded"));
- }
-
- // Reject unsupported actions before resolving or dispatching to a backend.
- let action_str = args
- .get("action")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow::anyhow!("Missing 'action' parameter"))?;
-
- if !is_supported_browser_action(action_str) {
- return Ok(ToolResult::error(format!("Unknown action: {action_str}")));
- }
-
- let backend = match self.resolve_backend().await {
- Ok(selected) => selected,
- Err(error) => {
- return Ok(ToolResult::error(error.to_string()));
- }
- };
-
- if backend == ResolvedBackend::ComputerUse {
- return self.execute_computer_use_action(action_str, &args).await;
- }
-
- if is_computer_use_only_action(action_str) {
- return Ok(ToolResult::error(unavailable_action_for_backend_error(
- action_str, backend,
- )));
- }
-
- let action = match parse_browser_action(action_str, &args) {
- Ok(a) => a,
- Err(e) => {
- return Ok(ToolResult::error(e.to_string()));
- }
- };
-
- self.execute_action(action, backend).await
- }
-}
diff --git a/crates/openhuman-core/src/tools/impl/browser/browser_tool_impl.rs b/crates/openhuman-core/src/tools/impl/browser/browser_tool_impl.rs
index 02c0bf4eaa..a9ad1dbe98 100644
--- a/crates/openhuman-core/src/tools/impl/browser/browser_tool_impl.rs
+++ b/crates/openhuman-core/src/tools/impl/browser/browser_tool_impl.rs
@@ -2,7 +2,6 @@
use super::*;
-
#[async_trait]
impl Tool for BrowserTool {
fn name(&self) -> &str {
diff --git a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
new file mode 100644
index 0000000000..cf0aa5cab9
--- /dev/null
+++ b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
@@ -0,0 +1,165 @@
+//! The two standard web-channel turn guards — the wall-clock backstop and
+//! cooperative cancellation — plus the Sentry-suppression / timeout-tagging
+//! policy applied to whatever error a guarded turn produces.
+
+use std::time::Duration;
+
+use tokio_util::sync::CancellationToken;
+
+use super::super::types::WebChatTaskResult;
+
+/// Default wall-clock backstop for a single web chat turn, in seconds.
+///
+/// This is the OUTER safety net (issue #4746). The primary, root-cause guard is
+/// the harness policy's `max_wall_clock_ms` (`tinyagents::run_policy_for`,
+/// default 600s), which interrupts a hung/slow model or tool/sub-agent call
+/// mid-flight and returns a proper `Timeout` → `chat_error`. This channel-level
+/// backstop sits ABOVE that (900s) and only fires if a turn wedges OUTSIDE the
+/// harness run entirely (e.g. session assembly / persistence plumbing), so the
+/// client still always gets a terminal event instead of an empty reply / an
+/// endless `inference_heartbeat` stream. Deliberately generous — a hang
+/// backstop, not a UX deadline. Override via `OPENHUMAN_WEB_TURN_TIMEOUT_SECS`;
+/// set it to `0` to disable the backstop.
+const DEFAULT_WEB_TURN_TIMEOUT_SECS: u64 = 900;
+
+/// Resolve the per-turn wall-clock backstop. Returns `None` when disabled
+/// (env `OPENHUMAN_WEB_TURN_TIMEOUT_SECS=0`).
+fn web_turn_deadline() -> Option<Duration> {
+ let secs = std::env::var("OPENHUMAN_WEB_TURN_TIMEOUT_SECS")
+ .ok()
+ .and_then(|v| v.trim().parse::<u64>().ok())
+ .unwrap_or(DEFAULT_WEB_TURN_TIMEOUT_SECS);
+ (secs > 0).then(|| Duration::from_secs(secs))
+}
+
+/// Drive a chat-turn future under the wall-clock backstop.
+///
+/// On elapse the inner future is dropped (cooperative teardown at its next
+/// await point) and a synthetic `turn_timeout` error is returned, so the
+/// caller's existing `chat_error` emission path fires. This is the outermost
+/// guarantee that a wedged turn always ends in a terminal event rather than an
+/// empty reply / an endless `inference_heartbeat` stream (issue #4746).
+async fn drive_turn_with_deadline<F>(
+ deadline: Option<Duration>,
+ fut: F,
+) -> Result<WebChatTaskResult, String>
+where
+ F: std::future::Future<Output = Result<WebChatTaskResult, String>>,
+{
+ match deadline {
+ Some(d) => match tokio::time::timeout(d, fut).await {
+ Ok(res) => res,
+ Err(_elapsed) => {
+ log::warn!(
+ "[web-channel] turn wall-clock backstop fired after {}s with no terminal event; \
+ emitting graceful turn_timeout chat_error (issue #4746)",
+ d.as_secs()
+ );
+ Err(super::super::web_errors::turn_timeout_error_message(
+ d.as_secs(),
+ ))
+ }
+ },
+ None => fut.await,
+ }
+}
+
+/// Run a chat-turn future under the two standard web-channel guards, inside the
+/// shared origin + approval-context scope: the cooperative cancel token
+/// (interrupt/cancel paths tear the turn down at its next await point) and the
+/// wall-clock backstop ([`drive_turn_with_deadline`]).
+///
+/// Returns `None` when the turn was cancelled cooperatively before producing a
+/// result — the cancelling side already emitted the user-facing `chat_error`,
+/// so the caller just unwinds quietly. Otherwise `Some(res)` carries the turn's
+/// `Result`. Extracted so `start_chat` and `spawn_parallel_turn` share one copy
+/// of this wiring and can't drift apart (issue #4746 review); the only per-site
+/// differences are the `fork` flag and run-queue handle passed to
+/// `run_chat_task` when building `fut`.
+pub(crate) async fn run_turn_under_cancel_and_deadline<F>(
+ cancel_token: CancellationToken,
+ origin: crate::agent::turn_origin::AgentTurnOrigin,
+ approval_ctx: crate::security::approval::ApprovalChatContext,
+ fut: F,
+) -> Option<Result<WebChatTaskResult, String>>
+where
+ F: std::future::Future<Output = Result<WebChatTaskResult, String>>,
+{
+ tokio::select! {
+ biased;
+ _ = cancel_token.cancelled() => None,
+ res = drive_turn_with_deadline(
+ web_turn_deadline(),
+ crate::agent::turn_origin::with_origin(
+ origin,
+ crate::security::approval::APPROVAL_CHAT_CONTEXT.scope(approval_ctx, fut),
+ ),
+ ) => Some(res),
+ }
+}
+
+/// Reason a terminal `run_chat_task` error should be kept OUT of Sentry, or
+/// `None` when it is a genuine defect that must page.
+///
+/// A suppressed case is a deterministic, user-surfaced, retryable agent-loop
+/// outcome — a terminal `chat_error` already reaches the client, so a Sentry
+/// event is pure noise (same tier as `MaxIterationsExceeded` /
+/// `EmptyProviderResponse`, which are demoted the same way):
+///
+/// - the max-iteration cap (`is_max_iterations_error`), and
+/// - the **outer** web-turn wall-clock backstop (`is_outer_backstop_timeout`,
+/// issue #4746) — the turn wedged outside the harness and produced no
+/// terminal event, so without this arm every such turn would emit a spurious
+/// Sentry event, contradicting the graceful `turn_timeout` framing.
+///
+/// **Not suppressed: the harness's own `Timeout` (#5804).** This arm used to
+/// cover both, via `is_turn_timeout_error`, because the two are hard to tell
+/// apart once stringified. They are not the same event. The outer backstop
+/// fires with *nothing in flight*; the harness `Timeout` fires while bounding
+/// a real model or tool call, which means the run spent its budget doing work
+/// — and every result that work produced is discarded along with the turn. A
+/// turn that lost eighteen sub-agents' worth of accumulated work was reported
+/// here as `suppressed Sentry emission for turn wall-clock backstop` and
+/// reached telemetry as nothing at all, which is why the defect survived. See
+/// [`is_outer_backstop_timeout`](super::super::web_errors::is_outer_backstop_timeout)
+/// for the structural argument.
+///
+/// The user-facing classification is deliberately untouched: both still render
+/// the graceful `turn_timeout` copy via `is_turn_timeout_error`. Only the
+/// telemetry decision splits.
+///
+/// Kept as a pure predicate over the already-formatted error string so the
+/// suppression policy is unit-testable without a Sentry harness.
+pub(crate) fn sentry_suppression_reason(detailed: &str) -> Option<&'static str> {
+ if crate::agent::error::is_max_iterations_error(detailed) {
+ Some("max-iteration cap")
+ } else if super::super::web_errors::is_outer_backstop_timeout(detailed) {
+ Some("turn wall-clock backstop (no terminal event)")
+ } else {
+ None
+ }
+}
+
+/// Which wall-clock bound a reported timeout hit, as a Sentry tag value.
+///
+/// Only meaningful once [`sentry_suppression_reason`] has decided to report —
+/// i.e. for a harness `Timeout`, never for the suppressed outer backstop. The
+/// crate names the bound in the message (`RUN_BOUND_LABEL` vs
+/// `PER_CALL_BOUND_LABEL`), and the two are different triage paths: a run that
+/// spent its whole budget doing real work is a capacity/planning problem, while
+/// one call that blew a per-call ceiling is a wedged provider. Emitting them
+/// under one tag would rebuild, in the dashboard, exactly the conflation this
+/// change removed from the code (#5804).
+///
+/// Pure over the formatted error string, for the same reason its neighbour is.
+pub(crate) fn timeout_bound_tag(detailed: &str) -> &'static str {
+ if detailed.contains("per-model-call ceiling") {
+ "per_model_call"
+ } else if detailed.contains("remaining wall-clock budget") {
+ "run_remaining"
+ } else if super::super::web_errors::is_turn_timeout_error(detailed) {
+ "unclassified_timeout"
+ } else {
+ "none"
+ }
+}