diff --git a/scripts/check-core-boundaries.test.mjs b/scripts/check-core-boundaries.test.mjs index cf6ba2d599..c05fc5fdea 100644 --- a/scripts/check-core-boundaries.test.mjs +++ b/scripts/check-core-boundaries.test.mjs @@ -3022,6 +3022,7 @@ test('services integrations Tokio owner contracts reject feature-union masking', 'utf8', ); const mutations = [ + ['browser-control', 'tokio/rt', /browser-control missing effective Tokio capabilities: rt/], ['plugin-source', 'tokio/time', /plugin-source missing effective Tokio capabilities: time/], ['mcp', 'tokio/process', /mcp missing effective Tokio capabilities: process/], ['miniapp-market', 'miniapp-runtime', /miniapp-market missing effective Tokio capabilities: fs/], diff --git a/scripts/core-boundaries/cargo-dependency-boundaries.mjs b/scripts/core-boundaries/cargo-dependency-boundaries.mjs index 5414edce87..599ec75ba1 100644 --- a/scripts/core-boundaries/cargo-dependency-boundaries.mjs +++ b/scripts/core-boundaries/cargo-dependency-boundaries.mjs @@ -147,7 +147,8 @@ const SERVICES_INTEGRATIONS_TOKIO_FEATURES = new Map([ ['account-identity', ['rt', 'sync']], // Large catalog validation/hash work uses spawn_blocking, outside async IO workers. ['models-dev', ['fs', 'rt', 'sync', 'time']], - ['browser-control', ['time']], + // Browser profile files and process probes use spawn_blocking off async IO workers. + ['browser-control', ['rt', 'time']], ['canvas-runtime', ['fs']], ['deep-research', []], ['git', ['fs', 'io-util', 'macros', 'rt', 'time']], diff --git a/src/apps/desktop/src/api/browser_control_api.rs b/src/apps/desktop/src/api/browser_control_api.rs index d85e11ff85..d47eec6929 100644 --- a/src/apps/desktop/src/api/browser_control_api.rs +++ b/src/apps/desktop/src/api/browser_control_api.rs @@ -1,12 +1,16 @@ //! Browser control API — Tauri commands for CDP-based browser control. use openbitfun_core::agentic::tools::browser_control::browser_launcher::{ - BrowserKind, BrowserLauncher, LaunchResult, DEFAULT_CDP_PORT, + BrowserKind, BrowserLauncher, CdpPortProbe, LaunchResult, DEFAULT_CDP_PORT, +}; +use openbitfun_core::agentic::tools::browser_control::cdp_client::{ + CdpClient, UserProfileConnectError, USER_PROFILE_APPROVAL_TIMEOUT, }; -use openbitfun_core::agentic::tools::browser_control::cdp_client::CdpClient; use openbitfun_core::agentic::tools::implementations::control_hub_tool::disconnect_external_browser; use openbitfun_core::service::config::{get_global_config_service, GlobalConfig}; use serde::{Deserialize, Serialize}; +use std::time::Duration; +use tokio::time::Instant; #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] @@ -43,9 +47,25 @@ pub fn init_on_startup() { let Ok(kind) = selected_browser_kind().await else { return; }; - let Some(endpoint) = BrowserLauncher::user_profile_debug_endpoint(&kind) else { + let Some(endpoint) = + BrowserLauncher::user_profile_debug_endpoint_or_guarded_port(&kind, DEFAULT_CDP_PORT) + .await + else { return; }; + // Nobody asked for this connection, so never raise an approval prompt + // in a browser that may not be the selected one: a port inferred from + // a 404 probe is ambiguous while the other guarded browser runs too. + if BrowserLauncher::is_inferred_guarded_endpoint(&endpoint) + && BrowserLauncher::other_guarded_browser_running(&kind).await + { + log::info!( + "Skipping startup reattach to {}: port {} has no DevToolsActivePort and another guarded browser is running", + kind, + endpoint.port + ); + return; + } if CdpClient::browser_connection_for_kind(DEFAULT_CDP_PORT, &kind) .await .is_some() @@ -183,21 +203,33 @@ pub async fn browser_control_get_status( let default_cdp_supported = BrowserLauncher::supports_default_cdp(&configured_kind); // Probe the live endpoint once and answer both questions from it: whether // the persistent setting is on, and whether there is something to attach to - // right now. The probe is a file read plus a short local TCP connect, so it - // never prompts the browser the way attaching does. - let user_profile_endpoint = BrowserLauncher::user_profile_debug_endpoint(&configured_kind); + // right now. The probe is a file read, a short local TCP connect and, when + // no DevToolsActivePort file is published, one HTTP request to the port; + // none of these opens a WebSocket, so it never prompts the browser the way + // attaching does. + let user_profile_endpoint = + BrowserLauncher::user_profile_debug_endpoint_or_guarded_port(&configured_kind, port).await; + // An endpoint inferred from a 404 port probe is only a candidate until + // the browser accepts the WebSocket, so it makes the browser "ready" but + // never proves the persistent setting is on. + let published_endpoint = user_profile_endpoint + .as_ref() + .is_some_and(|endpoint| !BrowserLauncher::is_inferred_guarded_endpoint(endpoint)); let default_cdp_enabled = default_cdp_supported - && (user_profile_endpoint.is_some() - || BrowserLauncher::is_default_cdp_enabled(&configured_kind)); + && (published_endpoint + || BrowserLauncher::is_default_cdp_enabled_async(&configured_kind).await); let user_profile_connection = CdpClient::browser_connection_for_kind(port, &configured_kind).await; let browser_connection_suppressed = CdpClient::browser_connection_suppressed(port).await; - let legacy_version = - if user_profile_connection.is_none() && BrowserLauncher::is_cdp_available(port).await { - CdpClient::get_version(port).await.ok() - } else { - None - }; + // Guarded remote debugging answers 404 on /json*, so only a legacy + // HTTP endpoint is read through the HTTP discovery API. + let legacy_version = if user_profile_connection.is_none() + && BrowserLauncher::probe_cdp_port(port).await == CdpPortProbe::Http + { + CdpClient::get_version(port).await.ok() + } else { + None + }; // Chrome and Edge share the logical 9222 slot in Settings. Do not report // the selected browser as connected merely because the other one owns a // legacy fixed-port endpoint left from an earlier selection. @@ -347,48 +379,120 @@ fn to_launch_response(kind: &BrowserKind, result: LaunchResult) -> BrowserContro } } +/// Overall budget for one Browser Control setup command, measured from its +/// start. It stays below the Peer host invoke limit for these commands +/// (`peer_host_invoke::BROWSER_CONTROL_SETUP_INVOKE_TIMEOUT`, 180 s) so a late +/// fallback cannot outlive the request that is waiting for it. +const BROWSER_CONTROL_SETUP_BUDGET: Duration = Duration::from_secs(170); +/// Approval time kept back when a late 404 sends the flow back to setup. +const FALLBACK_APPROVAL_RESERVE: Duration = Duration::from_secs(20); + +/// Setup wait available to the late-404 fallback, leaving the approval +/// reserve. `None` means the overall budget cannot fit another round. +fn fallback_setup_wait(remaining: Duration) -> Option { + remaining + .checked_sub(FALLBACK_APPROVAL_RESERVE) + .filter(|wait| !wait.is_zero()) +} + +/// Approval wait for the next WebSocket attempt inside the overall deadline. +fn approval_budget(remaining: Duration) -> Duration { + remaining.min(USER_PROFILE_APPROVAL_TIMEOUT) +} + +fn setup_budget_exhausted(kind: &BrowserKind) -> BrowserControlLaunchResponse { + BrowserControlLaunchResponse { + success: false, + status: "user_profile_connection_failed".into(), + message: Some(format!( + "Browser Control setup for {kind} ran out of time. Connect again from Settings > Browser control." + )), + browser_kind: kind.to_string(), + setup_url: None, + } +} + async fn complete_launch( kind: &BrowserKind, logical_port: u16, result: LaunchResult, + wait_for_user_profile_setup: bool, + deadline: Instant, ) -> Result { - match result { - LaunchResult::UserProfileReady { endpoint } => { - // Attaching to a guarded real profile makes the browser show its own - // approval request, and that prompt is only answerable from a - // visible window. Browser control itself is background work, so - // this is one of the few flows that must surface the browser. - BrowserLauncher::activate_browser(kind); - let connection = CdpClient::connect_user_profile_browser( - logical_port, - endpoint.port, - kind, - &endpoint.web_socket_url, - ) - .await; - if let Err(error) = connection { + let mut result = result; + // An endpoint inferred from a 404 port probe gets one chance: a 404 on + // the WebSocket upgrade falls back to setup. Authorization denials and + // other handshake failures remain errors, never another setup attempt. + let mut inferred_fallback_available = true; + loop { + let LaunchResult::UserProfileReady { endpoint } = result else { + let response = to_launch_response(kind, result); + if response.success { + CdpClient::authorize_legacy_browser(logical_port, kind).await; + } + return Ok(response); + }; + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return Ok(setup_budget_exhausted(kind)); + } + // Attaching to a guarded real profile makes the browser show its own + // approval request, and that prompt is only answerable from a + // visible window. Browser control itself is background work, so + // this is one of the few flows that must surface the browser. + BrowserLauncher::activate_browser(kind); + let connection = CdpClient::connect_user_profile_browser_within( + logical_port, + endpoint.port, + kind, + &endpoint.web_socket_url, + approval_budget(remaining), + ) + .await; + match connection { + Ok(_) => { + return Ok(BrowserControlLaunchResponse { + success: true, + status: "connected_user_profile".into(), + message: None, + browser_kind: kind.to_string(), + setup_url: None, + }) + } + Err(UserProfileConnectError::NotABrowserEndpoint(error)) + if inferred_fallback_available + && BrowserLauncher::is_inferred_guarded_endpoint(&endpoint) => + { + log::info!( + "Port {} is not a guarded browser endpoint, continuing with {} setup: {}", + endpoint.port, + kind, + error + ); + inferred_fallback_available = false; + let Some(setup_wait) = + fallback_setup_wait(deadline.saturating_duration_since(Instant::now())) + else { + return Ok(setup_budget_exhausted(kind)); + }; + result = BrowserLauncher::enable_default_cdp_without_port_fallback( + kind, + logical_port, + wait_for_user_profile_setup, + setup_wait, + ) + .await + .map_err(|e| e.to_string())?; + } + Err(error) => { return Ok(BrowserControlLaunchResponse { success: false, status: "user_profile_connection_failed".into(), - message: Some(error.to_string()), + message: Some(error.into_error().to_string()), browser_kind: kind.to_string(), setup_url: None, }); } - Ok(BrowserControlLaunchResponse { - success: true, - status: "connected_user_profile".into(), - message: None, - browser_kind: kind.to_string(), - setup_url: None, - }) - } - other => { - let response = to_launch_response(kind, other); - if response.success { - CdpClient::authorize_legacy_browser(logical_port, kind).await; - } - Ok(response) } } } @@ -398,6 +502,7 @@ async fn complete_launch( pub async fn browser_control_launch( request: BrowserControlLaunchRequest, ) -> Result { + let deadline = Instant::now() + BROWSER_CONTROL_SETUP_BUDGET; let port = request.port; let kind = selected_browser_kind().await?; if CdpClient::authorized_browser_kind(port) @@ -421,7 +526,7 @@ pub async fn browser_control_launch( .await .map_err(|e| e.to_string())?; - complete_launch(&kind, port, result).await + complete_launch(&kind, port, result, false, deadline).await } /// Open the selected browser's persistent guarded-CDP setting and wait for the @@ -431,6 +536,7 @@ pub async fn browser_control_launch( pub async fn browser_control_enable_default_cdp( request: BrowserControlLaunchRequest, ) -> Result { + let deadline = Instant::now() + BROWSER_CONTROL_SETUP_BUDGET; let port = request.port; let kind = selected_browser_kind().await?; if CdpClient::authorized_browser_kind(port) @@ -463,7 +569,7 @@ pub async fn browser_control_enable_default_cdp( let result = BrowserLauncher::enable_default_cdp(&kind, port) .await .map_err(|e| e.to_string())?; - complete_launch(&kind, port, result).await + complete_launch(&kind, port, result, true, deadline).await } /// Restart the user's default browser with CDP debug port enabled. @@ -471,6 +577,7 @@ pub async fn browser_control_enable_default_cdp( pub async fn browser_control_restart_with_cdp( request: BrowserControlLaunchRequest, ) -> Result { + let deadline = Instant::now() + BROWSER_CONTROL_SETUP_BUDGET; let port = request.port; let kind = selected_browser_kind().await?; disconnect_external_browser(port).await; @@ -480,7 +587,7 @@ pub async fn browser_control_restart_with_cdp( .await .map_err(|e| e.to_string())?; - complete_launch(&kind, port, result).await + complete_launch(&kind, port, result, false, deadline).await } #[derive(Debug, Serialize)] @@ -510,3 +617,62 @@ pub async fn browser_control_disconnect( browser_kind: kind.to_string(), }) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn setup_budget_fits_inside_the_peer_host_invoke_limit() { + assert!( + BROWSER_CONTROL_SETUP_BUDGET + < super::super::peer_host_invoke::BROWSER_CONTROL_SETUP_INVOKE_TIMEOUT + ); + } + + #[test] + fn late_404_fallback_is_bounded_by_the_remaining_budget() { + // A 404 arriving after the first setup wait leaves 110 s: the + // fallback setup may use 90 s and approval keeps the reserve. + assert_eq!( + fallback_setup_wait(Duration::from_secs(110)), + Some(Duration::from_secs(90)) + ); + assert_eq!(fallback_setup_wait(FALLBACK_APPROVAL_RESERVE), None); + assert_eq!(fallback_setup_wait(Duration::from_secs(5)), None); + assert_eq!( + approval_budget(Duration::from_secs(30)), + Duration::from_secs(30) + ); + assert_eq!( + approval_budget(Duration::from_secs(170)), + USER_PROFILE_APPROVAL_TIMEOUT + ); + // Worst case: setup (60 s) + approval (90 s) + late 404 fallback + // setup + approval never exceeds the overall budget because every + // step is capped by what remains of the same deadline. + let after_first_round = BROWSER_CONTROL_SETUP_BUDGET - Duration::from_secs(60); + let fallback = fallback_setup_wait(after_first_round).unwrap(); + assert!(fallback + FALLBACK_APPROVAL_RESERVE <= after_first_round); + } + + #[tokio::test] + async fn exhausted_budget_reports_a_clear_failure() { + let response = complete_launch( + &BrowserKind::Chrome, + 1, + LaunchResult::UserProfileReady { + endpoint: openbitfun_core::agentic::tools::browser_control::browser_launcher::BrowserDebugEndpoint { + port: 1, + web_socket_url: "ws://127.0.0.1:1/devtools/browser".into(), + }, + }, + false, + Instant::now(), + ) + .await + .unwrap(); + assert!(!response.success); + assert!(response.message.unwrap().contains("ran out of time")); + } +} diff --git a/src/apps/desktop/src/api/peer_host_invoke.rs b/src/apps/desktop/src/api/peer_host_invoke.rs index 097d3bbecd..13f4b54035 100644 --- a/src/apps/desktop/src/api/peer_host_invoke.rs +++ b/src/apps/desktop/src/api/peer_host_invoke.rs @@ -25,6 +25,19 @@ use tokio::sync::oneshot; use super::remote_connect_api::{account_app_handle, current_device_id_for_peer, RelayRoute}; const DEFAULT_INVOKE_TIMEOUT: Duration = Duration::from_secs(120); +/// Browser Control setup waits for browser-owned consent: up to one minute for +/// the Remote debugging toggle plus up to 90 seconds for the connection +/// approval prompt. The controller adapter uses the same budget. +pub(crate) const BROWSER_CONTROL_SETUP_INVOKE_TIMEOUT: Duration = Duration::from_secs(180); + +fn invoke_timeout_for(command: &str) -> Duration { + match command { + "browser_control_launch" + | "browser_control_enable_default_cdp" + | "browser_control_restart_with_cdp" => BROWSER_CONTROL_SETUP_INVOKE_TIMEOUT, + _ => DEFAULT_INVOKE_TIMEOUT, + } +} static PENDING: OnceLock>>> = OnceLock::new(); @@ -447,14 +460,15 @@ async fn bridge_via_webview( return Err(format!("failed to emit peer host invoke request: {e}")); } - match tokio::time::timeout(DEFAULT_INVOKE_TIMEOUT, rx).await { + let invoke_timeout = invoke_timeout_for(command); + match tokio::time::timeout(invoke_timeout, rx).await { Ok(Ok(result)) => Ok(result), Ok(Err(_)) => Err("peer host invoke channel closed".to_string()), Err(_) => { pending_map().lock().ok().map(|mut map| map.remove(&id)); Err(format!( "peer host invoke timed out after {}s for '{command}'", - DEFAULT_INVOKE_TIMEOUT.as_secs() + invoke_timeout.as_secs() )) } } @@ -474,6 +488,24 @@ mod tests { } } + #[test] + fn browser_control_setup_commands_get_the_consent_budget() { + for command in [ + "browser_control_launch", + "browser_control_enable_default_cdp", + "browser_control_restart_with_cdp", + ] { + assert_eq!( + invoke_timeout_for(command), + BROWSER_CONTROL_SETUP_INVOKE_TIMEOUT + ); + } + assert_eq!( + invoke_timeout_for("browser_control_get_status"), + DEFAULT_INVOKE_TIMEOUT + ); + } + #[test] fn detaching_one_route_preserves_the_other_controller_and_permissions() { let mut state = control_state(&["same-device"], &["pending-approval"]); diff --git a/src/apps/desktop/src/api/remote_connect_api.rs b/src/apps/desktop/src/api/remote_connect_api.rs index 70ce375e21..6cd91f4c53 100644 --- a/src/apps/desktop/src/api/remote_connect_api.rs +++ b/src/apps/desktop/src/api/remote_connect_api.rs @@ -3302,13 +3302,17 @@ pub async fn account_delete_device(targetDeviceId: String) -> Result<(), String> /// Returns the decrypted response JSON. const ACCOUNT_DEVICE_RPC_DEFAULT_TIMEOUT_MS: u64 = 120_000; const ACCOUNT_DEVICE_RPC_MIN_TIMEOUT_MS: u64 = 1_000; +/// Upper bound for a controller-requested deadline. Ordinary commands keep +/// the 120 s default; Browser Control setup asks for 185 s because it waits +/// on browser-owned consent (see `peer_host_invoke::invoke_timeout_for`). +const ACCOUNT_DEVICE_RPC_MAX_TIMEOUT_MS: u64 = 190_000; fn account_device_rpc_timeout_ms(requested: Option) -> u64 { requested .unwrap_or(ACCOUNT_DEVICE_RPC_DEFAULT_TIMEOUT_MS) .clamp( ACCOUNT_DEVICE_RPC_MIN_TIMEOUT_MS, - ACCOUNT_DEVICE_RPC_DEFAULT_TIMEOUT_MS, + ACCOUNT_DEVICE_RPC_MAX_TIMEOUT_MS, ) } @@ -3322,9 +3326,18 @@ pub async fn account_device_rpc( let (session, relay_url) = read_account_context_for_generation(account_generation).await?; let client = AccountClient::new(); let timeout_ms = account_device_rpc_timeout_ms(timeout_ms); + let timeout = std::time::Duration::from_millis(timeout_ms); + // The relay forwards this deadline to the target as `timeoutMs`; the local + // guard below only bounds the controller wait for the same budget. let response = tokio::time::timeout( - std::time::Duration::from_millis(timeout_ms), - client.device_rpc(&relay_url, &session, &target_device_id, &command_json), + timeout + std::time::Duration::from_secs(5), + client.device_rpc_with_timeout( + &relay_url, + &session, + &target_device_id, + &command_json, + timeout, + ), ) .await .map_err(|_| format!("device RPC timed out after {timeout_ms}ms"))? @@ -3670,7 +3683,15 @@ mod sync_state_tests { ); assert_eq!( account_device_rpc_timeout_ms(Some(u64::MAX)), - ACCOUNT_DEVICE_RPC_DEFAULT_TIMEOUT_MS + ACCOUNT_DEVICE_RPC_MAX_TIMEOUT_MS + ); + // Browser Control setup's Peer budget must survive the clamp and + // still exceed the host invoke limit for those commands. + assert_eq!(account_device_rpc_timeout_ms(Some(185_000)), 185_000); + assert!( + account_device_rpc_timeout_ms(Some(185_000)) + > crate::api::peer_host_invoke::BROWSER_CONTROL_SETUP_INVOKE_TIMEOUT.as_millis() + as u64 ); } diff --git a/src/crates/assembly/core/src/agentic/tools/browser_control/browser_launcher.rs b/src/crates/assembly/core/src/agentic/tools/browser_control/browser_launcher.rs index 03d682c0fb..ae46e0a444 100644 --- a/src/crates/assembly/core/src/agentic/tools/browser_control/browser_launcher.rs +++ b/src/crates/assembly/core/src/agentic/tools/browser_control/browser_launcher.rs @@ -7,8 +7,8 @@ use openbitfun_services_integrations::browser_control::launcher as provider; pub use provider::{ - BrowserDebugEndpoint, BrowserInfo, BrowserKind, BrowserLaunchOptions, LaunchResult, - DEFAULT_CDP_PORT, + BrowserDebugEndpoint, BrowserInfo, BrowserKind, BrowserLaunchOptions, CdpPortProbe, + LaunchResult, DEFAULT_CDP_PORT, }; use std::path::PathBuf; @@ -22,6 +22,43 @@ impl BrowserLauncher { provider::BrowserLauncher::is_cdp_available(port).await } + /// Classify a local debug port without opening a WebSocket, so a guarded + /// endpoint (404 on `/json*`) is distinguished from nothing listening. + pub async fn probe_cdp_port(port: u16) -> CdpPortProbe { + provider::BrowserLauncher::probe_cdp_port(port).await + } + + /// Like [`Self::user_profile_debug_endpoint`], but also accepts a guarded + /// remote-debugging port that serves only the browser WebSocket. + pub async fn user_profile_debug_endpoint_or_guarded_port( + kind: &BrowserKind, + port: u16, + ) -> Option { + provider::BrowserLauncher::user_profile_debug_endpoint_or_guarded_port(kind, port).await + } + + /// Whether `endpoint` was inferred from a 404 port probe instead of a + /// published `DevToolsActivePort` file. + pub fn is_inferred_guarded_endpoint(endpoint: &BrowserDebugEndpoint) -> bool { + provider::BrowserLauncher::is_inferred_guarded_endpoint(endpoint) + } + + /// Settings setup flow used after an inferred guarded endpoint rejected + /// the WebSocket upgrade: open the browser's Remote debugging page and + /// wait for a real `DevToolsActivePort`, without probing the port again. + pub async fn enable_default_cdp_without_port_fallback( + kind: &BrowserKind, + port: u16, + wait_for_user_profile_setup: bool, + setup_wait_limit: std::time::Duration, + ) -> OpenBitFunResult { + let mut options = Self::launch_options(None, true); + options.wait_for_user_profile_setup = wait_for_user_profile_setup; + options.skip_guarded_port_fallback = true; + options.user_profile_setup_wait = Some(setup_wait_limit); + Ok(provider::BrowserLauncher::launch_with_cdp_options(kind, port, options).await?) + } + pub fn detect_default_browser() -> OpenBitFunResult { Ok(provider::BrowserLauncher::detect_default_browser()?) } @@ -61,6 +98,16 @@ impl BrowserLauncher { provider::BrowserLauncher::is_default_cdp_enabled(kind) } + pub async fn is_default_cdp_enabled_async(kind: &BrowserKind) -> bool { + provider::BrowserLauncher::is_default_cdp_enabled_async(kind).await + } + + /// Whether Chrome or Edge other than `kind` is running, so a port inferred + /// for `kind` from a 404 probe may belong to that browser. + pub async fn other_guarded_browser_running(kind: &BrowserKind) -> bool { + provider::BrowserLauncher::other_guarded_browser_running(kind).await + } + pub fn user_profile_debugging_setup_url(kind: &BrowserKind) -> Option<&'static str> { provider::BrowserLauncher::user_profile_debugging_setup_url(kind) } @@ -129,6 +176,8 @@ impl BrowserLauncher { managed_profile_root: Some(get_path_manager_arc().user_data_dir()), wait_for_user_profile_setup: false, activate, + skip_guarded_port_fallback: false, + user_profile_setup_wait: None, } } } diff --git a/src/crates/assembly/core/src/agentic/tools/browser_control/cdp_client.rs b/src/crates/assembly/core/src/agentic/tools/browser_control/cdp_client.rs index 6b46fc896c..9ed6a36e44 100644 --- a/src/crates/assembly/core/src/agentic/tools/browser_control/cdp_client.rs +++ b/src/crates/assembly/core/src/agentic/tools/browser_control/cdp_client.rs @@ -16,7 +16,7 @@ use tokio::sync::{broadcast, Mutex, RwLock}; use tokio_tungstenite::tungstenite::Message; use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream}; -use super::browser_launcher::BrowserKind; +use super::browser_launcher::{BrowserKind, BrowserLauncher}; use super::{BrowserAutomationCapabilities, BrowserAutomationClient, BrowserAutomationEvent}; type WsSink = SplitSink>, Message>; @@ -26,7 +26,44 @@ type EventChannels = Arc, broadcast::Sender>>>; const PAGE_CDP_CONNECT_TIMEOUT: Duration = Duration::from_secs(30); -const USER_PROFILE_APPROVAL_TIMEOUT: Duration = Duration::from_secs(90); +pub const USER_PROFILE_APPROVAL_TIMEOUT: Duration = Duration::from_secs(90); +/// Backoff between guarded WebSocket attempts that failed before the upgrade. +/// All attempts share [`USER_PROFILE_APPROVAL_TIMEOUT`]. +const USER_PROFILE_CONNECT_RETRY_BACKOFF: [Duration; 4] = [ + Duration::from_millis(250), + Duration::from_millis(500), + Duration::from_secs(1), + Duration::from_secs(2), +]; +/// A reset faster than this cannot follow a user's answer to the approval +/// prompt, so it is treated as the endpoint not being ready yet. +const USER_PROFILE_FAST_RESET_WINDOW: Duration = Duration::from_secs(1); + +/// Why a guarded user-profile connection could not be established. +#[derive(Debug)] +pub enum UserProfileConnectError { + /// The endpoint answered the WebSocket upgrade with HTTP 404. An inferred + /// endpoint may fall back to setup; authentication/permission refusals may not. + NotABrowserEndpoint(OpenBitFunError), + /// Any other failure: timeout, denial, transport error, product mismatch. + Failed(OpenBitFunError), +} + +impl UserProfileConnectError { + pub fn into_error(self) -> OpenBitFunError { + match self { + Self::NotABrowserEndpoint(error) | Self::Failed(error) => error, + } + } +} + +/// Why a WebSocket connection could not be opened. +enum WsConnectError { + /// The TCP connect or HTTP upgrade did not finish in time. For a guarded + /// endpoint this usually means the approval prompt is still pending. + Timeout, + Failed(tokio_tungstenite::tungstenite::Error), +} /// Backward-compatible name for events recorded by CDP-only diagnostics. pub type CdpEvent = BrowserAutomationEvent; @@ -162,11 +199,45 @@ impl CdpClient { browser_kind: &BrowserKind, ws_url: &str, ) -> OpenBitFunResult { + Self::connect_user_profile_browser_checked(logical_port, actual_port, browser_kind, ws_url) + .await + .map_err(UserProfileConnectError::into_error) + } + + /// [`Self::connect_user_profile_browser`] with a distinct HTTP 404 result. + /// Callers that inferred the endpoint from a 404 port probe may fall back + /// to setup; other failures, including permission refusals, stay failures. + pub async fn connect_user_profile_browser_checked( + logical_port: u16, + actual_port: u16, + browser_kind: &BrowserKind, + ws_url: &str, + ) -> Result { + Self::connect_user_profile_browser_within( + logical_port, + actual_port, + browser_kind, + ws_url, + USER_PROFILE_APPROVAL_TIMEOUT, + ) + .await + } + + /// [`Self::connect_user_profile_browser_checked`] whose approval wait is + /// capped by the caller's remaining overall deadline. The cap never + /// exceeds the default 90 second approval budget. + pub async fn connect_user_profile_browser_within( + logical_port: u16, + actual_port: u16, + browser_kind: &BrowserKind, + ws_url: &str, + approval_budget: Duration, + ) -> Result { if Self::browser_connection_suppressed(logical_port).await { - return Err(OpenBitFunError::tool( + return Err(UserProfileConnectError::Failed(OpenBitFunError::tool( "Browser control was disconnected in Settings. Reconnect it there before attaching again." .to_string(), - )); + ))); } if let Some(existing) = Self::browser_connection(logical_port).await { if existing.actual_port == actual_port && existing.browser_kind == *browser_kind { @@ -178,19 +249,58 @@ impl CdpClient { "Requesting user-approved browser profile connection on port {}", actual_port ); + let wrap = |error: OpenBitFunError| { + OpenBitFunError::tool(format!( + "Could not connect to the current browser profile. Approve OpenBitFun's remote debugging request in the browser, then try again: {}", + error + )) + }; let client = Arc::new( - Self::connect_with_timeout(ws_url, USER_PROFILE_APPROVAL_TIMEOUT) - .await - .map_err(|error| { - OpenBitFunError::tool(format!( - "Could not connect to the current browser profile. Approve OpenBitFun's remote debugging request in the browser, then try again: {}", - error - )) - })?, + Self::connect_user_profile_websocket( + ws_url, + approval_budget.min(USER_PROFILE_APPROVAL_TIMEOUT), + &USER_PROFILE_CONNECT_RETRY_BACKOFF, + ) + .await + .map_err(|error| match error { + UserProfileConnectError::NotABrowserEndpoint(error) => { + UserProfileConnectError::NotABrowserEndpoint(wrap(error)) + } + UserProfileConnectError::Failed(error) => { + UserProfileConnectError::Failed(wrap(error)) + } + })?, ); + Self::retain_user_profile_browser(logical_port, actual_port, browser_kind, client) + .await + .map_err(UserProfileConnectError::Failed) + } + + async fn retain_user_profile_browser( + logical_port: u16, + actual_port: u16, + browser_kind: &BrowserKind, + client: Arc, + ) -> OpenBitFunResult { // Validate that this is a browser-level CDP endpoint before retaining // it. This also fails quickly if the DevToolsActivePort file was stale. - client.browser_version().await?; + let version = match client.browser_version().await { + Ok(version) => version, + Err(error) => { + client.disconnect().await; + return Err(error); + } + }; + // A guarded port found without DevToolsActivePort carries no product + // identity, and Chrome and Edge both default to 9222. Never retain a + // connection to the other browser's profile under this selection. + if let Some(detected) = Self::guarded_product_mismatch(browser_kind, &version) { + client.disconnect().await; + return Err(OpenBitFunError::tool(format!( + "The browser on port {} is {}, not the selected {}. Select {} in Settings > Browser control, or turn off remote debugging in it and connect {} instead.", + actual_port, detected, browser_kind, detected, browser_kind + ))); + } if Self::browser_connection_suppressed(logical_port).await { client.disconnect().await; return Err(OpenBitFunError::tool( @@ -324,17 +434,140 @@ impl CdpClient { .contains(&logical_port) } + /// Detect a retained-connection candidate whose product is the other + /// guarded browser (Chrome vs Edge). Edge may report a Chrome-like + /// `product`, so its `Edg/` user-agent token is checked first. + fn guarded_product_mismatch( + expected: &BrowserKind, + version: &CdpVersionInfo, + ) -> Option { + let detected = if version + .user_agent + .as_deref() + .is_some_and(|agent| agent.contains("Edg/")) + { + Some(BrowserKind::Edge) + } else { + version + .browser + .as_deref() + .and_then(BrowserLauncher::browser_kind_from_cdp_version) + }?; + match (expected, &detected) { + (BrowserKind::Chrome, BrowserKind::Edge) | (BrowserKind::Edge, BrowserKind::Chrome) => { + Some(detected) + } + _ => None, + } + } + + /// Open the guarded browser WebSocket within one overall budget. + /// + /// Guarded remote debugging sometimes refuses or resets a connection + /// before the upgrade while the browser is still bringing its endpoint up, + /// so those outright failures are retried with backoff. A handshake that + /// stalls is different: the browser is showing its approval prompt, and + /// every new socket would raise another prompt, so it is never retried. + async fn connect_user_profile_websocket( + ws_url: &str, + budget: Duration, + backoff: &[Duration], + ) -> Result { + let deadline = tokio::time::Instant::now() + budget; + let mut delays = backoff.iter(); + loop { + let remaining = deadline.saturating_duration_since(tokio::time::Instant::now()); + if remaining.is_zero() { + return Err(UserProfileConnectError::Failed( + Self::websocket_timeout_error(), + )); + } + let attempt_started = tokio::time::Instant::now(); + let error = match Self::open_websocket(ws_url, remaining).await { + Ok(client) => return Ok(client), + Err(WsConnectError::Timeout) => { + return Err(UserProfileConnectError::Failed( + Self::websocket_timeout_error(), + )) + } + Err(WsConnectError::Failed(error)) => error, + }; + // Only a missing endpoint permits the setup fallback. Authentication + // or permission refusals must remain failures, not trigger a new prompt. + if matches!( + &error, + tokio_tungstenite::tungstenite::Error::Http(response) + if response.status() == tokio_tungstenite::tungstenite::http::StatusCode::NOT_FOUND + ) { + return Err(UserProfileConnectError::NotABrowserEndpoint( + Self::websocket_failed_error(&error), + )); + } + let retryable = Self::is_retryable_before_upgrade(&error, attempt_started.elapsed()); + let delay = delays.next().copied(); + match delay { + Some(delay) + if retryable + && deadline.saturating_duration_since(tokio::time::Instant::now()) + > delay => + { + debug!( + "Guarded browser WebSocket connect failed before upgrade, retrying in {:?}: {}", + delay, error + ); + tokio::time::sleep(delay).await; + } + _ => { + return Err(UserProfileConnectError::Failed( + Self::websocket_failed_error(&error), + )) + } + } + } + } + + /// A refused connection never reached the browser. A reset or abort is + /// retried only when it arrives faster than any user decision could, so a + /// browser that drops the socket after its prompt is not asked again. + fn is_retryable_before_upgrade( + error: &tokio_tungstenite::tungstenite::Error, + elapsed: Duration, + ) -> bool { + use std::io::ErrorKind; + let tokio_tungstenite::tungstenite::Error::Io(io_error) = error else { + return false; + }; + match io_error.kind() { + ErrorKind::ConnectionRefused => true, + ErrorKind::ConnectionReset | ErrorKind::ConnectionAborted => { + elapsed < USER_PROFILE_FAST_RESET_WINDOW + } + _ => false, + } + } + + fn websocket_timeout_error() -> OpenBitFunError { + OpenBitFunError::tool("Timed out waiting for the CDP WebSocket connection".to_string()) + } + + fn websocket_failed_error(error: &tokio_tungstenite::tungstenite::Error) -> OpenBitFunError { + OpenBitFunError::tool(format!("CDP WebSocket connect failed: {}", error)) + } + async fn connect_with_timeout(ws_url: &str, timeout: Duration) -> OpenBitFunResult { + Self::open_websocket(ws_url, timeout) + .await + .map_err(|error| match error { + WsConnectError::Timeout => Self::websocket_timeout_error(), + WsConnectError::Failed(error) => Self::websocket_failed_error(&error), + }) + } + + async fn open_websocket(ws_url: &str, timeout: Duration) -> Result { let (ws_stream, _) = tokio::time::timeout(timeout, connect_async(ws_url)) .await - .map_err(|_| { - OpenBitFunError::tool( - "Timed out waiting for the CDP WebSocket connection".to_string(), - ) - })? - .map_err(|error| { - OpenBitFunError::tool(format!("CDP WebSocket connect failed: {}", error)) - })?; + .map_err(|_| WsConnectError::Timeout)? + .map_err(WsConnectError::Failed)?; let (sink, stream) = ws_stream.split(); let sink = Arc::new(Mutex::new(sink)); @@ -1041,4 +1274,292 @@ mod tests { assert!(error.to_string().contains("response channel closed")); server.await.expect("mock CDP server"); } + + /// Mock of Chromium's guarded remote debugging: every `/json*` HTTP + /// request answers an empty 404, and only `/devtools/browser` upgrades to + /// a browser-level CDP WebSocket that reports `product`. + async fn spawn_guarded_browser( + product: &'static str, + user_agent: &'static str, + ) -> (u16, Arc>>) { + use tokio::io::AsyncWriteExt; + use tokio_tungstenite::tungstenite::handshake::server::{Request, Response}; + + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) + .await + .expect("bind guarded browser"); + let port = listener.local_addr().expect("address").port(); + let upgraded_paths = Arc::new(std::sync::Mutex::new(Vec::new())); + let paths = upgraded_paths.clone(); + tokio::spawn(async move { + loop { + let Ok((mut stream, _)) = listener.accept().await else { + return; + }; + let paths = paths.clone(); + tokio::spawn(async move { + let mut head = [0_u8; 2048]; + let read = stream.peek(&mut head).await.unwrap_or(0); + let request = String::from_utf8_lossy(&head[..read]).to_ascii_lowercase(); + if !request.contains("upgrade: websocket") { + let _ = stream + .write_all( + b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ) + .await; + return; + } + let callback = |request: &Request, response: Response| { + paths.lock().unwrap().push(request.uri().path().to_string()); + Ok(response) + }; + let Ok(mut socket) = + tokio_tungstenite::accept_hdr_async(stream, callback).await + else { + return; + }; + while let Some(Ok(message)) = socket.next().await { + let Message::Text(text) = message else { + continue; + }; + let command: Value = serde_json::from_str(&text).expect("command"); + let result = match command["method"].as_str() { + Some("Browser.getVersion") => json!({ + "product": product, + "userAgent": user_agent, + "protocolVersion": "1.3" + }), + Some("Target.getTargets") => json!({ + "targetInfos": [{ + "targetId": "page-1", + "type": "page", + "title": "Signed-in page", + "url": "https://example.test/" + }] + }), + _ => json!({}), + }; + let _ = socket + .send(Message::Text( + json!({ "id": command["id"], "result": result }) + .to_string() + .into(), + )) + .await; + } + }); + } + }); + (port, upgraded_paths) + } + + #[tokio::test] + async fn guarded_port_without_json_endpoints_connects_over_browser_websocket() { + let (port, upgraded_paths) = spawn_guarded_browser( + "Chrome/156.0.8078.74", + "Mozilla/5.0 (Macintosh) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36", + ) + .await; + // The legacy HTTP discovery path reports actionable guidance instead + // of a JSON parse error. + let http_error = CdpClient::get_version(port).await.unwrap_err(); + assert!(http_error + .to_string() + .contains("Settings > Browser control")); + + // The endpoint the launcher infers for a 404 port whose browser runs. + let endpoint = super::super::browser_launcher::BrowserDebugEndpoint { + port, + web_socket_url: format!("ws://127.0.0.1:{port}/devtools/browser"), + }; + assert!( + openbitfun_services_integrations::browser_control::BrowserLauncher::is_inferred_guarded_endpoint(&endpoint) + ); + let logical_port = port; + let connection = CdpClient::connect_user_profile_browser( + logical_port, + endpoint.port, + &BrowserKind::Chrome, + &endpoint.web_socket_url, + ) + .await + .expect("connect guarded browser"); + assert_eq!(connection.browser_kind, BrowserKind::Chrome); + assert_eq!( + upgraded_paths.lock().unwrap().as_slice(), + ["/devtools/browser".to_string()] + ); + let pages = connection.client.browser_pages().await.expect("targets"); + assert_eq!(pages.len(), 1); + assert!(CdpClient::browser_connection(logical_port).await.is_some()); + assert!(CdpClient::disconnect_browser_connection(logical_port).await); + } + + #[tokio::test] + async fn guarded_port_owned_by_the_other_browser_is_not_retained() { + let (port, _) = spawn_guarded_browser( + "Chrome/156.0.0.0", + "Mozilla/5.0 AppleWebKit/537.36 Chrome/156.0.0.0 Safari/537.36 Edg/156.0.0.0", + ) + .await; + let error = CdpClient::connect_user_profile_browser( + port, + port, + &BrowserKind::Chrome, + &format!("ws://127.0.0.1:{port}/devtools/browser"), + ) + .await + .err() + .expect("Edge must not be retained as Chrome"); + assert!(error.to_string().contains("Microsoft Edge")); + assert!(CdpClient::browser_connection(port).await.is_none()); + } + + #[test] + fn product_mismatch_only_rejects_the_other_guarded_browser() { + let version = |product: &str, agent: &str| CdpVersionInfo { + user_agent: Some(agent.to_string()), + browser: Some(product.to_string()), + protocol_version: None, + web_socket_debugger_url: None, + }; + let chrome = version("Chrome/156.0", "Mozilla/5.0 Chrome/156.0 Safari/537.36"); + let edge = version("Chrome/156.0", "Mozilla/5.0 Chrome/156.0 Edg/156.0"); + assert_eq!( + CdpClient::guarded_product_mismatch(&BrowserKind::Chrome, &chrome), + None + ); + assert_eq!( + CdpClient::guarded_product_mismatch(&BrowserKind::Edge, &chrome), + Some(BrowserKind::Chrome) + ); + assert_eq!( + CdpClient::guarded_product_mismatch(&BrowserKind::Chrome, &edge), + Some(BrowserKind::Edge) + ); + assert_eq!( + CdpClient::guarded_product_mismatch(&BrowserKind::Brave, &chrome), + None + ); + } + + #[tokio::test] + async fn guarded_websocket_retries_refused_connections_within_budget() { + let reserved = std::net::TcpListener::bind("127.0.0.1:0").expect("reserve port"); + let port = reserved.local_addr().expect("address").port(); + drop(reserved); + + let server = tokio::spawn(async move { + // Refuse the first attempts, then come up like a browser that is + // still starting its guarded endpoint. + tokio::time::sleep(Duration::from_millis(400)).await; + let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)) + .await + .expect("rebind port"); + let (stream, _) = listener.accept().await.expect("accept"); + let mut socket = tokio_tungstenite::accept_async(stream) + .await + .expect("upgrade"); + while let Some(Ok(message)) = socket.next().await { + if matches!(message, Message::Close(_)) { + break; + } + } + }); + + let backoff = [ + Duration::from_millis(100), + Duration::from_millis(200), + Duration::from_millis(400), + Duration::from_millis(800), + ]; + let client = CdpClient::connect_user_profile_websocket( + &format!("ws://127.0.0.1:{port}/devtools/browser"), + Duration::from_secs(10), + &backoff, + ) + .await + .expect("retry until the endpoint accepts"); + client.disconnect().await; + server.await.expect("server"); + } + + #[tokio::test] + async fn guarded_websocket_never_retries_a_stalled_handshake() { + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) + .await + .expect("bind"); + let port = listener.local_addr().expect("address").port(); + let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let counter = accepted.clone(); + tokio::spawn(async move { + let mut held = Vec::new(); + while let Ok((stream, _)) = listener.accept().await { + // Hold the socket open without answering, like a browser + // waiting on its approval prompt. + counter.fetch_add(1, Ordering::SeqCst); + held.push(stream); + } + }); + + let error = CdpClient::connect_user_profile_websocket( + &format!("ws://127.0.0.1:{port}/devtools/browser"), + Duration::from_millis(300), + &USER_PROFILE_CONNECT_RETRY_BACKOFF, + ) + .await + .err() + .expect("stalled handshake must time out"); + assert!(matches!(error, UserProfileConnectError::Failed(_))); + assert!(error.into_error().to_string().contains("Timed out")); + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!(accepted.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn http_upgrade_denial_does_not_trigger_not_found_setup_fallback() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + for (status, not_found) in [ + ("404 Not Found", true), + ("401 Unauthorized", false), + ("403 Forbidden", false), + ] { + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) + .await + .expect("bind"); + let port = listener.local_addr().expect("address").port(); + let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let counter = accepted.clone(); + let server = tokio::spawn(async move { + while let Ok((mut stream, _)) = listener.accept().await { + counter.fetch_add(1, Ordering::SeqCst); + let mut buffer = [0_u8; 2048]; + let _ = stream.read(&mut buffer).await; + let response = format!( + "HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ); + let _ = stream.write_all(response.as_bytes()).await; + } + }); + + let error = CdpClient::connect_user_profile_browser_checked( + port, + port, + &BrowserKind::Chrome, + &format!("ws://127.0.0.1:{port}/devtools/browser"), + ) + .await + .err() + .expect("a rejected upgrade must fail"); + server.abort(); + assert_eq!( + matches!(error, UserProfileConnectError::NotABrowserEndpoint(_)), + not_found, + "access denial must not reopen setup: {status}" + ); + assert_eq!(accepted.load(Ordering::SeqCst), 1); + assert!(CdpClient::browser_connection(port).await.is_none()); + } + } } diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/control_hub_tool.rs b/src/crates/assembly/core/src/agentic/tools/implementations/control_hub_tool.rs index b12896b74d..173b5d80c9 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/control_hub_tool.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/control_hub_tool.rs @@ -13,7 +13,7 @@ use crate::agentic::tools::browser_control::automation_client::{ BrowserAutomationClient, EXTERNAL_CDP_EXTENSIONS, SHARED_BROWSER_ACTIONS, }; use crate::agentic::tools::browser_control::browser_launcher::{ - BrowserKind, BrowserLauncher, DEFAULT_CDP_PORT, + BrowserKind, BrowserLauncher, CdpPortProbe, DEFAULT_CDP_PORT, }; use crate::agentic::tools::browser_control::builtin_browser::{ builtin_browser_host_available, connect_builtin_browser_for_session, @@ -1780,19 +1780,41 @@ Results: `{ok, domain, action, data? , error?: {code, message, hints}}`. Check o } let mode = if headless { "headless" } else { "default" }; - if mode == "headless" && !BrowserLauncher::is_cdp_available(port).await { - return Ok(err_response( - "browser", - "connect", - ControlHubError::new( - ErrorCode::NotAvailable, - format!( - "Headless browser test port {} is not available. Start the dedicated headless browser first, then connect via ControlHub browser actions.", - port - ), - ) - .with_hints(Self::headless_browser_connect_hints(port)), - )); + if mode == "headless" { + match BrowserLauncher::probe_cdp_port(port).await { + CdpPortProbe::Http => {} + CdpPortProbe::GuardedNoHttp => { + // Guarded remote debugging belongs to a user's + // real browser profile, never a disposable test + // browser, and it serves no /json endpoints. + return Ok(err_response( + "browser", + "connect", + ControlHubError::new( + ErrorCode::NotAvailable, + format!( + "Port {} answers 404 on its /json HTTP endpoints, so it is not a headless test browser. If it is a browser with guarded remote debugging, that is a user's real browser profile; the user can connect it from Settings > Browser control.", + port + ), + ) + .with_hints(Self::headless_browser_connect_hints(port)), + )); + } + CdpPortProbe::Unreachable => { + return Ok(err_response( + "browser", + "connect", + ControlHubError::new( + ErrorCode::NotAvailable, + format!( + "Headless browser test port {} is not available. Start the dedicated headless browser first, then connect via ControlHub browser actions.", + port + ), + ) + .with_hints(Self::headless_browser_connect_hints(port)), + )); + } + } } let kind = if headless { diff --git a/src/crates/services/services-integrations/Cargo.toml b/src/crates/services/services-integrations/Cargo.toml index 6e3a86f6eb..b93e1b8f61 100644 --- a/src/crates/services/services-integrations/Cargo.toml +++ b/src/crates/services/services-integrations/Cargo.toml @@ -110,7 +110,7 @@ models-dev = [ "tokio/time", "windows", ] -browser-control = ["anyhow", "openbitfun-services-core/process-runtime", "openbitfun-services-core/tls-provider", "dirs", "reqwest", "reqwest/json", "reqwest/rustls-no-provider", "thiserror", "tokio/time"] +browser-control = ["anyhow", "openbitfun-services-core/process-runtime", "openbitfun-services-core/tls-provider", "dirs", "reqwest", "reqwest/json", "reqwest/rustls-no-provider", "thiserror", "tokio/rt", "tokio/time"] canvas-runtime = [ "dep:openbitfun-product-domains", "oxc", diff --git a/src/crates/services/services-integrations/src/browser_control/cdp.rs b/src/crates/services/services-integrations/src/browser_control/cdp.rs index 4a8dc06b10..5beb41fc38 100644 --- a/src/crates/services/services-integrations/src/browser_control/cdp.rs +++ b/src/crates/services/services-integrations/src/browser_control/cdp.rs @@ -40,6 +40,11 @@ pub struct CdpVersionInfo { #[derive(Debug, Error)] pub enum CdpEndpointError { + /// Chromium's user-approved remote debugging serves no `/json*` HTTP + /// discovery API; only the approved browser WebSocket works. A 404 alone + /// does not prove the port is a browser, so the message stays conditional. + #[error("Port {port} answers 404 on its /json HTTP endpoints, so it is not a legacy CDP debug port. If it is a browser with guarded remote debugging, connect it from Settings > Browser control so OpenBitFun can use the approved browser WebSocket connection.")] + GuardedNoHttp { port: u16 }, #[error("Cannot reach browser CDP on port {port}: {message}")] VersionRequest { port: u16, message: String }, #[error("Invalid CDP version response: {0}")] @@ -56,6 +61,18 @@ pub enum CdpEndpointError { pub struct CdpEndpointProvider; +/// Reject a guarded endpoint's 404 before the body is parsed, so callers see +/// actionable guidance instead of a JSON decode error on an empty body. +fn reject_guarded_endpoint( + response: reqwest::Response, + port: u16, +) -> Result { + if response.status() == reqwest::StatusCode::NOT_FOUND { + return Err(CdpEndpointError::GuardedNoHttp { port }); + } + Ok(response) +} + impl CdpEndpointProvider { /// Discover browser version on the given debug port. pub async fn get_version(port: u16) -> Result { @@ -68,7 +85,8 @@ impl CdpEndpointProvider { port, message: source.to_string(), })?; - resp.json() + reject_guarded_endpoint(resp, port)? + .json() .await .map_err(|source| CdpEndpointError::VersionResponse(source.to_string())) } @@ -84,7 +102,8 @@ impl CdpEndpointProvider { port, message: source.to_string(), })?; - resp.json() + reject_guarded_endpoint(resp, port)? + .json() .await .map_err(|source| CdpEndpointError::ListPagesResponse(source.to_string())) } @@ -108,7 +127,8 @@ impl CdpEndpointProvider { port, message: source.to_string(), })?; - resp.json() + reject_guarded_endpoint(resp, port)? + .json() .await .map_err(|source| CdpEndpointError::CreatePageResponse(source.to_string())) } @@ -118,6 +138,25 @@ impl CdpEndpointProvider { mod tests { use super::*; + #[tokio::test] + async fn guarded_endpoint_404_returns_actionable_error_for_every_http_call() { + let port = + crate::browser_control::test_support::serve_fixed_http("404 Not Found", "").await; + + let version = CdpEndpointProvider::get_version(port).await.unwrap_err(); + let pages = CdpEndpointProvider::list_pages(port).await.unwrap_err(); + let created = CdpEndpointProvider::create_page(port, Some("https://example.com")) + .await + .unwrap_err(); + for error in [version, pages, created] { + assert!( + matches!(error, CdpEndpointError::GuardedNoHttp { port: p } if p == port), + "unexpected error: {error}" + ); + assert!(error.to_string().contains("Settings > Browser control")); + } + } + #[test] fn cdp_page_info_preserves_websocket_debugger_field() { let page: CdpPageInfo = serde_json::from_value(serde_json::json!({ diff --git a/src/crates/services/services-integrations/src/browser_control/launcher.rs b/src/crates/services/services-integrations/src/browser_control/launcher.rs index 49875c45cf..1e8e188701 100644 --- a/src/crates/services/services-integrations/src/browser_control/launcher.rs +++ b/src/crates/services/services-integrations/src/browser_control/launcher.rs @@ -84,19 +84,213 @@ pub struct BrowserLaunchOptions { /// attach steals focus from whatever they were doing. Opt in only for a /// user-visible action such as restarting their browser from Settings. pub activate: bool, + /// Do not infer a guarded endpoint from a 404 port probe. Set after such + /// an inferred endpoint rejected the WebSocket upgrade, so the setup flow + /// waits for a real `DevToolsActivePort` instead of retrying the same + /// non-browser port. + pub skip_guarded_port_fallback: bool, + /// Upper bound for the setup wait, for callers that must finish inside + /// their own overall deadline. `None` keeps the default wait. + pub user_profile_setup_wait: Option, } +/// What a local CDP debug port answers on its HTTP discovery endpoint. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CdpPortProbe { + /// `/json/version` answered successfully: a legacy fixed-port endpoint + /// with the `/json*` HTTP discovery API. + Http, + /// The port speaks HTTP but `/json/version` returns 404. Chromium's + /// user-approved remote debugging (`chrome://inspect/#remote-debugging`, + /// Chrome 144+) deliberately serves no `/json*` endpoints; only the + /// browser-level WebSocket at `/devtools/browser` is available. + GuardedNoHttp, + /// Nothing usable is listening on the port. + Unreachable, +} + +/// Path of the browser-level WebSocket served by guarded remote debugging. +pub const GUARDED_BROWSER_WEBSOCKET_PATH: &str = "/devtools/browser"; + +const CDP_PROBE_TIMEOUT: Duration = Duration::from_secs(2); +/// How long an explicit Settings setup waits for the consent toggle. +const USER_PROFILE_SETUP_WAIT: Duration = Duration::from_secs(60); +/// How long an ordinary connect waits for the normal-start fast path. +const USER_PROFILE_FAST_PATH_WAIT: Duration = Duration::from_secs(2); +const USER_PROFILE_SETUP_POLL_INTERVAL: Duration = Duration::from_millis(250); +/// How long one process-listing answer is reused during a setup poll. +const BROWSER_RUNNING_CACHE_MAX_AGE: Duration = Duration::from_secs(3); + impl BrowserLauncher { - /// Check if a CDP debug port is already listening. - pub async fn is_cdp_available(port: u16) -> bool { + /// Classify what a local CDP debug port answers. This only performs an + /// HTTP request; it never opens a WebSocket, so it cannot raise a + /// browser-owned approval prompt. + pub async fn probe_cdp_port(port: u16) -> CdpPortProbe { let url = format!("http://127.0.0.1:{}/json/version", port); - crate::reqwest_client() + match crate::reqwest_client() .get(&url) - .timeout(std::time::Duration::from_secs(2)) + .timeout(CDP_PROBE_TIMEOUT) .send() .await - .map(|r| r.status().is_success()) - .unwrap_or(false) + { + Ok(response) if response.status().is_success() => CdpPortProbe::Http, + Ok(response) if response.status() == reqwest::StatusCode::NOT_FOUND => { + CdpPortProbe::GuardedNoHttp + } + Ok(response) => { + debug!( + "CDP port {} answered /json/version with unexpected status {}", + port, + response.status() + ); + CdpPortProbe::Unreachable + } + Err(_) => CdpPortProbe::Unreachable, + } + } + + /// Check if a legacy CDP debug port with the `/json*` HTTP API is + /// listening. A guarded endpoint that only serves the browser WebSocket + /// is reported by [`Self::probe_cdp_port`] instead. + pub async fn is_cdp_available(port: u16) -> bool { + Self::probe_cdp_port(port).await == CdpPortProbe::Http + } + + /// Browser-level endpoint for a guarded remote-debugging port whose + /// `DevToolsActivePort` file is not where OpenBitFun looks for it. A 404 + /// alone does not identify a browser, so the fallback additionally + /// requires the selected browser to be running, and skips a port that + /// the other guarded browser's `DevToolsActivePort` already claims + /// (Chrome and Edge share the default 9222 slot). The caller must still + /// verify the product through `Browser.getVersion` after the approved + /// WebSocket connects. Only an HTTP 404 upgrade response allows a setup + /// fallback; authorization denials must remain failures. + pub async fn guarded_port_debug_endpoint( + kind: &BrowserKind, + port: u16, + ) -> Option { + Self::guarded_port_debug_endpoint_cached(kind, port, &mut BrowserRunningCache::new(kind)) + .await + } + + /// [`Self::guarded_port_debug_endpoint`] that reuses one process-running + /// answer across a setup poll. The cheap HTTP probe and the port-claim + /// file check run first, so the process listing is only consulted for a + /// port that could still belong to the selected browser. + async fn guarded_port_debug_endpoint_cached( + kind: &BrowserKind, + port: u16, + running: &mut BrowserRunningCache, + ) -> Option { + if !Self::supports_default_cdp(kind) || port == 0 { + return None; + } + let probe = Self::probe_cdp_port(port).await; + if probe != CdpPortProbe::GuardedNoHttp { + return None; + } + let selected = kind.clone(); + let claimed_by_other = Self::run_blocking(move || { + Self::port_claimed_by_other_guarded_browser(&selected, port) + }) + .await + .unwrap_or(true); + if claimed_by_other { + return None; + } + let selected_running = running.is_running().await; + Self::guarded_port_fallback_decision(port, probe, claimed_by_other, selected_running) + } + + /// Pure decision behind [`Self::guarded_port_debug_endpoint`]. + fn guarded_port_fallback_decision( + port: u16, + probe: CdpPortProbe, + claimed_by_other: bool, + selected_running: bool, + ) -> Option { + (probe == CdpPortProbe::GuardedNoHttp && !claimed_by_other && selected_running) + .then(|| Self::guarded_port_endpoint(port)) + } + + fn guarded_port_endpoint(port: u16) -> BrowserDebugEndpoint { + BrowserDebugEndpoint { + port, + web_socket_url: format!("ws://127.0.0.1:{port}{GUARDED_BROWSER_WEBSOCKET_PATH}"), + } + } + + /// Whether this endpoint was inferred from a 404 port probe rather than + /// read from `DevToolsActivePort`, whose path always carries a browser id. + pub fn is_inferred_guarded_endpoint(endpoint: &BrowserDebugEndpoint) -> bool { + endpoint == &Self::guarded_port_endpoint(endpoint.port) + } + + fn port_claimed_by_other_guarded_browser(kind: &BrowserKind, port: u16) -> bool { + [BrowserKind::Chrome, BrowserKind::Edge] + .iter() + .filter(|other| *other != kind) + .any(|other| { + Self::user_profile_debug_endpoint(other) + .is_some_and(|endpoint| endpoint.port == port) + }) + } + + /// Run a filesystem, TCP, or process-listing check off the async runtime. + async fn run_blocking( + work: impl FnOnce() -> T + Send + 'static, + ) -> Option { + tokio::task::spawn_blocking(work).await.ok() + } + + /// [`Self::user_profile_debug_endpoint`] without blocking the async + /// runtime on its file reads and TCP probes. + pub async fn user_profile_debug_endpoint_async( + kind: &BrowserKind, + ) -> Option { + let kind = kind.clone(); + Self::run_blocking(move || Self::user_profile_debug_endpoint(&kind)) + .await + .flatten() + } + + /// A running browser that can own a guarded remote-debugging port. A 404 + /// on `/json/version` without one is an unrelated HTTP server. + async fn running_guarded_browser() -> Option { + Self::run_blocking(|| { + [BrowserKind::Chrome, BrowserKind::Edge] + .into_iter() + .find(Self::is_browser_running) + }) + .await + .flatten() + } + + /// Whether a guarded browser other than `kind` is running, in which case a + /// port inferred for `kind` from a 404 probe may belong to that browser. + pub async fn other_guarded_browser_running(kind: &BrowserKind) -> bool { + let selected = kind.clone(); + Self::run_blocking(move || { + [BrowserKind::Chrome, BrowserKind::Edge] + .iter() + .filter(|other| **other != selected) + .any(Self::is_browser_running) + }) + .await + .unwrap_or(true) + } + + /// Endpoint for the selected browser's real profile: the published + /// `DevToolsActivePort` file first, then a guarded port that answers 404 + /// on `/json/version` while the selected browser is running. + pub async fn user_profile_debug_endpoint_or_guarded_port( + kind: &BrowserKind, + port: u16, + ) -> Option { + if let Some(endpoint) = Self::user_profile_debug_endpoint_async(kind).await { + return Some(endpoint); + } + Self::guarded_port_debug_endpoint(kind, port).await } /// Detect the user's default browser on the current platform. @@ -346,52 +540,45 @@ impl BrowserLauncher { } /// Return the browser's normal user-data directory. Browsers that expose - /// approval-based remote debugging write `DevToolsActivePort` here. + /// approval-based remote debugging write `DevToolsActivePort` here. This is + /// the stable-channel directory; see [`Self::user_profile_data_dirs`] for + /// every candidate that is probed. pub fn user_profile_data_dir(kind: &BrowserKind) -> Option { + Self::user_profile_data_dirs(kind).into_iter().next() + } + + /// Every user-data directory that may hold the selected browser's + /// `DevToolsActivePort`, stable channel first, followed by Beta / Dev / + /// Canary channels and sandboxed (Snap / Flatpak) installs. The first + /// directory that publishes a live endpoint wins. + pub fn user_profile_data_dirs(kind: &BrowserKind) -> Vec { #[cfg(target_os = "macos")] { - let home = dirs::home_dir()?; - let application_support = home.join("Library").join("Application Support"); - let relative = match kind { - BrowserKind::Chrome => Path::new("Google/Chrome"), - BrowserKind::Edge => Path::new("Microsoft Edge"), - BrowserKind::Chromium => Path::new("Chromium"), - BrowserKind::Brave => Path::new("BraveSoftware/Brave-Browser"), - BrowserKind::Arc => Path::new("Arc/User Data"), - BrowserKind::Unknown(_) => return None, + let Some(home) = dirs::home_dir() else { + return Vec::new(); }; - return Some(application_support.join(relative)); + macos_profile_dir_candidates(kind, &home.join("Library").join("Application Support")) } #[cfg(target_os = "windows")] { - let local_app_data = std::env::var_os("LOCALAPPDATA").map(PathBuf::from)?; - let relative = match kind { - BrowserKind::Chrome => Path::new("Google/Chrome/User Data"), - BrowserKind::Edge => Path::new("Microsoft/Edge/User Data"), - BrowserKind::Chromium => Path::new("Chromium/User Data"), - BrowserKind::Brave => Path::new("BraveSoftware/Brave-Browser/User Data"), - BrowserKind::Arc => Path::new("Arc/User Data"), - BrowserKind::Unknown(_) => return None, + let Some(local_app_data) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) else { + return Vec::new(); }; - return Some(local_app_data.join(relative)); + windows_profile_dir_candidates(kind, &local_app_data) } #[cfg(target_os = "linux")] { - let config_root = std::env::var_os("CHROME_CONFIG_HOME") + let home = dirs::home_dir(); + let Some(config_root) = std::env::var_os("CHROME_CONFIG_HOME") .or_else(|| std::env::var_os("XDG_CONFIG_HOME")) .map(PathBuf::from) - .or_else(|| dirs::home_dir().map(|home| home.join(".config")))?; - let relative = match kind { - BrowserKind::Chrome => Path::new("google-chrome"), - BrowserKind::Edge => Path::new("microsoft-edge"), - BrowserKind::Chromium => Path::new("chromium"), - BrowserKind::Brave => Path::new("BraveSoftware/Brave-Browser"), - BrowserKind::Arc => Path::new("arc"), - BrowserKind::Unknown(_) => return None, + .or_else(|| home.as_ref().map(|home| home.join(".config"))) + else { + return Vec::new(); }; - return Some(config_root.join(relative)); + linux_profile_dir_candidates(kind, &config_root, home.as_deref()) } } @@ -431,7 +618,13 @@ impl BrowserLauncher { /// in its normal user-data directory. Malformed or stale files are treated /// as unavailable; the subsequent WebSocket connection is the source of truth. pub fn user_profile_debug_endpoint(kind: &BrowserKind) -> Option { - let path = Self::user_profile_data_dir(kind)?.join("DevToolsActivePort"); + Self::user_profile_data_dirs(kind) + .iter() + .find_map(|directory| Self::debug_endpoint_in_dir(directory)) + } + + fn debug_endpoint_in_dir(directory: &Path) -> Option { + let path = directory.join("DevToolsActivePort"); let contents = std::fs::read_to_string(&path).ok()?; match Self::parse_devtools_active_port(&contents) { Ok(endpoint) => { @@ -486,22 +679,38 @@ impl BrowserLauncher { /// Whether the browser's persistent, approval-based CDP preference is on. /// The endpoint is also accepted as proof because the browser may create it - /// before its Local State update has been flushed to disk. + /// before its Local State update has been flushed to disk. Without a live + /// endpoint only the stable channel's Local State counts: a Beta/Dev + /// channel preference says nothing about the browser that will start. pub fn is_default_cdp_enabled(kind: &BrowserKind) -> bool { if !Self::supports_default_cdp(kind) { return false; } - if Self::user_profile_debug_endpoint(kind).is_some() { + Self::default_cdp_enabled_in_dirs(&Self::user_profile_data_dirs(kind)) + } + + /// [`Self::is_default_cdp_enabled`] without blocking the async runtime on + /// its file reads and TCP probes. + pub async fn is_default_cdp_enabled_async(kind: &BrowserKind) -> bool { + let kind = kind.clone(); + Self::run_blocking(move || Self::is_default_cdp_enabled(&kind)) + .await + .unwrap_or(false) + } + + /// `directories` is the candidate list, stable channel first. + fn default_cdp_enabled_in_dirs(directories: &[PathBuf]) -> bool { + if directories + .iter() + .any(|directory| Self::debug_endpoint_in_dir(directory).is_some()) + { return true; } - let Some(path) = - Self::user_profile_data_dir(kind).map(|directory| directory.join("Local State")) - else { - return false; - }; - std::fs::read_to_string(path) - .ok() - .is_some_and(|contents| Self::default_cdp_preference_enabled(&contents)) + directories.first().is_some_and(|directory| { + std::fs::read_to_string(directory.join("Local State")) + .ok() + .is_some_and(|contents| Self::default_cdp_preference_enabled(&contents)) + }) } /// Open the browser's Remote debugging settings page. @@ -586,25 +795,63 @@ impl BrowserLauncher { } } + async fn discover_user_profile_endpoint( + kind: &BrowserKind, + port: u16, + allow_port_fallback: bool, + running: &mut BrowserRunningCache, + ) -> Option { + if let Some(endpoint) = Self::user_profile_debug_endpoint_async(kind).await { + return Some(endpoint); + } + if !allow_port_fallback { + return None; + } + Self::guarded_port_debug_endpoint_cached(kind, port, running).await + } + async fn prepare_user_profile_connection( kind: &BrowserKind, + port: u16, wait_for_user_setup: bool, + allow_port_fallback: bool, + setup_wait_override: Option, ) -> Result { - if let Some(endpoint) = Self::user_profile_debug_endpoint(kind) { + let mut running = BrowserRunningCache::new(kind); + if let Some(endpoint) = + Self::discover_user_profile_endpoint(kind, port, allow_port_fallback, &mut running) + .await + { return Ok(LaunchResult::UserProfileReady { endpoint }); } let setup_url = Self::user_profile_debugging_setup_url(kind) .ok_or_else(|| anyhow!("{} does not support guarded user-profile CDP", kind))?; - let opened = Self::open_user_profile_debugging_setup(kind, setup_url); + let setup_kind = kind.clone(); + let opened = Self::run_blocking(move || { + Self::open_user_profile_debugging_setup(&setup_kind, setup_url) + }) + .await + .unwrap_or(false); // An explicit Settings action waits up to one minute so the user can // tick the browser-owned consent checkbox; an ordinary agent connect // only waits for the normal-start fast path before returning guidance. - let attempts = if wait_for_user_setup { 240 } else { 8 }; - for _ in 0..attempts { - tokio::time::sleep(Duration::from_millis(250)).await; - if let Some(endpoint) = Self::user_profile_debug_endpoint(kind) { + // The budget is a deadline so slow probes cannot stretch it, and a + // caller with its own overall deadline may shorten it. + let default_wait = if wait_for_user_setup { + USER_PROFILE_SETUP_WAIT + } else { + USER_PROFILE_FAST_PATH_WAIT + }; + let wait = setup_wait_override.map_or(default_wait, |limit| limit.min(default_wait)); + let deadline = tokio::time::Instant::now() + wait; + while tokio::time::Instant::now() < deadline { + tokio::time::sleep(USER_PROFILE_SETUP_POLL_INTERVAL).await; + if let Some(endpoint) = + Self::discover_user_profile_endpoint(kind, port, allow_port_fallback, &mut running) + .await + { return Ok(LaunchResult::UserProfileReady { endpoint }); } } @@ -874,6 +1121,17 @@ impl BrowserLauncher { Self::launch_with_cdp_options(kind, port, BrowserLaunchOptions::default()).await } + /// Guidance when a launch targets a port that a running guarded browser + /// owns. A managed instance cannot bind it and the legacy HTTP attach path + /// cannot use it. `None` keeps the ordinary launch path. + fn guarded_port_launch_conflict(port: u16, owner: Option<&BrowserKind>) -> Option { + owner.map(|owner| { + format!( + "Port {port} appears to be served by {owner} with guarded remote debugging, which has no /json HTTP endpoints. Connect it from Settings > Browser control instead." + ) + }) + } + /// Same as [`launch_with_cdp`] but allows passing an isolated /// `--user-data-dir`. When the user is already running their main /// browser without CDP, an isolated profile lets us start a sibling @@ -887,21 +1145,36 @@ impl BrowserLauncher { // Opportunistically reuse the real profile for any Chromium browser // that already publishes a browser-level endpoint. Chrome and Edge // additionally get a first-class setup flow when it is not enabled. - if let Some(endpoint) = Self::user_profile_debug_endpoint(kind) { + if let Some(endpoint) = Self::user_profile_debug_endpoint_async(kind).await { return Ok(LaunchResult::UserProfileReady { endpoint }); } if Self::supports_default_cdp(kind) { return Self::prepare_user_profile_connection( kind, + port, options.wait_for_user_profile_setup, + !options.skip_guarded_port_fallback, + options.user_profile_setup_wait, ) .await; } } - if Self::is_cdp_available(port).await { - info!("CDP already available on port {} for {}", port, kind); - return Ok(LaunchResult::AlreadyConnected); + match Self::probe_cdp_port(port).await { + CdpPortProbe::Http => { + info!("CDP already available on port {} for {}", port, kind); + return Ok(LaunchResult::AlreadyConnected); + } + CdpPortProbe::GuardedNoHttp => { + // Only a running Chrome / Edge confirms that guarded remote + // debugging owns this port; any other 404 server keeps the + // ordinary launch path and its existing not-ready result. + let owner = Self::running_guarded_browser().await; + if let Some(message) = Self::guarded_port_launch_conflict(port, owner.as_ref()) { + return Err(anyhow!(message)); + } + } + CdpPortProbe::Unreachable => {} } let exe = Self::browser_executable(kind); @@ -1068,45 +1341,26 @@ impl BrowserLauncher { } /// Check if a browser process is currently running. + /// + /// Matches the exact process name (`pgrep -x` / `tasklist` image name), + /// never a command-line substring: `pgrep -f chrome` also matched helper + /// processes such as Electron apps' `chrome_crashpad_handler`. #[allow(dead_code)] fn is_browser_running(kind: &BrowserKind) -> bool { - // Per-platform process names. - // macOS / Linux match against the executable filename via `pgrep -f`. - // Windows must use the *.exe image name as it appears in `tasklist`. #[cfg(target_os = "macos")] - let process_names: Vec<&str> = match kind { - BrowserKind::Chrome => vec!["Google Chrome"], - BrowserKind::Edge => vec!["Microsoft Edge"], - BrowserKind::Brave => vec!["Brave Browser"], - BrowserKind::Arc => vec!["Arc"], - BrowserKind::Chromium => vec!["Chromium"], - BrowserKind::Unknown(_) => return false, - }; - + let process_names = macos_browser_process_names(kind); #[cfg(target_os = "linux")] - let process_names: Vec<&str> = match kind { - BrowserKind::Chrome => vec!["chrome", "google-chrome"], - BrowserKind::Edge => vec!["msedge", "microsoft-edge"], - BrowserKind::Brave => vec!["brave", "brave-browser"], - BrowserKind::Arc => vec!["arc"], - BrowserKind::Chromium => vec!["chromium", "chromium-browser"], - BrowserKind::Unknown(_) => return false, - }; - + let process_names = linux_browser_process_names(kind); #[cfg(target_os = "windows")] - let process_names: Vec<&str> = match kind { - BrowserKind::Chrome => vec!["chrome.exe"], - BrowserKind::Edge => vec!["msedge.exe"], - BrowserKind::Brave => vec!["brave.exe"], - BrowserKind::Arc => vec!["arc.exe"], - BrowserKind::Chromium => vec!["chrome.exe", "chromium.exe"], - BrowserKind::Unknown(_) => return false, - }; + let process_names = windows_browser_process_names(kind); #[cfg(any(target_os = "macos", target_os = "linux"))] { - for name in &process_names { - let output = silent_command("pgrep").args(["-f", name]).output().ok(); + for name in process_names { + let output = silent_command("pgrep") + .args(pgrep_exact_args(name)) + .output() + .ok(); if let Some(out) = output { if out.status.success() && !out.stdout.is_empty() { return true; @@ -1118,7 +1372,7 @@ impl BrowserLauncher { #[cfg(target_os = "windows")] { - for image in &process_names { + for image in process_names { let filter = format!("IMAGENAME eq {}", image); let output = silent_command("tasklist") .args(["/FI", &filter, "/NH", "/FO", "CSV"]) @@ -1141,6 +1395,188 @@ impl BrowserLauncher { } } +/// `pgrep` arguments that match one exact process name. +#[cfg_attr( + not(any(test, target_os = "macos", target_os = "linux")), + allow(dead_code) +)] +fn pgrep_exact_args(name: &str) -> [&str; 2] { + ["-x", name] +} + +/// macOS main-process names. Helpers (`Google Chrome Helper`, ...) differ. +#[cfg_attr(not(any(test, target_os = "macos")), allow(dead_code))] +fn macos_browser_process_names(kind: &BrowserKind) -> &'static [&'static str] { + match kind { + BrowserKind::Chrome => &["Google Chrome"], + BrowserKind::Edge => &["Microsoft Edge"], + BrowserKind::Brave => &["Brave Browser"], + BrowserKind::Arc => &["Arc"], + BrowserKind::Chromium => &["Chromium"], + BrowserKind::Unknown(_) => &[], + } +} + +/// Linux executable names as `/proc//comm` reports them (at most 15 +/// bytes). Launcher wrappers such as `google-chrome` exec these binaries. +#[cfg_attr(not(any(test, target_os = "linux")), allow(dead_code))] +fn linux_browser_process_names(kind: &BrowserKind) -> &'static [&'static str] { + match kind { + BrowserKind::Chrome => &["chrome", "google-chrome"], + BrowserKind::Edge => &["msedge", "microsoft-edge"], + BrowserKind::Brave => &["brave", "brave-browser"], + BrowserKind::Arc => &["arc"], + BrowserKind::Chromium => &["chromium", "chromium-browse"], + BrowserKind::Unknown(_) => &[], + } +} + +/// Windows image names as `tasklist` reports them. +#[cfg_attr(not(any(test, target_os = "windows")), allow(dead_code))] +fn windows_browser_process_names(kind: &BrowserKind) -> &'static [&'static str] { + match kind { + BrowserKind::Chrome => &["chrome.exe"], + BrowserKind::Edge => &["msedge.exe"], + BrowserKind::Brave => &["brave.exe"], + BrowserKind::Arc => &["arc.exe"], + BrowserKind::Chromium => &["chrome.exe", "chromium.exe"], + BrowserKind::Unknown(_) => &[], + } +} + +/// Process-running answer cached for one setup call so the 250 ms endpoint +/// poll does not spawn a process listing every iteration. +struct BrowserRunningCache { + kind: BrowserKind, + max_age: Duration, + checked: Option<(tokio::time::Instant, bool)>, + check: fn(&BrowserKind) -> bool, +} + +impl BrowserRunningCache { + fn new(kind: &BrowserKind) -> Self { + Self::with_check( + kind, + BROWSER_RUNNING_CACHE_MAX_AGE, + BrowserLauncher::is_browser_running, + ) + } + + fn with_check(kind: &BrowserKind, max_age: Duration, check: fn(&BrowserKind) -> bool) -> Self { + Self { + kind: kind.clone(), + max_age, + checked: None, + check, + } + } + + async fn is_running(&mut self) -> bool { + let now = tokio::time::Instant::now(); + if let Some((at, running)) = self.checked { + if now.saturating_duration_since(at) < self.max_age { + return running; + } + } + let kind = self.kind.clone(); + let check = self.check; + let running = BrowserLauncher::run_blocking(move || check(&kind)) + .await + .unwrap_or(false); + self.checked = Some((now, running)); + running + } +} + +fn join_candidates(root: &Path, relatives: &[&str]) -> Vec { + relatives + .iter() + .map(|relative| root.join(relative)) + .collect() +} + +#[cfg_attr(not(any(test, target_os = "macos")), allow(dead_code))] +fn macos_profile_dir_candidates(kind: &BrowserKind, application_support: &Path) -> Vec { + let relatives: &[&str] = match kind { + BrowserKind::Chrome => &[ + "Google/Chrome", + "Google/Chrome Beta", + "Google/Chrome Dev", + "Google/Chrome Canary", + ], + BrowserKind::Edge => &[ + "Microsoft Edge", + "Microsoft Edge Beta", + "Microsoft Edge Dev", + "Microsoft Edge Canary", + ], + BrowserKind::Chromium => &["Chromium"], + BrowserKind::Brave => &["BraveSoftware/Brave-Browser"], + BrowserKind::Arc => &["Arc/User Data"], + BrowserKind::Unknown(_) => &[], + }; + join_candidates(application_support, relatives) +} + +#[cfg_attr(not(any(test, target_os = "windows")), allow(dead_code))] +fn windows_profile_dir_candidates(kind: &BrowserKind, local_app_data: &Path) -> Vec { + let relatives: &[&str] = match kind { + BrowserKind::Chrome => &[ + "Google/Chrome/User Data", + "Google/Chrome Beta/User Data", + "Google/Chrome Dev/User Data", + "Google/Chrome SxS/User Data", + ], + BrowserKind::Edge => &[ + "Microsoft/Edge/User Data", + "Microsoft/Edge Beta/User Data", + "Microsoft/Edge Dev/User Data", + "Microsoft/Edge SxS/User Data", + ], + BrowserKind::Chromium => &["Chromium/User Data"], + BrowserKind::Brave => &["BraveSoftware/Brave-Browser/User Data"], + BrowserKind::Arc => &["Arc/User Data"], + BrowserKind::Unknown(_) => &[], + }; + join_candidates(local_app_data, relatives) +} + +#[cfg_attr(not(any(test, target_os = "linux")), allow(dead_code))] +fn linux_profile_dir_candidates( + kind: &BrowserKind, + config_root: &Path, + home: Option<&Path>, +) -> Vec { + let (relatives, home_relatives): (&[&str], &[&str]) = match kind { + BrowserKind::Chrome => ( + &[ + "google-chrome", + "google-chrome-beta", + "google-chrome-unstable", + "google-chrome-canary", + ], + &[".var/app/com.google.Chrome/config/google-chrome"], + ), + BrowserKind::Edge => ( + &[ + "microsoft-edge", + "microsoft-edge-beta", + "microsoft-edge-dev", + ], + &[".var/app/com.microsoft.Edge/config/microsoft-edge"], + ), + BrowserKind::Chromium => (&["chromium"], &["snap/chromium/common/chromium"]), + BrowserKind::Brave => (&["BraveSoftware/Brave-Browser"], &[]), + BrowserKind::Arc => (&["arc"], &[]), + BrowserKind::Unknown(_) => (&[], &[]), + }; + let mut candidates = join_candidates(config_root, relatives); + if let Some(home) = home { + candidates.extend(join_candidates(home, home_relatives)); + } + candidates +} + /// Result of a browser launch attempt. #[derive(Debug, Clone, Serialize, Deserialize)] pub enum LaunchResult { @@ -1256,6 +1692,348 @@ mod tests { assert!(!BrowserLauncher::default_cdp_preference_enabled("{}")); } + #[test] + fn default_cdp_preference_reads_only_the_stable_local_state() { + let enabled = r#"{"devtools":{"remote_debugging":{"user-enabled":true}}}"#; + let stable = tempfile::tempdir().unwrap(); + let beta = tempfile::tempdir().unwrap(); + std::fs::write(beta.path().join("Local State"), enabled).unwrap(); + let dirs = vec![stable.path().to_path_buf(), beta.path().to_path_buf()]; + // A Beta-only preference does not describe the stable browser. + assert!(!BrowserLauncher::default_cdp_enabled_in_dirs(&dirs)); + std::fs::write(stable.path().join("Local State"), enabled).unwrap(); + assert!(BrowserLauncher::default_cdp_enabled_in_dirs(&dirs)); + } + + #[tokio::test] + async fn probe_classifies_guarded_http_and_unreachable_ports() { + use crate::browser_control::test_support::{closed_port, serve_fixed_http}; + + let guarded = serve_fixed_http("404 Not Found", "").await; + assert_eq!( + BrowserLauncher::probe_cdp_port(guarded).await, + CdpPortProbe::GuardedNoHttp + ); + assert!(!BrowserLauncher::is_cdp_available(guarded).await); + + let legacy = serve_fixed_http( + "200 OK", + r#"{"Browser":"Chrome/156.0","webSocketDebuggerUrl":"ws://127.0.0.1/devtools/browser/x"}"#, + ) + .await; + assert_eq!( + BrowserLauncher::probe_cdp_port(legacy).await, + CdpPortProbe::Http + ); + assert!(BrowserLauncher::is_cdp_available(legacy).await); + + assert_eq!( + BrowserLauncher::probe_cdp_port(closed_port()).await, + CdpPortProbe::Unreachable + ); + } + + #[tokio::test] + async fn guarded_port_fallback_is_limited_to_chrome_and_edge_on_a_404_port() { + use crate::browser_control::test_support::serve_fixed_http; + + // Browsers without the guarded flow never guess a WebSocket. + let guarded = serve_fixed_http("404 Not Found", "").await; + assert!( + BrowserLauncher::guarded_port_debug_endpoint(&BrowserKind::Brave, guarded) + .await + .is_none() + ); + // A legacy fixed port keeps the HTTP discovery path. + let legacy = serve_fixed_http("200 OK", "{}").await; + for kind in [BrowserKind::Chrome, BrowserKind::Edge] { + assert!(BrowserLauncher::guarded_port_debug_endpoint(&kind, legacy) + .await + .is_none()); + } + } + + #[test] + fn guarded_port_fallback_requires_the_selected_browser_running() { + let port = 9222; + let expected = BrowserDebugEndpoint { + port, + web_socket_url: "ws://127.0.0.1:9222/devtools/browser".to_string(), + }; + assert_eq!( + BrowserLauncher::guarded_port_fallback_decision( + port, + CdpPortProbe::GuardedNoHttp, + false, + true + ), + Some(expected.clone()) + ); + assert!(BrowserLauncher::is_inferred_guarded_endpoint(&expected)); + // A 404 from an unrelated server while the selected browser is not + // running (for example Chrome selected, Edge guarded on 9222). + assert_eq!( + BrowserLauncher::guarded_port_fallback_decision( + port, + CdpPortProbe::GuardedNoHttp, + false, + false + ), + None + ); + // The other guarded browser's DevToolsActivePort claims the port. + assert_eq!( + BrowserLauncher::guarded_port_fallback_decision( + port, + CdpPortProbe::GuardedNoHttp, + true, + true + ), + None + ); + for probe in [CdpPortProbe::Http, CdpPortProbe::Unreachable] { + assert_eq!( + BrowserLauncher::guarded_port_fallback_decision(port, probe, false, true), + None + ); + } + // An endpoint read from DevToolsActivePort carries a browser id. + assert!(!BrowserLauncher::is_inferred_guarded_endpoint( + &BrowserDebugEndpoint { + port, + web_socket_url: "ws://127.0.0.1:9222/devtools/browser/abc".to_string(), + } + )); + } + + #[test] + fn launch_conflict_requires_a_confirmed_guarded_browser() { + assert!(BrowserLauncher::guarded_port_launch_conflict(9222, None).is_none()); + let message = BrowserLauncher::guarded_port_launch_conflict(9222, Some(&BrowserKind::Edge)) + .expect("confirmed owner"); + assert!(message.contains("Microsoft Edge")); + assert!(message.contains("Settings > Browser control")); + } + + #[tokio::test] + async fn setup_without_port_fallback_never_infers_a_404_port() { + use crate::browser_control::test_support::serve_fixed_http; + + let port = serve_fixed_http("404 Not Found", "").await; + for kind in [BrowserKind::Chrome, BrowserKind::Edge] { + let mut running = + BrowserRunningCache::with_check(&kind, Duration::from_secs(3), |_| true); + let endpoint = + BrowserLauncher::discover_user_profile_endpoint(&kind, port, false, &mut running) + .await; + assert!(!endpoint.is_some_and(|endpoint| endpoint.port == port)); + // The process listing is not consulted without the port fallback. + assert!(running.checked.is_none()); + } + } + + static RUNNING_CHECKS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + + fn counting_running_check(_: &BrowserKind) -> bool { + RUNNING_CHECKS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + true + } + + #[tokio::test(start_paused = true)] + async fn running_check_is_cached_across_a_setup_poll() { + use std::sync::atomic::Ordering; + + let before = RUNNING_CHECKS.load(Ordering::SeqCst); + let mut running = BrowserRunningCache::with_check( + &BrowserKind::Chrome, + Duration::from_secs(3), + counting_running_check, + ); + // Twelve 250 ms polls inside one cache window list processes once. + for _ in 0..12 { + assert!(running.is_running().await); + tokio::time::advance(Duration::from_millis(240)).await; + } + assert_eq!(RUNNING_CHECKS.load(Ordering::SeqCst) - before, 1); + tokio::time::advance(Duration::from_secs(1)).await; + assert!(running.is_running().await); + assert_eq!(RUNNING_CHECKS.load(Ordering::SeqCst) - before, 2); + } + + #[tokio::test] + async fn running_check_is_skipped_for_ports_without_a_guarded_404() { + use crate::browser_control::test_support::{closed_port, serve_fixed_http}; + + let legacy = serve_fixed_http("200 OK", "{}").await; + for port in [legacy, closed_port()] { + let mut running = BrowserRunningCache::with_check( + &BrowserKind::Chrome, + Duration::from_secs(3), + |_| true, + ); + assert!(BrowserLauncher::guarded_port_debug_endpoint_cached( + &BrowserKind::Chrome, + port, + &mut running + ) + .await + .is_none()); + assert!(running.checked.is_none()); + } + } + + #[test] + fn process_match_uses_exact_names_not_command_lines() { + assert_eq!(pgrep_exact_args("chrome"), ["-x", "chrome"]); + for kind in [ + BrowserKind::Chrome, + BrowserKind::Edge, + BrowserKind::Brave, + BrowserKind::Chromium, + BrowserKind::Arc, + ] { + for name in linux_browser_process_names(&kind) { + // `/proc//comm` holds at most 15 bytes; longer names + // could never match exactly. + assert!(name.len() <= 15, "{name}"); + assert!(!name.contains("crashpad")); + } + assert!(!macos_browser_process_names(&kind).is_empty()); + assert!(windows_browser_process_names(&kind) + .iter() + .all(|name| name.ends_with(".exe"))); + } + assert_eq!( + linux_browser_process_names(&BrowserKind::Edge), + &["msedge", "microsoft-edge"] + ); + assert!(linux_browser_process_names(&BrowserKind::Unknown("x".into())).is_empty()); + } + + #[test] + fn macos_profile_candidates_cover_release_channels() { + let root = PathBuf::from("/Users/u/Library/Application Support"); + assert_eq!( + macos_profile_dir_candidates(&BrowserKind::Chrome, &root), + vec![ + root.join("Google/Chrome"), + root.join("Google/Chrome Beta"), + root.join("Google/Chrome Dev"), + root.join("Google/Chrome Canary"), + ] + ); + assert_eq!( + macos_profile_dir_candidates(&BrowserKind::Edge, &root), + vec![ + root.join("Microsoft Edge"), + root.join("Microsoft Edge Beta"), + root.join("Microsoft Edge Dev"), + root.join("Microsoft Edge Canary"), + ] + ); + assert!(macos_profile_dir_candidates(&BrowserKind::Unknown("x".into()), &root).is_empty()); + } + + #[test] + fn windows_profile_candidates_cover_release_channels() { + let root = PathBuf::from("/LocalAppData"); + assert_eq!( + windows_profile_dir_candidates(&BrowserKind::Chrome, &root), + vec![ + root.join("Google/Chrome/User Data"), + root.join("Google/Chrome Beta/User Data"), + root.join("Google/Chrome Dev/User Data"), + root.join("Google/Chrome SxS/User Data"), + ] + ); + assert_eq!( + windows_profile_dir_candidates(&BrowserKind::Edge, &root), + vec![ + root.join("Microsoft/Edge/User Data"), + root.join("Microsoft/Edge Beta/User Data"), + root.join("Microsoft/Edge Dev/User Data"), + root.join("Microsoft/Edge SxS/User Data"), + ] + ); + } + + #[test] + fn linux_profile_candidates_cover_channels_and_sandboxed_installs() { + let config = PathBuf::from("/home/u/.config"); + let home = PathBuf::from("/home/u"); + assert_eq!( + linux_profile_dir_candidates(&BrowserKind::Chrome, &config, Some(&home)), + vec![ + config.join("google-chrome"), + config.join("google-chrome-beta"), + config.join("google-chrome-unstable"), + config.join("google-chrome-canary"), + home.join(".var/app/com.google.Chrome/config/google-chrome"), + ] + ); + assert_eq!( + linux_profile_dir_candidates(&BrowserKind::Edge, &config, Some(&home)), + vec![ + config.join("microsoft-edge"), + config.join("microsoft-edge-beta"), + config.join("microsoft-edge-dev"), + home.join(".var/app/com.microsoft.Edge/config/microsoft-edge"), + ] + ); + assert_eq!( + linux_profile_dir_candidates(&BrowserKind::Chromium, &config, Some(&home)), + vec![ + config.join("chromium"), + home.join("snap/chromium/common/chromium"), + ] + ); + assert_eq!( + linux_profile_dir_candidates(&BrowserKind::Chromium, &config, None), + vec![config.join("chromium")] + ); + } + + #[test] + fn stable_profile_dir_stays_the_first_candidate() { + for kind in [BrowserKind::Chrome, BrowserKind::Edge, BrowserKind::Brave] { + assert_eq!( + BrowserLauncher::user_profile_data_dir(&kind), + BrowserLauncher::user_profile_data_dirs(&kind) + .into_iter() + .next() + ); + } + } + + #[test] + fn first_live_devtools_active_port_candidate_wins() { + let stale = tempfile::tempdir().expect("tempdir"); + let live = tempfile::tempdir().expect("tempdir"); + let closed = crate::browser_control::test_support::closed_port(); + std::fs::write( + stale.path().join("DevToolsActivePort"), + format!("{closed}\n/devtools/browser/stale\n"), + ) + .unwrap(); + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let live_port = listener.local_addr().unwrap().port(); + std::fs::write( + live.path().join("DevToolsActivePort"), + format!("{live_port}\n/devtools/browser/live\n"), + ) + .unwrap(); + + let found = [stale.path(), live.path()] + .iter() + .find_map(|directory| BrowserLauncher::debug_endpoint_in_dir(directory)) + .expect("live candidate"); + assert_eq!(found.port, live_port); + assert_eq!( + found.web_socket_url, + format!("ws://127.0.0.1:{live_port}/devtools/browser/live") + ); + } + #[test] fn browser_launch_does_not_activate_by_default() { assert!(!BrowserLaunchOptions::default().activate); diff --git a/src/crates/services/services-integrations/src/browser_control/mod.rs b/src/crates/services/services-integrations/src/browser_control/mod.rs index e9df814b57..3a225730e7 100644 --- a/src/crates/services/services-integrations/src/browser_control/mod.rs +++ b/src/crates/services/services-integrations/src/browser_control/mod.rs @@ -8,8 +8,46 @@ pub mod cdp; pub mod launcher; -pub use cdp::{CdpEndpointProvider, CdpPageInfo, CdpVersionInfo}; +pub use cdp::{CdpEndpointError, CdpEndpointProvider, CdpPageInfo, CdpVersionInfo}; pub use launcher::{ - BrowserDebugEndpoint, BrowserKind, BrowserLaunchOptions, BrowserLauncher, LaunchResult, - DEFAULT_CDP_PORT, + BrowserDebugEndpoint, BrowserKind, BrowserLaunchOptions, BrowserLauncher, CdpPortProbe, + LaunchResult, DEFAULT_CDP_PORT, GUARDED_BROWSER_WEBSOCKET_PATH, }; + +#[cfg(test)] +pub(crate) mod test_support { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::TcpListener; + + /// Loopback HTTP server that answers every request with one fixed status + /// line and body, like a guarded Chromium endpoint answering `/json*` + /// with an empty 404. Returns the bound port. + pub(crate) async fn serve_fixed_http(status: &'static str, body: &'static str) -> u16 { + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let port = listener.local_addr().expect("addr").port(); + tokio::spawn(async move { + loop { + let Ok((mut socket, _)) = listener.accept().await else { + return; + }; + tokio::spawn(async move { + let mut buffer = [0_u8; 4096]; + let _ = socket.read(&mut buffer).await; + let response = format!( + "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = socket.write_all(response.as_bytes()).await; + let _ = socket.shutdown().await; + }); + } + }); + port + } + + /// A loopback port with nothing listening on it. + pub(crate) fn closed_port() -> u16 { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); + listener.local_addr().expect("addr").port() + } +} diff --git a/src/crates/services/services-integrations/src/remote_connect/account.rs b/src/crates/services/services-integrations/src/remote_connect/account.rs index 7279382499..b751864605 100644 --- a/src/crates/services/services-integrations/src/remote_connect/account.rs +++ b/src/crates/services/services-integrations/src/remote_connect/account.rs @@ -713,6 +713,26 @@ impl AccountClient { session: &AccountSession, target_device_id: &str, plaintext_command: &str, + ) -> Result { + self.device_rpc_with_timeout( + relay_url, + session, + target_device_id, + plaintext_command, + super::realtime_client::DEFAULT_RPC_TIMEOUT, + ) + .await + } + + /// Like [`Self::device_rpc`], with an explicit end-to-end deadline that + /// the relay forwards to the target as its reply deadline. + pub async fn device_rpc_with_timeout( + &self, + relay_url: &str, + session: &AccountSession, + target_device_id: &str, + plaintext_command: &str, + timeout: std::time::Duration, ) -> Result { // Encrypt for the authenticated target device let (data, nonce) = session @@ -789,7 +809,7 @@ impl AccountClient { }) .await?; let (encrypted_data, nonce) = transport - .request_device(target_device_id, &data, &nonce) + .request_device_with_timeout(target_device_id, &data, &nonce, timeout) .await?; // Decrypt using the authenticated target device key session diff --git a/src/crates/services/services-integrations/src/remote_connect/realtime_client.rs b/src/crates/services/services-integrations/src/remote_connect/realtime_client.rs index d9ca5a5526..3f6697d168 100644 --- a/src/crates/services/services-integrations/src/remote_connect/realtime_client.rs +++ b/src/crates/services/services-integrations/src/remote_connect/realtime_client.rs @@ -6,6 +6,36 @@ use serde_json::{json, Value}; use sioc::prelude::*; use std::time::Duration; +/// Default end-to-end device RPC deadline, unchanged for ordinary commands. +pub const DEFAULT_RPC_TIMEOUT: Duration = Duration::from_secs(120); + +/// Deadlines for one relay RPC: the target's reply deadline (sent as +/// `timeoutMs`), the Socket.IO acknowledgement wait, and the overall guard. +/// The acknowledgement and guard keep the previous 3 s / 5 s margins over the +/// target deadline so the target's own timeout error arrives first. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct RpcCallDeadlines { + pub target: Duration, + pub ack: Duration, + pub overall: Duration, +} + +impl RpcCallDeadlines { + pub(crate) fn for_timeout(timeout: Duration) -> Self { + let target = timeout.max(Duration::from_secs(1)); + Self { + target, + ack: target + Duration::from_secs(3), + overall: target + Duration::from_secs(5), + } + } +} + +pub(crate) fn rpc_call_payload(target: &str, params: Value, timeout: Duration) -> Value { + let timeout_ms = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX); + json!({"method":format!("{target}:invoke"),"params":params,"timeoutMs":timeout_ms}) +} + /// Authentication payload shared by all Rust hosts and controllers. /// /// Every (re)connect carries the build string and control-contract protocol @@ -224,14 +254,25 @@ impl RealtimeSender { Ok(()) } pub async fn call(&self, target: &str, params: Value) -> Result { + self.call_with_timeout(target, params, DEFAULT_RPC_TIMEOUT) + .await + } + /// Call a target device with an explicit end-to-end deadline. The relay + /// forwards `timeoutMs` to the target, whose reply owner uses it as its + /// deadline, so a long-running command must carry its budget here. + pub async fn call_with_timeout( + &self, + target: &str, + params: Value, + timeout: Duration, + ) -> Result { let params = self.payloads.upload_if_large(params).await?; - let ack = tokio::time::timeout(Duration::from_secs(125), async { + let deadlines = RpcCallDeadlines::for_timeout(timeout); + let ack = tokio::time::timeout(deadlines.overall, async { self.sender - .emit(RpcCall( - json!({"method":format!("{target}:invoke"),"params":params,"timeoutMs":120_000}), - )) + .emit(RpcCall(rpc_call_payload(target, params, deadlines.target))) .await? - .timeout(Duration::from_secs(123)) + .timeout(deadlines.ack) .await .map_err(anyhow::Error::from) }) @@ -261,3 +302,29 @@ impl RealtimeSender { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_rpc_payload_keeps_the_legacy_deadlines() { + let deadlines = RpcCallDeadlines::for_timeout(DEFAULT_RPC_TIMEOUT); + assert_eq!(deadlines.target, Duration::from_secs(120)); + assert_eq!(deadlines.ack, Duration::from_secs(123)); + assert_eq!(deadlines.overall, Duration::from_secs(125)); + let payload = rpc_call_payload("device-1", json!({"nonce":"n"}), deadlines.target); + assert_eq!(payload["method"], "device-1:invoke"); + assert_eq!(payload["timeoutMs"], 120_000); + } + + #[test] + fn long_rpc_carries_its_budget_to_the_target() { + let deadlines = RpcCallDeadlines::for_timeout(Duration::from_millis(185_000)); + let payload = rpc_call_payload("device-1", json!({}), deadlines.target); + // Hosts derive their reply deadline from this field. + assert_eq!(payload["timeoutMs"], 185_000); + assert!(deadlines.ack > deadlines.target); + assert!(deadlines.overall > deadlines.ack); + } +} diff --git a/src/crates/services/services-integrations/src/remote_connect/relay_client.rs b/src/crates/services/services-integrations/src/remote_connect/relay_client.rs index 624c44271c..1c846c6369 100644 --- a/src/crates/services/services-integrations/src/remote_connect/relay_client.rs +++ b/src/crates/services/services-integrations/src/remote_connect/relay_client.rs @@ -418,6 +418,23 @@ impl RelayClient { target: &str, encrypted_data: &str, nonce: &str, + ) -> Result<(String, String)> { + self.request_device_with_timeout( + target, + encrypted_data, + nonce, + super::realtime_client::DEFAULT_RPC_TIMEOUT, + ) + .await + } + /// Like [`Self::request_device`], with an explicit end-to-end deadline + /// carried to the target as the relay RPC `timeoutMs`. + pub async fn request_device_with_timeout( + &self, + target: &str, + encrypted_data: &str, + nonce: &str, + timeout: Duration, ) -> Result<(String, String)> { let sender = self .owner @@ -427,9 +444,10 @@ impl RelayClient { .clone() .ok_or_else(|| anyhow!("Relay is disconnected; request was not submitted"))?; let result = sender - .call( + .call_with_timeout( target, json!({"encrypted_data":encrypted_data,"nonce":nonce}), + timeout, ) .await?; let data = result["encrypted_data"] diff --git a/src/web-ui/src/app/scenes/settings/pages/shared/RuntimeSettings.test.tsx b/src/web-ui/src/app/scenes/settings/pages/shared/RuntimeSettings.test.tsx index 3908e9a690..b51381b317 100644 --- a/src/web-ui/src/app/scenes/settings/pages/shared/RuntimeSettings.test.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/shared/RuntimeSettings.test.tsx @@ -176,15 +176,31 @@ describe('Browser and desktop control settings', () => { expect(container.textContent).toContain('browserControl.readyNotConnected'); expect(Array.from(container.querySelectorAll('button')).filter(el => el.textContent === 'browserControl.connect')).toHaveLength(1); await act(async () => connect.click()); - expect(mocks.invoke).toHaveBeenCalledWith('browser_control_enable_default_cdp', expect.anything()); + expect(mocks.invoke).toHaveBeenCalledWith('browser_control_enable_default_cdp', expect.anything(), expect.anything()); + }); + + it('gives browser setup commands a deadline beyond the backend consent budget', async () => { + await render(); + await act(async () => button('browserControl.connect').click()); + const call = mocks.invoke.mock.calls.find(([name]) => name === 'browser_control_enable_default_cdp'); + expect(call?.[1]).toEqual({ request: { port: 9222 } }); + // Backend waits up to 60 s for the setting and 90 s for approval; the + // default 30 s deadline used to report "Request timeout" mid-approval. + expect((call?.[2] as { timeout: number }).timeout).toBeGreaterThan(150_000); }); it('uses the existing launch path when the browser cannot reuse its current profile', async () => { status.defaultCdpSupported = false; await render(); await act(async () => button('browserControl.connect').click()); - expect(mocks.invoke).toHaveBeenCalledWith('browser_control_launch', { request: { port: 9222 } }); - expect(mocks.invoke).not.toHaveBeenCalledWith('browser_control_enable_default_cdp', expect.anything()); + expect(mocks.invoke).toHaveBeenCalledWith( + 'browser_control_launch', + { request: { port: 9222 } }, + { timeout: expect.any(Number) }, + ); + const call = mocks.invoke.mock.calls.find(([name]) => name === 'browser_control_launch'); + expect((call?.[2] as { timeout: number }).timeout).toBeGreaterThan(150_000); + expect(mocks.invoke).not.toHaveBeenCalledWith('browser_control_enable_default_cdp', expect.anything(), expect.anything()); }); it.each([false, true])('revokes previous browser access before saving a new choice (disconnect fails: %s)', async (fails) => { diff --git a/src/web-ui/src/app/scenes/settings/pages/tools/DeviceControlSettingsPage.tsx b/src/web-ui/src/app/scenes/settings/pages/tools/DeviceControlSettingsPage.tsx index 25fe0ddbe6..55ace0fb71 100644 --- a/src/web-ui/src/app/scenes/settings/pages/tools/DeviceControlSettingsPage.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/tools/DeviceControlSettingsPage.tsx @@ -81,6 +81,16 @@ function browserSetupUrlFallback(browser: string): string { const DEFAULT_BROWSER_CONTROL_BROWSER = 'default'; +/** + * Browser Control setup commands wait on browser-owned consent: up to one + * minute for the Remote debugging toggle plus up to 90 seconds for the + * connection approval prompt. The default 30 s request deadline reported + * "Request timeout" while the backend was still waiting, so these requests + * outlast the backend budget (and the Peer RPC budget, which is 185 s). + */ +const BROWSER_CONTROL_SETUP_REQUEST_TIMEOUT_MS = 190_000; +const BROWSER_CONTROL_SETUP_REQUEST_CONFIG = { timeout: BROWSER_CONTROL_SETUP_REQUEST_TIMEOUT_MS }; + const DeviceControlSettingsPage: React.FC = () => { const { t } = useTranslation('settings/runtime'); @@ -349,7 +359,11 @@ const DeviceControlSettingsPage: React.FC = () => { const handleBrowserControlLaunch = async () => { setBrowserControlBusy(true); try { - const result = await api.invoke('browser_control_launch', { request: { port: 9222 } }); + const result = await api.invoke( + 'browser_control_launch', + { request: { port: 9222 } }, + BROWSER_CONTROL_SETUP_REQUEST_CONFIG, + ); presentBrowserControlLaunchResult(result); await refreshBrowserControlStatus(); } catch (error) { @@ -376,6 +390,7 @@ const DeviceControlSettingsPage: React.FC = () => { const result = await api.invoke( 'browser_control_enable_default_cdp', { request: { port: 9222 } }, + BROWSER_CONTROL_SETUP_REQUEST_CONFIG, ); notificationService.dismiss(promptNotificationId); presentBrowserControlLaunchResult(result); @@ -413,9 +428,11 @@ const DeviceControlSettingsPage: React.FC = () => { if (!browserRestartPrompt) return; setBrowserControlBusy(true); try { - const result = await api.invoke('browser_control_restart_with_cdp', { - request: { port: 9222 }, - }); + const result = await api.invoke( + 'browser_control_restart_with_cdp', + { request: { port: 9222 } }, + BROWSER_CONTROL_SETUP_REQUEST_CONFIG, + ); if (result.success) { notificationService.success( t('browserControl.restartSuccess', { browser: result.browserKind }), diff --git a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts index 175a5ca19a..785bf766cb 100644 --- a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts +++ b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { + PEER_BROWSER_CONTROL_SETUP_TIMEOUT_MS, PEER_MUTATION_REQUEST_TIMEOUT_MS, PEER_READ_MAX_RETRIES, PEER_READ_REQUEST_TIMEOUT_MS, @@ -122,6 +123,32 @@ describe('whole-session copy capability', () => { }); }); +describe('browser control setup deadline', () => { + it.each([ + 'browser_control_launch', + 'browser_control_enable_default_cdp', + 'browser_control_restart_with_cdp', + ])('gives %s the browser consent budget without retrying', async command => { + const deviceRpc = vi.fn().mockResolvedValue(JSON.stringify({ + resp: 'host_invoke_result', ok: true, value: { success: true }, + })); + const adapter = new PeerDeviceTransportAdapter('peer-1', deviceRpc); + await adapter.request(command, { request: { port: 9222 } }); + expect(deviceRpc).toHaveBeenCalledTimes(1); + expect(deviceRpc.mock.calls[0][2]).toBe(PEER_BROWSER_CONTROL_SETUP_TIMEOUT_MS); + expect(PEER_BROWSER_CONTROL_SETUP_TIMEOUT_MS).toBeGreaterThan(150_000); + }); + + it('keeps the ordinary deadline for browser control status reads', async () => { + const deviceRpc = vi.fn().mockResolvedValue(JSON.stringify({ + resp: 'host_invoke_result', ok: true, value: {}, + })); + const adapter = new PeerDeviceTransportAdapter('peer-1', deviceRpc); + await adapter.request('browser_control_get_status', { request: { port: 9222 } }); + expect(deviceRpc.mock.calls[0][2]).toBe(PEER_READ_REQUEST_TIMEOUT_MS); + }); +}); + describe('isPeerLocalOnlyCommand', () => { it('keeps file-search streaming on the negotiated response path', () => { const adapter = new PeerDeviceTransportAdapter('peer-1', vi.fn()); diff --git a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts index e643fdf832..e71b5fc4f2 100644 --- a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts +++ b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts @@ -280,6 +280,28 @@ const IDEMPOTENT_MUTATION_RPC_POLICY: PeerRpcPolicy = { retryKind: 'idempotent-mutation', }; +/** + * Browser Control setup waits on browser-owned consent on the host: up to one + * minute for the Remote debugging toggle and up to 90 seconds for the + * connection approval prompt. Updated hosts allow 180 s for these commands; + * the controller waits slightly longer so the host's own outcome arrives + * first. An older host still answers with its 120 s timeout error. + */ +export const PEER_BROWSER_CONTROL_SETUP_TIMEOUT_MS = 185_000; + +const BROWSER_CONTROL_SETUP_COMMANDS = new Set([ + 'browser_control_launch', + 'browser_control_enable_default_cdp', + 'browser_control_restart_with_cdp', +]); + +const BROWSER_CONTROL_SETUP_RPC_POLICY: PeerRpcPolicy = { + timeoutMs: PEER_BROWSER_CONTROL_SETUP_TIMEOUT_MS, + maxRetries: 0, + retryKind: 'none', +}; + + type DeviceRpcFn = ( targetDeviceId: string, commandJson: string, @@ -880,12 +902,14 @@ export class PeerDeviceTransportAdapter implements ITransportAdapter { command: action, args: translateAgentIdentityCommand(action, params ?? {}, 'legacy'), }); - const rpcPolicy = isPeerRetryableReadCommand(action) - ? READ_RPC_POLICY - : this.hooks.supportsIdempotentDialogSubmit === true && - isPeerRetryableIdempotentMutation(action, params) - ? IDEMPOTENT_MUTATION_RPC_POLICY - : MUTATION_RPC_POLICY; + const rpcPolicy = BROWSER_CONTROL_SETUP_COMMANDS.has(action) + ? BROWSER_CONTROL_SETUP_RPC_POLICY + : isPeerRetryableReadCommand(action) + ? READ_RPC_POLICY + : this.hooks.supportsIdempotentDialogSubmit === true && + isPeerRetryableIdempotentMutation(action, params) + ? IDEMPOTENT_MUTATION_RPC_POLICY + : MUTATION_RPC_POLICY; try { const raw = await this.invokeDeviceRpc(