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.

fix(cua-driver): clean up Chromium remote debugging after browser sessions (#3372)

Francesco Bonacci85d77792e2f4
diff --git a/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md b/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md
index 918e92794f..35e652fb61 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md
@@ -199,11 +199,13 @@ process/profile proof remains valid. After preparation or reconnect, discard
all previous target, tab, and ref values, list windows again when the pid
changed, and bind again.
-Chrome's remote-debugging setting can remain enabled after the Cua session
-ends or Chrome restarts. Session cleanup revokes the in-memory grant and closes
-the Cua socket, but it leaves Chrome running and does not change browser
-preferences. The user can disable the setting from Chrome's fixed
-remote-debugging page.
+When Cua enabled a Chromium browser's remote-debugging setting, ending the last
+Cua session for that browser process restores the setting through the same
+exact, bounded setup-page route and dismisses any exact browser-owned
+remote-debugging consent prompt. A session that attached to a
+setting already enabled by the user does not claim ownership or turn it off. An
+abrupt daemon or browser crash can prevent cleanup; the user can disable the
+setting from the browser's fixed remote-debugging page.
On the attached path tested during development, `navigator.webdriver` remained
`false`. Treat that as an observation, since browser releases may change it.
diff --git a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
index 84bbc03a6c..080de925b0 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
@@ -676,6 +676,12 @@ launch_app(target, session)
end_session(session?) # optional explicit cleanup
```
+An existing-profile `end_session` restores the Chromium browser's
+remote-debugging toggle when Cua enabled it and no other Cua session still uses
+that browser process and dismisses the exact native consent prompt. If exact
+cleanup cannot be proven, session cleanup fails closed and a later
+`end_session` retries it.
+
For screen-absolute work, replace the window portion with
`get_desktop_state() → action(target={kind:"desktop",display_id:"primary"}, ...)
→ get_desktop_state()`. Desktop actions use coordinates from that exact
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
index 93a08d35b9..5f4d1a0760 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
@@ -31,7 +31,7 @@ use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use uuid::Uuid;
-use crate::session::register_scoped_session_end_hook;
+use crate::session::register_scoped_fallible_session_end_hook;
use super::binding::{
cardinality_exact_candidate, correlate, selected_tab_target_id, BindingOutcome,
@@ -42,7 +42,7 @@ use super::grant::{ExistingProfileGrant, ExistingProfileGrants, GrantLookup};
use super::mutation::{MutationGates, MutationKey};
use super::platform::{
BrowserConsentOutcome, BrowserConsentRequest, BrowserPlatform, BrowserVisualAction,
- BrowserVisualActionKind,
+ BrowserVisualActionKind, ExistingProfileSetupRequest,
};
use super::prepare::ManagedBrowsers;
use super::reconnect::ReconnectGates;
@@ -82,6 +82,7 @@ pub struct BrowserEngine {
pub(crate) protected_resource_ownership: Arc<crate::consent::ProtectedResourceOwnershipStore>,
mutation_gates: MutationGates,
reconnect_gates: ReconnectGates,
+ pending_existing_profile_cleanups: Mutex<HashMap<String, Vec<ExistingProfileSetupRequest>>>,
session_end_hook: Mutex<Option<crate::session::SessionEndHookRegistration>>,
}
@@ -635,33 +636,70 @@ impl BrowserEngine {
protected_resource_ownership,
mutation_gates: MutationGates::new(),
reconnect_gates: ReconnectGates::new(),
+ pending_existing_profile_cleanups: Mutex::new(HashMap::new()),
session_end_hook: Mutex::new(None),
});
let weak: Weak<Self> = Arc::downgrade(&engine);
- let registration = register_scoped_session_end_hook(move |session_id| {
- if let Some(engine) = weak.upgrade() {
- engine.store.remove_session(session_id);
- engine.cleanup_prepared_session(session_id);
- for grant in engine.existing_profile_grants.remove_session(session_id) {
- engine.pool.release_claim_marker(&grant.endpoint_ws_url);
- if let Some(protected) = grant.protected_consent.as_ref() {
- protected.revoke();
- }
- if let Ok(runtime) = tokio::runtime::Handle::try_current() {
- let engine = engine.clone();
- runtime.spawn(async move {
- engine
- .pool
- .release_existing(&grant.endpoint_ws_url, grant.generation)
- .await;
+ let registration =
+ register_scoped_fallible_session_end_hook("browser_state", move |session_id| {
+ let mut cleanup_errors = Vec::new();
+ if let Some(engine) = weak.upgrade() {
+ engine.store.remove_session(session_id);
+ engine.cleanup_prepared_session(session_id);
+ let pending = {
+ let mut pending = engine.pending_existing_profile_cleanups.lock().unwrap();
+ let mut requests = pending.remove(session_id).unwrap_or_default();
+ for grant in engine.existing_profile_grants.remove_session(session_id) {
+ engine.pool.release_claim_marker(&grant.endpoint_ws_url);
+ if grant.cleanup_remote_debugging {
+ requests.push(ExistingProfileSetupRequest {
+ pid: grant.pid,
+ window_id: grant.window_id,
+ browser: grant.browser_product,
+ });
+ }
if let Some(protected) = grant.protected_consent.as_ref() {
- engine.approval_broker.revoke(protected).await;
+ protected.revoke();
+ }
+ if let Ok(runtime) = tokio::runtime::Handle::try_current() {
+ let engine = engine.clone();
+ runtime.spawn(async move {
+ engine
+ .pool
+ .release_existing(&grant.endpoint_ws_url, grant.generation)
+ .await;
+ if let Some(protected) = grant.protected_consent.as_ref() {
+ engine.approval_broker.revoke(protected).await;
+ }
+ });
}
- });
+ }
+ requests
+ };
+
+ let mut failed = Vec::new();
+ for request in pending {
+ if let Err(error) = engine
+ .platform
+ .cleanup_existing_profile_setup(request.clone())
+ {
+ cleanup_errors.push(error.message);
+ failed.push(request);
+ }
+ }
+ let mut pending = engine.pending_existing_profile_cleanups.lock().unwrap();
+ if failed.is_empty() {
+ pending.remove(session_id);
+ } else {
+ pending.insert(session_id.to_owned(), failed);
}
}
- }
- });
+ if cleanup_errors.is_empty() {
+ Ok(())
+ } else {
+ Err(cleanup_errors.join("; "))
+ }
+ });
*engine.session_end_hook.lock().unwrap() = Some(registration);
engine
}
@@ -682,6 +720,25 @@ impl BrowserEngine {
GrantLookup::Live(grant) => Ok(Some(grant)),
GrantLookup::Expired(grant) => {
self.pool.release_claim_marker(&grant.endpoint_ws_url);
+ if grant.cleanup_remote_debugging {
+ let request = ExistingProfileSetupRequest {
+ pid: grant.pid,
+ window_id: grant.window_id,
+ browser: grant.browser_product,
+ };
+ if self
+ .platform
+ .cleanup_existing_profile_setup(request.clone())
+ .is_err()
+ {
+ self.pending_existing_profile_cleanups
+ .lock()
+ .unwrap()
+ .entry(session.to_owned())
+ .or_default()
+ .push(request);
+ }
+ }
self.pool
.release_existing(&grant.endpoint_ws_url, grant.generation)
.await;
@@ -707,6 +764,25 @@ impl BrowserEngine {
.revoke(session, transport_session, pid)
{
self.pool.release_claim_marker(&grant.endpoint_ws_url);
+ if grant.cleanup_remote_debugging {
+ let request = ExistingProfileSetupRequest {
+ pid: grant.pid,
+ window_id: grant.window_id,
+ browser: grant.browser_product,
+ };
+ if self
+ .platform
+ .cleanup_existing_profile_setup(request.clone())
+ .is_err()
+ {
+ self.pending_existing_profile_cleanups
+ .lock()
+ .unwrap()
+ .entry(session.to_owned())
+ .or_default()
+ .push(request);
+ }
+ }
self.pool
.release_existing(&grant.endpoint_ws_url, grant.generation)
.await;
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/grant.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/grant.rs
index 638fbabbdb..98af8fb2c6 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/grant.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/grant.rs
@@ -9,7 +9,7 @@ use std::sync::Mutex;
use std::time::{Duration, Instant};
use super::refusal::{BrowserRefusal, BrowserRefusalCode};
-use super::types::ProcessFingerprint;
+use super::types::{BrowserProduct, ProcessFingerprint};
const GRANT_IDLE_TTL: Duration = Duration::from_secs(30 * 60);
const GRANT_ABSOLUTE_TTL: Duration = Duration::from_secs(8 * 60 * 60);
@@ -30,8 +30,10 @@ pub(crate) struct ExistingProfileGrant {
pub window_id: u64,
pub fingerprint: ProcessFingerprint,
pub browser: String,
+ pub browser_product: BrowserProduct,
pub endpoint_ws_url: String,
pub generation: u64,
+ pub cleanup_remote_debugging: bool,
pub reconnect_attempts_remaining: u8,
pub protected_consent: Option<crate::consent::ProtectedGrant>,
pub permission_mode: crate::authorization::PermissionMode,
@@ -97,7 +99,9 @@ impl ExistingProfileGrants {
window_id: u64,
fingerprint: ProcessFingerprint,
browser: String,
+ browser_product: BrowserProduct,
endpoint_ws_url: String,
+ cleanup_remote_debugging: bool,
protected_consent: Option<crate::consent::ProtectedGrant>,
) -> ExistingProfileGrant {
let now = Instant::now();
@@ -115,8 +119,10 @@ impl ExistingProfileGrants {
window_id,
fingerprint,
browser,
+ browser_product,
endpoint_ws_url,
generation,
+ cleanup_remote_debugging,
reconnect_attempts_remaining: MAX_RECONNECT_ATTEMPTS,
protected_consent,
permission_mode: crate::tool::current_dispatch_authorization_context()
@@ -146,7 +152,9 @@ impl ExistingProfileGrants {
return GrantLookup::Missing;
};
if grant.expired(now) || !grant.authorization_context_matches() {
- return GrantLookup::Expired(grants.remove(&key).expect("expired grant exists"));
+ let mut expired = grants.remove(&key).expect("expired grant exists");
+ transfer_cleanup_ownership(&mut grants, &mut expired);
+ return GrantLookup::Expired(expired);
}
grant.last_used_at = now;
GrantLookup::Live(grant.clone())
@@ -158,21 +166,25 @@ impl ExistingProfileGrants {
transport_session: Option<&str>,
pid: i64,
) -> Option<ExistingProfileGrant> {
- self.inner
- .lock()
- .unwrap()
- .remove(&Self::key(public_session, transport_session, pid))
+ let mut grants = self.inner.lock().unwrap();
+ let mut removed = grants.remove(&Self::key(public_session, transport_session, pid))?;
+ transfer_cleanup_ownership(&mut grants, &mut removed);
+ Some(removed)
}
pub fn remove_session(&self, session: &str) -> Vec<ExistingProfileGrant> {
let mut removed = Vec::new();
- self.inner.lock().unwrap().retain(|_, grant| {
+ let mut grants = self.inner.lock().unwrap();
+ grants.retain(|_, grant| {
let keep = grant.public_session != session && grant.transport_session != session;
if !keep {
removed.push(grant.clone());
}
keep
});
+ for grant in &mut removed {
+ transfer_cleanup_ownership(&mut grants, grant);
+ }
removed
}
@@ -203,6 +215,23 @@ impl ExistingProfileGrants {
}
}
+fn transfer_cleanup_ownership(
+ grants: &mut HashMap<GrantKey, ExistingProfileGrant>,
+ removed: &mut ExistingProfileGrant,
+) {
+ if !removed.cleanup_remote_debugging {
+ return;
+ }
+ if let Some(successor) = grants.values_mut().find(|grant| {
+ grant.pid == removed.pid
+ && grant.fingerprint.matches(&removed.fingerprint)
+ && grant.browser_product == removed.browser_product
+ }) {
+ successor.cleanup_remote_debugging = true;
+ removed.cleanup_remote_debugging = false;
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -225,7 +254,9 @@ mod tests {
9,
fingerprint(42),
"chromium".to_owned(),
+ BrowserProduct::GoogleChrome,
"ws://127.0.0.1:1/devtools/browser/x".to_owned(),
+ false,
None,
);
assert!(matches!(
@@ -252,7 +283,9 @@ mod tests {
9,
fingerprint(42),
"chromium".to_owned(),
+ BrowserProduct::GoogleChrome,
"ws://127.0.0.1:1/devtools/browser/x".to_owned(),
+ false,
None,
);
assert_eq!(grants.remove_session("transport-a").len(), 1);
@@ -272,7 +305,9 @@ mod tests {
9,
fingerprint(42),
"chromium".to_owned(),
+ BrowserProduct::GoogleChrome,
"ws://127.0.0.1:1/devtools/browser/x".to_owned(),
+ false,
None,
);
let key = ExistingProfileGrants::key("public-a", Some("transport-a"), 42);
@@ -298,4 +333,86 @@ mod tests {
GrantLookup::Missing
));
}
+
+ #[test]
+ fn cleanup_ownership_moves_to_another_live_grant_for_the_same_process() {
+ let grants = ExistingProfileGrants::new();
+ grants.mint(
+ "public-a",
+ Some("transport-a"),
+ 42,
+ 9,
+ fingerprint(42),
+ "chromium".to_owned(),
+ BrowserProduct::GoogleChrome,
+ "ws://127.0.0.1:1/devtools/browser/x".to_owned(),
+ true,
+ None,
+ );
+ grants.mint(
+ "public-b",
+ Some("transport-b"),
+ 42,
+ 9,
+ fingerprint(42),
+ "chromium".to_owned(),
+ BrowserProduct::GoogleChrome,
+ "ws://127.0.0.1:1/devtools/browser/x".to_owned(),
+ false,
+ None,
+ );
+
+ let removed = grants.remove_session("transport-a");
+ assert_eq!(removed.len(), 1);
+ assert!(!removed[0].cleanup_remote_debugging);
+ let GrantLookup::Live(successor) = grants.lookup("public-b", Some("transport-b"), 42)
+ else {
+ panic!("successor grant must remain live");
+ };
+ assert!(successor.cleanup_remote_debugging);
+
+ let removed = grants.remove_session("transport-b");
+ assert_eq!(removed.len(), 1);
+ assert!(removed[0].cleanup_remote_debugging);
+ }
+
+ #[test]
+ fn cleanup_ownership_does_not_move_to_a_reused_pid() {
+ let grants = ExistingProfileGrants::new();
+ grants.mint(
+ "public-a",
+ Some("transport-a"),
+ 42,
+ 9,
+ fingerprint(42),
+ "chromium".to_owned(),
+ BrowserProduct::GoogleChrome,
+ "ws://127.0.0.1:1/devtools/browser/x".to_owned(),
+ true,
+ None,
+ );
+ let mut reused = fingerprint(42);
+ reused.start_time = Some(8);
+ grants.mint(
+ "public-b",
+ Some("transport-b"),
+ 42,
+ 10,
+ reused,
+ "chromium".to_owned(),
+ BrowserProduct::GoogleChrome,
+ "ws://127.0.0.1:2/devtools/browser/y".to_owned(),
+ false,
+ None,
+ );
+
+ let removed = grants.remove_session("transport-a");
+ assert_eq!(removed.len(), 1);
+ assert!(removed[0].cleanup_remote_debugging);
+ let GrantLookup::Live(reused_process) = grants.lookup("public-b", Some("transport-b"), 42)
+ else {
+ panic!("reused-pid grant must remain live");
+ };
+ assert!(!reused_process.cleanup_remote_debugging);
+ }
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/platform.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/platform.rs
index 387958eb8c..bf0912f4b5 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/platform.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/platform.rs
@@ -390,6 +390,16 @@ pub trait BrowserPlatform: Send + Sync {
Ok(false)
}
+ /// Restore a browser-owned remote-debugging setting that Cua enabled for
+ /// an existing-profile grant. Core calls this only when the last grant for
+ /// the process ends and only when setup recorded that Cua changed it.
+ fn cleanup_existing_profile_setup(
+ &self,
+ _request: ExistingProfileSetupRequest,
+ ) -> Result<bool, BrowserRefusal> {
+ Ok(false)
+ }
+
/// Roll back a setup transition that core could not safely claim. The
/// adapter must preserve `error`, adding exact cleanup evidence where
/// useful, and must never act on an unproven current tab or control.
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
index adb4135293..1d10b31955 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
@@ -1055,6 +1055,10 @@ impl BrowserEngine {
}
};
let previous_generation = previous_grant.as_ref().map_or(0, |grant| grant.generation);
+ let cleanup_remote_debugging = setup.enabled_remote_debugging
+ || previous_grant
+ .as_ref()
+ .is_some_and(|grant| grant.cleanup_remote_debugging);
let grant = self.existing_profile_grants.mint(
&request.session,
request.transport_session.as_deref(),
@@ -1062,7 +1066,9 @@ impl BrowserEngine {
window_id,
fingerprint,
"chromium".to_owned(),
+ classification.product_kind,
endpoint.ws_url.clone(),
+ cleanup_remote_debugging,
protected_consent,
);
if let Some(previous) = previous_grant {
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 ea5f2b8baf..1f50e0da29 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
@@ -1157,6 +1157,38 @@ fn wait_for_pid_windows_to_close(driver: &mut McpDriver, pid: u32) {
}
}
+fn devtools_active_port(profile: &Path) -> Option<u16> {
+ std::fs::read_to_string(profile.join("DevToolsActivePort"))
+ .ok()?
+ .lines()
+ .next()?
+ .trim()
+ .parse()
+ .ok()
+}
+
+fn wait_for_devtools_listener_to_close(profile: &Path, port: u16) {
+ let deadline = Instant::now() + Duration::from_secs(5);
+ loop {
+ let listener_closed = TcpStream::connect_timeout(
+ &format!("127.0.0.1:{port}")
+ .parse()
+ .expect("loopback socket"),
+ Duration::from_millis(100),
+ )
+ .is_err();
+ if listener_closed {
+ return;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "existing-profile DevTools listener {port} remained reachable after end_session; active-port-file={:?}",
+ devtools_active_port(profile)
+ );
+ thread::sleep(Duration::from_millis(100));
+ }
+}
+
fn spawn_browser_command(
driver: &mut McpDriver,
spec: &BrowserSpec,
@@ -2690,6 +2722,12 @@ fn run_existing_profile_setup(spec: &BrowserSpec) {
prepared.structured()["side_effects"]["created_profile"],
false
);
+ let setup_port = devtools_active_port(fixture._profile.path()).unwrap_or_else(|| {
+ panic!(
+ "existing-profile setup exposed no DevToolsActivePort in {}",
+ fixture._profile.path().display()
+ )
+ });
let public_result = prepared.raw.to_string();
assert!(!public_result.contains("ws://"), "{}", prepared.raw);
@@ -2699,7 +2737,7 @@ fn run_existing_profile_setup(spec: &BrowserSpec) {
prepared.raw
);
- run_with_background_oracles(&mut fixture, |fixture| {
+ let observation = run_with_background_oracles(&mut fixture, |fixture| {
let state = fixture.driver.call(
"get_browser_state",
serde_json::json!({
@@ -2761,25 +2799,52 @@ fn run_existing_profile_setup(spec: &BrowserSpec) {
clicked.raw
);
wait_for_text(&fixture.server, "lbl-counter", "counter=1");
-
- let ended = fixture
- .driver
- .call("end_session", serde_json::json!({ "session": session }));
- assert!(!ended.is_error(), "end_session failed: {}", ended.raw);
- let windows = fixture
- .driver
- .call("list_windows", serde_json::json!({"pid": fixture.pid}));
- assert!(
- windows.structured()["windows"]
- .as_array()
- .is_some_and(|windows| windows.iter().any(|window| {
- window["window_id"].as_u64() == Some(fixture.window_id)
- })),
- "ending the setup grant must not close the user-owned browser: {}",
- windows.raw
- );
Observation::delivered(vec![OracleKind::FixtureState], Evidence::default())
- })
+ });
+
+ // Linux must foreground Chromium briefly to navigate its browser-owned
+ // setup surface: Chromium rejects background XSendEvent keystrokes and
+ // does not expose an AT-SPI editable-text setter for the omnibox. Keep
+ // that bounded native cleanup outside the CDP background-input oracle,
+ // then prove its externally visible result exactly on every platform.
+ let ended = fixture
+ .driver
+ .call("end_session", serde_json::json!({ "session": session }));
+ assert!(!ended.is_error(), "end_session failed: {}", ended.raw);
+ wait_for_devtools_listener_to_close(fixture._profile.path(), setup_port);
+ let native = fixture.driver.call(
+ "get_window_state",
+ serde_json::json!({
+ "pid": fixture.pid as i64,
+ "window_id": fixture.window_id,
+ }),
+ );
+ assert!(
+ !native.is_error(),
+ "post-cleanup native state failed: {}",
+ native.raw
+ );
+ assert!(
+ !native
+ .tree_text()
+ .to_ascii_lowercase()
+ .contains("allow remote debugging"),
+ "ending the setup grant left browser-owned consent UI visible: {}",
+ native.raw
+ );
+ let windows = fixture
+ .driver
+ .call("list_windows", serde_json::json!({"pid": fixture.pid}));
+ assert!(
+ windows.structured()["windows"]
+ .as_array()
+ .is_some_and(|windows| windows
+ .iter()
+ .any(|window| { window["window_id"].as_u64() == Some(fixture.window_id) })),
+ "ending the setup grant must not close the user-owned browser: {}",
+ windows.raw
+ );
+ observation
},
);
}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/browser_consent_ui.rs b/libs/cua-driver/rust/crates/platform-linux/src/browser_consent_ui.rs
index 100862b4ab..24806906dc 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/browser_consent_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/browser_consent_ui.rs
@@ -72,9 +72,10 @@ fn remote_debugging_prompt_present(nodes: &[AtspiNode]) -> bool {
&& body.contains("navigate to any url")
}
-fn exact_allow_button(
+fn exact_prompt_button(
nodes: &[AtspiNode],
bounds: &[(usize, i32, i32, u32, u32)],
+ label: &str,
) -> Result<Option<usize>, BrowserRefusal> {
if !remote_debugging_prompt_present(nodes) {
return Ok(None);
@@ -82,7 +83,7 @@ fn exact_allow_button(
let matches = trusted_prompt_nodes(nodes)
.filter(|node| {
role_is(node, &["push button", "button"])
- && normalized_text(node) == "allow"
+ && normalized_text(node) == label
&& !node.actions.is_empty()
&& node.element_index.is_some()
})
@@ -125,7 +126,7 @@ fn exact_allow_button(
[(index, ..)] => Ok(Some(*index)),
_ => Err(refusal(
BrowserRefusalCode::BrowserWrongTargetRefused,
- "multiple exact Allow actions matched the browser consent prompt",
+ format!("multiple exact {label} actions matched the browser consent prompt"),
)
.with_detail(serde_json::json!({
"candidates": matches.iter().map(|(element_index, element_key, depth, role, actions, parent_element_index)| {
@@ -146,6 +147,20 @@ fn exact_allow_button(
}
}
+fn exact_allow_button(
+ nodes: &[AtspiNode],
+ bounds: &[(usize, i32, i32, u32, u32)],
+) -> Result<Option<usize>, BrowserRefusal> {
+ exact_prompt_button(nodes, bounds, "allow")
+}
+
+fn exact_cancel_button(
+ nodes: &[AtspiNode],
+ bounds: &[(usize, i32, i32, u32, u32)],
+) -> Result<Option<usize>, BrowserRefusal> {
+ exact_prompt_button(nodes, bounds, "cancel")
+}
+
fn prove_window_owner(pid: u32, window_id: u64) -> Result<(), BrowserRefusal> {
let owned = crate::wayland::list_windows_dispatch(Some(pid))
.into_iter()
@@ -211,6 +226,40 @@ fn trusted_allow_click(pid: u32, window_id: u64) -> anyhow::Result<()> {
})
}
+pub fn dismiss(pid: u32, window_id: u64) -> Result<bool, BrowserRefusal> {
+ prove_window_owner(pid, window_id)?;
+ let deadline = Instant::now() + Duration::from_secs(2);
+ let mut dismissed = false;
+ loop {
+ prove_window_owner(pid, window_id)?;
+ let tree = crate::atspi::walk_tree(pid, window_id, None);
+ let prompt_present = remote_debugging_prompt_present(&tree.nodes);
+ if !prompt_present {
+ return Ok(dismissed);
+ }
+ let index = exact_cancel_button(&tree.nodes, &tree.bounds)?.ok_or_else(|| {
+ refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "the exact remote-debugging consent prompt exposed no semantic cancel action",
+ )
+ })?;
+ crate::atspi::perform_action(pid, index).map_err(|error| {
+ refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ format!("the exact browser consent cancel action failed: {error}"),
+ )
+ })?;
+ dismissed = true;
+ if Instant::now() >= deadline {
+ return Err(refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "the remote-debugging consent prompt remained after its exact cancel action",
+ ));
+ }
+ std::thread::sleep(Duration::from_millis(100));
+ }
+}
+
pub async fn handle(
request: BrowserConsentRequest,
) -> Result<BrowserConsentOutcome, BrowserRefusal> {
@@ -344,6 +393,7 @@ mod tests {
#[test]
fn matcher_requires_exact_security_prompt_and_unique_allow_action() {
assert_eq!(exact_allow_button(&prompt(), &[]).unwrap(), Some(7));
+ assert_eq!(exact_cancel_button(&prompt(), &[]).unwrap(), Some(7));
assert!(
exact_allow_button(&[node("push button", "Allow", &["click"])], &[])
.unwrap()
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs b/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs
index 0816d173d8..a4e17cac25 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs
@@ -27,6 +27,27 @@ fn refusal(code: BrowserRefusalCode, message: impl Into<String>) -> BrowserRefus
BrowserRefusal::new(code, message)
}
+fn run_existing_profile_cleanup<T: Send + 'static>(
+ cleanup: impl FnOnce() -> T + Send + 'static,
+) -> Result<T, BrowserRefusal> {
+ std::thread::Builder::new()
+ .name("cua-browser-cleanup".into())
+ .spawn(cleanup)
+ .map_err(|error| {
+ refusal(
+ BrowserRefusalCode::BrowserRouteUnavailable,
+ format!("could not start exact browser cleanup: {error}"),
+ )
+ })?
+ .join()
+ .map_err(|_| {
+ refusal(
+ BrowserRefusalCode::BrowserRouteUnavailable,
+ "exact browser cleanup worker panicked",
+ )
+ })
+}
+
fn is_chromium(name: &str) -> bool {
let name = name.to_ascii_lowercase();
let products = [
@@ -1079,6 +1100,34 @@ impl BrowserPlatform for LinuxBrowserPlatform {
})?
}
+ fn cleanup_existing_profile_setup(
+ &self,
+ request: ExistingProfileSetupRequest,
+ ) -> Result<bool, BrowserRefusal> {
+ let descriptor = existing_profile_setup_descriptor(request.browser).ok_or_else(|| {
+ refusal(
+ BrowserRefusalCode::BrowserRouteUnavailable,
+ format!(
+ "existing-profile cleanup is not implemented for {:?}",
+ request.browser
+ ),
+ )
+ })?;
+ let pid = u32::try_from(request.pid).map_err(|_| {
+ refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "the approved browser pid is outside the Linux process-id range",
+ )
+ })?;
+ let window_id = request.window_id;
+ run_existing_profile_cleanup(move || {
+ let dismissed_before = crate::browser_consent_ui::dismiss(pid, window_id)?;
+ let closed_setup_page = crate::browser_setup_ui::disable(pid, window_id, descriptor)?;
+ let dismissed_after = crate::browser_consent_ui::dismiss(pid, window_id)?;
+ Ok(dismissed_before || closed_setup_page || dismissed_after)
+ })?
+ }
+
async fn abort_existing_profile_setup(
&self,
request: ExistingProfileSetupRequest,
@@ -1153,6 +1202,20 @@ impl BrowserPlatform for LinuxBrowserPlatform {
mod tests {
use super::*;
+ #[tokio::test(flavor = "multi_thread")]
+ async fn existing_profile_cleanup_can_drive_atspi_runtime_from_async_session_teardown() {
+ let cleaned = run_existing_profile_cleanup(|| {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("AT-SPI-style cleanup runtime")
+ .block_on(async { true })
+ })
+ .expect("cleanup worker");
+
+ assert!(cleaned);
+ }
+
#[test]
fn isolated_browser_candidates_use_only_root_managed_payloads() {
let candidates = isolated_browser_candidates();
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs b/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs
index 237fbe57d4..7f1d815a12 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs
@@ -491,10 +491,11 @@ pub fn abort_pending(pid: u32, window_id: u64, error: BrowserRefusal) -> Browser
}
}
-pub fn enable(
+fn set_remote_debugging(
pid: u32,
window_id: u64,
descriptor: &'static BrowserSetupDescriptor,
+ desired_enabled: bool,
) -> Result<SetupUiHandle, BrowserRefusal> {
let initial = window_scoped_tree(pid, window_id)?;
let initial_checkbox = exact_setup_checkbox(&initial.nodes, descriptor, false)?;
@@ -546,13 +547,15 @@ pub fn enable(
};
match exact_setup_checkbox(&tree.nodes, descriptor, handle.trusted_setup_navigation) {
Ok(Some(node)) => match node.checked {
- Some(true) => {
- if handle.enable_attempted {
+ Some(state) if state == desired_enabled => {
+ if desired_enabled && handle.enable_attempted {
handle.enabled_remote_debugging = true;
+ } else if !desired_enabled {
+ handle.enabled_remote_debugging = false;
}
return Ok(handle);
}
- Some(false) if !handle.enable_attempted => {
+ Some(_) if !handle.enable_attempted => {
let index = node.element_index.expect("actionable checkbox index");
if let Err(error) = crate::atspi::perform_action(pid, index) {
return Err(handle.abort(refusal(
@@ -562,7 +565,7 @@ pub fn enable(
}
handle.enable_attempted = true;
}
- Some(false)
+ Some(_)
if descriptor.product == BrowserProduct::MicrosoftEdge
&& !handle.trusted_checkbox_fallback_attempted =>
{
@@ -583,10 +586,10 @@ pub fn enable(
"the exact Microsoft Edge remote-debugging checkbox became stale before the trusted click"
)
})?;
- if checkbox.checked == Some(true) {
+ if checkbox.checked == Some(desired_enabled) {
return Ok(false);
}
- if checkbox.checked != Some(false) {
+ if checkbox.checked != Some(!desired_enabled) {
anyhow::bail!(
"the exact Microsoft Edge remote-debugging checkbox had an unknown state before the trusted click"
);
@@ -623,7 +626,7 @@ pub fn enable(
}
}
}
- Some(false) => {}
+ Some(_) => {}
None => {
return Err(handle.abort(refusal(
BrowserRefusalCode::BrowserWrongTargetRefused,
@@ -644,6 +647,23 @@ pub fn enable(
}
}
+pub fn enable(
+ pid: u32,
+ window_id: u64,
+ descriptor: &'static BrowserSetupDescriptor,
+) -> Result<SetupUiHandle, BrowserRefusal> {
+ set_remote_debugging(pid, window_id, descriptor, true)
+}
+
+pub fn disable(
+ pid: u32,
+ window_id: u64,
+ descriptor: &'static BrowserSetupDescriptor,
+) -> Result<bool, BrowserRefusal> {
+ let handle = set_remote_debugging(pid, window_id, descriptor, false)?;
+ Ok(handle.close().unwrap_or(false))
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/browser/consent_ui.rs b/libs/cua-driver/rust/crates/platform-macos/src/browser/consent_ui.rs
index f2999aeb16..ff05feaf12 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/browser/consent_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/browser/consent_ui.rs
@@ -133,6 +133,137 @@ fn exact_allow_button(nodes: &[AXNode]) -> Result<Option<usize>, BrowserRefusal>
}
}
+fn exact_cancel_button(nodes: &[AXNode]) -> Result<Option<usize>, BrowserRefusal> {
+ let mut matches = Vec::new();
+ for (sheet_index, sheet) in nodes
+ .iter()
+ .enumerate()
+ .filter(|(_, node)| node.role == "AXSheet")
+ {
+ let end = nodes
+ .iter()
+ .enumerate()
+ .skip(sheet_index + 1)
+ .find(|(_, node)| node.depth <= sheet.depth)
+ .map_or(nodes.len(), |(index, _)| index);
+ let sheet_nodes = &nodes[sheet_index..end];
+ let prompt_is_remote_debugging = sheet_nodes.iter().any(|node| {
+ let text = normalized_text(node);
+ text.contains("remote debugging") || text.contains("remote-debugging")
+ });
+ if !prompt_is_remote_debugging {
+ continue;
+ }
+ for node in sheet_nodes {
+ if node.role == "AXButton"
+ && node.actions.iter().any(|action| action == "AXPress")
+ && normalized_text(node) == "cancel"
+ {
+ matches.push(node.element_ptr);
+ }
+ }
+ }
+ match matches.as_slice() {
+ [] => Ok(None),
+ [element] => Ok(Some(*element)),
+ _ => Err(refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "multiple semantic cancel actions matched the browser consent sheet",
+ )),
+ }
+}
+
+/// Dismiss any exact Chrome-owned remote-debugging sheet before teardown.
+/// Turning off the setting does not reliably close a sheet that an existing
+/// WebSocket connection already presented.
+pub fn dismiss(pid: i32, approved_window_id: u32) -> Result<bool, BrowserRefusal> {
+ let deadline = Instant::now() + Duration::from_secs(2);
+ let mut dismissed = false;
+ loop {
+ let trees = consent_surface_ids(crate::windows::all_windows(), pid, approved_window_id)
+ .into_iter()
+ .map(|candidate_window_id| {
+ walk_tree_bounded(
+ pid,
+ Some(candidate_window_id),
+ None,
+ CONSENT_MAX_ELEMENTS,
+ DEFAULT_MAX_DEPTH,
+ )
+ .nodes
+ })
+ .collect::<Vec<_>>();
+ let prompt_present = trees
+ .iter()
+ .any(|nodes| remote_debugging_sheet_present(nodes));
+ if !prompt_present {
+ for nodes in &trees {
+ release_actionable_nodes(nodes);
+ }
+ return Ok(dismissed);
+ }
+
+ let mut candidates = Vec::new();
+ let mut matcher_error = None;
+ for nodes in &trees {
+ match exact_cancel_button(nodes) {
+ Ok(Some(element)) => candidates.push(element),
+ Ok(None) => {}
+ Err(error) => {
+ matcher_error = Some(error);
+ break;
+ }
+ }
+ }
+ candidates.sort_unstable();
+ candidates.dedup();
+ if let Some(error) = matcher_error {
+ for nodes in &trees {
+ release_actionable_nodes(nodes);
+ }
+ return Err(error);
+ }
+ let pressed = match candidates.as_slice() {
+ [element] => unsafe { perform_action(*element as AXUIElementRef, "AXPress") },
+ [] => {
+ for nodes in &trees {
+ release_actionable_nodes(nodes);
+ }
+ return Err(refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "the exact remote-debugging consent sheet exposed no semantic cancel action",
+ ));
+ }
+ _ => {
+ for nodes in &trees {
+ release_actionable_nodes(nodes);
+ }
+ return Err(refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "multiple Chrome-owned remote-debugging consent sheets exposed semantic cancel actions",
+ ));
+ }
+ };
+ for nodes in &trees {
+ release_actionable_nodes(nodes);
+ }
+ if pressed != kAXErrorSuccess {
+ return Err(refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "the exact browser consent cancel action became stale before AXPress",
+ ));
+ }
+ dismissed = true;
+ if Instant::now() >= deadline {
+ return Err(refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "the remote-debugging consent sheet remained after its exact cancel action",
+ ));
+ }
+ std::thread::sleep(Duration::from_millis(100));
+ }
+}
+
pub async fn handle(
request: BrowserConsentRequest,
) -> Result<BrowserConsentOutcome, BrowserRefusal> {
@@ -304,6 +435,23 @@ mod tests {
);
}
+ #[test]
+ fn cancel_matcher_requires_remote_debugging_sheet() {
+ let nodes = vec![
+ node("AXWindow", 0, Some("Chrome"), &[]),
+ node("AXSheet", 1, Some("Allow remote debugging?"), &[]),
+ node("AXButton", 2, Some("Cancel"), &["AXPress"]),
+ node("AXButton", 2, Some("Allow"), &["AXPress"]),
+ ];
+ assert_eq!(exact_cancel_button(&nodes).unwrap(), Some(7));
+
+ let unrelated = vec![
+ node("AXSheet", 1, Some("Save changes?"), &[]),
+ node("AXButton", 2, Some("Cancel"), &["AXPress"]),
+ ];
+ assert_eq!(exact_cancel_button(&unrelated).unwrap(), None);
+ }
+
#[test]
fn consent_surfaces_keep_approved_window_then_frontmost_normal_windows() {
let window = |window_id, title: &str, z_index| crate::windows::WindowInfo {
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs b/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs
index 3d86ea7e8c..261139794e 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs
@@ -1087,6 +1087,37 @@ impl BrowserPlatform for MacOsBrowserPlatform {
})?
}
+ fn cleanup_existing_profile_setup(
+ &self,
+ request: ExistingProfileSetupRequest,
+ ) -> Result<bool, BrowserRefusal> {
+ let descriptor = existing_profile_setup_descriptor(request.browser).ok_or_else(|| {
+ refusal(
+ BrowserRefusalCode::BrowserRouteUnavailable,
+ format!(
+ "existing-profile cleanup is not implemented for {:?}",
+ request.browser
+ ),
+ )
+ })?;
+ let pid = i32::try_from(request.pid).map_err(|_| {
+ refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "the approved browser pid is outside the macOS process-id range",
+ )
+ })?;
+ let window_id = u32::try_from(request.window_id).map_err(|_| {
+ refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "the approved browser window is outside the macOS window-id range",
+ )
+ })?;
+ let dismissed_before = super::consent_ui::dismiss(pid, window_id)?;
+ let closed_setup_page = super::setup_ui::disable(pid, window_id, descriptor)?;
+ let dismissed_after = super::consent_ui::dismiss(pid, window_id)?;
+ Ok(dismissed_before || closed_setup_page || dismissed_after)
+ }
+
async fn abort_existing_profile_setup(
&self,
request: ExistingProfileSetupRequest,
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/browser/setup_ui.rs b/libs/cua-driver/rust/crates/platform-macos/src/browser/setup_ui.rs
index 2cacc0850f..dcdc4ec0fe 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/browser/setup_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/browser/setup_ui.rs
@@ -1168,10 +1168,11 @@ pub fn abort_pending(pid: i32, window_id: u32, error: BrowserRefusal) -> Browser
}
}
-pub fn enable(
+fn set_remote_debugging(
pid: i32,
window_id: u32,
descriptor: &'static BrowserSetupDescriptor,
+ desired_enabled: bool,
) -> Result<SetupUiHandle, BrowserRefusal> {
let initial = walk_tree(pid, Some(window_id), None);
let initial_checkbox = exact_setup_checkbox(&initial, descriptor);
@@ -1494,14 +1495,20 @@ pub fn enable(
Ok(Some(element)) => {
let value = unsafe { copy_number_attr(element as AXUIElementRef, "AXValue") };
match checkbox_state(value) {
- Ok(CheckboxState::On) => {
- if handle.enable_attempted || handle.remote_debugging_mutation_possible {
+ Ok(state) if (state == CheckboxState::On) == desired_enabled => {
+ if desired_enabled
+ && (handle.enable_attempted
+ || handle.remote_debugging_mutation_possible)
+ {
handle.enabled_remote_debugging = true;
+ } else if !desired_enabled {
+ handle.enabled_remote_debugging = false;
+ handle.remote_debugging_mutation_possible = false;
}
release_actionable_nodes(&tree.nodes);
return Ok(handle);
}
- Ok(CheckboxState::Off) => {
+ Ok(_) => {
if !handle.enable_attempted {
handle.enable_attempted = true;
handle.remote_debugging_mutation_possible = true;
@@ -1590,12 +1597,7 @@ pub fn enable(
descriptor,
handle.setup_navigation_committed,
) {
- Ok(Some(
- checkbox @ PixelCheckbox {
- state: CheckboxState::On,
- ..
- },
- )) => {
+ Ok(Some(checkbox)) if (checkbox.state == CheckboxState::On) == desired_enabled => {
handle.used_bounded_pixel_fallback = true;
if handle
.pixel_checkbox
@@ -1614,8 +1616,11 @@ pub fn enable(
),
));
}
- if handle.remote_debugging_mutation_possible {
+ if desired_enabled && handle.remote_debugging_mutation_possible {
handle.enabled_remote_debugging = true;
+ } else if !desired_enabled {
+ handle.enabled_remote_debugging = false;
+ handle.remote_debugging_mutation_possible = false;
}
release_actionable_nodes(&tree.nodes);
return Ok(handle);
@@ -1679,6 +1684,23 @@ pub fn enable(
}
}
+pub fn enable(
+ pid: i32,
+ window_id: u32,
+ descriptor: &'static BrowserSetupDescriptor,
+) -> Result<SetupUiHandle, BrowserRefusal> {
+ set_remote_debugging(pid, window_id, descriptor, true)
+}
+
+pub fn disable(
+ pid: i32,
+ window_id: u32,
+ descriptor: &'static BrowserSetupDescriptor,
+) -> Result<bool, BrowserRefusal> {
+ let handle = set_remote_debugging(pid, window_id, descriptor, false)?;
+ Ok(handle.close().unwrap_or(false))
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/browser_consent_ui.rs b/libs/cua-driver/rust/crates/platform-windows/src/browser_consent_ui.rs
index 80163868fe..11dd682235 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/browser_consent_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/browser_consent_ui.rs
@@ -185,9 +185,9 @@ fn edge_gap(first: (i32, i32, i32, i32), second: (i32, i32, i32, i32)) -> Option
}
}
-fn select_language_independent_allow(
+fn select_language_independent_actions(
candidates: &[ConsentButtonCandidate],
-) -> Result<usize, BrowserRefusal> {
+) -> Result<(usize, usize), BrowserRefusal> {
// Chromium builds this modal from one separated extra action plus the
// standard OK/Cancel pair. Accessible names are localized, and the whole
// footer mirrors for RTL locales, but adjacency and separation are stable.
@@ -278,13 +278,16 @@ fn select_language_independent_allow(
"the native Chromium consent prompt focus contradicted the structural cancel button",
));
}
- Ok(candidates[allow_index].element_ptr)
+ Ok((
+ candidates[allow_index].element_ptr,
+ candidates[cancel_index].element_ptr,
+ ))
}
-fn exact_allow_button_with<F>(
+fn exact_consent_actions_with<F>(
nodes: &[UiaNode],
mut properties: F,
-) -> Result<Option<usize>, BrowserRefusal>
+) -> Result<Option<(usize, usize)>, BrowserRefusal>
where
F: FnMut(usize) -> Result<(String, bool), BrowserRefusal>,
{
@@ -322,7 +325,7 @@ where
has_keyboard_focus,
});
}
- matches.push(select_language_independent_allow(&candidates)?);
+ matches.push(select_language_independent_actions(&candidates)?);
}
match matches.as_slice() {
[element] => Ok(Some(*element)),
@@ -333,8 +336,22 @@ where
}
}
+fn exact_allow_button_with<F>(
+ nodes: &[UiaNode],
+ properties: F,
+) -> Result<Option<usize>, BrowserRefusal>
+where
+ F: FnMut(usize) -> Result<(String, bool), BrowserRefusal>,
+{
+ Ok(exact_consent_actions_with(nodes, properties)?.map(|actions| actions.0))
+}
+
fn exact_allow_button(nodes: &[UiaNode]) -> Result<Option<usize>, BrowserRefusal> {
- exact_allow_button_with(nodes, native_button_properties)
+ Ok(exact_consent_actions_with(nodes, native_button_properties)?.map(|actions| actions.0))
+}
+
+fn exact_cancel_button(nodes: &[UiaNode]) -> Result<Option<usize>, BrowserRefusal> {
+ Ok(exact_consent_actions_with(nodes, native_button_properties)?.map(|actions| actions.1))
}
unsafe fn invoke(element_ptr: usize) -> Result<(), BrowserRefusal> {
@@ -364,6 +381,40 @@ fn prove_window_owner(hwnd: u64, pid: u32) -> Result<(), BrowserRefusal> {
Ok(())
}
+pub fn dismiss(pid: u32, hwnd: u64) -> Result<bool, BrowserRefusal> {
+ prove_window_owner(hwnd, pid)?;
+ let deadline = Instant::now() + Duration::from_secs(2);
+ let mut dismissed = false;
+ loop {
+ prove_window_owner(hwnd, pid)?;
+ let tree = crate::uia::walk_tree(hwnd, None);
+ let prompt_present = native_prompt_surface_present(&tree.nodes);
+ if !prompt_present {
+ release_nodes(&tree.nodes);
+ return Ok(dismissed);
+ }
+ let cancel = exact_cancel_button(&tree.nodes);
+ let invoked = match cancel {
+ Ok(Some(element)) => unsafe { invoke(element) },
+ Ok(None) => Err(refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "the exact remote-debugging consent prompt exposed no structural cancel action",
+ )),
+ Err(error) => Err(error),
+ };
+ release_nodes(&tree.nodes);
+ invoked?;
+ dismissed = true;
+ if Instant::now() >= deadline {
+ return Err(refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "the remote-debugging consent prompt remained after its exact cancel action",
+ ));
+ }
+ std::thread::sleep(Duration::from_millis(100));
+ }
+}
+
pub async fn handle(
request: BrowserConsentRequest,
) -> Result<BrowserConsentOutcome, BrowserRefusal> {
@@ -516,6 +567,18 @@ mod tests {
}
}
+ #[test]
+ fn cancel_matcher_selects_the_structural_default_action() {
+ let nodes = prompt(
+ "Allow remote debugging?",
+ ["Turn off in settings", "Allow", "Cancel"],
+ );
+ assert_eq!(
+ exact_consent_actions_with(&nodes, properties).unwrap(),
+ Some((12, 13))
+ );
+ }
+
#[test]
fn matcher_supports_pane_rooted_native_edge_prompt() {
assert_eq!(
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs b/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs
index b1ecbfc7ff..5793d75094 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs
@@ -1851,6 +1851,31 @@ impl BrowserPlatform for WindowsBrowserPlatform {
})?
}
+ fn cleanup_existing_profile_setup(
+ &self,
+ request: ExistingProfileSetupRequest,
+ ) -> Result<bool, BrowserRefusal> {
+ let descriptor = existing_profile_setup_descriptor(request.browser).ok_or_else(|| {
+ refusal(
+ BrowserRefusalCode::BrowserRouteUnavailable,
+ format!(
+ "existing-profile cleanup is not implemented for {:?}",
+ request.browser
+ ),
+ )
+ })?;
+ let pid = u32::try_from(request.pid).map_err(|_| {
+ refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "the approved browser pid is outside the Windows process-id range",
+ )
+ })?;
+ let dismissed_before = crate::browser_consent_ui::dismiss(pid, request.window_id)?;
+ let closed_setup_page = crate::browser_setup_ui::disable(request.window_id, descriptor)?;
+ let dismissed_after = crate::browser_consent_ui::dismiss(pid, request.window_id)?;
+ Ok(dismissed_before || closed_setup_page || dismissed_after)
+ }
+
async fn abort_existing_profile_setup(
&self,
request: ExistingProfileSetupRequest,
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/browser_setup_ui.rs b/libs/cua-driver/rust/crates/platform-windows/src/browser_setup_ui.rs
index 8e80f51aea..7f42fa7a9e 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/browser_setup_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/browser_setup_ui.rs
@@ -505,9 +505,10 @@ pub fn abort_pending(hwnd: u64, error: BrowserRefusal) -> BrowserRefusal {
}
}
-pub fn enable(
+fn set_remote_debugging(
hwnd: u64,
descriptor: &'static BrowserSetupDescriptor,
+ desired_enabled: bool,
) -> Result<SetupUiHandle, BrowserRefusal> {
let initial = crate::uia::walk_tree(hwnd, None);
let initial_checkbox = exact_setup_checkbox(&initial.nodes, descriptor);
@@ -658,16 +659,16 @@ pub fn enable(
Ok(Some(element)) => {
let state = unsafe { checkbox_state(element) };
let outcome = match state {
- Ok(CheckboxState::On) => {
- if handle.enable_attempted {
+ Ok(state) if (state == CheckboxState::On) == desired_enabled => {
+ if desired_enabled && handle.enable_attempted {
handle.enabled_remote_debugging = true;
+ } else if !desired_enabled {
+ handle.enabled_remote_debugging = false;
}
Ok(true)
}
- Ok(CheckboxState::Off) if !handle.enable_attempted => unsafe {
- toggle(element).map(|_| false)
- },
- Ok(CheckboxState::Off) => Ok(false),
+ Ok(_) if !handle.enable_attempted => unsafe { toggle(element).map(|_| false) },
+ Ok(_) => Ok(false),
Err(error) => Err(error),
};
release_nodes(&tree.nodes);
@@ -696,6 +697,21 @@ pub fn enable(
}
}
+pub fn enable(
+ hwnd: u64,
+ descriptor: &'static BrowserSetupDescriptor,
+) -> Result<SetupUiHandle, BrowserRefusal> {
+ set_remote_debugging(hwnd, descriptor, true)
+}
+
+pub fn disable(
+ hwnd: u64,
+ descriptor: &'static BrowserSetupDescriptor,
+) -> Result<bool, BrowserRefusal> {
+ let handle = set_remote_debugging(hwnd, descriptor, false)?;
+ Ok(handle.close().unwrap_or(false))
+}
+
#[cfg(test)]
mod tests {
use super::*;