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-spaces): save relay-reported.json off the connect path (#6456)
injaneity2acdbd9f690c
diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rsindex 7203f5923f..fadd47e14e 100644--- a/libs/cua/crates/cua-spaces/src/spaces.rs+++ b/libs/cua/crates/cua-spaces/src/spaces.rs@@ -16,6 +16,7 @@ use cua_spacesd_client::{ConnectOptions, SpacesdClient, pb};use std::collections::{BTreeMap, HashMap};use std::path::{Path, PathBuf};use std::sync::Arc;+use std::sync::atomic::{AtomicBool, Ordering};use std::time::{Duration, SystemTime};/// Default time allowed for the `GetCapabilities` handshake.@@ -401,6 +402,7 @@ impl SpacesBuilder {relay_cache: std::sync::Mutex::new(Vec::new()),team_facts: std::sync::Mutex::new(Default::default()),relay_reported: std::sync::Mutex::new(relay_reported),+ reported_saves: Default::default(),relay_read: tokio::sync::Mutex::new(None),relay_confirmed: std::sync::atomic::AtomicBool::new(false),rounds: Default::default(),@@ -517,7 +519,7 @@ pub(crate) fn os_names(space: &Space) -> (String, String) {/// What a relay machine's cua-spacesd reported about itself at connect./// Kept in `relay-reported.json` in the cua home, so a later process (the/// CLI, another app) lists the machine's OS without connecting first.-#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]+#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]#[serde(default)]struct ReportedFacts {os: String,@@ -528,6 +530,12 @@ struct ReportedFacts {const RELAY_REPORTED_FILE: &str = "relay-reported.json";+#[derive(Default)]+struct ReportedSaves {+ dirty: AtomicBool,+ running: AtomicBool,+}+/// What earlier processes learned from relay machines (empty when none, or/// unreadable).fn load_reported(home: &Path) -> HashMap<String, ReportedFacts> {@@ -642,6 +650,9 @@ pub(crate) struct Inner {/// process last connected to it (by `relay:<id>`): the directory/// listing carries no OS, so without it a Mac lists as Linux.relay_reported: std::sync::Mutex<HashMap<String, ReportedFacts>>,+ /// Whether `relay_reported` has changes not yet on disk, and whether a+ /// save is running ([`Spaces::remember_reported`]).+ reported_saves: ReportedSaves,/// Held across a read so only one directory read runs at a time.relay_read: tokio::sync::Mutex<Option<std::time::Instant>>,/// The relay answered a directory read in this process (until then the@@ -1518,12 +1529,39 @@ impl Spaces {os_pretty_name,arch,};- let mut reported = self.inner.relay_reported.lock().expect("relay reported");- reported.insert(key.to_string(), facts);- // Best effort: the listing in this process has it either way.- if let Err(e) = save_reported(self.home_dir(), &reported) {- tracing::debug!(error = %e, "relay-reported.json not written");+ {+ let mut reported = self.inner.relay_reported.lock().expect("relay reported");+ if reported.get(key) == Some(&facts) {+ return;+ }+ reported.insert(key.to_string(), facts);+ }+ // Saved off the connect path, one save at a time: a launch connects+ // to every Space at once, and a synced write per connect held up+ // the runtime. A change made while a save runs gets one more save.+ let saves = &self.inner.reported_saves;+ saves.dirty.store(true, Ordering::SeqCst);+ if saves.running.swap(true, Ordering::SeqCst) {+ return;}+ let inner = self.inner.clone();+ tokio::task::spawn_blocking(move || {+ let saves = &inner.reported_saves;+ loop {+ while saves.dirty.swap(false, Ordering::SeqCst) {+ let snapshot = inner.relay_reported.lock().expect("relay reported").clone();+ // Best effort: the listing in this process has it either way.+ if let Err(e) = save_reported(inner.registry.dir(), &snapshot) {+ tracing::debug!(error = %e, "relay-reported.json not written");+ }+ }+ saves.running.store(false, Ordering::SeqCst);+ if !saves.dirty.load(Ordering::SeqCst) || saves.running.swap(true, Ordering::SeqCst)+ {+ return;+ }+ }+ });}/// A relay machine's listing, with what its cua-spacesd reported (itdiff --git a/libs/cua/crates/cua-spaces/tests/relay.rs b/libs/cua/crates/cua-spaces/tests/relay.rsindex c8e33dca2b..2204443254 100644--- a/libs/cua/crates/cua-spaces/tests/relay.rs+++ b/libs/cua/crates/cua-spaces/tests/relay.rs@@ -237,6 +237,72 @@ async fn connects_through_the_relay_path_with_the_account_token_per_call() {assert!(wrong.space(&format!("relay:{MACHINE}")).await.is_err());}+/// What a relay machine reported at connect reaches the next process: the+/// CLI lists the machine's OS without connecting first.+#[tokio::test]+async fn a_later_process_lists_the_os_a_relay_machine_reported() {+ let relay = FakeRelay::start().await;+ relay.add_account("tok", "ada", None);+ cua_host::RelayClient::new(&relay.url)+ .unwrap()+ .register(+ "tok",+ &cua_host::relay::RegisterRequest {+ id: MACHINE.into(),+ name: "studio".into(),+ allow: vec![],+ host: None,+ meta: Default::default(),+ },+ )+ .await+ .unwrap();+ relay.set_online(MACHINE, true, "1.0.0");+ let srv = MockServer::start(MockAuth {+ token: None,+ gateway: None,+ prefix: None,+ })+ .await;+ relay.tunnel(MACHINE, &srv.url());+ let home = tempfile::tempdir().unwrap();+ let build = || {+ Spaces::builder()+ .home(home.path())+ .relay(RelayAccount::new(+ relay.url.clone(),+ Arc::new(StaticToken("tok".into())),+ ))+ .build()+ };+ let id = format!("relay:{MACHINE}");+ let first = build();+ first.list_all().await.unwrap();+ first.space(&id).await.unwrap();+ let os = |s: &Spaces| {+ s.list()+ .unwrap()+ .into_iter()+ .find(|i| i.id == id)+ .map(|i| i.os)+ };+ // Saved in the background: give it a moment.+ let deadline = std::time::Instant::now() + Duration::from_secs(10);+ loop {+ let later = build();+ later.list_all().await.unwrap();+ if os(&later).as_deref() == Some("linux") {+ break;+ }+ assert!(+ std::time::Instant::now() < deadline,+ "listed {:?}",+ os(&later)+ );+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+}+/// The relay requires an enrolled client device: the account token alone/// lists nothing, and with the device every directory call and every/// connection to `relay:<id>` carries the device's session.