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): settle started browser consent before claim completion

injaneityd2d8d263a924
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 c2cfff8a7a..68ca93ce8e 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
@@ -939,6 +939,7 @@ impl BrowserEngine {
result = &mut reconnect => result,
_ = tokio::time::sleep(std::time::Duration::from_millis(500)) => {
match self.platform.handle_existing_profile_consent(BrowserConsentRequest {
+ action: Default::default(),
pid,
window_id: grant.window_id,
attempt,
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 37385d9a3e..012658da8b 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
@@ -205,8 +205,23 @@ pub enum PrepareAttachmentKind {
ExistingProfile,
}
+#[derive(Debug, Clone, Default)]
+pub struct BrowserConsentAction(std::sync::Arc<std::sync::atomic::AtomicBool>);
+
+impl BrowserConsentAction {
+ pub fn perform<T>(&self, action: impl FnOnce() -> T) -> T {
+ self.0.store(true, std::sync::atomic::Ordering::Release);
+ action()
+ }
+
+ pub(crate) fn started(&self) -> bool {
+ self.0.load(std::sync::atomic::Ordering::Acquire)
+ }
+}
+
#[derive(Debug, Clone)]
pub struct BrowserConsentRequest {
+ pub action: BrowserConsentAction,
pub pid: i64,
pub window_id: u64,
pub attempt: u8,
@@ -506,6 +521,26 @@ pub trait BrowserPlatform: Send + Sync {
#[cfg(test)]
mod tests {
+ #[test]
+ fn consent_action_boundary_precedes_success_and_failure_and_never_resets() {
+ for succeeds in [true, false] {
+ let action = super::BrowserConsentAction::default();
+ let observer = action.clone();
+ assert!(!observer.started());
+ let result = action.perform(|| {
+ assert!(observer.started());
+ if succeeds {
+ Ok(())
+ } else {
+ Err("native action failed")
+ }
+ });
+ assert_eq!(result.is_ok(), succeeds);
+ assert!(observer.started());
+ assert!(!super::BrowserConsentAction::default().started());
+ }
+ }
+
use super::select_isolated_browser_executable;
#[test]
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 e6e9cc6383..85811f5989 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
@@ -13,10 +13,10 @@ use serde::{Deserialize, Serialize};
use super::engine::unsupported_engine_refusal;
use super::platform::{
- BrowserConsentOutcome, BrowserConsentRequest, ExistingProfileSetupOutcome,
- ExistingProfileSetupRequest, IsolatedBrowserProcess, PrepareAction, PrepareAttachment,
- PrepareAttachmentKind, PrepareOutcome, PrepareProfile, PrepareProfileMode, PrepareRequest,
- PrepareSideEffects, PrepareStrategy,
+ BrowserConsentAction, BrowserConsentOutcome, BrowserConsentRequest,
+ ExistingProfileSetupOutcome, ExistingProfileSetupRequest, IsolatedBrowserProcess,
+ PrepareAction, PrepareAttachment, PrepareAttachmentKind, PrepareOutcome, PrepareProfile,
+ PrepareProfileMode, PrepareRequest, PrepareSideEffects, PrepareStrategy,
};
use super::refusal::{BrowserRefusal, BrowserRefusalCode};
use super::types::{
@@ -62,27 +62,51 @@ fn validate_profile(profile: &PrepareProfile) -> Result<(), BrowserRefusal> {
async fn claim_with_optional_consent<T, Claim, Consent>(
claim: &mut Pin<Box<Claim>>,
+ action: &BrowserConsentAction,
consent: Consent,
) -> Result<(anyhow::Result<T>, bool), BrowserRefusal>
where
Claim: Future<Output = anyhow::Result<T>>,
Consent: Future<Output = Result<BrowserConsentOutcome, BrowserRefusal>>,
{
- let mut consent = Box::pin(consent);
- tokio::select! {
- result = claim.as_mut() => Ok((result, false)),
- outcome = consent.as_mut() => match outcome? {
- BrowserConsentOutcome::Accepted => Ok((claim.as_mut().await, true)),
- BrowserConsentOutcome::NotPresent => Ok((claim.as_mut().await, false)),
+ let mut consent = Box::pin(tokio::time::timeout(Duration::from_secs(4), consent));
+ let (result, outcome) = tokio::select! {
+ result = claim.as_mut() => {
+ if !action.started() {
+ return Ok((result, false));
+ }
+ (Some(result), consent.await)
},
+ outcome = consent.as_mut() => (None, outcome),
+ };
+ let outcome = outcome.map_err(|_| {
+ refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "browser consent did not settle within its bounded attempt",
+ )
+ })??;
+ let accepted = outcome == BrowserConsentOutcome::Accepted;
+ if action.started() && !accepted {
+ return Err(refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "browser consent action did not produce a confirmed outcome",
+ ));
}
+ Ok((
+ match result {
+ Some(result) => result,
+ None => claim.as_mut().await,
+ },
+ accepted,
+ ))
}
-async fn claim_with_delayed_consent<T, Claim, Consent>(
+async fn claim_with_delayed_consent<T, Claim, Consent, MakeConsent>(
claim: Claim,
- consent: Consent,
+ consent: MakeConsent,
) -> Result<(anyhow::Result<T>, bool), BrowserRefusal>
where
+ MakeConsent: FnOnce(BrowserConsentAction) -> Consent,
Claim: Future<Output = anyhow::Result<T>>,
Consent: Future<Output = Result<BrowserConsentOutcome, BrowserRefusal>>,
{
@@ -93,7 +117,10 @@ where
};
match initial {
Some(result) => Ok((result, false)),
- None => claim_with_optional_consent(&mut claim, consent).await,
+ None => {
+ let action = BrowserConsentAction::default();
+ claim_with_optional_consent(&mut claim, &action, consent(action.clone())).await
+ }
}
}
@@ -1148,12 +1175,15 @@ impl BrowserEngine {
}
let (claimed, displayed_consent_prompt) = match claim_with_delayed_consent(
self.pool.claim_existing(&endpoint.ws_url, grant.generation),
- self.platform
- .handle_existing_profile_consent(BrowserConsentRequest {
- pid,
- window_id,
- attempt: 1,
- }),
+ |action| {
+ self.platform
+ .handle_existing_profile_consent(BrowserConsentRequest {
+ action,
+ pid,
+ window_id,
+ attempt: 1,
+ })
+ },
)
.await
{
@@ -1188,12 +1218,15 @@ impl BrowserEngine {
// one exact browser-owned prompt against the same PID and window.
let retry = claim_with_delayed_consent(
self.pool.claim_existing(&endpoint.ws_url, grant.generation),
- self.platform
- .handle_existing_profile_consent(BrowserConsentRequest {
- pid,
- window_id,
- attempt: 2,
- }),
+ |action| {
+ self.platform
+ .handle_existing_profile_consent(BrowserConsentRequest {
+ action,
+ pid,
+ window_id,
+ attempt: 2,
+ })
+ },
);
let (claimed, initial_claim_error, fresh_consent_prompt) =
match retry_claim_after_accepted_consent(claimed, displayed_consent_prompt, retry).await
@@ -1311,6 +1344,137 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn claim_completion_preserves_started_consent_confirmation() {
+ use std::sync::atomic::{AtomicBool, Ordering};
+ let confirmed = Arc::new(AtomicBool::new(false));
+ let confirmation = confirmed.clone();
+ let (action_tx, action_rx) = tokio::sync::oneshot::channel();
+ let mut claim = Box::pin(async {
+ action_rx.await.unwrap();
+ Ok::<_, anyhow::Error>(7_u8)
+ });
+ let action = BrowserConsentAction::default();
+ let marker = action.clone();
+ let consent = async move {
+ marker.perform(|| ());
+ action_tx.send(()).unwrap();
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ confirmation.store(true, Ordering::SeqCst);
+ Ok(BrowserConsentOutcome::Accepted)
+ };
+ let (result, displayed) = claim_with_optional_consent(&mut claim, &action, consent)
+ .await
+ .unwrap();
+ assert_eq!(result.unwrap(), 7);
+ assert!(displayed, "performed consent must be reported");
+ assert!(
+ confirmed.load(Ordering::SeqCst),
+ "post-action confirmation was cancelled"
+ );
+ }
+
+ #[tokio::test]
+ async fn started_consent_settles_success_refusal_and_timeout_for_both_claim_results() {
+ use std::sync::atomic::{AtomicBool, Ordering};
+ for claim_succeeds in [true, false] {
+ for outcome in 0..3 {
+ let action = BrowserConsentAction::default();
+ let marker = action.clone();
+ let settled = Arc::new(AtomicBool::new(false));
+ let settle_marker = settled.clone();
+ let dropped = Arc::new(AtomicBool::new(false));
+ let drop_signal = DropSignal(dropped.clone());
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ let mut claim = Box::pin(async move {
+ rx.await.unwrap();
+ if claim_succeeds {
+ Ok(7_u8)
+ } else {
+ Err(anyhow::anyhow!("claim failed"))
+ }
+ });
+ let consent = async move {
+ let _drop_signal = drop_signal;
+ marker.perform(|| tx.send(()).unwrap());
+ if outcome == 2 {
+ loop {
+ marker.perform(|| ());
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ settle_marker.store(true, Ordering::SeqCst);
+ if outcome == 0 {
+ Ok(BrowserConsentOutcome::Accepted)
+ } else {
+ Err(refusal(
+ BrowserRefusalCode::BrowserConsentRevoked,
+ "native action refused",
+ ))
+ }
+ };
+ let result = claim_with_optional_consent(&mut claim, &action, consent).await;
+ assert!(dropped.load(Ordering::SeqCst));
+ match outcome {
+ 0 => {
+ let (claim, displayed) = result.unwrap();
+ assert_eq!(claim.is_ok(), claim_succeeds);
+ assert!(displayed && settled.load(Ordering::SeqCst));
+ }
+ 1 => assert_eq!(
+ result.unwrap_err().code,
+ BrowserRefusalCode::BrowserConsentRevoked
+ ),
+ _ => {
+ assert_eq!(
+ result.unwrap_err().code,
+ BrowserRefusalCode::BrowserWrongTargetRefused
+ );
+ assert!(!settled.load(Ordering::SeqCst));
+ }
+ }
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn idle_claim_failure_cancels_unused_consent_without_waiting() {
+ let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let signal = DropSignal(dropped.clone());
+ let mut claim = Box::pin(async { Err::<u8, _>(anyhow::anyhow!("dial failed")) });
+ let consent = async move {
+ let _signal = signal;
+ std::future::pending::<Result<BrowserConsentOutcome, BrowserRefusal>>().await
+ };
+ let (result, displayed) = tokio::time::timeout(
+ Duration::from_millis(100),
+ claim_with_optional_consent(&mut claim, &BrowserConsentAction::default(), consent),
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(result.unwrap_err().to_string(), "dial failed");
+ assert!(!displayed);
+ assert!(dropped.load(std::sync::atomic::Ordering::SeqCst));
+ }
+
+ #[tokio::test]
+ async fn started_action_cannot_settle_as_not_present() {
+ let action = BrowserConsentAction::default();
+ let marker = action.clone();
+ let mut claim = Box::pin(std::future::pending::<anyhow::Result<u8>>());
+ let result = claim_with_optional_consent(&mut claim, &action, async move {
+ marker.perform(|| ());
+ Ok(BrowserConsentOutcome::NotPresent)
+ })
+ .await;
+ assert_eq!(
+ result.unwrap_err().code,
+ BrowserRefusalCode::BrowserWrongTargetRefused
+ );
+ }
+
#[tokio::test]
async fn completed_claim_wins_while_optional_consent_is_absent() {
let mut claim = Box::pin(async {
@@ -1324,9 +1488,10 @@ mod tests {
"no consent surface",
))
};
- let (result, displayed) = claim_with_optional_consent(&mut claim, consent)
- .await
- .expect("the completed claim should win the race");
+ let (result, displayed) =
+ claim_with_optional_consent(&mut claim, &BrowserConsentAction::default(), consent)
+ .await
+ .expect("the completed claim should win the race");
assert_eq!(result.unwrap(), 7);
assert!(!displayed);
}
@@ -1338,9 +1503,11 @@ mod tests {
Ok::<_, anyhow::Error>(9_u8)
});
let (result, displayed) =
- claim_with_optional_consent(&mut claim, async { Ok(BrowserConsentOutcome::Accepted) })
- .await
- .expect("accepted consent should resume the existing claim");
+ claim_with_optional_consent(&mut claim, &BrowserConsentAction::default(), async {
+ Ok(BrowserConsentOutcome::Accepted)
+ })
+ .await
+ .expect("accepted consent should resume the existing claim");
assert_eq!(result.unwrap(), 9);
assert!(displayed);
}
@@ -1355,9 +1522,10 @@ mod tests {
first_waiting.await.expect("first consent should complete");
Err::<u8, _>(anyhow::anyhow!("first handshake rejected"))
},
- async move {
+ |action| async move {
+ assert!(!action.started());
first_attempts.lock().unwrap().push(1_u8);
- first_approved.send(()).unwrap();
+ action.perform(|| first_approved.send(()).unwrap());
Ok(BrowserConsentOutcome::Accepted)
},
)
@@ -1373,9 +1541,10 @@ mod tests {
.expect("second consent should complete");
Ok::<_, anyhow::Error>(11_u8)
},
- async move {
+ |action| async move {
+ assert!(!action.started());
second_attempts.lock().unwrap().push(2_u8);
- second_approved.send(()).unwrap();
+ action.perform(|| second_approved.send(()).unwrap());
Ok(BrowserConsentOutcome::Accepted)
},
);
@@ -1398,7 +1567,7 @@ mod tests {
let consent_polled = Arc::new(std::sync::atomic::AtomicBool::new(false));
let consent_marker = consent_polled.clone();
let retry =
- claim_with_delayed_consent(async { Ok::<_, anyhow::Error>(17_u8) }, async move {
+ claim_with_delayed_consent(async { Ok::<_, anyhow::Error>(17_u8) }, |_| async move {
consent_marker.store(true, std::sync::atomic::Ordering::SeqCst);
Ok(BrowserConsentOutcome::Accepted)
});
@@ -1425,7 +1594,8 @@ mod tests {
let _drop_signal = drop_signal;
std::future::pending::<anyhow::Result<u8>>().await
},
- async {
+ |action| async move {
+ action.perform(|| ());
Err(refusal(
BrowserRefusalCode::BrowserConsentRevoked,
"second consent was revoked",
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 4d2e131a9a..122ea8c6c3 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
@@ -47,6 +47,17 @@ fn release_actionable_nodes(nodes: &[AXNode]) {
}
}
+// Own references before crossing the blocking-task boundary, including cancellation.
+struct ConsentTrees(Vec<Vec<AXNode>>);
+
+impl Drop for ConsentTrees {
+ fn drop(&mut self) {
+ for nodes in &self.0 {
+ release_actionable_nodes(nodes);
+ }
+ }
+}
+
fn consent_surface_ids(
windows: impl IntoIterator<Item = crate::windows::WindowInfo>,
pid: i32,
@@ -288,9 +299,11 @@ pub async fn handle(
let mut accepted_prompt = false;
loop {
let trees = tokio::task::spawn_blocking(move || {
- consent_surface_ids(crate::windows::all_windows(), pid, window_id)
- .into_iter()
- .map(|candidate_window_id| {
+ let mut trees = ConsentTrees(Vec::new());
+ for candidate_window_id in
+ consent_surface_ids(crate::windows::all_windows(), pid, window_id)
+ {
+ trees.0.push(
walk_tree_bounded(
pid,
Some(candidate_window_id),
@@ -298,9 +311,10 @@ pub async fn handle(
CONSENT_MAX_ELEMENTS,
DEFAULT_MAX_DEPTH,
)
- .nodes
- })
- .collect::<Vec<_>>()
+ .nodes,
+ );
+ }
+ trees
})
.await
.map_err(|error| {
@@ -309,13 +323,23 @@ pub async fn handle(
format!("could not inspect the browser consent UI: {error}"),
)
})?;
+ if Instant::now() >= deadline {
+ return Err(refusal(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ format!(
+ "Chrome remote-debugging consent did not settle for reconnect attempt {}",
+ request.attempt
+ ),
+ ));
+ }
let prompt_present = trees
+ .0
.iter()
.any(|nodes| remote_debugging_sheet_present(nodes));
saw_prompt |= prompt_present;
let mut candidates = Vec::new();
let mut matcher_error = None;
- for nodes in &trees {
+ for nodes in &trees.0 {
match exact_allow_button(nodes) {
Ok(Some(element)) => candidates.push(element),
Ok(None) => {}
@@ -328,16 +352,13 @@ pub async fn handle(
candidates.sort_unstable();
candidates.dedup();
if let Some(error) = matcher_error {
- for nodes in &trees {
- release_actionable_nodes(nodes);
- }
return Err(error);
}
if let [element] = candidates.as_slice() {
- let pressed = unsafe { perform_action(*element as AXUIElementRef, "AXPress") };
- for nodes in &trees {
- release_actionable_nodes(nodes);
- }
+ let pressed = request
+ .action
+ .perform(|| unsafe { perform_action(*element as AXUIElementRef, "AXPress") });
+ drop(trees);
if pressed != kAXErrorSuccess {
return Err(refusal(
BrowserRefusalCode::BrowserWrongTargetRefused,
@@ -353,9 +374,7 @@ pub async fn handle(
tokio::time::sleep(Duration::from_millis(100)).await;
continue;
}
- for nodes in &trees {
- release_actionable_nodes(nodes);
- }
+ drop(trees);
if candidates.len() > 1 {
return Err(refusal(
BrowserRefusalCode::BrowserWrongTargetRefused,
@@ -371,15 +390,6 @@ pub async fn handle(
"the person dismissed the browser consent sheet",
));
}
- if Instant::now() >= deadline {
- return Err(refusal(
- BrowserRefusalCode::BrowserWrongTargetRefused,
- format!(
- "no exact Chrome remote-debugging consent sheet appeared for reconnect attempt {}",
- request.attempt
- ),
- ));
- }
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
@@ -412,6 +422,43 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn cancelled_scan_releases_late_blocking_result() {
+ use core_foundation::base::{CFGetRetainCount, CFRetain, TCFType};
+ use core_foundation::string::CFString;
+
+ struct Finished(Option<tokio::sync::oneshot::Sender<()>>);
+ impl Drop for Finished {
+ fn drop(&mut self) {
+ let _ = self.0.take().unwrap().send(());
+ }
+ }
+ let value = CFString::new("consent-cancelled-scan-owned-reference");
+ let ptr = value.as_concrete_TypeRef() as usize;
+ let base = unsafe { CFGetRetainCount(ptr as CFTypeRef) };
+ let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
+ let (finish_tx, finish_rx) = std::sync::mpsc::channel();
+ let (dropped_tx, dropped_rx) = tokio::sync::oneshot::channel();
+ let scan = tokio::task::spawn_blocking(move || {
+ let mut element = node("AXButton", 0, Some("Allow"), &["AXPress"]);
+ element.element_ptr = unsafe { CFRetain(ptr as CFTypeRef) } as usize;
+ let owned = ConsentTrees(vec![vec![element]]);
+ ready_tx.send(()).unwrap();
+ finish_rx.recv().unwrap();
+ // Tuple fields drop in order: release the native reference before signalling.
+ (owned, Finished(Some(dropped_tx)))
+ });
+ ready_rx.await.unwrap();
+ assert_eq!(unsafe { CFGetRetainCount(ptr as CFTypeRef) }, base + 1);
+ drop(scan);
+ finish_tx.send(()).unwrap();
+ tokio::time::timeout(Duration::from_secs(2), dropped_rx)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(unsafe { CFGetRetainCount(ptr as CFTypeRef) }, base);
+ }
+
#[test]
fn matcher_requires_sheet_prompt_and_unique_press_action() {
let nodes = vec![
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 a9c1a599e8..25f91303b3 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
@@ -33,6 +33,15 @@ fn release_nodes(nodes: &[UiaNode]) {
}
}
+// Own references before crossing the blocking-task boundary, including cancellation.
+struct ConsentNodes(Vec<UiaNode>);
+
+impl Drop for ConsentNodes {
+ fn drop(&mut self) {
+ release_nodes(&self.0);
+ }
+}
+
fn is_in_web_content(nodes: &[UiaNode], node: &UiaNode) -> bool {
let mut parent = node.parent_element_index;
for _ in 0..nodes.len() {
@@ -431,26 +440,28 @@ pub async fn handle(
loop {
prove_window_owner(request.window_id, pid)?;
let hwnd = request.window_id;
- let tree = tokio::task::spawn_blocking(move || crate::uia::walk_tree(hwnd, None))
- .await
- .map_err(|error| {
- refusal(
- BrowserRefusalCode::BrowserRouteUnavailable,
- format!("could not inspect the browser consent UI: {error}"),
- )
- })?;
- let prompt_present = native_prompt_surface_present(&tree.nodes);
+ let tree = tokio::task::spawn_blocking(move || {
+ ConsentNodes(crate::uia::walk_tree(hwnd, None).nodes)
+ })
+ .await
+ .map_err(|error| {
+ refusal(
+ BrowserRefusalCode::BrowserRouteUnavailable,
+ format!("could not inspect the browser consent UI: {error}"),
+ )
+ })?;
+ let prompt_present = native_prompt_surface_present(&tree.0);
saw_prompt |= prompt_present;
- match exact_allow_button(&tree.nodes) {
+ match exact_allow_button(&tree.0) {
Ok(Some(element)) => {
- let invoked = unsafe { invoke(element) };
- release_nodes(&tree.nodes);
+ let invoked = request.action.perform(|| unsafe { invoke(element) });
+ drop(tree);
invoked?;
return Ok(BrowserConsentOutcome::Accepted);
}
- Ok(None) => release_nodes(&tree.nodes),
+ Ok(None) => drop(tree),
Err(error) => {
- release_nodes(&tree.nodes);
+ drop(tree);
return Err(error);
}
}
@@ -555,6 +566,61 @@ mod tests {
Ok((CHROMIUM_DIALOG_BUTTON_CLASS.to_owned(), element_ptr == 13))
}
+ #[tokio::test]
+ async fn cancelled_scan_releases_late_blocking_result() {
+ use std::ffi::c_void;
+ use windows::core::{IUnknown_Vtbl, GUID, HRESULT};
+
+ // Only IUnknown::Release is used, as in the existing snapshot ownership tests.
+ #[repr(C)]
+ struct OwnedReference {
+ vtable: *const IUnknown_Vtbl,
+ released: Option<tokio::sync::oneshot::Sender<()>>,
+ }
+ unsafe extern "system" fn query(
+ _: *mut c_void,
+ _: *const GUID,
+ _: *mut *mut c_void,
+ ) -> HRESULT {
+ HRESULT(0x8000_4002u32 as i32)
+ }
+ unsafe extern "system" fn retain(_: *mut c_void) -> u32 {
+ 2
+ }
+ unsafe extern "system" fn release(this: *mut c_void) -> u32 {
+ let mut owned = unsafe { Box::from_raw(this as *mut OwnedReference) };
+ let _ = owned.released.take().unwrap().send(());
+ 0
+ }
+ static VTABLE: IUnknown_Vtbl = IUnknown_Vtbl {
+ QueryInterface: query,
+ AddRef: retain,
+ Release: release,
+ };
+ let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
+ let (finish_tx, finish_rx) = std::sync::mpsc::channel();
+ let (dropped_tx, dropped_rx) = tokio::sync::oneshot::channel();
+ let scan = tokio::task::spawn_blocking(move || {
+ let ptr = Box::into_raw(Box::new(OwnedReference {
+ vtable: &VTABLE,
+ released: Some(dropped_tx),
+ }));
+ let mut element = node("Button", "Allow", &["Invoke"]);
+ element.element_ptr = ptr as usize;
+ let owned = ConsentNodes(vec![element]);
+ ready_tx.send(()).unwrap();
+ finish_rx.recv().unwrap();
+ owned
+ });
+ ready_rx.await.unwrap();
+ drop(scan);
+ finish_tx.send(()).unwrap();
+ tokio::time::timeout(Duration::from_secs(2), dropped_rx)
+ .await
+ .unwrap()
+ .unwrap();
+ }
+
#[test]
fn matcher_is_language_independent_across_localized_native_dialogs() {
for (title, labels) in [