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(spaces): say why a running Space is not on your account (#6536)
ddupont84a1353ca5ee
diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rsindex 9abf4e471a..d799517f87 100644--- a/libs/cua/crates/cua-cli/src/host.rs+++ b/libs/cua/crates/cua-cli/src/host.rs@@ -3190,6 +3190,20 @@ pub async fn run_host_to();} else {render(&s, out);+ if s.configured {+ let spaces = cua_spaces::Spaces::builder()+ .home(home)+ .relay(cua_spaces::RelayAccount::new(+ relay_url(None, home),+ Arc::new(SessionTokens),+ ))+ .build();+ if let Ok(list) = spaces.list() {+ for l in spaces.relay_publish_status(&list).await.notes() {+ line(out, format!(" {l}"));+ }+ }+ }for l in crate::resources_view::this_mac_lines(&resources) {line(out, l);}@@ -4276,6 +4290,11 @@ pub async fn run_spaces(own_machine: spaces.this_relay_machine_id(),};let on_account = spaces.relay_states(&list);+ let publish_notes = if spaces.relay_account().is_some() {+ spaces.relay_publish_status(&list).await.notes()+ } else {+ Vec::new()+ };if json {let mut rows = ls_json(&list);// Never holds the list up: signed out or a relay that does not@@ -4294,7 +4313,8 @@ pub async fn run_spaces(}}let mut body = serde_json::json!({ "spaces": rows, "machines": hosts, "durable": durable,- "relay_error": relay_error });+ "relay_error": relay_error,+ "account_notes": publish_notes });if let (Some(o), Some(extra)) = (body.as_object_mut(),crate::resources_view::ls_extras(&resources)@@ -4338,6 +4358,9 @@ pub async fn run_spaces(for line_text in hidden_notes(&list) {line(out, line_text);}+ for line_text in publish_notes {+ line(out, format!("({line_text})"));+ }let stay_off: Vec<&str> = list.iter().filter(|i| !i.hidden && on_account.get(&i.id) == Some(&"off"))diff --git a/libs/cua/crates/cua-spaces/src/share.rs b/libs/cua/crates/cua-spaces/src/share.rsindex 54c19d6361..b0ddce796d 100644--- a/libs/cua/crates/cua-spaces/src/share.rs+++ b/libs/cua/crates/cua-spaces/src/share.rs@@ -162,7 +162,9 @@ struct Attached {}mod publish;-pub use publish::{CHANGED as PUBLISH_CHANGED, Off, PublishReport, breaker_wait, jitter};+pub use publish::{+ CHANGED as PUBLISH_CHANGED, Off, PublishReport, PublishStatus, breaker_wait, jitter,+};/// Normalizes an invitee: an email (lowercased) or an account id. Teams and/// organizations are not relay principals, so `team:` / `org:` entries arediff --git a/libs/cua/crates/cua-spaces/src/share/publish.rs b/libs/cua/crates/cua-spaces/src/share/publish.rsindex c928810418..dd63df35e5 100644--- a/libs/cua/crates/cua-spaces/src/share/publish.rs+++ b/libs/cua/crates/cua-spaces/src/share/publish.rs@@ -150,6 +150,105 @@ pub struct PublishReport {pub more: bool,}+const STATUS_FILE: &str = "relay-publish.json";+/// How long what the daemon last failed to list is still told.+const STATUS_FRESH: u64 = 600;++#[derive(Default, serde::Serialize, serde::Deserialize)]+struct Saved {+ at: u64,+ failed: BTreeMap<String, String>,+}++fn load_saved(home: &std::path::Path) -> Saved {+ std::fs::read(home.join(STATUS_FILE))+ .ok()+ .and_then(|b| serde_json::from_slice(&b).ok())+ .unwrap_or_default()+}++fn unix_now() -> u64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| d.as_secs())+}++/// Where this computer's running Spaces stand on the account.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct PublishStatus {+ /// Why nothing is listed at all, when that is so.+ pub off: Option<Off>,+ /// Running Spaces that did not opt out.+ pub running: usize,+ /// Of those, listed on the account.+ pub listed: usize,+ /// Stopped Spaces (listed once they run).+ pub stopped: usize,+ /// Running Spaces that are not listed, with why (name, reason).+ pub not_listed: Vec<(String, String)>,+}++impl Off {+ /// Why, in words for the person.+ pub fn why(self) -> &'static str {+ match self {+ Off::NoAccount => "no cua.ai account is set up on this computer",+ Off::SignedOut => {+ "you are signed out of cua.ai (sign in from the app or run `cua auth login`)"+ }+ Off::Setting => "the relay.spaces setting (or CUA_RELAY_SPACES) is off",+ Off::NotSharing => {+ "this computer stopped sharing (turn sharing on in the app or run `cua host start`)"+ }+ }+ }+}++impl PublishStatus {+ /// Plain lines for `cua spaces ls` and `cua host status`; none when all+ /// is well and there is nothing to say.+ pub fn notes(&self) -> Vec<String> {+ let mut out = Vec::new();+ let plural = |n: usize| if n == 1 { "Space is" } else { "Spaces are" };+ if let Some(off) = self.off {+ if self.running > 0 {+ out.push(format!(+ "{} running {} not on your account: {}.",+ self.running,+ plural(self.running),+ off.why()+ ));+ }+ return out;+ }+ if !self.not_listed.is_empty() {+ let items: Vec<String> = self+ .not_listed+ .iter()+ .map(|(n, w)| format!("{n} ({w})"))+ .collect();+ out.push(format!(+ "{} running {} not on your account: {}.",+ self.not_listed.len(),+ plural(self.not_listed.len()),+ items.join("; ")+ ));+ }+ if self.stopped > 0 {+ out.push(format!(+ "{} stopped {} on your account once running.",+ self.stopped,+ if self.stopped == 1 {+ "Space shows"+ } else {+ "Spaces show"+ }+ ));+ }+ out+ }+}+/// Why nothing is listed now, or `None` when Spaces may be.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum Off {@@ -253,8 +352,13 @@ impl Spaces {{return false;}- // Opted out itself or through a parent.- let mut at = Some(info.id.clone());+ !Self::opted_out(&info.id, meta) && !Self::network_blocks_relay(&info.id, meta)+ }++ /// Whether the Space `id` (or a parent) opted out of the account's relay+ /// (`--no-relay`, `cua.relay=off`) or is hidden.+ fn opted_out(id: &str, meta: &BTreeMap<String, crate::registry::SpaceMeta>) -> bool {+ let mut at = Some(id.to_string());let mut seen = BTreeSet::new();while let Some(id) = at {if !seen.insert(id.clone()) {@@ -268,20 +372,22 @@ impl Spaces {crate::registry::RelaySetting::parse(v).is_ok_and(|s| !s.is_on())})}) {- return false;+ return true;}at = m.and_then(|m| m.parent.clone());}- // The Space dials the relay itself: with no network it never reaches- // it (`custom` starts from `internet` or `none`).+ false+ }++ /// The Space dials the relay itself: with no network it never reaches+ /// it (`custom` starts from `internet` or `none`).+ fn network_blocks_relay(id: &str, meta: &BTreeMap<String, crate::registry::SpaceMeta>) -> bool {use cua_vmm::network::NetworkPreset as P;- let no_network = meta- .get(&info.id)+ meta.get(id).and_then(|m| m.network.as_ref()).is_some_and(|n| {n.preset == P::None || (n.preset == P::Custom && n.custom_base == P::None)- });- !no_network+ })}/// Where each local Space of `infos` stands on the account: `on` (listed@@ -324,6 +430,12 @@ impl Spaces {/// growing, jittered time that is never shorter than its `Retry-After`;/// Spaces keep being made here meanwhile.pub async fn publish_to_relay(&self) -> Result<PublishReport> {+ let report = self.publish_pass().await?;+ self.record_outcome(&report);+ Ok(report)+ }++ async fn publish_pass(&self) -> Result<PublishReport> {let mut report = PublishReport::default();let home = self.home_dir().to_path_buf();let gate = self.relay_publishing().await;@@ -728,6 +840,87 @@ impl Spaces {}}+ /// Remembers, for `cua spaces ls` and `cua host status` (other+ /// processes), which Spaces the last passes could not list and why.+ fn record_outcome(&self, report: &PublishReport) {+ let home = self.home_dir();+ let mut saved = load_saved(home);+ let before = saved.failed.clone();+ let clean = memo(home, |m| m.settled.is_some() && m.breaker.fails == 0);+ if clean {+ saved.failed.clear();+ }+ for id in report.published.iter().chain(&report.unpublished) {+ saved.failed.remove(id);+ }+ for (id, why) in &report.failed {+ saved.failed.insert(id.clone(), why.clone());+ }+ if saved.failed != before {+ saved.at = unix_now();+ let _ = std::fs::write(+ home.join(STATUS_FILE),+ serde_json::to_vec(&saved).unwrap_or_default(),+ );+ }+ }++ /// Where this computer's running Spaces stand on the account, in plain+ /// words for the person: which are not listed and why (nothing is+ /// silent). Reads the same rules a pass follows.+ pub async fn relay_publish_status(&self, infos: &[crate::SpaceInfo]) -> PublishStatus {+ let off = self.relay_publishing().await.err();+ let meta = self.inner.registry.all_meta();+ let attached = self.attached();+ let provided = self.provided_here();+ let saved = load_saved(self.home_dir());+ let fresh = unix_now().saturating_sub(saved.at) < STATUS_FRESH;+ let mut st = PublishStatus {+ off,+ ..Default::default()+ };+ for info in infos+ .iter()+ .filter(|i| i.id.starts_with("local:") && !provided.contains(&i.id))+ {+ if self.is_off(info) {+ st.stopped += 1;+ continue;+ }+ if !self.recorded_running(info) || Self::opted_out(&info.id, &meta) {+ continue;+ }+ st.running += 1;+ if attached.get(&info.id).is_some_and(|a| a.auto) {+ st.listed += 1;+ continue;+ }+ if off.is_some() {+ continue;+ }+ let why = if !info+ .features+ .iter()+ .any(|f| f == super::RELAY_ATTACH_FEATURE)+ {+ crate::space::unreported_feature_limitation(+ &info.spacesd_version,+ super::RELAY_ATTACH_FEATURE,+ )+ } else if Self::network_blocks_relay(&info.id, &meta) {+ "its network cannot reach the relay".to_string()+ } else if let Some(e) = saved.failed.get(&info.id).filter(|_| fresh) {+ format!("not listed yet: {e}")+ } else if let Some(e) = saved.failed.get("").filter(|_| fresh) {+ format!("the relay did not answer: {e}")+ } else {+ "waiting for the next check".to_string()+ };+ st.not_listed.push((info.shown_name().to_string(), why));+ }+ st+ }+/// Makes a hidden Space ([`crate::registry::HIDDEN_LABEL`]) visible: the/// apps list it from now on and the next publish pass puts it on the/// owner's account (`set_on_relay` on). The daemon calls it when adiff --git a/libs/cua/crates/cua-spaces/tests/relay_publish.rs b/libs/cua/crates/cua-spaces/tests/relay_publish.rsindex 8def715136..5ab2d17fee 100644--- a/libs/cua/crates/cua-spaces/tests/relay_publish.rs+++ b/libs/cua/crates/cua-spaces/tests/relay_publish.rs@@ -848,3 +848,117 @@ async fn a_throttled_relay_is_left_alone() {}assert_eq!(w.relay.requests(), 1, "asked again while paused");}++/// A running Space that is not on the account is never a mystery: the+/// status says how many and why (an old driver, a relay that fails, signed+/// out, the switch, sharing stopped), and stopped Spaces are counted as+/// waiting until they run.+#[tokio::test]+async fn running_spaces_that_are_not_on_the_account_say_why() {+ let w = World::new().await;+ w.create("good", "linux", Kind::Container).await;+ // A driver that cannot join the relay (it predates `relay_attach`).+ let old = MockServer::start(MockAuth::default()).await;+ let port: u16 = old.url().rsplit(':').next().unwrap().parse().unwrap();+ w.rt.spacesd.lock().unwrap().insert("old".into(), port);+ let old_id = w+ .spaces+ .create(SpaceCreate {+ on: Some(On::Local),+ image: Some("linux".into()),+ name: Some("old".into()),+ timeout: Some(Duration::from_secs(30)),+ ..Default::default()+ })+ .await+ .unwrap()+ .ready()+ .unwrap()+ .id;+ w.age(&old_id);+ w.create("sleeper", "linux", Kind::Container).await;+ w.power("sleeper", "stopped");++ w.spaces.publish_to_relay().await.unwrap();+ let st = w+ .spaces+ .relay_publish_status(&w.spaces.list().unwrap())+ .await;+ assert_eq!(st.off, None);+ assert_eq!((st.running, st.listed, st.stopped), (2, 1, 1), "{st:?}");+ assert_eq!(st.not_listed.len(), 1, "{st:?}");+ assert_eq!(st.not_listed[0].0, "old");+ let notes = st.notes().join("\n");+ assert!(+ notes.contains("1 running Space is not on your account: old (")+ && notes.contains("1 stopped Space shows"),+ "{notes}"+ );++ // Signed out: one plain reason for all of them.+ *w.account.0.lock().unwrap() = None;+ let st = w+ .spaces+ .relay_publish_status(&w.spaces.list().unwrap())+ .await;+ assert_eq!(st.off, Some(cua_spaces::share::Off::SignedOut));+ assert!(st.notes()[0].contains("2 running Spaces are not on your account: you are signed out"));++ // The switch.+ *w.account.0.lock().unwrap() = Some("ada-token".into());+ std::fs::write(+ w.home.path().join("config.toml"),+ "[relay]\nspaces = \"off\"\n",+ )+ .unwrap();+ let st = w+ .spaces+ .relay_publish_status(&w.spaces.list().unwrap())+ .await;+ assert_eq!(st.off, Some(cua_spaces::share::Off::Setting));+ std::fs::remove_file(w.home.path().join("config.toml")).unwrap();+}++/// A relay that fails is told, from another process too (`cua spaces ls`+/// reads what the daemon's pass recorded), and the note goes once listing+/// works again.+#[tokio::test]+async fn a_failing_relay_is_told_and_forgotten_when_listing_works() {+ let w = World::new().await;+ w.create("a", "linux", Kind::Container).await;+ w.relay.set_reads_down(true);+ let r = w.spaces.publish_to_relay().await.unwrap();+ assert!(!r.failed.is_empty(), "{r:?}");+ let infos = w.spaces.list().unwrap();+ // Another process: same home, no shared memory.+ let other = Spaces::builder()+ .home(w.home.path())+ .sandboxes(+ Sandboxes::builder()+ .local(w.rt.clone())+ .state_dir(w.state.path())+ .build(),+ )+ .relay(RelayAccount::new(&w.relay.url, w.account.clone()))+ .build();+ let st = other.relay_publish_status(&infos).await;+ assert_eq!(st.not_listed.len(), 1, "{st:?}");+ assert!(+ st.not_listed[0].1.contains("relay did not answer")+ || st.not_listed[0].1.contains("not listed yet"),+ "{st:?}"+ );++ w.relay.set_reads_down(false);+ let started = std::time::Instant::now();+ loop {+ let r = w.spaces.publish_to_relay().await.unwrap();+ if !r.published.is_empty() {+ break;+ }+ assert!(started.elapsed() < Duration::from_secs(20), "never resumed");+ tokio::time::sleep(Duration::from_millis(250)).await;+ }+ let st = other.relay_publish_status(&w.spaces.list().unwrap()).await;+ assert_eq!((st.listed, st.not_listed.len()), (1, 0), "{st:?}");+}