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
refactor(cua-driver): share lock-map and session identity helpers (#4142)
Francesco Bonacci02534af16613
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.rsindex 5f4d1a0760..73bdd663e4 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@@ -45,7 +45,7 @@ use super::platform::{BrowserVisualActionKind, ExistingProfileSetupRequest,};use super::prepare::ManagedBrowsers;-use super::reconnect::ReconnectGates;+use super::reconnect::{ReconnectGates, ReconnectKey};use super::refusal::{BrowserRefusal, BrowserRefusalCode};use super::semantic::{build_dom_index, build_layout_index, compose_accessibility_tree, parse_viewport,@@ -835,7 +835,10 @@ impl BrowserEngine {// socket rather than opening another browser-level connection.let _leader = self.reconnect_gates- .lock(&grant.fingerprint, &grant.endpoint_ws_url)+ .lock(ReconnectKey::new(+ &grant.fingerprint,+ &grant.endpoint_ws_url,+ )).await;let mut grant = self.existing_profile_grant(session, transport_session, pid)diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/keyed_gates.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/keyed_gates.rsnew file mode 100644index 0000000000..19ffdf3225--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/keyed_gates.rs@@ -0,0 +1,67 @@+//! Keyed async gates: callers with the same key serialize, and callers with+//! different keys proceed independently.+//!+//! Browser mutation and reconnect leadership both key on process identity+//! plus one CDP resource. They differ only in the key, so they share this map.++use std::collections::HashMap;+use std::hash::Hash;+use std::sync::{Arc, Mutex};++use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard};++pub(crate) struct KeyedGates<K> {+ gates: Mutex<HashMap<K, Arc<AsyncMutex<()>>>>,+}++impl<K> Default for KeyedGates<K> {+ fn default() -> Self {+ Self {+ gates: Mutex::new(HashMap::new()),+ }+ }+}++impl<K: Eq + Hash> KeyedGates<K> {+ pub fn new() -> Self {+ Self::default()+ }++ /// Wait for exclusive ownership of `key`. The gate is held until the+ /// returned guard drops.+ pub async fn lock(&self, key: K) -> OwnedMutexGuard<()> {+ let gate = self+ .gates+ .lock()+ .unwrap()+ .entry(key)+ .or_insert_with(|| Arc::new(AsyncMutex::new(())))+ .clone();+ gate.lock_owned().await+ }+}++#[cfg(test)]+mod tests {+ use super::KeyedGates;+ use std::time::Duration;++ #[tokio::test]+ async fn same_key_serializes_and_different_keys_do_not_block() {+ let gates = KeyedGates::new();+ let first = gates.lock("a").await;++ assert!(+ tokio::time::timeout(Duration::from_millis(20), gates.lock("a"))+ .await+ .is_err(),+ "the same key must wait for the live holder"+ );+ tokio::time::timeout(Duration::from_millis(20), gates.lock("b"))+ .await+ .expect("an independent key must not block");++ drop(first);+ let _next = gates.lock("a").await;+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mod.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mod.rsindex 8d6e5534e5..8462884713 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mod.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mod.rs@@ -41,6 +41,7 @@ pub mod cdp_ws;pub mod download;pub mod engine;mod grant;+mod keyed_gates;#[cfg(test)]pub(crate) mod mock_cdp;mod mutation;diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mutation.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mutation.rsindex dfe5425665..a901dd4016 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mutation.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mutation.rs@@ -4,11 +4,7 @@//! therefore key on process identity plus the real CDP target so two sessions//! addressing one tab serialize while independently proven tabs can proceed.-use std::collections::HashMap;-use std::sync::{Arc, Mutex};--use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard};-+use super::keyed_gates::KeyedGates;use super::types::ProcessFingerprint;#[derive(Debug, Clone, PartialEq, Eq, Hash)]@@ -30,69 +26,4 @@ impl MutationKey {}}-#[derive(Default)]-pub(crate) struct MutationGates {- gates: Mutex<HashMap<MutationKey, Arc<AsyncMutex<()>>>>,-}--impl MutationGates {- pub fn new() -> Self {- Self::default()- }-- pub async fn lock(&self, key: MutationKey) -> OwnedMutexGuard<()> {- let gate = self- .gates- .lock()- .unwrap()- .entry(key)- .or_insert_with(|| Arc::new(AsyncMutex::new(())))- .clone();- gate.lock_owned().await- }-}--#[cfg(test)]-mod tests {- use super::*;-- fn fingerprint() -> ProcessFingerprint {- ProcessFingerprint {- pid: 42,- start_time: Some(1),- executable: Some("chrome".to_owned()),- }- }-- #[tokio::test]- async fn same_real_tab_serializes_across_callers() {- let gates = MutationGates::new();- let key = MutationKey::new(&fingerprint(), "target-a");- let first = gates.lock(key.clone()).await;- let second = tokio::time::timeout(- std::time::Duration::from_millis(20),- gates.lock(key.clone()),- )- .await;- assert!(- second.is_err(),- "same target must wait for the live mutation"- );- drop(first);- let _next = gates.lock(key).await;- }-- #[tokio::test]- async fn independent_tabs_do_not_block_each_other() {- let gates = MutationGates::new();- let _first = gates- .lock(MutationKey::new(&fingerprint(), "target-a"))- .await;- tokio::time::timeout(- std::time::Duration::from_millis(20),- gates.lock(MutationKey::new(&fingerprint(), "target-b")),- )- .await- .expect("independent target should not block");- }-}+pub(crate) type MutationGates = KeyedGates<MutationKey>;diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/reconnect.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/reconnect.rsindex a6e328c98d..b6b14ad68f 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/reconnect.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/reconnect.rs@@ -4,15 +4,11 @@//! single-flight on the approved process fingerprint and endpoint while//! unrelated browsers remain independent.-use std::collections::HashMap;-use std::sync::{Arc, Mutex};--use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard};-+use super::keyed_gates::KeyedGates;use super::types::ProcessFingerprint;#[derive(Debug, Clone, PartialEq, Eq, Hash)]-struct ReconnectKey {+pub(crate) struct ReconnectKey {pid: i64,start_time: Option<u64>,executable: Option<String>,@@ -20,7 +16,7 @@ struct ReconnectKey {}impl ReconnectKey {- fn new(fingerprint: &ProcessFingerprint, endpoint_ws_url: &str) -> Self {+ pub fn new(fingerprint: &ProcessFingerprint, endpoint_ws_url: &str) -> Self {Self {pid: fingerprint.pid,start_time: fingerprint.start_time,@@ -30,71 +26,4 @@ impl ReconnectKey {}}-#[derive(Default)]-pub(crate) struct ReconnectGates {- gates: Mutex<HashMap<ReconnectKey, Arc<AsyncMutex<()>>>>,-}--impl ReconnectGates {- pub fn new() -> Self {- Self::default()- }-- pub async fn lock(- &self,- fingerprint: &ProcessFingerprint,- endpoint_ws_url: &str,- ) -> OwnedMutexGuard<()> {- let gate = self- .gates- .lock()- .unwrap()- .entry(ReconnectKey::new(fingerprint, endpoint_ws_url))- .or_insert_with(|| Arc::new(AsyncMutex::new(())))- .clone();- gate.lock_owned().await- }-}--#[cfg(test)]-mod tests {- use super::*;-- fn fingerprint(pid: i64) -> ProcessFingerprint {- ProcessFingerprint {- pid,- start_time: Some(11),- executable: Some("chrome".to_owned()),- }- }-- #[tokio::test]- async fn same_browser_has_one_reconnect_leader() {- let gates = ReconnectGates::new();- let identity = fingerprint(42);- let endpoint = "ws://127.0.0.1:1/devtools/browser/a";- let first = gates.lock(&identity, endpoint).await;- assert!(tokio::time::timeout(- std::time::Duration::from_millis(20),- gates.lock(&identity, endpoint),- )- .await- .is_err());- drop(first);- let _next = gates.lock(&identity, endpoint).await;- }-- #[tokio::test]- async fn unrelated_browsers_reconnect_independently() {- let gates = ReconnectGates::new();- let _first = gates- .lock(&fingerprint(42), "ws://127.0.0.1:1/devtools/browser/a")- .await;- tokio::time::timeout(- std::time::Duration::from_millis(20),- gates.lock(&fingerprint(43), "ws://127.0.0.1:2/devtools/browser/b"),- )- .await- .expect("an unrelated browser must not wait on another prompt");- }-}+pub(crate) type ReconnectGates = KeyedGates<ReconnectKey>;diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool_args.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool_args.rsindex be38fee372..56fa539c22 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool_args.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool_args.rs@@ -104,6 +104,108 @@ pub fn sanitize_reserved_args(args: &mut Value) {}}+/// Resolve and apply the session identity for one tool call at a trusted+/// transport boundary, returning the effective `_session_id`.+///+/// Public naming and the transport's lifecycle identity resolve+/// independently. A non-empty `session` label is mirrored into the reserved+/// `_session_id`; otherwise the transport's own session (a per-connection+/// lease or MCP HTTP session) becomes the implicit lifecycle key.+/// `_transport_session_id` always carries the transport session. Any+/// caller-supplied value for either reserved key is replaced, never trusted.+/// With neither a label nor a transport session the call stays anonymous.+pub fn apply_session_identity(args: &mut Value, transport_session: Option<&str>) -> Option<String> {+ let object = args.as_object_mut()?;+ let effective = object+ .get("session")+ .and_then(Value::as_str)+ .filter(|session| !session.is_empty())+ .or(transport_session)+ .map(str::to_owned);+ object.remove("_session_id");+ object.remove("_transport_session_id");+ if let Some(id) = &effective {+ object.insert("_session_id".to_owned(), Value::String(id.clone()));+ }+ if let Some(id) = transport_session {+ object.insert(+ "_transport_session_id".to_owned(),+ Value::String(id.to_owned()),+ );+ }+ effective+}++#[cfg(test)]+mod session_identity_tests {+ use super::apply_session_identity;+ use serde_json::json;++ #[test]+ fn public_label_and_transport_session_resolve_independently() {+ // (args, transport session) -> (effective _session_id, _transport_session_id)+ for (mut args, transport, session_id, transport_id) in [+ (+ json!({ "x": 1, "session": "research-1" }),+ None,+ Some("research-1"),+ None,+ ),+ (+ json!({ "session": "capability-session" }),+ Some("proxy-session"),+ Some("capability-session"),+ Some("proxy-session"),+ ),+ // The transport session drives the implicit lifecycle without+ // manufacturing a caller-visible public `session` label.+ (+ json!({ "x": 1 }),+ Some("mcp-123"),+ Some("mcp-123"),+ Some("mcp-123"),+ ),+ (+ json!({ "session": "" }),+ Some("mcp-1"),+ Some("mcp-1"),+ Some("mcp-1"),+ ),+ (json!({ "x": 1 }), None, None, None),+ // Caller-supplied reserved keys are replaced or removed.+ (+ json!({ "_session_id": "caller-set", "_transport_session_id": "forged" }),+ Some("mcp-999"),+ Some("mcp-999"),+ Some("mcp-999"),+ ),+ (+ json!({ "_session_id": "caller-set", "_transport_session_id": "forged" }),+ None,+ None,+ None,+ ),+ ] {+ let before = args.clone();+ let effective = apply_session_identity(&mut args, transport);+ assert_eq!(effective.as_deref(), session_id, "{before}");+ assert_eq!(args["_session_id"].as_str(), session_id, "{before}");+ assert_eq!(+ args["_transport_session_id"].as_str(),+ transport_id,+ "{before}"+ );+ assert_eq!(args.get("session"), before.get("session"), "{before}");+ }++ let mut not_an_object = json!(["session"]);+ assert_eq!(+ apply_session_identity(&mut not_an_object, Some("mcp")),+ None+ );+ }+}+/// The session key an isolation-scoped state store should key on for this/// call: the public `session` label, else the proxy-minted `_session_id`,/// else the legacy `cursor_id`, else a shared `"default"` bucket fordiff --git a/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs b/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rsindex 4a61d595a0..414b3e2366 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs@@ -258,31 +258,19 @@ fn serialize(resp: &Response) -> String {})}-/// Mirror an explicit `session` arg into `_session_id` (the per-session config /-/// recording key) — the HTTP-side equivalent of-/// `serve.rs::apply_session_identity`. Runtime-private idle-TTL activity is-/// refreshed later at the authorized registry boundary.+/// Apply the shared session identity mapping+/// ([`cua_driver_core::tool_args::apply_session_identity`]) to a tool call's+/// arguments, with the MCP HTTP session as the transport session.+/// Runtime-private idle-TTL activity is refreshed later at the authorized+/// registry boundary.fn apply_session_identity(req: &mut Request, transport_session: &str) {- let Some(params) = req.params.as_mut() else {- return;- };- let Some(args) = params.get_mut("arguments").and_then(|a| a.as_object_mut()) else {- return;- };- let session = args- .get("session")- .and_then(|v| v.as_str())- .filter(|s| !s.is_empty())- .map(|s| s.to_owned());- let effective = session.unwrap_or_else(|| transport_session.to_owned());- args.insert(- "_session_id".to_owned(),- serde_json::Value::String(effective),- );- args.insert(- "_transport_session_id".to_owned(),- serde_json::Value::String(transport_session.to_owned()),- );+ if let Some(args) = req+ .params+ .as_mut()+ .and_then(|params| params.get_mut("arguments"))+ {+ cua_driver_core::tool_args::apply_session_identity(args, Some(transport_session));+ }}/// One parsed HTTP/1.1 request.@@ -613,20 +601,6 @@ mod tests {sdk.shutdown().await.expect("SDK shutdown");}- #[test]- fn apply_session_identity_mirrors_session_to_session_id() {- let mut req: Request = serde_json::from_value(json!({- "jsonrpc": "2.0", "id": 1, "method": "tools/call",- "params": { "name": "click", "arguments": { "pid": 1, "session": "alpha" } }- }))- .unwrap();- apply_session_identity(&mut req, "http-test");- let args = req.params.unwrap();- let args = args.get("arguments").unwrap();- assert_eq!(args.get("_session_id").unwrap(), "alpha");- assert_eq!(args.get("session").unwrap(), "alpha");- }-#[test]fn apply_session_identity_uses_transport_implicit_without_session() {let mut req: Request = serde_json::from_value(json!({diff --git a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs b/libs/cua-driver/rust/crates/cua-driver/src/serve.rsindex 67e123bc78..f06bcc2f36 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs@@ -163,43 +163,6 @@ fn inject_browser_approvals(tool_name: &str, args: &mut serde_json::Value, sessi}}-/// Resolve + apply the session identity for a tool call at the daemon boundary.-///-/// Resolve optional public naming and the trusted transport's default lifecycle-/// identity independently. An explicit `session` is mirrored into the reserved-/// `_session_id` key; otherwise the per-connection lease id becomes the implicit-/// lifecycle key. Cursor, recording, configuration, and cleanup all use that-/// resolved identity, so ordinary callers do not need a setup call.-///-/// The registry refreshes the runtime-private idle-TTL key after authorization;-/// this transport helper only returns the effective `_session_id` for the-/// resurrection guard.-fn apply_session_identity(args: &mut serde_json::Value, minted: &Option<String>) -> Option<String> {- let explicit = args- .as_object()- .and_then(|o| o.get("session"))- .and_then(|v| v.as_str())- .filter(|s| !s.is_empty())- .map(|s| s.to_owned());- if let Some(obj) = args.as_object_mut() {- obj.remove("_session_id");- obj.remove("_transport_session_id");- if let Some(id) = explicit.clone().or_else(|| minted.clone()) {- obj.insert("_session_id".to_owned(), serde_json::Value::String(id));- }- if let Some(id) = minted.clone() {- obj.insert(- "_transport_session_id".to_owned(),- serde_json::Value::String(id),- );- }- }- args.as_object()- .and_then(|o| o.get("_session_id"))- .and_then(|v| v.as_str())- .map(|s| s.to_owned())-}-/// Whether `tool_name` manages session lifecycle and so must be EXEMPT from the/// resurrection guard. `start_session` revives an ended id (the explicit,/// caller-intended way to reuse one) and `end_session` is idempotent — both@@ -487,7 +450,8 @@ async fn invoke_daemon_tool(.args.unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new()));cua_driver_core::tool_args::sanitize_reserved_args(&mut args);- let effective_session = apply_session_identity(&mut args, &req.session_id);+ let effective_session =+ cua_driver_core::tool_args::apply_session_identity(&mut args, req.session_id.as_deref());let operation = cua_driver_core::server::tool_operation(&tool_name, Some(&args));let observation = observation_transport.map(|transport| {(@@ -2974,58 +2938,10 @@ mod service_authorization_status_tests {#[cfg(test)]mod session_boundary_tests {- use super::{active_proxy_sessions, apply_session_identity, inject_browser_approvals};+ use super::{active_proxy_sessions, inject_browser_approvals};use cua_driver_core::browser::download::MCP_HOST_DOWNLOAD_APPROVAL_ARG;use serde_json::json;- #[test]- fn explicit_session_becomes_session_id_and_is_returned() {- let mut args = json!({ "x": 1, "session": "research-1" });- let eff = apply_session_identity(&mut args, &None);- assert_eq!(eff.as_deref(), Some("research-1"));- assert_eq!(args["_session_id"], "research-1");- assert!(args.get("_transport_session_id").is_none());- }-- #[test]- fn public_and_transport_sessions_remain_independent() {- let mut args = json!({ "session": "capability-session" });- let eff = apply_session_identity(&mut args, &Some("proxy-session".to_owned()));- assert_eq!(eff.as_deref(), Some("capability-session"));- assert_eq!(args["_session_id"], "capability-session");- assert_eq!(args["_transport_session_id"], "proxy-session");- }-- #[test]- fn no_session_falls_back_to_minted_for_session_id_only() {- // The minted per-connection id drives the complete implicit lifecycle,- // including cursor, recording, configuration, and cleanup, without- // manufacturing a caller-visible public `session` label.- let mut args = json!({ "x": 1 });- let eff = apply_session_identity(&mut args, &Some("mcp-123".to_owned()));- assert_eq!(args["_session_id"], "mcp-123");- assert_eq!(eff.as_deref(), Some("mcp-123"));- assert_eq!(args["_transport_session_id"], "mcp-123");- assert!(args.get("session").is_none());- }-- #[test]- fn anonymous_when_no_session_and_no_minted() {- let mut args = json!({ "x": 1 });- let eff = apply_session_identity(&mut args, &None);- assert!(eff.is_none());- assert!(args.get("_session_id").is_none());- }-- #[test]- fn caller_set_session_id_is_replaced_by_minted() {- let mut args = json!({ "_session_id": "caller-set" });- let eff = apply_session_identity(&mut args, &Some("mcp-999".to_owned()));- assert_eq!(args["_session_id"], "mcp-999");- assert_eq!(args["_transport_session_id"], "mcp-999");- assert_eq!(eff.as_deref(), Some("mcp-999"));- }-#[test]fn browser_download_approval_requires_a_live_proxy_session() {let session = "approval-boundary-test";