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): report a timed-out capture worker to the next caller (#6809)
injaneity85f9187d0c04
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/capture.rs b/libs/cua-driver/rust/crates/platform-macos/src/capture.rsindex d923830a8f..66e5a1bf85 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/capture.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/capture.rs@@ -48,7 +48,7 @@ use objc2::rc::autoreleasepool;use std::collections::HashMap;use std::hash::Hash;use std::process::Command;-use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::atomic::{AtomicU64, Ordering};use std::sync::{mpsc, Mutex, OnceLock};use std::time::{Duration, Instant};@@ -372,33 +372,68 @@ const WINDOW_CAPTURE_NATIVE_TIMEOUT: Duration = Duration::from_secs(3);/// Permit at most one ScreenCaptureKit worker. If an Apple completion callback/// never fires, the timed-out worker keeps this permit, and every later request/// goes straight to the compatibility fallback instead of leaking more-/// blocked threads.+/// blocked threads. The refusal says whether the holder is a live capture or a+/// worker its caller already gave up on.struct NativeCaptureGate {- active: AtomicBool,+ tickets: AtomicU64,+ state: Mutex<NativeCaptureState>,+}++/// `ticket` identifies one permit, so a caller that times out after its worker+/// released the gate cannot mark a newer caller's permit as stalled.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum NativeCaptureState {+ Idle,+ InFlight { ticket: u64 },+ Stalled { ticket: u64, since: Instant },}impl NativeCaptureGate {const fn new() -> Self {Self {- active: AtomicBool::new(false),+ tickets: AtomicU64::new(0),+ state: Mutex::new(NativeCaptureState::Idle),+ }+ }++ fn lock(&self) -> std::sync::MutexGuard<'_, NativeCaptureState> {+ self.state+ .lock()+ .unwrap_or_else(|poison| poison.into_inner())+ }++ /// On refusal, returns the state that holds the gate.+ fn try_acquire(&'static self) -> Result<NativeCapturePermit, NativeCaptureState> {+ let mut state = self.lock();+ match *state {+ NativeCaptureState::Idle => {+ let ticket = self.tickets.fetch_add(1, Ordering::Relaxed);+ *state = NativeCaptureState::InFlight { ticket };+ Ok(NativeCapturePermit { gate: self, ticket })+ }+ held => Err(held),}}- fn try_acquire(&'static self) -> Option<NativeCapturePermit> {- self.active- .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)- .ok()- .map(|_| NativeCapturePermit { gate: self })+ fn mark_stalled(&self, ticket: u64) {+ let mut state = self.lock();+ if *state == (NativeCaptureState::InFlight { ticket }) {+ *state = NativeCaptureState::Stalled {+ ticket,+ since: Instant::now(),+ };+ }}}struct NativeCapturePermit {gate: &'static NativeCaptureGate,+ ticket: u64,}impl Drop for NativeCapturePermit {fn drop(&mut self) {- self.gate.active.store(false, Ordering::Release);+ *self.gate.lock() = NativeCaptureState::Idle;}}@@ -416,9 +451,14 @@ whereT: Send + 'static,F: FnOnce() -> anyhow::Result<T> + Send + 'static,{- let permit = gate- .try_acquire()- .ok_or_else(|| anyhow::anyhow!("ScreenCaptureKit capture already in flight"))?;+ let permit = gate.try_acquire().map_err(|held| match held {+ NativeCaptureState::Stalled { since, .. } => anyhow::anyhow!(+ "a timed-out ScreenCaptureKit worker is still blocked after {} ms",+ since.elapsed().as_millis()+ ),+ _ => anyhow::anyhow!("ScreenCaptureKit capture already in flight"),+ })?;+ let ticket = permit.ticket;let (sender, receiver) = mpsc::sync_channel(1);std::thread::Builder::new().name("cua-sck-window-capture".into())@@ -432,6 +472,7 @@ wherematch receiver.recv_timeout(timeout) {Ok(result) => result,Err(mpsc::RecvTimeoutError::Timeout) => {+ gate.mark_stalled(ticket);anyhow::bail!("ScreenCaptureKit capture timed out after {} ms",timeout.as_millis()@@ -1568,17 +1609,32 @@ mod tests {let permit = GATE.try_acquire().expect("first worker acquires gate");assert!(- GATE.try_acquire().is_none(),+ matches!(GATE.try_acquire(), Err(NativeCaptureState::InFlight { .. })),"a second worker must fall back while the first is active");drop(permit);assert!(- GATE.try_acquire().is_some(),+ GATE.try_acquire().is_ok(),"gate reopens only when the worker-owned permit drops");}+ #[test]+ fn late_timeout_cannot_mark_a_newer_permit_stalled() {+ static GATE: NativeCaptureGate = NativeCaptureGate::new();++ let stale_ticket = GATE.try_acquire().expect("first permit").ticket;+ let current = GATE.try_acquire().expect("gate idle after drop");+ GATE.mark_stalled(stale_ticket);+ assert_eq!(+ *GATE.lock(),+ NativeCaptureState::InFlight {+ ticket: current.ticket+ }+ );+ }+#[test]fn pooled_native_worker_returns_work_result_and_error() {static GATE: NativeCaptureGate = NativeCaptureGate::new();@@ -1631,7 +1687,7 @@ mod tests {assert!(second.expect_err("replacement is refused while original remains blocked").to_string()- .contains("already in flight"));+ .contains("timed-out ScreenCaptureKit worker is still blocked"));assert_eq!(SPAWNED_WORK.load(AtomicOrdering::SeqCst),1,@@ -1640,10 +1696,10 @@ mod tests {release_sender.send(()).expect("release original worker");let deadline = Instant::now() + Duration::from_secs(1);- while GATE.active.load(AtomicOrdering::Acquire) && Instant::now() < deadline {+ while *GATE.lock() != NativeCaptureState::Idle && Instant::now() < deadline {std::thread::yield_now();}- assert!(!GATE.active.load(AtomicOrdering::Acquire));+ assert_eq!(*GATE.lock(), NativeCaptureState::Idle);assert_eq!(run_native_capture_worker(&GATE, Duration::from_secs(1), || {