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): commit or roll back browser setup explicitly (#6808)
injaneity169a6c6c5ffd
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.rsindex e5746627ec..29872fef84 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@@ -224,9 +224,15 @@ fn with_prepare_side_effects(error}+/// An existing-profile setup the platform holds open until core calls+/// `commit` or `rollback`. Drop rolls back only a request that was cancelled+/// mid-flight, and logs it.struct PendingExistingProfileSetup {platform: Arc<dyn super::platform::BrowserPlatform>,- request: Option<ExistingProfileSetupRequest>,+ request: ExistingProfileSetupRequest,+ // Set only once the platform call returns, so a cancellation while it is+ // awaited still reaches the Drop backstop.+ settled: bool,}impl PendingExistingProfileSetup {@@ -236,52 +242,68 @@ impl PendingExistingProfileSetup {) -> Self {Self {platform,- request: Some(request),+ request,+ settled: false,}}- async fn abort(&mut self, error: BrowserRefusal) -> BrowserRefusal {- let Some(request) = self.request.clone() else {- return error;- };+ async fn rollback(mut self, error: BrowserRefusal) -> BrowserRefusal {let result = self.platform- .abort_existing_profile_setup(request, error)+ .abort_existing_profile_setup(self.request.clone(), error).await;- self.request = None;+ self.settled = true;result}- async fn commit(&mut self) -> Result<bool, BrowserRefusal> {- let request = self.request.clone().ok_or_else(|| {- BrowserRefusal::new(- BrowserRefusalCode::BrowserBindingStale,- "the pending browser setup was already finalized",- )- })?;- let result = self.platform.commit_existing_profile_setup(request).await;- if result.is_ok() {- self.request = None;- }+ /// A failed commit is rolled back by the platform before it returns.+ async fn commit(mut self) -> Result<bool, BrowserRefusal> {+ let result = self+ .platform+ .commit_existing_profile_setup(self.request.clone())+ .await;+ self.settled = true;result}}+async fn rollback_pending_setup(+ setup: Option<PendingExistingProfileSetup>,+ error: BrowserRefusal,+) -> BrowserRefusal {+ match setup {+ Some(setup) => setup.rollback(error).await,+ None => error,+ }+}+impl Drop for PendingExistingProfileSetup {fn drop(&mut self) {- let Some(request) = self.request.take() else {+ if self.settled {+ return;+ }+ let request = self.request.clone();+ let Ok(runtime) = tokio::runtime::Handle::try_current() else {+ tracing::error!(+ pid = request.pid,+ window_id = request.window_id,+ "existing-profile setup dropped outside a runtime; its pending setup was not rolled back"+ );return;};+ tracing::warn!(+ pid = request.pid,+ window_id = request.window_id,+ "existing-profile setup dropped before commit or rollback; scheduling rollback"+ );let platform = self.platform.clone();let error = BrowserRefusal::new(BrowserRefusalCode::BrowserBindingStale,"the existing-profile setup request ended before commit; rolling back its exact pending setup",);- if let Ok(runtime) = tokio::runtime::Handle::try_current() {- runtime.spawn(async move {- let _ = platform.abort_existing_profile_setup(request, error).await;- });- }+ runtime.spawn(async move {+ let _ = platform.abort_existing_profile_setup(request, error).await;+ });}}@@ -1166,8 +1188,7 @@ impl BrowserEngine {window_id,browser: classification.product_kind,};- let mut setup_pending = false;- let mut setup_guard = None;+ let mut pending_setup = None;let mut endpoint = self.platform.discover_existing_profile_endpoint(pid)@@ -1177,8 +1198,7 @@ impl BrowserEngine {.platform.setup_existing_profile_endpoint(setup_request.clone()).await?;- setup_pending = true;- setup_guard = Some(PendingExistingProfileSetup::new(+ pending_setup = Some(PendingExistingProfileSetup::new(self.platform.clone(),setup_request.clone(),));@@ -1187,20 +1207,20 @@ impl BrowserEngine {// process/window generation. Re-prove both before accepting the// newly exposed listener.if let Err(error) = self.native_window_checked(pid, window_id).await {- return Err(setup_guard- .as_mut()- .expect("setup guard exists while setup is pending")- .abort(with_setup_side_effects(error, &setup))- .await);+ return Err(rollback_pending_setup(+ pending_setup,+ with_setup_side_effects(error, &setup),+ )+ .await);}let current_fingerprint = match self.platform.process_fingerprint(pid).await {Ok(fingerprint) => fingerprint,Err(error) => {- return Err(setup_guard- .as_mut()- .expect("setup guard exists while setup is pending")- .abort(with_setup_side_effects(error, &setup))- .await)+ return Err(rollback_pending_setup(+ pending_setup,+ with_setup_side_effects(error, &setup),+ )+ .await)}};if current_fingerprint != fingerprint {@@ -1211,22 +1231,18 @@ impl BrowserEngine {),&setup,);- return Err(setup_guard- .as_mut()- .expect("setup guard exists while setup is pending")- .abort(error)- .await);+ return Err(rollback_pending_setup(pending_setup, error).await);}endpoint = setup.endpoint.clone();if endpoint.is_none() {endpoint = match self.platform.discover_existing_profile_endpoint(pid).await {Ok(endpoint) => endpoint,Err(error) => {- return Err(setup_guard- .as_mut()- .expect("setup guard exists while setup is pending")- .abort(with_setup_side_effects(error, &setup))- .await)+ return Err(rollback_pending_setup(+ pending_setup,+ with_setup_side_effects(error, &setup),+ )+ .await)}};}@@ -1238,14 +1254,7 @@ impl BrowserEngine {BrowserRefusalCode::BrowserRequiresSetup,"the approved browser still has no uniquely proven DevTools endpoint after bounded setup",), &setup);- if setup_pending {- return Err(setup_guard- .as_mut()- .expect("setup guard exists while setup is pending")- .abort(error)- .await);- }- return Err(error);+ return Err(rollback_pending_setup(pending_setup, error).await);}};if endpoint.ownership.owner_pid != pid {@@ -1256,14 +1265,7 @@ impl BrowserEngine {),&setup,);- if setup_pending {- return Err(setup_guard- .as_mut()- .expect("setup guard exists while setup is pending")- .abort(error)- .await);- }- return Err(error);+ return Err(rollback_pending_setup(pending_setup, error).await);}// Host authorization is requested only after the exact process,@@ -1293,23 +1295,22 @@ impl BrowserEngine {classification.product_kind, window_id),);- Some(- self.approval_broker- .approve(&approval_request)- .await- .map_err(|error| {- BrowserRefusal::new(- BrowserRefusalCode::BrowserConsentRequired,- format!("existing-profile authorization was not granted: {error}"),- )- .with_detail(serde_json::json!({- "permission_mode": mode.as_str(),- "trusted_consent_required": true,- "provider": self.approval_broker.provider_id(),- "approval_request_id": approval_request.nonce,- }))- })?,- )+ match self.approval_broker.approve(&approval_request).await {+ Ok(consent) => Some(consent),+ Err(error) => {+ let error = BrowserRefusal::new(+ BrowserRefusalCode::BrowserConsentRequired,+ format!("existing-profile authorization was not granted: {error}"),+ )+ .with_detail(serde_json::json!({+ "permission_mode": mode.as_str(),+ "trusted_consent_required": true,+ "provider": self.approval_broker.provider_id(),+ "approval_request_id": approval_request.nonce,+ }));+ return Err(rollback_pending_setup(pending_setup, error).await);+ }+ }} else {None};@@ -1324,14 +1325,7 @@ impl BrowserEngine {self.approval_broker.revoke(protected).await;}let error = with_setup_side_effects(error, &setup);- if setup_pending {- return Err(setup_guard- .as_mut()- .expect("setup guard exists while setup is pending")- .abort(error)- .await);- }- return Err(error);+ return Err(rollback_pending_setup(pending_setup, error).await);}};let previous_generation = previous_grant.as_ref().map_or(0, |grant| grant.generation);@@ -1389,14 +1383,7 @@ impl BrowserEngine {).await;let error = with_setup_side_effects(error, &setup);- if setup_pending {- return Err(setup_guard- .as_mut()- .expect("setup guard exists while setup is pending")- .abort(error)- .await);- }- return Err(error);+ return Err(rollback_pending_setup(pending_setup, error).await);}};// Chrome on Windows can reject the WebSocket handshake that was@@ -1430,14 +1417,7 @@ impl BrowserEngine {).await;let error = with_prepare_side_effects(error, &setup, displayed_consent_prompt);- if setup_pending {- return Err(setup_guard- .as_mut()- .expect("setup guard exists while setup is pending")- .abort(error)- .await);- }- return Err(error);+ return Err(rollback_pending_setup(pending_setup, error).await);}};let displayed_consent_prompt = displayed_consent_prompt || fresh_consent_prompt;@@ -1460,22 +1440,10 @@ impl BrowserEngine {&setup,displayed_consent_prompt,);- if setup_pending {- return Err(setup_guard- .as_mut()- .expect("setup guard exists while setup is pending")- .abort(error)- .await);- }- return Err(error);+ return Err(rollback_pending_setup(pending_setup, error).await);}- if setup_pending {- match setup_guard- .as_mut()- .expect("setup guard exists while setup is pending")- .commit()- .await- {+ if let Some(pending_setup) = pending_setup {+ match pending_setup.commit().await {Ok(closed) => setup.closed_setup_page = closed,Err(error) => {self.revoke_existing_profile_grant(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 7ea7147cd6..5ea9be67d6 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@@ -1948,6 +1948,66 @@ async fn cancelled_prepare_aborts_the_exact_pending_setup() {stalled_server.abort();}+struct DecliningProtectedProvider;++#[async_trait]+impl crate::consent::ProtectedConsentProvider for DecliningProtectedProvider {+ fn provider_id(&self) -> &'static str {+ "test.browser-declining-provider"+ }++ async fn request_consent(+ &self,+ request: &crate::consent::ConsentRequest,+ ) -> Result<crate::consent::ProviderDecision, String> {+ Ok(crate::consent::ProviderDecision {+ action: crate::consent::ConsentAction::Decline,+ request_digest: request.request_digest.clone(),+ })+ }+}++#[tokio::test]+async fn declined_consent_rolls_back_pending_setup_before_refusing() {+ let setup_aborted = Arc::new(AtomicBool::new(false));+ let engine = BrowserEngine::new_with_protected_consent_provider(+ Arc::new(FixturePlatform {+ endpoint_state: None,+ ws_url: "ws://127.0.0.1:9/devtools/browser".to_owned(),+ trusted_input_limited: false,+ managed_endpoint_visible: false,+ process_role: BrowserProcessRole::StandaloneConsumer,+ managed_discovery_invoked: Arc::new(AtomicBool::new(false)),+ existing_endpoint_visible: Arc::new(AtomicBool::new(false)),+ setup_invoked: Arc::new(AtomicBool::new(false)),+ setup_aborted: setup_aborted.clone(),+ stall_consent: false,+ focus: Default::default(),+ }),+ Some(Arc::new(DecliningProtectedProvider)),+ );+ let refused = BrowserPrepareTool::new(engine)+ .invoke(json!({+ "pid": 1,+ "window_id": 7,+ "session": SESSION,+ "strategy": { "kind": "existing_profile" }+ }))+ .await;+ assert_eq!(+ structured(&refused)["refusal"]["code"],+ "browser_consent_required",+ "{}",+ structured(&refused)+ );+ // Checked before yielding: a rollback left to the Drop backstop would+ // only be spawned, not finished, when the refusal returns.+ assert!(+ setup_aborted.load(Ordering::SeqCst),+ "declined consent must roll back the pending setup before refusing"+ );+}+async fn snapshot(f: &Fixture, target_id: &str, tab_id: &str) -> Value {let tool = GetBrowserStateTool::new(f.engine.clone());let result = tool