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-sdk): remove a deleted Space's stale relay machine record (#4510)
ddupont5526f71b7b70
diff --git a/docs/content/docs/cua-cli/reference/cli/spaces.mdx b/docs/content/docs/cua-cli/reference/cli/spaces.mdxindex 7f576b6b7d..73b389bc0c 100644--- a/docs/content/docs/cua-cli/reference/cli/spaces.mdx+++ b/docs/content/docs/cua-cli/reference/cli/spaces.mdx@@ -223,7 +223,7 @@ cua spaces start studio --json## `cua spaces rm`-Forget a registered Space and its stored token. The sandbox keeps running.+Forget a registered Space and its stored token. The sandbox keeps running. The `relay:<machine>` record of a Space that registered itself and is gone (not connected) also leaves your relay directory.```text outputcua spaces rm [OPTIONS] <SPACE>@@ -331,7 +331,7 @@ cua spaces relay-register local:studio## `cua spaces relay-unregister`-Take a Space off the relay (every share with it ends).+Take a Space off the relay (every share with it ends). With a `relay:<machine>` id, removes that machine's record from your relay directory: a Space that registered itself (also after it was deleted), or a machine of yours that is gone. Only its owner can.```text outputcua spaces relay-unregister [OPTIONS] <SPACE>@@ -345,6 +345,7 @@ cua spaces relay-unregister [OPTIONS] <SPACE>```bash test="cli-shape" id="ref-cua-spaces-relay-unregister"cua spaces relay-unregister local:studio+cua spaces relay-unregister relay:space-0123abcd4567ef89```## Exit codesdiff --git a/docs/content/docs/spaces/reference/errors.mdx b/docs/content/docs/spaces/reference/errors.mdxindex b99d02eedd..67a4fec8da 100644--- a/docs/content/docs/spaces/reference/errors.mdx+++ b/docs/content/docs/spaces/reference/errors.mdx@@ -68,7 +68,7 @@ An argument is missing, malformed or out of range.Fix: Check the call against the tool's input schema; the message names the argument.-Listed by [`volume_storage_set`](/spaces/reference/volume#volume_storage_set), [`volume_cache_set`](/spaces/reference/volume#volume_cache_set).+Listed by [`volume_storage_set`](/spaces/reference/volume#volume_storage_set), [`volume_cache_set`](/spaces/reference/volume#volume_cache_set), [`relay_unregister_space`](/spaces/reference/sharing#relay_unregister_space).### not_found@@ -118,7 +118,7 @@ The signed-in account may not reach that relay machine.Fix: Sign in with the account that owns the machine.-Listed by [`stop_space`](/spaces/reference/lifecycle#stop_space), [`start_space`](/spaces/reference/lifecycle#start_space), [`share_space`](/spaces/reference/sharing#share_space), [`unshare_space`](/spaces/reference/sharing#unshare_space).+Listed by [`stop_space`](/spaces/reference/lifecycle#stop_space), [`start_space`](/spaces/reference/lifecycle#start_space), [`share_space`](/spaces/reference/sharing#share_space), [`unshare_space`](/spaces/reference/sharing#unshare_space), [`relay_unregister_space`](/spaces/reference/sharing#relay_unregister_space).### ambiguous_hostdiff --git a/docs/content/docs/spaces/reference/lifecycle.mdx b/docs/content/docs/spaces/reference/lifecycle.mdxindex 502c0889fa..8f49c61230 100644--- a/docs/content/docs/spaces/reference/lifecycle.mdx+++ b/docs/content/docs/spaces/reference/lifecycle.mdx@@ -102,7 +102,7 @@ No parameters.### Result-JSON: an array of Spaces (`id`, `name`, `provider`, `spacesd_version`, `features`, `os`, `services`, `added_at`, for a Space one of your machines provides `host` and `host_name`, for a Space that can be turned off and on `power` (`suspend` or `stop`) and `power_state`, and for a Space in your cloud `cloud`, `cloud_place` and `cloud_delete`), each with `phase: "ready"`.+JSON: an array of Spaces (`id`, `name`, `provider`, `spacesd_version`, `features`, `os`, `services`, `added_at`, for a Space one of your machines provides `host` and `host_name`, for a Space that can be turned off and on `power` (`suspend` or `stop`) and `power_state`, and for a Space in your cloud `cloud`, `cloud_place` and `cloud_delete`, and for a relay machine the relay cannot reach now `status` (`offline` or `not sharing`)), each with `phase`: `ready`, or `offline` for a relay machine the relay cannot reach now (a machine that is off or stopped sharing, or a Space that is gone and left its record; `relay_unregister_space` removes it).### Errorsdiff --git a/docs/content/docs/spaces/reference/sharing.mdx b/docs/content/docs/spaces/reference/sharing.mdxindex b154ea06bb..1f134807c3 100644--- a/docs/content/docs/spaces/reference/sharing.mdx+++ b/docs/content/docs/spaces/reference/sharing.mdx@@ -150,7 +150,7 @@ JSON: `space`, `relay_space` (`relay:<machine>`: how the account's other devicesTake a Space off the relay.-Takes the Space off the relay: its driver leaves and its machine is removed, with every share. A host is removed with `cua host remove` on that machine instead.+Takes the Space off the relay: its driver leaves and its machine is removed, with every share. A `relay:<machine>` id removes that machine's record from the relay directory, which only its owner may do: a Space that registered itself (also after it was deleted), or a machine that is no longer connected. A host that is connected now is taken off with `cua host remove` on that machine instead.| | || --- | --- |@@ -174,4 +174,4 @@ JSON: `space` and `unregistered` (false when it was not on the relay).### Errors-[`invalid_argument`](/spaces/reference/errors#invalid_argument), [`not_found`](/spaces/reference/errors#not_found), [`ambiguous_sandbox`](/spaces/reference/errors#ambiguous_sandbox), [`host_capability_missing`](/spaces/reference/errors#host_capability_missing), [`relay`](/spaces/reference/errors#relay), [`unauthenticated`](/spaces/reference/errors#unauthenticated)+[`invalid_argument`](/spaces/reference/errors#invalid_argument), [`not_found`](/spaces/reference/errors#not_found), [`ambiguous_sandbox`](/spaces/reference/errors#ambiguous_sandbox), [`host_capability_missing`](/spaces/reference/errors#host_capability_missing), [`relay`](/spaces/reference/errors#relay), [`unauthenticated`](/spaces/reference/errors#unauthenticated), [`permission_denied`](/spaces/reference/errors#permission_denied)diff --git a/libs/cua-spacesd/crates/cua-relay/tests/viewer_shares.rs b/libs/cua-spacesd/crates/cua-relay/tests/viewer_shares.rsindex 232b96d82f..92976bb883 100644--- a/libs/cua-spacesd/crates/cua-relay/tests/viewer_shares.rs+++ b/libs/cua-spacesd/crates/cua-relay/tests/viewer_shares.rs@@ -156,3 +156,71 @@ async fn viewers_get_a_viewer_assertion_and_revocation_is_immediate() {assert_eq!(role_of(seen.lock().unwrap().last().unwrap()), "owner");stop.cancel();}++/// Only a machine's owner can remove it from the directory (#4486): an+/// editor or a viewer it is shared with is refused, an account it is not+/// shared with does not even see it, and the record stays until its owner+/// removes it.+#[tokio::test]+async fn only_the_owner_removes_a_machine() {+ let issuer = FakeIssuer::new(ISSUER);+ let relay = Relay::new(RelayConfig {+ oidc: Some(Arc::new(OidcValidator::with_jwks(+ OidcConfig::new(ISSUER),+ issuer.jwks(),+ ))),+ device_enrollment: false,+ ..RelayConfig::default()+ });+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let base = format!("http://{}", listener.local_addr().unwrap());+ let serving = relay.clone();+ tokio::spawn(async move {+ let _ = serving.serve(listener, std::future::pending()).await;+ });+ let http = reqwest::Client::new();+ let ada = issuer.token("ada", Some("[email protected]"), "cua-relay", 600);+ let bob = issuer.token("bob", Some("[email protected]"), "cua-relay", 600);+ let eve = issuer.token("eve", Some("[email protected]"), "cua-relay", 600);+ let id = format!("space-{}", &uuid::Uuid::new_v4().simple().to_string()[..16]);+ let r = http+ .post(format!("{base}/v1/machines"))+ .bearer_auth(&ada)+ .json(&serde_json::json!({"id": id, "name": "gone space"}))+ .send()+ .await+ .unwrap();+ assert!(r.status().is_success(), "{}", r.status());+ let url = format!("{base}/v1/machines/{id}");+ let delete = |token: String| {+ let (http, url) = (http.clone(), url.clone());+ async move {+ http.delete(url)+ .bearer_auth(token)+ .send()+ .await+ .unwrap()+ .status()+ }+ };+ for share in [+ serde_json::json!({"allow": ["[email protected]"]}),+ serde_json::json!({"allow": [], "viewers": ["[email protected]"]}),+ ] {+ let r = http+ .patch(&url)+ .bearer_auth(&ada)+ .json(&share)+ .send()+ .await+ .unwrap();+ assert!(r.status().is_success(), "{}", r.status());+ assert_eq!(delete(bob.clone()).await, reqwest::StatusCode::FORBIDDEN);+ }+ assert_eq!(delete(eve.clone()).await, reqwest::StatusCode::NOT_FOUND);+ let still = http.get(&url).bearer_auth(&ada).send().await.unwrap();+ assert_eq!(still.status(), reqwest::StatusCode::OK, "the record stays");+ assert_eq!(delete(ada.clone()).await, reqwest::StatusCode::NO_CONTENT);+ let gone = http.get(&url).bearer_auth(&ada).send().await.unwrap();+ assert_eq!(gone.status(), reqwest::StatusCode::NOT_FOUND);+}diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rsindex ee95e6214a..fa0e97d6ef 100644--- a/libs/cua/crates/cua-cli/src/host.rs+++ b/libs/cua/crates/cua-cli/src/host.rs@@ -307,7 +307,8 @@ pub enum SpacesCmd {space: String,},/// Forget a registered Space and its stored token. The sandbox keeps- /// running.+ /// running. The `relay:<machine>` record of a Space that registered+ /// itself and is gone (not connected) also leaves your relay directory.#[command(visible_alias = "remove",after_help = "Examples:@@ -372,11 +373,15 @@ pub enum SpacesCmd {/// Space id, address or display name.space: String,},- /// Take a Space off the relay (every share with it ends).+ /// Take a Space off the relay (every share with it ends). With a+ /// `relay:<machine>` id, removes that machine's record from your relay+ /// directory: a Space that registered itself (also after it was+ /// deleted), or a machine of yours that is gone. Only its owner can.#[command(name = "relay-unregister",after_help = "Examples:- cua spaces relay-unregister local:studio"+ cua spaces relay-unregister local:studio+ cua spaces relay-unregister relay:space-0123abcd4567ef89")]RelayUnregister {/// Space id, address or display name.diff --git a/libs/cua/crates/cua-spaces-contract/src/lib.rs b/libs/cua/crates/cua-spaces-contract/src/lib.rsindex f63a05ca29..ca0fe63c16 100644--- a/libs/cua/crates/cua-spaces-contract/src/lib.rs+++ b/libs/cua/crates/cua-spaces-contract/src/lib.rs@@ -657,7 +657,7 @@ pub fn tools() -> Vec<Tool> {.with::<i::RemoveSpace>(),Spec {category: Category::Lifecycle,- result: "JSON: an array of Spaces (`id`, `name`, `provider`, `spacesd_version`, `features`, `os`, `services`, `added_at`, for a Space one of your machines provides `host` and `host_name`, for a Space that can be turned off and on `power` (`suspend` or `stop`) and `power_state`, and for a Space in your cloud `cloud`, `cloud_place` and `cloud_delete`), each with `phase: \"ready\"`.",+ result: "JSON: an array of Spaces (`id`, `name`, `provider`, `spacesd_version`, `features`, `os`, `services`, `added_at`, for a Space one of your machines provides `host` and `host_name`, for a Space that can be turned off and on `power` (`suspend` or `stop`) and `power_state`, and for a Space in your cloud `cloud`, `cloud_place` and `cloud_delete`, and for a relay machine the relay cannot reach now `status` (`offline` or `not sharing`)), each with `phase`: `ready`, or `offline` for a relay machine the relay cannot reach now (a machine that is off or stopped sharing, or a Space that is gone and left its record; `relay_unregister_space` removes it).",errors: &["relay", "unauthenticated"],instructions: "Every registered Space (cloud, local, direct and relay) with its id (local:<name>, cloud:<name>, direct:<host:port>, relay:<machine-id>), provider, spacesd version (empty without one) and supported features as of the last handshake. The signed-in account's machines on the relay are listed too: those are the names `create_space` accepts as on=\"host:<machine>\". A Space a machine provides carries `host` (that machine's id) and `host_name`; group them under it when you show them. A Space in your cloud carries `cloud` (the provider: aws, gcp, modal), `cloud_place` (account and region, to show with it) and `cloud_delete` (where delete_space can delete it: here, host:<machine>, or elsewhere).",capabilities: &["space.discover"],@@ -1615,8 +1615,8 @@ pub fn tools() -> Vec<Tool> {Spec {category: Category::Sharing,result: "JSON: `space` and `unregistered` (false when it was not on the relay).",- errors: &["relay", "unauthenticated"],- instructions: "Takes the Space off the relay: its driver leaves and its machine is removed, with every share. A host is removed with `cua host remove` on that machine instead.",+ errors: &["relay", "unauthenticated", "permission_denied", "invalid_argument"],+ instructions: "Takes the Space off the relay: its driver leaves and its machine is removed, with every share. A `relay:<machine>` id removes that machine's record from the relay directory, which only its owner may do: a Space that registered itself (also after it was deleted), or a machine that is no longer connected. A host that is connected now is taken off with `cua host remove` on that machine instead.",capabilities: &["space.relay"],host_requires: &[host::RELAY_ACCOUNT],annotations: Annotations::mutating_idempotent(),diff --git a/libs/cua/crates/cua-spaces/src/mcp/tools.rs b/libs/cua/crates/cua-spaces/src/mcp/tools.rsindex e8a2748a8f..92b211e532 100644--- a/libs/cua/crates/cua-spaces/src/mcp/tools.rs+++ b/libs/cua/crates/cua-spaces/src/mcp/tools.rs@@ -112,6 +112,10 @@ pub(super) async fn call_on(space: &Space, tool: &str, mut arguments: Value) ->pub const PHASE_READY: &str = "ready";/// See [`PHASE_READY`].pub const PHASE_STARTING: &str = "starting";+/// A relay machine the relay cannot reach now (its `status`): a machine+/// that is off or stopped sharing, or a Space that is gone and left its+/// record (`relay_unregister_space` removes it).+pub const PHASE_OFFLINE: &str = "offline";async fn dispatch(spaces: &Spaces,@@ -171,7 +175,17 @@ async fn dispatch(.list_all().await?.iter()- .map(|info| with(info, row_extra(info, &direct_hosts, PHASE_READY)))+ .map(|info| {+ // A relay machine the relay cannot reach is not ready (a+ // Space that is gone left its record; a host is off or+ // stopped sharing).+ let phase = if !info.status.is_empty() {+ PHASE_OFFLINE+ } else {+ PHASE_READY+ };+ with(info, row_extra(info, &direct_hosts, phase))+ }).collect();Ok(ToolOutcome::json(&rows))}diff --git a/libs/cua/crates/cua-spaces/src/relay.rs b/libs/cua/crates/cua-spaces/src/relay.rsindex ffc75595bc..9e9900443f 100644--- a/libs/cua/crates/cua-spaces/src/relay.rs+++ b/libs/cua/crates/cua-spaces/src/relay.rs@@ -112,3 +112,99 @@ impl std::fmt::Debug for RelayAccount {.finish_non_exhaustive()}}++/// Whether `m` is a Space that registered itself on the relay as its own+/// machine (`relay_register`, or its first share): not a host from `cua+/// host setup`, not a Space a host provides, not a Space in someone's own+/// cloud. Only that Space's own driver ever joins as it, so once the Space+/// is gone the record is stale.+pub(crate) fn is_registered_space(m: &RelayMachine) -> bool {+ m.host.as_deref().is_none_or(str::is_empty)+ && !crate::cloud::is_cloud_machine(m)+ && !m.meta.contains_key(cua_host::META_PROVIDES_SPACES)+ && m.id.starts_with("space-")+}++impl crate::Spaces {+ /// Removes `relay:<machine_id>` from the account's relay directory and+ /// forgets it here. Only the machine's owner may: a machine shared with+ /// you is refused here, and the relay refuses anyone but the owner+ /// (`DELETE /v1/machines/{id}` is owner-only). A host (or a Space in+ /// your cloud) that is connected now is refused too: `cua host remove`+ /// on it takes it off cleanly (`cua spaces delete` deletes the other). A+ /// Space this device attached to the relay is detached first. Returns+ /// the removed row, or `None` when the directory no longer lists it+ /// (it is forgotten here all the same).+ pub(crate) async fn forget_relay_machine(+ &self,+ machine_id: &str,+ ) -> crate::Result<Option<RelayMachine>> {+ use crate::Error;+ let id = format!("relay:{machine_id}");+ let relay = self.relay()?;+ let token = relay.tokens.access_token().await?;+ let client = relay.client().await?;+ let m = match client.machine(&token, machine_id).await {+ Ok(m) => m,+ Err(cua_host::Error::NotFound(_)) => {+ // Already gone from the directory: forget it here.+ self.forget_relay_locally(machine_id).await;+ return Ok(None);+ }+ Err(e) => return Err(e.into()),+ };+ if m.role != "owner" {+ let owner = m+ .owner+ .clone()+ .filter(|e| !e.is_empty())+ .unwrap_or_else(|| m.owner.id.clone());+ return Err(Error::Relay(cua_host::Error::PermissionDenied(format!(+ "{id} is shared with you by {owner}; only its owner can remove it from the relay directory"+ ))));+ }+ // A Space a host provides is the account's own registration (its+ // host keeps providing it, or it is a stale entry): it goes. A host+ // or a Space in your cloud that is connected now does not.+ let provided = m.host.as_deref().is_some_and(|h| !h.is_empty());+ if m.online && !provided && !is_registered_space(&m) {+ let name = if m.name.is_empty() { &m.id } else { &m.name };+ return Err(Error::invalid(if crate::cloud::is_cloud_machine(&m) {+ format!("{id} ({name}) is a running Space; delete it with `cua spaces delete {id}`")+ } else {+ format!(+ "{id} ({name}) is one of your machines and is connected now; take it off \+ the relay with `cua host remove` on that machine"+ )+ }));+ }+ #[cfg(feature = "spaces-agents")]+ self.detach_attached_driver(machine_id).await;+ match client.delete(&token, machine_id).await {+ Ok(()) | Err(cua_host::Error::NotFound(_)) => {}+ Err(e) => return Err(e.into()),+ }+ self.forget_relay_locally(machine_id).await;+ Ok(Some(m))+ }++ /// Forgets `relay:<machine_id>` on this device: the cached row, any+ /// registry entry, its thumbnail and connection, and (with sharing) the+ /// Space attached as it.+ async fn forget_relay_locally(&self, machine_id: &str) {+ let id = crate::SpaceId::Relay {+ machine_id: machine_id.to_string(),+ };+ self.drop_connection(&id).await;+ self.inner+ .relay_cache+ .lock()+ .expect("relay cache")+ .retain(|m| m.id != machine_id);+ let _ = self.inner.registry.remove(&id.to_string());+ self.inner.thumbnails.remove(&id.to_string());+ #[cfg(feature = "spaces-agents")]+ self.forget_attached_machine(machine_id);+ }+}diff --git a/libs/cua/crates/cua-spaces/src/share.rs b/libs/cua/crates/cua-spaces/src/share.rsindex 6afa0347be..00b90dd122 100644--- a/libs/cua/crates/cua-spaces/src/share.rs+++ b/libs/cua/crates/cua-spaces/src/share.rs@@ -520,8 +520,12 @@ impl Spaces {}/// Takes `space` off the relay: its driver leaves, its machine is- /// removed (and with it every share). A host (`relay:<id>`) is removed- /// with `cua host remove` on that machine instead.+ /// removed (and with it every share). `relay:<machine>` removes that+ /// machine's record from the relay directory, which only its owner may+ /// do (the relay enforces it): a Space that registered itself (also+ /// after the Space is gone), or a machine that is no longer connected.+ /// A host that is connected now is taken off with `cua host remove` on+ /// it instead.pub async fn relay_unregister(&self, space: &str) -> Result<bool> {let id = match self.resolve(space) {// A bare relay machine id (`space-…`) is known once the@@ -534,21 +538,11 @@ impl Spaces {};let canonical = id.to_string();if let SpaceId::Relay { machine_id } = &id {- // A Space a host provides (or a stale entry of one) is your- // account's registration, not a host: take it off the relay.- let provided = self- .relay_row(machine_id)- .await- .filter(|m| m.role == "owner" && m.host.as_deref().is_some_and(|h| !h.is_empty()));- if provided.is_none() {- return Err(Error::invalid(format!(- "{canonical} is a host; remove it with `cua host remove` on that machine"- )));+ let removed = self.forget_relay_machine(machine_id).await?;+ if removed.is_some() {+ self.audit_share("forget", &canonical, &format!("machine={machine_id}"));}- self.remove_relay_machine(machine_id).await?;- let _ = self.inner.registry.remove(&canonical);- self.audit_share("detach", &canonical, &format!("machine={machine_id}"));- return Ok(true);+ return Ok(removed.is_some());}let Some(machine) = self.share_machine(&canonical, &id) else {return Ok(false);@@ -557,6 +551,90 @@ impl Spaces {Ok(true)}+ /// The Space this device attached to the relay as `machine`.+ fn attached_space_of(&self, machine: &str) -> Option<String> {+ self.attached()+ .into_iter()+ .find(|(_, a)| a.machine == machine)+ .map(|(space, _)| space)+ }++ /// Asks the driver of the Space attached as `machine` (when it still+ /// answers, briefly) to leave the relay, so it does not keep dialing+ /// with a token the relay no longer knows.+ pub(crate) async fn detach_attached_driver(&self, machine: &str) {+ if let Some(space) = self.attached_space_of(machine) {+ self.detach_attached_space(&space).await;+ }+ }++ /// [`Self::detach_attached_driver`] by the Space's id (a Space that was+ /// never attached is left alone).+ pub(crate) async fn detach_attached_space(&self, space: &str) {+ if !self.attached().contains_key(space) {+ return;+ }+ let detach = async {+ if let Ok(s) = self.space(space).await+ && let Ok(d) = s.spacesd()+ {+ let _ = d+ .system()+ .detach_relay(cua_proto::env::v1::DetachRelayRequest {})+ .await;+ }+ };+ let _ = tokio::time::timeout(std::time::Duration::from_secs(10), detach).await;+ }++ /// Forgets that a Space was attached as `machine`.+ pub(crate) fn forget_attached_machine(&self, machine: &str) {+ let mut all = self.attached();+ let before = all.len();+ all.retain(|_, a| a.machine != machine);+ if all.len() != before+ && let Err(e) = self.save_attached(&all)+ {+ tracing::warn!("shared spaces: {e}");+ }+ }++ /// A Space being deleted that registered itself on the relay leaves it:+ /// its machine record is removed (as its owner), so no stale row stays+ /// behind. Best effort: a failure is logged and returned as a note for+ /// the delete's message.+ pub(crate) async fn release_attached(&self, canonical: &str) -> Option<String> {+ let machine = self.attached().get(canonical).map(|a| a.machine.clone())?;+ let removed = async {+ let relay = self.relay()?;+ let token = relay.tokens.access_token().await?;+ match relay.client().await?.delete(&token, &machine).await {+ Ok(()) | Err(cua_host::Error::NotFound(_)) => Ok(()),+ Err(e) => Err(Error::from(e)),+ }+ }+ .await;+ match removed {+ Ok(()) => {+ self.forget_attached_machine(&machine);+ self.inner+ .relay_cache+ .lock()+ .expect("relay cache")+ .retain(|m| m.id != machine);+ self.audit_share("detach", canonical, &format!("machine={machine}"));+ None+ }+ Err(e) => {+ tracing::warn!(space = canonical, machine, "relay machine not removed: {e}");+ Some(format!(+ "its relay machine relay:{machine} could not be removed ({e}); remove it with \+ `cua spaces relay-unregister relay:{machine}`"+ ))+ }+ }+ }+/// Who `space` is shared with, and who of them is connected now.pub async fn space_shares(&self, space: &str) -> Result<SpaceShares> {let id = self.resolve(space)?;diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rsindex b36fc89486..1711d5e800 100644--- a/libs/cua/crates/cua-spaces/src/spaces.rs+++ b/libs/cua/crates/cua-spaces/src/spaces.rs@@ -617,7 +617,7 @@ pub(crate) struct Inner {#[cfg(feature = "spaces-agents")]relay: std::sync::RwLock<Option<crate::relay::RelayAccount>>,/// The last directory listing (so `list` and `resolve` stay sync).- relay_cache: std::sync::Mutex<Vec<crate::relay::RelayMachine>>,+ pub(crate) relay_cache: std::sync::Mutex<Vec<crate::relay::RelayMachine>>,/// The Keyvault broker `request_site_login` signs in through (the/// daemon sets it once its Keyvault is up).site_login: std::sync::RwLock<Option<Arc<dyn crate::site_login::SiteLoginBroker>>>,@@ -982,6 +982,23 @@ impl Spaces {let id = self.resolve(space)?;let info = self.info(&id).ok();self.drop_connection(&id).await;+ // A Space that registered itself on the relay and is gone (its+ // machine is not connected) leaves the relay directory: otherwise+ // its stale record would list again on the next refresh. Only its+ // owner can remove it; anything else is only dropped here.+ if let SpaceId::Relay { machine_id } = &id+ && self.relay_account().is_some()+ && let Some(m) = self+ .relay_machines()+ .await+ .ok()+ .and_then(|all| all.into_iter().find(|m| &m.id == machine_id))+ && m.role == "owner"+ && !m.online+ && crate::relay::is_registered_space(&m)+ {+ self.forget_relay_machine(machine_id).await?;+ }// A direct host, or a Space one created, leaves the direct-host list.if matches!(id, SpaceId::Direct { .. }) {let _ = self.inner.registry.forget_direct(&id.to_string());@@ -2337,9 +2354,32 @@ impl Spaces {/// Deletes a Space's sandbox and forgets it: a cloud Space's sandbox is/// deleted (metering stops), a local one's instance is deleted. A Space/// added by address (`direct:`, `relay:`) is only forgotten: cua did not- /// create it. Hotspots on it stop.+ /// create it. Hotspots on it stop. A Space that registered itself on+ /// the relay (`relay_register`, or a share) leaves the relay directory+ /// with it, and deleting such a Space's `relay:<machine>` removes that+ /// record (as its owner) even when the Space itself is already gone.pub async fn delete(&self, space: &str) -> Result<String> {let id = self.resolve(space)?;+ // A Space added by address keeps running: if it is attached to the+ // relay, its driver is asked to leave while it is still reachable.+ #[cfg(feature = "spaces-agents")]+ if matches!(id, SpaceId::Direct { .. }) {+ self.detach_attached_space(&id.to_string()).await;+ }+ let message = self.delete_space(&id).await?;+ // A Space this device attached to the relay as a machine of its own+ // takes that machine with it.+ #[cfg(feature = "spaces-agents")]+ if !matches!(id, SpaceId::Relay { .. })+ && let Some(note) = self.release_attached(&id.to_string()).await+ {+ return Ok(format!("{message} Note: {note}."));+ }+ Ok(message)+ }++ async fn delete_space(&self, id: &SpaceId) -> Result<String> {+ let id = id.clone();self.drop_connection(&id).await;self.inner.thumbnails.remove(&id.to_string());// A Space in your cloud: its sandbox goes, with everything the@@ -2416,9 +2456,24 @@ impl Spaces {let _ = self.relay_machines().await;return Ok(message);}- None => format!(- "Removed {id} (disconnected; the machine stays in your relay directory)."- ),+ // A Space that registered itself as a machine of yours:+ // its record leaves the relay directory.+ None => match row {+ Some(m) if m.role == "owner" && crate::relay::is_registered_space(&m) => {+ self.forget_relay_machine(machine_id).await?;+ format!("Removed {id} from your relay directory.")+ }+ Some(m) if m.role != "owner" => format!(+ "Removed {id} (disconnected; it is shared with you, so only its \+ owner can remove it from the relay directory)."+ ),+ Some(_) => format!(+ "Removed {id} (disconnected; it is one of your machines, so it stays \+ in your relay directory: run `cua host remove` on it, or if that \+ machine is gone, `cua spaces relay-unregister {id}`)."+ ),+ None => format!("Removed {id} (disconnected)."),+ },}}};diff --git a/libs/cua/crates/cua-spaces/tests/relay.rs b/libs/cua/crates/cua-spaces/tests/relay.rsindex 9928412384..5d53067135 100644--- a/libs/cua/crates/cua-spaces/tests/relay.rs+++ b/libs/cua/crates/cua-spaces/tests/relay.rs@@ -202,10 +202,7 @@ async fn connects_through_the_relay_path_with_the_account_token_per_call() {);// Relay Spaces are not registry entries; releasing just disconnects.let released = spaces.delete(&format!("relay:{MACHINE}")).await.unwrap();- assert!(- released.contains("stays in your relay directory"),- "{released}"- );+ assert!(released.contains("disconnected"), "{released}");// A wrong account token is refused by the (emulated) relay.let home = tempfile::tempdir().unwrap();diff --git a/libs/cua/crates/cua-spaces/tests/share.rs b/libs/cua/crates/cua-spaces/tests/share.rsindex 86075ce680..40f19a8c74 100644--- a/libs/cua/crates/cua-spaces/tests/share.rs+++ b/libs/cua/crates/cua-spaces/tests/share.rs@@ -414,9 +414,230 @@ async fn relay_register_publishes_a_space_for_the_accounts_devices() {assert!(env.state.relay_attached.lock().unwrap().is_none());assert!(relay.machine(&r.machine).is_none());assert!(!spaces.relay_unregister(&info.id).await.unwrap());- let e = spaces- .relay_unregister(&format!("relay:{}", "0123abcd4567ef89"))+ // A machine the relay does not list is not on the relay.+ assert!(+ !spaces+ .relay_unregister(&format!("relay:{}", "0123abcd4567ef89"))+ .await+ .unwrap()+ );+}++/// The hermetic world of the tests below: a fake relay with two accounts+/// (`ada` owns, `bob` is someone she shares with) and Spaces for each.+async fn two_accounts() -> (FakeRelay, Spaces, Spaces, Vec<tempfile::TempDir>) {+ let relay = FakeRelay::start().await;+ relay.add_account("ada-token", "ada", Some("[email protected]"));+ relay.add_account("bob-token", "bob", Some("[email protected]"));+ let homes = vec![tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()];+ let spaces = |home: &std::path::Path, token: &str| {+ Spaces::builder()+ .home(home)+ .relay(RelayAccount::new(+ &relay.url,+ Arc::new(StaticToken(token.into())),+ ))+ .build()+ };+ let ada = spaces(homes[0].path(), "ada-token");+ let bob = spaces(homes[1].path(), "bob-token");+ (relay, ada, bob, homes)+}++/// Registers `id` as one of ada's machines, as a Space's relay_register+/// (no meta) or a host's setup (`host_meta`) does.+async fn register(relay: &FakeRelay, id: &str, host_meta: bool) {+ let meta = if host_meta {+ [(cua_host::META_PROVIDES_SPACES.to_string(), "on".to_string())].into()+ } else {+ Default::default()+ };+ cua_host::RelayClient::new(&relay.url)+ .unwrap()+ .register(+ "ada-token",+ &cua_host::relay::RegisterRequest {+ id: id.into(),+ name: "vps-desktop".into(),+ allow: vec![],+ host: None,+ meta,+ },+ )+ .await+ .unwrap();+}++/// Deleting a Space that registered itself on the relay takes its machine+/// out of the relay directory (#4486): deleting the Space by its own id+/// detaches its driver and removes the machine, and deleting its+/// `relay:<machine>` after the Space is gone removes the stale record.+#[tokio::test]+async fn deleting_a_relay_registered_space_removes_its_machine() {+ let (relay, ada, _bob, _homes) = two_accounts().await;+ let env = MockServer::start(MockAuth::default()).await;+ env.state.advertise(&["relay_attach"]);+ let info = ada.add(&env.url(), None, Some("bot".into())).await.unwrap();+ let state = env.state.clone();+ let handle = relay.clone();+ tokio::spawn(async move {+ for _ in 0..400 {+ if let Some(a) = state.relay_attached.lock().unwrap().clone() {+ handle.set_online(&a.machine_id, true, "0.1.0");+ return;+ }+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ }+ });+ let r = ada.relay_register(&info.id).await.unwrap();+ assert!(relay.machine(&r.machine).is_some());+ // Deleting the Space itself: its driver leaves and its machine goes.+ let message = ada.delete(&info.id).await.unwrap();+ assert!(!message.contains("Note"), "{message}");+ assert!(env.state.relay_attached.lock().unwrap().is_none());+ assert!(relay.machine(&r.machine).is_none(), "machine removed");++ // The issue's case: the Space is gone (its sandbox deleted elsewhere),+ // only its record is left, listed as offline, not ready.+ let stale = "space-00000000000000aa";+ register(&relay, stale, false).await;+ let id = format!("relay:{stale}");+ let row = ada+ .list_all()+ .await+ .unwrap()+ .into_iter()+ .find(|i| i.id == id)+ .expect("listed");+ assert_eq!(row.status, "offline");+ let listed = cua_spaces::mcp::McpServer::new(ada.clone())+ .call("list_spaces", serde_json::json!({}))+ .await;+ let rows: serde_json::Value = serde_json::from_str(listed.first_text().expect("rows")).unwrap();+ let phase = rows+ .as_array()+ .unwrap()+ .iter()+ .find(|r| r["id"] == id)+ .map(|r| r["phase"].clone());+ assert_eq!(phase, Some(serde_json::json!("offline")), "{rows}");+ let message = ada.delete(&id).await.unwrap();+ assert!(+ message.contains("from your relay directory")+ && !message.contains("stays in your relay directory"),+ "{message}"+ );+ assert!(relay.machine(stale).is_none(), "stale record removed");+ assert!(!ada.list_all().await.unwrap().iter().any(|i| i.id == id));+}++/// Removing a stale record: `rm` of a gone Space's `relay:<machine>` and+/// `relay_unregister` of a machine that is no longer connected remove it+/// from the relay directory; a host that is connected now is refused with+/// the remedy that works (`cua host remove` on it), and a live Space+/// registration is untouched by `rm`.+#[tokio::test]+async fn stale_relay_records_can_be_removed() {+ let (relay, ada, _bob, _homes) = two_accounts().await;+ let gone = "space-00000000000000bb";+ register(&relay, gone, false).await;+ ada.relay_machines().await.unwrap();+ ada.remove(&format!("relay:{gone}")).await.unwrap();+ assert!(relay.machine(gone).is_none(), "rm removed the stale record");++ // A live Space registration: `rm` only drops it here.+ let live = "space-00000000000000cc";+ register(&relay, live, false).await;+ relay.set_online(live, true, "0.1.0");+ ada.remove(&format!("relay:{live}")).await.unwrap();+ assert!(+ relay.machine(live).is_some(),+ "a live Space keeps its record"+ );+ assert!(+ ada.relay_unregister(&format!("relay:{live}"))+ .await+ .unwrap()+ );+ assert!(relay.machine(live).is_none());++ // A host: connected, it is refused with a remedy that can be carried+ // out; once that machine is gone, its record is removed.+ let host = "0123abcd4567ef890123abcd4567ef89";+ register(&relay, host, true).await;+ relay.set_online(host, true, "0.1.0");+ let e = ada+ .relay_unregister(&format!("relay:{host}")).await.unwrap_err();+ assert_eq!(e.tag(), "invalid_argument", "{e}");assert!(e.to_string().contains("cua host remove"), "{e}");+ assert!(relay.machine(host).is_some());+ // `rm` and `delete` never remove a host's record.+ ada.remove(&format!("relay:{host}")).await.unwrap();+ relay.set_online(host, false, "");+ ada.remove(&format!("relay:{host}")).await.unwrap();+ let message = ada.delete(&format!("relay:{host}")).await.unwrap();+ assert!(message.contains("relay-unregister"), "{message}");+ assert!(relay.machine(host).is_some());+ assert!(+ ada.relay_unregister(&format!("relay:{host}"))+ .await+ .unwrap()+ );+ assert!(+ relay.machine(host).is_none(),+ "the gone host's record removed"+ );+ let audit = ada.share_audit(None, 10).unwrap();+ assert!(audit.iter().any(|a| a.action == "forget"), "{audit:?}");+}++/// Only a machine's owner can remove its record: someone it is shared+/// with (editor or viewer) is refused by every path, here and by the+/// relay itself, and the record stays.+#[tokio::test]+async fn only_the_owner_removes_a_relay_record() {+ let (relay, ada, bob, _homes) = two_accounts().await;+ let gone = "space-00000000000000dd";+ register(&relay, gone, false).await;+ let ada_client = cua_host::RelayClient::new(&relay.url).unwrap();+ for patch in [+ cua_host::MachinePatch {+ allow: Some(vec!["[email protected]".into()]),+ ..Default::default()+ },+ cua_host::MachinePatch {+ allow: Some(vec![]),+ viewers: Some(vec!["[email protected]".into()]),+ ..Default::default()+ },+ ] {+ ada_client.patch("ada-token", gone, &patch).await.unwrap();+ let id = format!("relay:{gone}");+ bob.relay_machines().await.unwrap();+ let e = bob.relay_unregister(&id).await.unwrap_err();+ assert_eq!(e.tag(), "permission_denied", "{e}");+ assert!(e.to_string().contains("only its owner"), "{e}");+ let message = bob.delete(&id).await.unwrap();+ assert!(message.contains("only its"), "{message}");+ bob.relay_machines().await.unwrap();+ bob.remove(&id).await.unwrap();+ // The relay refuses anyone but the owner, whatever the client does.+ let e = cua_host::RelayClient::new(&relay.url)+ .unwrap()+ .delete("bob-token", gone)+ .await+ .unwrap_err();+ assert!(matches!(e, cua_host::Error::PermissionDenied(_)), "{e:?}");+ assert!(relay.machine(gone).is_some(), "the record stays");+ }+ // The owner can.+ ada.relay_machines().await.unwrap();+ assert!(+ ada.relay_unregister(&format!("relay:{gone}"))+ .await+ .unwrap()+ );+ assert!(relay.machine(gone).is_none());}diff --git a/libs/cua/spaces-contract/manifest.json b/libs/cua/spaces-contract/manifest.jsonindex 6c1e1d6902..b1b25aaf46 100644--- a/libs/cua/spaces-contract/manifest.json+++ b/libs/cua/spaces-contract/manifest.json@@ -387,7 +387,7 @@"sdk_symbol": "SpacesConnection.spaces()","rust_symbol": "Spaces::list","notes": [],- "result": "JSON: an array of Spaces (`id`, `name`, `provider`, `spacesd_version`, `features`, `os`, `services`, `added_at`, for a Space one of your machines provides `host` and `host_name`, for a Space that can be turned off and on `power` (`suspend` or `stop`) and `power_state`, and for a Space in your cloud `cloud`, `cloud_place` and `cloud_delete`), each with `phase: \"ready\"`.",+ "result": "JSON: an array of Spaces (`id`, `name`, `provider`, `spacesd_version`, `features`, `os`, `services`, `added_at`, for a Space one of your machines provides `host` and `host_name`, for a Space that can be turned off and on `power` (`suspend` or `stop`) and `power_state`, and for a Space in your cloud `cloud`, `cloud_place` and `cloud_delete`, and for a relay machine the relay cannot reach now `status` (`offline` or `not sharing`)), each with `phase`: `ready`, or `offline` for a relay machine the relay cannot reach now (a machine that is off or stopped sharing, or a Space that is gone and left its record; `relay_unregister_space` removes it).","errors": ["relay","unauthenticated"@@ -4847,7 +4847,7 @@"name": "relay_unregister_space","category": "sharing","description": "Take a Space off the relay.",- "instructions": "Takes the Space off the relay: its driver leaves and its machine is removed, with every share. A host is removed with `cua host remove` on that machine instead.",+ "instructions": "Takes the Space off the relay: its driver leaves and its machine is removed, with every share. A `relay:<machine>` id removes that machine's record from the relay directory, which only its owner may do: a Space that registered itself (also after it was deleted), or a machine that is no longer connected. A host that is connected now is taken off with `cua host remove` on that machine instead.","platforms": ["macos","windows",@@ -4879,7 +4879,9 @@"result": "JSON: `space` and `unregistered` (false when it was not on the relay).","errors": ["relay",- "unauthenticated"+ "unauthenticated",+ "permission_denied",+ "invalid_argument"],"input_schema": {"properties": {diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.jsonindex 980e7d9442..70d6ce3f66 100644--- a/scripts/docs-generators/cli-specs/cua.json+++ b/scripts/docs-generators/cli-specs/cua.json@@ -10058,7 +10058,7 @@"usage": "cua spaces start [OPTIONS] <SPACE>"},{- "abstract": "Forget a registered Space and its stored token. The sandbox keeps running",+ "abstract": "Forget a registered Space and its stored token. The sandbox keeps running. The `relay:<machine>` record of a Space that registered itself and is gone (not connected) also leaves your relay directory","after_help": "Examples:\n cua spaces rm direct:10.0.0.5:3211\n cua spaces rm studio","aliases": ["remove"@@ -10249,8 +10249,8 @@"usage": "cua spaces relay-register [OPTIONS] <SPACE>"},{- "abstract": "Take a Space off the relay (every share with it ends)",- "after_help": "Examples:\n cua spaces relay-unregister local:studio",+ "abstract": "Take a Space off the relay (every share with it ends). With a `relay:<machine>` id, removes that machine's record from your relay directory: a Space that registered itself (also after it was deleted), or a machine of yours that is gone. Only its owner can",+ "after_help": "Examples:\n cua spaces relay-unregister local:studio\n cua spaces relay-unregister relay:space-0123abcd4567ef89","aliases": [],"arguments": [{