Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-driver): return from a dom_event click when its handler opens a dialog (#5621)
injaneity380dc8bd09e2
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/pointer-cursor-and-browser.mdx b/docs/content/docs/cua-driver/reference/mcp-tools/pointer-cursor-and-browser.mdxindex a16aa917f0..1a3ea0ce84 100644--- a/docs/content/docs/cua-driver/reference/mcp-tools/pointer-cursor-and-browser.mdx+++ b/docs/content/docs/cua-driver/reference/mcp-tools/pointer-cursor-and-browser.mdx@@ -580,7 +580,7 @@ Exact browser input over CDP: clicks, typing, pointer, dialogs, files and downlo### `browser_click`-Click a page element (by ref) or viewport coordinates in an exactly-bound tab. Default route is trusted hardware-like input (Input.dispatchMouseEvent), and refuses where that route cannot preserve standalone-browser background posture unless delivery_mode="foreground" accepts that the browser window may activate (including Linux Chromium configurations whose trusted route cannot stay in the background; for example a browser inside a sandbox). input_route="dom_event" (synthetic pointer and mouse down/up/click sequence at the element's center, ref required) is used only when explicitly requested; it proves dispatch, not control activation, because trust-gated controls may ignore synthetic events. Refused for heuristic bindings.+Click a page element (by ref) or viewport coordinates in an exactly-bound tab. Default route is trusted hardware-like input (Input.dispatchMouseEvent), and refuses where that route cannot preserve standalone-browser background posture unless delivery_mode="foreground" accepts that the browser window may activate (including Linux Chromium configurations whose trusted route cannot stay in the background; for example a browser inside a sandbox). input_route="dom_event" (synthetic pointer and mouse down/up/click sequence at the element's center, ref required) is used only when explicitly requested; it proves dispatch, not control activation, because trust-gated controls may ignore synthetic events. If the handler opens a page-owned JavaScript dialog, the call returns at once with a dialog block (present, kind, dialog_id) to pass to browser_dialog. Refused while a page-owned dialog is open on the tab, and for heuristic bindings.Effect: mutating. Platforms: macOS, Linux, Windows.diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mock_cdp.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mock_cdp.rsindex a375cab7da..c34e92ff0e 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mock_cdp.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mock_cdp.rs@@ -46,6 +46,15 @@ impl MockReply {}}+ /// A command whose reply never comes; any attached events still go out.+ pub fn hang() -> Self {+ Self {+ events: Vec::new(),+ result: Ok(json!({})),+ suppress_response: true,+ }+ }+pub fn err(code: i64, message: &str) -> Self {Self {events: Vec::new(),@@ -117,9 +126,6 @@ impl MockCdpServer {.map(str::to_owned),};let reply = handler(&call);- if reply.suppress_response {- continue;- }for event in reply.events {let mut frame =json!({ "method": event.method, "params": event.params });@@ -130,6 +136,9 @@ impl MockCdpServer {return;}}+ if reply.suppress_response {+ continue;+ }let mut response = match reply.result {Ok(result) => json!({ "id": id, "result": result }),Err((code, message)) => {diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rsindex da318a3339..7b8c42a817 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs@@ -1154,8 +1154,11 @@ impl BrowserClickTool {input_route=\"dom_event\" (synthetic pointer and mouse \down/up/click sequence at the element's center, ref required) is used only when explicitly requested; \it proves dispatch, not control activation, because trust-gated \- controls may ignore synthetic events. \- Refused for heuristic bindings."+ controls may ignore synthetic events. If the handler opens a \+ page-owned JavaScript dialog, the call returns at once with a \+ dialog block (present, kind, dialog_id) to pass to browser_dialog. \+ Refused while a page-owned dialog is open on the tab, and for \+ heuristic bindings.".into(),input_schema: json!({"type": "object",@@ -1297,6 +1300,23 @@ impl Tool for BrowserClickTool {}}+ // A page-owned dialog blocks the renderer, so any frame revalidation+ // below would wait out its timeout. Refuse before touching the page.+ if let Some(open) = validated+ .conn+ .dialog_state(validated.tab.cdp_target_id.as_str())+ {+ return BrowserRefusal::new(+ BrowserRefusalCode::BrowserActionUnavailable,+ format!(+ "a {} dialog is already open on the exact tab; resolve it with browser_dialog before clicking",+ open.kind+ ),+ )+ .with_detail(json!({ "dialog": dialog_block(&open) }))+ .to_tool_result();+ }+// Ref path: re-prove the ref's frame/document identity and get// the session (tab or contained OOPIF child) its node lives in.let (backend_node_id, frame_kind, cdp_session) = match &ext_ref {@@ -1345,6 +1365,7 @@ impl Tool for BrowserClickTool {// dom_event route: explicit opt-in only.if route == "dom_event" {let backend = backend_node_id.expect("checked above");+ let cdp_target_id = validated.tab.cdp_target_id.as_str();let resolved = match conn.call(Some(cdp),@@ -1408,18 +1429,27 @@ impl Tool for BrowserClickTool {}let before =read_dom_click_state(conn, cdp, &object_id, DOM_CLICK_BASELINE_DEADLINE).await;- return match conn- .call(- Some(cdp),- "Runtime.callFunctionOn",- json!({- "objectId": object_id,- "functionDeclaration": DOM_EVENT_CLICK_SEQUENCE,- }),- )- .await- {- Ok(_) => {+ let click = conn.call(+ Some(cdp),+ "Runtime.callFunctionOn",+ json!({+ "objectId": object_id,+ "functionDeclaration": DOM_EVENT_CLICK_SEQUENCE,+ }),+ );+ tokio::pin!(click);+ let outcome = loop {+ tokio::select! {+ replied = &mut click => break replied,+ _ = tokio::time::sleep(std::time::Duration::from_millis(25)) => {+ if conn.dialog_state(cdp_target_id).is_some() {+ break Ok(json!({}));+ }+ }+ }+ };+ return match (outcome, conn.dialog_state(cdp_target_id)) {+ (Ok(_), None) => {let observation = observe_dom_click(conn, cdp, &object_id, before).await;let text = match observation.effect {ActionEffect::Confirmed => format!(@@ -1443,7 +1473,31 @@ impl Tool for BrowserClickTool {let action_record = dom_click_action_record(&observation);ToolResult::text(text).with_action_record(action_record)}- Err(e) => ToolResult::error(format!("DOM click failed: {e}")),+ (Ok(_), Some(open)) => {+ let text = format!(+ "dispatched synthetic DOM click on {} in {tab_id}; its handler opened \+ a {} dialog that is blocking the page. Inspect and resolve it with \+ browser_dialog (dialog_id {}) before any other action on this tab",+ ext_ref.as_deref().unwrap_or("?"),+ open.kind,+ dialog_capability_id(open.generation)+ );+ ToolResult::text(text).with_structured(json!({+ "status": "ok",+ "effect": "unverifiable",+ "route": "dom_event",+ "target_id": target_id,+ "tab_id": tab_id,+ "ref": ext_ref,+ "frame": frame_kind,+ "dialog": dialog_block(&open),+ "escalation": {+ "recommended": "page",+ "reason": "the click opened a page-owned JavaScript dialog; resolve it with browser_dialog, then refresh page state",+ },+ }))+ }+ (Err(e), _) => ToolResult::error(format!("DOM click failed: {e}")),};}@@ -1583,6 +1637,20 @@ impl Tool for BrowserClickTool {}}+/// The public id for one dialog generation, shared by `browser_click` and+/// `browser_dialog` so a caller can hand the click's id straight back.+fn dialog_capability_id(generation: u64) -> String {+ format!("dialog-{generation}")+}++fn dialog_block(dialog: &super::cdp_ws::CdpDialogState) -> Value {+ json!({+ "present": true,+ "kind": dialog.kind,+ "dialog_id": dialog_capability_id(dialog.generation),+ })+}+/// Center of the content quad from a `DOM.getBoxModel` result.fn quad_center(box_model: &Value) -> Option<(f64, f64)> {let quad = box_model.get("model")?.get("content")?.as_array()?;@@ -2764,7 +2832,7 @@ impl Tool for BrowserDialogTool {.to_tool_result()};};- let dialog_id = format!("dialog-{}", dialog.generation);+ let dialog_id = dialog_capability_id(dialog.generation);if action == "inspect" {return ToolResult::text(format!("{} dialog is open in {tab_id}", dialog.kind)).with_structured(json!({diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rsindex 89eaf9223b..008b844646 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs@@ -28,8 +28,8 @@ use super::platform::{use super::pointer::BrowserPointerTool;use super::refusal::BrowserRefusal;use super::tools::{- browser_protected_resource_scope, BrowserClickTool, BrowserNavigateTool, BrowserPrepareTool,- BrowserSelectTool, BrowserTypeTool, GetBrowserStateTool,+ browser_protected_resource_scope, BrowserClickTool, BrowserDialogTool, BrowserNavigateTool,+ BrowserPrepareTool, BrowserSelectTool, BrowserTypeTool, GetBrowserStateTool,};use super::types::{BrowserClassification, BrowserEngineFamily, BrowserProcessRole, BrowserProduct,@@ -58,6 +58,12 @@ pub(super) struct FixtureState {oopif_sessions: u64,fail_key_down_after: Option<usize>,completed_key_pairs: usize,+ /// A synthetic `this.click()` opens a confirm() dialog: the mock emits+ /// `Page.javascriptDialogOpening` and never answers the call.+ click_opens_dialog: bool,+ /// Tab sessions that enabled the Page domain. Chromium reports a dialog+ /// to each of them, not to the session whose call opened it.+ page_sessions: Vec<String>,semantic_large_page: bool,semantic_html_style: String,semantic_full_dom_fails: bool,@@ -113,6 +119,8 @@ impl Default for FixtureState {oopif_sessions: 0,fail_key_down_after: None,completed_key_pairs: 0,+ click_opens_dialog: false,+ page_sessions: Vec::new(),semantic_large_page: false,semantic_html_style: String::new(),semantic_full_dom_fails: false,@@ -511,6 +519,7 @@ fn fixture_handler(state: SharedState) -> MockHandler {MockReply::ok(json!({ "sessionId": format!("tab-sess-{}", st.tab_sessions) }))}"Page.enable" if is_tab => {+ st.page_sessions.push(sess.clone());let mut reply = MockReply::ok(json!({}));if st.dialog_open {reply = reply.with_events(vec![MockEvent {@@ -778,8 +787,35 @@ fn fixture_handler(state: SharedState) -> MockHandler {if st.dom_click_changes_readback {st.dom_click_generation += 1;}+ let declaration = call.params["functionDeclaration"]+ .as_str()+ .unwrap_or_default();+ if st.click_opens_dialog && declaration.contains("const el = this;") {+ let events = st+ .page_sessions+ .iter()+ .map(|page_session| MockEvent {+ method: "Page.javascriptDialogOpening".into(),+ session_id: Some(page_session.clone()),+ params: json!({+ "url": "https://fixture.test/",+ "message": "Delete?",+ "type": "confirm",+ "hasBrowserHandler": false,+ }),+ })+ .collect();+ return MockReply::hang().with_events(events);+ }MockReply::ok(json!({ "result": { "value": true } }))}+ "Page.handleJavaScriptDialog" if is_tab => {+ MockReply::ok(json!({})).with_events(vec![MockEvent {+ method: "Page.javascriptDialogClosed".into(),+ session_id: Some(sess.clone()),+ params: json!({ "result": call.params["accept"], "userInput": "" }),+ }])+ }other => MockReply::method_not_found(other),}})@@ -3758,3 +3794,151 @@ async fn method_unsupported_keeps_the_electron_none_path() {assert_eq!(tabs.len(), 1, "{s}");assert_eq!(tabs[0]["url"], "https://fixture.test/");}++#[tokio::test]+async fn dom_event_click_returns_when_its_handler_opens_a_dialog() {+ let f = fixture_with(|state| state.click_opens_dialog = true).await;+ let (target, tab) = bind(&f).await;+ let snap = snapshot(&f, &target, &tab).await;+ let button = ref_of(&snap, "main", "main-btn");++ let started = std::time::Instant::now();+ let clicked = BrowserClickTool::new(f.engine.clone())+ .invoke(json!({+ "target_id": target, "tab_id": tab, "ref": button,+ "input_route": "dom_event", "session": SESSION+ }))+ .await;+ assert!(+ started.elapsed() < std::time::Duration::from_secs(5),+ "the click must not wait out the CDP call timeout: {:?}",+ started.elapsed()+ );+ let s = structured(&clicked);+ assert_eq!(s["status"], "ok", "{s}");+ assert_eq!(s["effect"], "unverifiable", "{s}");+ assert_eq!(s["route"], "dom_event", "{s}");+ assert_eq!(s["dialog"]["present"], true, "{s}");+ assert_eq!(s["dialog"]["kind"], "confirm", "{s}");+ let dialog_id = s["dialog"]["dialog_id"]+ .as_str()+ .expect("dialog id")+ .to_owned();+ assert!(dialog_id.starts_with("dialog-"), "{s}");+ assert!(clicked.content.iter().any(|content| matches!(+ content,+ crate::protocol::Content::Text { text, .. } if text.contains("browser_dialog")+ )));++ // Page events were enabled on the tab session before the click went out.+ {+ let state = f.state.lock().unwrap();+ let enable_at = state+ .calls+ .iter()+ .position(|(_, m, _)| m == "Page.enable")+ .expect("Page.enable recorded");+ let click_at = state+ .calls+ .iter()+ .position(|(_, m, p)| {+ m == "Runtime.callFunctionOn"+ && p["functionDeclaration"]+ .as_str()+ .is_some_and(|d| d.contains("const el = this;"))+ })+ .expect("click recorded");+ assert!(enable_at < click_at, "Page.enable must precede the click");+ }++ // The dialog is reachable without a second Page.enable, and resolvable.+ let inspected = BrowserDialogTool::new(f.engine.clone())+ .invoke(json!({+ "target_id": target, "tab_id": tab, "action": "inspect", "session": SESSION+ }))+ .await;+ let i = structured(&inspected);+ assert_eq!(i["present"], true, "{i}");+ assert_eq!(i["dialog_id"], dialog_id, "{i}");+ assert_eq!(recorded_calls(&f, "Page.enable").len(), 1);++ let accepted = BrowserDialogTool::new(f.engine.clone())+ .invoke(json!({+ "target_id": target, "tab_id": tab, "action": "accept",+ "dialog_id": dialog_id, "session": SESSION, "delivery_mode": "foreground"+ }))+ .await;+ let a = structured(&accepted);+ assert_eq!(a["status"], "ok", "{a}");+ assert_eq!(a["action"], "accept", "{a}");+ let handled = recorded_calls(&f, "Page.handleJavaScriptDialog");+ assert_eq!(handled.len(), 1);+ assert_eq!(handled[0].1["accept"], true);+}++#[tokio::test]+async fn dom_event_click_without_a_dialog_reports_none() {+ let f = fixture().await;+ let (target, tab) = bind(&f).await;+ let snap = snapshot(&f, &target, &tab).await;+ let button = ref_of(&snap, "main", "main-btn");++ let clicked = BrowserClickTool::new(f.engine.clone())+ .invoke(json!({+ "target_id": target, "tab_id": tab, "ref": button,+ "input_route": "dom_event", "session": SESSION+ }))+ .await;+ assert_ne!(clicked.is_error, Some(true));+ assert!(clicked.action_record.is_some());+ assert!(recorded_calls(&f, "Page.handleJavaScriptDialog").is_empty());+}++#[tokio::test]+async fn dom_event_click_refuses_while_a_dialog_is_already_open() {+ let f = fixture_with(|state| state.click_opens_dialog = true).await;+ let (target, tab) = bind(&f).await;+ let snap = snapshot(&f, &target, &tab).await;+ let button = ref_of(&snap, "main", "main-btn");+ let args = json!({+ "target_id": target, "tab_id": tab, "ref": button,+ "input_route": "dom_event", "session": SESSION+ });+ let first = BrowserClickTool::new(f.engine.clone())+ .invoke(args.clone())+ .await;+ assert_eq!(structured(&first)["dialog"]["present"], true);+ let frame_trees_before = recorded_calls(&f, "Page.getFrameTree").len();++ let second = BrowserClickTool::new(f.engine.clone()).invoke(args).await;+ assert_eq!(+ recorded_calls(&f, "Page.getFrameTree").len(),+ frame_trees_before,+ "a blocked renderer must not be asked for its frame tree"+ );+ let s = structured(&second);+ assert_eq!(s["refusal"]["code"], "browser_action_unavailable", "{s}");+ assert_eq!(s["refusal"]["detail"]["dialog"]["present"], true, "{s}");+ let clicks = recorded_calls(&f, "Runtime.callFunctionOn")+ .into_iter()+ .filter(|(_, p)| {+ p["functionDeclaration"]+ .as_str()+ .is_some_and(|d| d.contains("const el = this;"))+ })+ .count();+ assert_eq!(+ clicks, 1,+ "no second click may be sent into a blocked frame"+ );++ // The trusted coordinate route is refused the same way.+ let trusted = BrowserClickTool::new(f.engine.clone())+ .invoke(json!({+ "target_id": target, "tab_id": tab, "session": SESSION, "x": 10, "y": 20+ }))+ .await;+ let t = structured(&trusted);+ assert_eq!(t["refusal"]["code"], "browser_action_unavailable", "{t}");+ assert!(recorded_calls(&f, "Input.dispatchMouseEvent").is_empty());+}diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.jsonindex b783441b23..94b9831fe9 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json@@ -2610,7 +2610,7 @@"read_only": false},{- "description": "Click a page element (by ref) or viewport coordinates in an exactly-bound tab. Default route is trusted hardware-like input (Input.dispatchMouseEvent), and refuses where that route cannot preserve standalone-browser background posture unless delivery_mode=\"foreground\" accepts that the browser window may activate (including Linux Chromium configurations whose trusted route cannot stay in the background; for example a browser inside a sandbox). input_route=\"dom_event\" (synthetic pointer and mouse down/up/click sequence at the element's center, ref required) is used only when explicitly requested; it proves dispatch, not control activation, because trust-gated controls may ignore synthetic events. Refused for heuristic bindings.",+ "description": "Click a page element (by ref) or viewport coordinates in an exactly-bound tab. Default route is trusted hardware-like input (Input.dispatchMouseEvent), and refuses where that route cannot preserve standalone-browser background posture unless delivery_mode=\"foreground\" accepts that the browser window may activate (including Linux Chromium configurations whose trusted route cannot stay in the background; for example a browser inside a sandbox). input_route=\"dom_event\" (synthetic pointer and mouse down/up/click sequence at the element's center, ref required) is used only when explicitly requested; it proves dispatch, not control activation, because trust-gated controls may ignore synthetic events. If the handler opens a page-owned JavaScript dialog, the call returns at once with a dialog block (present, kind, dialog_id) to pass to browser_dialog. Refused while a page-owned dialog is open on the tab, and for heuristic bindings.","destructive": false,"idempotent": false,"input_schema": {diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.jsonindex 791732b6a5..07ed2e3d8f 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json@@ -2338,7 +2338,7 @@"read_only": false},{- "description": "Click a page element (by ref) or viewport coordinates in an exactly-bound tab. Default route is trusted hardware-like input (Input.dispatchMouseEvent), and refuses where that route cannot preserve standalone-browser background posture unless delivery_mode=\"foreground\" accepts that the browser window may activate (including Linux Chromium configurations whose trusted route cannot stay in the background; for example a browser inside a sandbox). input_route=\"dom_event\" (synthetic pointer and mouse down/up/click sequence at the element's center, ref required) is used only when explicitly requested; it proves dispatch, not control activation, because trust-gated controls may ignore synthetic events. Refused for heuristic bindings.",+ "description": "Click a page element (by ref) or viewport coordinates in an exactly-bound tab. Default route is trusted hardware-like input (Input.dispatchMouseEvent), and refuses where that route cannot preserve standalone-browser background posture unless delivery_mode=\"foreground\" accepts that the browser window may activate (including Linux Chromium configurations whose trusted route cannot stay in the background; for example a browser inside a sandbox). input_route=\"dom_event\" (synthetic pointer and mouse down/up/click sequence at the element's center, ref required) is used only when explicitly requested; it proves dispatch, not control activation, because trust-gated controls may ignore synthetic events. If the handler opens a page-owned JavaScript dialog, the call returns at once with a dialog block (present, kind, dialog_id) to pass to browser_dialog. Refused while a page-owned dialog is open on the tab, and for heuristic bindings.","destructive": false,"idempotent": false,"input_schema": {diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.jsonindex 2664ebe866..4a367d6e67 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json@@ -2304,7 +2304,7 @@"read_only": false},{- "description": "Click a page element (by ref) or viewport coordinates in an exactly-bound tab. Default route is trusted hardware-like input (Input.dispatchMouseEvent), and refuses where that route cannot preserve standalone-browser background posture unless delivery_mode=\"foreground\" accepts that the browser window may activate (including Linux Chromium configurations whose trusted route cannot stay in the background; for example a browser inside a sandbox). input_route=\"dom_event\" (synthetic pointer and mouse down/up/click sequence at the element's center, ref required) is used only when explicitly requested; it proves dispatch, not control activation, because trust-gated controls may ignore synthetic events. Refused for heuristic bindings.",+ "description": "Click a page element (by ref) or viewport coordinates in an exactly-bound tab. Default route is trusted hardware-like input (Input.dispatchMouseEvent), and refuses where that route cannot preserve standalone-browser background posture unless delivery_mode=\"foreground\" accepts that the browser window may activate (including Linux Chromium configurations whose trusted route cannot stay in the background; for example a browser inside a sandbox). input_route=\"dom_event\" (synthetic pointer and mouse down/up/click sequence at the element's center, ref required) is used only when explicitly requested; it proves dispatch, not control activation, because trust-gated controls may ignore synthetic events. If the handler opens a page-owned JavaScript dialog, the call returns at once with a dialog block (present, kind, dialog_id) to pass to browser_dialog. Refused while a page-owned dialog is open on the tab, and for heuristic bindings.","destructive": false,"idempotent": false,"input_schema": {