Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

test(cua-driver): harden inactive browser tabs

trycua-release[bot]f378009b37f1
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/semantic.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/semantic.rs
index 5ae44da70a..956dc47a75 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/semantic.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/semantic.rs
@@ -5,6 +5,7 @@
//! DOM backend ids preserve exact mutation capabilities, and layout evidence
//! keeps hidden retained application state from displacing the active view.
+use std::cmp::Reverse;
use std::collections::{BTreeMap, HashMap, HashSet};
use serde_json::Value;
@@ -195,7 +196,13 @@ impl SemanticDocument {
BrowserVisibility::CssHidden | BrowserVisibility::PageOccluded
)
});
- candidates.sort_by_key(|idx| (rank(&self.nodes[*idx]), self.nodes[*idx].document_order));
+ candidates.sort_by_key(|idx| {
+ (
+ Reverse(query.map_or(0, |query| query_score(&self.nodes[*idx], query))),
+ rank(&self.nodes[*idx]),
+ self.nodes[*idx].document_order,
+ )
+ });
let start = offset.min(candidates.len());
let end = (start + budget.max(1)).min(candidates.len());
@@ -924,28 +931,69 @@ fn scoped_indices(
}
}
}
- let query = query.map(|value| value.to_ascii_lowercase());
+ let query = query.map(|value| value.trim().to_ascii_lowercase());
+ let in_scope =
+ |node: &SemanticNode| scope_backend_node_id.is_none() || allowed.contains(&node.ax_id);
+ let exact_match_exists = query.as_ref().is_some_and(|query| {
+ !query.is_empty()
+ && nodes
+ .iter()
+ .any(|node| in_scope(node) && node_contains_query(node, query))
+ });
nodes
.iter()
.enumerate()
.filter(|(_, node)| {
- (scope_backend_node_id.is_none() || allowed.contains(&node.ax_id))
+ in_scope(node)
&& query.as_ref().is_none_or(|query| {
- node.role.to_ascii_lowercase().contains(query)
- || node
- .name
- .as_ref()
- .is_some_and(|name| name.to_ascii_lowercase().contains(query))
- || node
- .value
- .as_ref()
- .is_some_and(|value| value.to_ascii_lowercase().contains(query))
+ query.is_empty()
+ || if exact_match_exists {
+ node_contains_query(node, query)
+ } else {
+ query_score(node, query) > 0
+ }
})
})
.map(|(idx, _)| idx)
.collect()
}
+fn node_contains_query(node: &SemanticNode, query: &str) -> bool {
+ node.role.to_ascii_lowercase().contains(query)
+ || node
+ .name
+ .as_ref()
+ .is_some_and(|name| name.to_ascii_lowercase().contains(query))
+ || node
+ .value
+ .as_ref()
+ .is_some_and(|value| value.to_ascii_lowercase().contains(query))
+}
+
+fn query_score(node: &SemanticNode, query: &str) -> usize {
+ let query = query.trim().to_ascii_lowercase();
+ if query.is_empty() {
+ return 0;
+ }
+ if node_contains_query(node, &query) {
+ return usize::MAX;
+ }
+ let fields = [
+ Some(node.role.as_str()),
+ node.name.as_deref(),
+ node.value.as_deref(),
+ ]
+ .into_iter()
+ .flatten()
+ .map(str::to_ascii_lowercase)
+ .collect::<Vec<_>>();
+ query
+ .split(|character: char| !character.is_alphanumeric())
+ .filter(|term| !term.is_empty())
+ .filter(|term| fields.iter().any(|field| field.contains(term)))
+ .count()
+}
+
fn with_ancestors(nodes: &[SemanticNode], selected: &[usize]) -> HashSet<usize> {
let by_ax_id: HashMap<&str, usize> = nodes
.iter()
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.rs
index 2bd6f483da..edd8ff2b70 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
@@ -22,7 +22,9 @@ use super::platform::{
ExistingProfileSetupRequest, PrepareAction, PrepareOutcome, PrepareRequest,
};
use super::refusal::BrowserRefusal;
-use super::tools::{BrowserClickTool, BrowserPrepareTool, BrowserTypeTool, GetBrowserStateTool};
+use super::tools::{
+ BrowserClickTool, BrowserNavigateTool, BrowserPrepareTool, BrowserTypeTool, GetBrowserStateTool,
+};
use super::types::{
BrowserClassification, BrowserEngineFamily, BrowserProduct, EndpointOwnershipMethod,
EndpointOwnershipProof, NativeOwnershipMethod, NativeOwnershipProof, NativeWindowInfo,
@@ -510,6 +512,10 @@ fn fixture_handler(state: SharedState) -> MockHandler {
"clientHeight": 600.0
}
})),
+ "Page.navigate" if is_tab => MockReply::ok(json!({
+ "frameId": "F_MAIN",
+ "loaderId": "L_MAIN_NAVIGATED",
+ })),
"Target.setAutoAttach" if is_tab => {
if call.params["autoAttach"].as_bool() == Some(false) {
return MockReply::ok(json!({}));
@@ -1303,6 +1309,17 @@ async fn semantic_query_and_content_scope_are_read_only_and_precise() {
assert_eq!(queried["refs"].as_array().unwrap().len(), 1, "{queried}");
assert_eq!(queried["refs"][0]["name"], "Archive item 304");
+ let natural =
+ semantic_snapshot_with(&f, &target, &tab, json!({"query": "reply archive 304"})).await;
+ assert_eq!(natural["snapshot"]["scope"], "query", "{natural}");
+ assert_eq!(natural["refs"][0]["name"], "Archive item 304", "{natural}");
+ assert!(
+ natural["refs"]
+ .as_array()
+ .is_some_and(|refs| refs.iter().any(|entry| entry["name"] == "Reply")),
+ "{natural}"
+ );
+
let fresh = semantic_snapshot(&f, &target, &tab).await;
let heading_ref = fresh["content_refs"]
.as_array()
@@ -1321,6 +1338,36 @@ async fn semantic_query_and_content_scope_are_read_only_and_precise() {
"{scoped}"
);
assert_eq!(scoped["content_refs"][0]["name"], "Visible message");
+ assert!(recorded_calls(&f, "Page.bringToFront").is_empty());
+ assert!(recorded_calls(&f, "Target.activateTarget").is_empty());
+}
+
+#[tokio::test]
+async fn navigation_targets_an_inactive_tab_without_activating_it() {
+ let f = fixture().await;
+ let (target, tab) = bind(&f).await;
+ let result = BrowserNavigateTool::new(f.engine.clone())
+ .invoke(json!({
+ "target_id": target,
+ "tab_id": tab,
+ "url": "https://fixture.test/background-navigation",
+ "session": SESSION,
+ }))
+ .await;
+
+ let structured = result
+ .structured_content
+ .as_ref()
+ .expect("navigation structured content");
+ assert_eq!(structured["status"], "ok", "{structured}");
+ let navigate = recorded_calls(&f, "Page.navigate");
+ assert_eq!(navigate.len(), 1, "{navigate:?}");
+ assert_eq!(
+ navigate[0].1["url"],
+ "https://fixture.test/background-navigation"
+ );
+ assert!(recorded_calls(&f, "Page.bringToFront").is_empty());
+ assert!(recorded_calls(&f, "Target.activateTarget").is_empty());
}
#[tokio::test]
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
index 49e79ef992..ff4dc4a0a7 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
@@ -1855,16 +1855,24 @@ fn run_multi_tab(spec: &BrowserSpec) {
*evidence = recording_evidence(fixture.driver.recording_dir());
let session = format!("standalone-multi-tab-{}", fixture.pid);
let _ = bind(&mut fixture, &session);
+ let first_target = cdp_target_for_url(fixture.cdp_port, fixture.server.page_url());
+ let second_server = BrowserFixtureServer::start(&standalone_fixture_html());
let created = harness_cdp_call(
fixture.cdp_port,
"Target.createTarget",
serde_json::json!({
- "url": format!("{}?tab=second", fixture.server.page_url()),
+ "url": second_server.page_url(),
"newWindow": false,
}),
);
assert!(created["targetId"].is_string(), "{created}");
- wait_for_observed(&fixture.server, "new_tab=open");
+ wait_for_observed(&second_server, "WEB_HARNESS_MARKER_v1");
+ let activated = harness_cdp_call(
+ fixture.cdp_port,
+ "Target.activateTarget",
+ serde_json::json!({"targetId": first_target}),
+ );
+ assert!(activated.is_object(), "{activated}");
run_with_background_oracles(&mut fixture, |fixture| {
let deadline = Instant::now() + Duration::from_secs(5);
@@ -1892,6 +1900,114 @@ fn run_multi_tab(spec: &BrowserSpec) {
thread::sleep(Duration::from_millis(100));
};
assert_eq!(rebound.structured()["binding_quality"], "exact");
+ let target = rebound.structured()["target_id"]
+ .as_str()
+ .expect("multi-tab target")
+ .to_owned();
+ let tabs = rebound.structured()["tabs"]
+ .as_array()
+ .expect("multi-tab list");
+ let active = tabs
+ .iter()
+ .find(|tab| tab["active"] == true)
+ .expect("one active tab");
+ assert_eq!(
+ active["url"],
+ fixture.server.page_url(),
+ "fixture setup must leave the first tab active: {}",
+ rebound.raw
+ );
+ let background_tab = tabs
+ .iter()
+ .find(|tab| tab["url"] == second_server.page_url())
+ .and_then(|tab| tab["tab_id"].as_str())
+ .expect("inactive second tab")
+ .to_owned();
+
+ let navigated_url = format!("{}?background=navigated", second_server.page_url());
+ let navigated = fixture.driver.call(
+ "browser_navigate",
+ serde_json::json!({
+ "target_id": target,
+ "tab_id": background_tab,
+ "url": navigated_url,
+ "session": session,
+ }),
+ );
+ assert_eq!(navigated.structured()["status"], "ok", "{}", navigated.raw);
+ wait_for_observed(&second_server, "WEB_HARNESS_MARKER_v1");
+
+ let snapshot = fixture.driver.call(
+ "get_browser_state",
+ serde_json::json!({
+ "target_id": target,
+ "tab_id": background_tab,
+ "session": session,
+ }),
+ );
+ assert_eq!(snapshot.structured()["status"], "ok", "{}", snapshot.raw);
+ let click_ref = ref_by_label(&snapshot, "id=btn-increment");
+ let clicked = fixture.driver.call(
+ "browser_click",
+ serde_json::json!({
+ "target_id": target,
+ "tab_id": background_tab,
+ "ref": click_ref,
+ "input_route": "dom_event",
+ "session": session,
+ }),
+ );
+ assert_eq!(clicked.structured()["status"], "ok", "{}", clicked.raw);
+
+ let snapshot = fixture.driver.call(
+ "get_browser_state",
+ serde_json::json!({
+ "target_id": target,
+ "tab_id": background_tab,
+ "session": session,
+ }),
+ );
+ let input_ref = ref_by_label(&snapshot, "id=txt-input");
+ let typed = fixture.driver.call(
+ "browser_type",
+ serde_json::json!({
+ "target_id": target,
+ "tab_id": background_tab,
+ "ref": input_ref,
+ "text": "inactive-tab",
+ "session": session,
+ }),
+ );
+ assert_eq!(typed.structured()["status"], "ok", "{}", typed.raw);
+ wait_for_text(&second_server, "lbl-counter", "counter=1");
+ wait_for_value(&second_server, "txt-input", "inactive-tab");
+ wait_for_text(&fixture.server, "lbl-counter", "counter=0");
+ wait_for_value(&fixture.server, "txt-input", "");
+
+ let verified = fixture.driver.call(
+ "get_browser_state",
+ serde_json::json!({
+ "pid": fixture.pid as i64,
+ "window_id": fixture.window_id,
+ "session": session,
+ }),
+ );
+ let tabs = verified.structured()["tabs"]
+ .as_array()
+ .expect("verified multi-tab list");
+ assert!(
+ tabs.iter().any(|tab| {
+ tab["active"] == true && tab["url"] == fixture.server.page_url()
+ }),
+ "the first tab must remain active: {}",
+ verified.raw
+ );
+ assert!(
+ tabs.iter()
+ .any(|tab| { tab["active"] == false && tab["url"] == navigated_url }),
+ "the mutated second tab must remain inactive: {}",
+ verified.raw
+ );
Observation::delivered(vec![OracleKind::FixtureState], Evidence::default())
})
});
diff --git a/scripts/ci/run-rust-standalone-browser-e2e.sh b/scripts/ci/run-rust-standalone-browser-e2e.sh
index 2df1b20f41..8b784c2af3 100755
--- a/scripts/ci/run-rust-standalone-browser-e2e.sh
+++ b/scripts/ci/run-rust-standalone-browser-e2e.sh
@@ -96,6 +96,7 @@ tests=(
standalone_browser_multi_tab
standalone_browser_prepare_isolated
standalone_browser_roundtrip
+ standalone_browser_semantic_state
standalone_browser_stale_ref
standalone_browser_trusted_click
standalone_browser_window_collision
diff --git a/scripts/ci/windows/run-rust-standalone-browser-e2e.ps1 b/scripts/ci/windows/run-rust-standalone-browser-e2e.ps1
index d9b623c681..6cb111ac86 100644
--- a/scripts/ci/windows/run-rust-standalone-browser-e2e.ps1
+++ b/scripts/ci/windows/run-rust-standalone-browser-e2e.ps1
@@ -123,6 +123,7 @@ $tests = @(
"standalone_browser_multi_tab",
"standalone_browser_prepare_isolated",
"standalone_browser_roundtrip",
+ "standalone_browser_semantic_state",
"standalone_browser_stale_ref",
"standalone_browser_trusted_click",
"standalone_browser_window_collision"