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): a computer keeps one identity when re-enabled, renamed or removed (CUA-3316, CUA-3315) (#6486)
ddupont21638877b566
diff --git a/apps/cua-spaces-desktop/src/bridge/machines.ts b/apps/cua-spaces-desktop/src/bridge/machines.tsindex 0ab2bf13e9..47aa7fd0bd 100644--- a/apps/cua-spaces-desktop/src/bridge/machines.ts+++ b/apps/cua-spaces-desktop/src/bridge/machines.ts@@ -129,6 +129,8 @@ export function machinesMethods({ model }: BridgeContext): Handlers {if (!machineId) throw Failure.badArgs("this machine is not on the relay");await relayCall(model, () => model.devices.renameMachine(machineId, name));if (id === "this-mac") await model.host.refresh();+ // The Spaces list and the registry hold the name too (the SDK updated the copies on disk by the machine id): read them again so the computer shows the new name, still online, everywhere at once.+ await model.refresh();return null;},// Remove from account: the machine leaves the relay directory, thendiff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rsindex 54605652ba..d1369e713e 100644--- a/libs/cua/crates/cua-cli/src/host.rs+++ b/libs/cua/crates/cua-cli/src/host.rs@@ -5942,8 +5942,20 @@ mod tests {#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn machines_rm_rechecks_after_confirmation() {let f = fx(&["old-laptop"]).await;+ // It connects while the prompt is open, and answers a fresh+ // connection through the relay (one that only the directory+ // lists as connected is a ghost, which a remove may take).+ let srv = cua_spacesd_client::testing::MockServer::start(+ cua_spacesd_client::testing::MockAuth {+ token: None,+ gateway: None,+ prefix: None,+ },+ )+ .await;let (r, _, asked) = rm(&f, "old-laptop", false, || {f.relay.set_online(ID, true, "1.0");+ f.relay.tunnel(ID, &srv.url());true}).await;diff --git a/libs/cua/crates/cua-host/src/device.rs b/libs/cua/crates/cua-host/src/device.rsindex 9ee5409ae9..ad398b75fe 100644--- a/libs/cua/crates/cua-host/src/device.rs+++ b/libs/cua/crates/cua-host/src/device.rs@@ -348,6 +348,16 @@ pub fn token_subject(token: &str) -> Option<String> {.filter(|s| !s.is_empty())}+/// The unverified, lowercased `email` claim of a JWT access token (a local+/// lookup key only; the relay verifies every token).+pub fn token_email(token: &str) -> Option<String> {+ token_claims(token)?+ .get("email")?+ .as_str()+ .map(|e| e.trim().to_lowercase())+ .filter(|e| !e.is_empty())+}+impl std::fmt::Debug for DeviceAuth {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {f.debug_struct("DeviceAuth")diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rsindex 7d46c15af4..2c714d459a 100644--- a/libs/cua/crates/cua-host/src/host.rs+++ b/libs/cua/crates/cua-host/src/host.rs@@ -74,6 +74,134 @@ struct StoredRegistration {/// that signed in here before and are not signed in now.type Registrations = std::collections::BTreeMap<String, StoredRegistration>;+/// This account's saved registration of this computer in `kept`: keyed by+/// the account id the relay gave back, which is the token's subject on+/// every relay that takes `sub` as the account (the default), else found by+/// the token's verified email (the registration is also kept under it).+fn saved_registration(kept: &Registrations, token: &str) -> Option<StoredRegistration> {+ let by_sub = crate::device::token_subject(token).and_then(|sub| kept.get(&sub).cloned());+ by_sub.or_else(|| {+ crate::device::token_email(token).and_then(|email| kept.get(&email_key(&email)).cloned())+ })+}++/// The key a registration is also kept under, for the account's email.+fn email_key(email: &str) -> String {+ format!("email:{}", email.trim().to_lowercase())+}++/// Why this computer was not registered again under its saved id.+fn refused_saved_registration(id: &str, e: Error) -> Error {+ let reason = match &e {+ Error::PermissionDenied(_) => {+ "the computer is connected to the relay right now with another credential"+ }+ Error::Conflict(_) => "the id belongs to another account",+ _ => "the sign-in was refused",+ };+ let message = format!(+ "the relay did not accept this computer's saved registration ({}): {reason} ({e}). \+ It was not registered as a new computer, so no duplicate is listed; fix that and \+ try again, or remove the computer from your account first.",+ &id[..id.len().min(8)],+ );+ match e {+ Error::Unauthenticated(_) => Error::Unauthenticated(message),+ Error::Conflict(_) => Error::Conflict(message),+ _ => Error::PermissionDenied(message),+ }+}++/// The file under the machine-id directory (`<home>/spacesd`, which a+/// removal keeps) that remembers relay registrations of this computer whose+/// delete did not reach the relay.+const PENDING_REMOVALS_FILE: &str = "pending-removals.json";+/// A removal the relay refuses or misses for this long is dropped.+const PENDING_REMOVAL_GIVE_UP_MS: u64 = 365 * 24 * 3600 * 1000;++/// A computer's registration on a relay that still has to be deleted.+#[derive(Clone, Serialize, Deserialize)]+pub struct PendingRemoval {+ /// The relay.+ pub relay_url: String,+ /// The computer's id on it.+ pub machine_id: String,+ /// What the relay last answered (or why it was not asked).+ #[serde(default)]+ pub last_error: Option<String>,+ #[serde(default)]+ machine_token: String,+ #[serde(default)]+ since_ms: u64,+}++impl std::fmt::Debug for PendingRemoval {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("PendingRemoval")+ .field("relay_url", &self.relay_url)+ .field("machine_id", &self.machine_id)+ .field("last_error", &self.last_error)+ .finish_non_exhaustive()+ }+}++impl PendingRemoval {+ fn new(url: &str, id: &str, machine_token: String) -> Self {+ Self {+ relay_url: url.trim_end_matches('/').to_string(),+ machine_id: id.to_string(),+ last_error: None,+ machine_token,+ since_ms: now_ms(),+ }+ }++ fn same(&self, url: &str, id: &str) -> bool {+ self.machine_id == id && self.relay_url.trim_end_matches('/') == url.trim_end_matches('/')+ }++ /// Deletes it on the relay: with the computer's token, else (refused,+ /// or none) as the owner through `account`. Already gone counts.+ async fn try_delete(&self, account: Option<&RemovalAccount<'_>>) -> Result<()> {+ let relay = RelayClient::new(&self.relay_url)?;+ let mut refused = None;+ if !self.machine_token.is_empty() {+ match relay.delete(&self.machine_token, &self.machine_id).await {+ Ok(()) | Err(Error::NotFound(_)) => return Ok(()),+ Err(e @ (Error::Unauthenticated(_) | Error::PermissionDenied(_))) => {+ refused = Some(e);+ }+ Err(e) => return Err(e),+ }+ }+ let Some(account) = account else {+ return Err(refused.unwrap_or_else(|| {+ Error::Unauthenticated("this computer has no token for the relay".into())+ }));+ };+ let token = account.tokens.access_token().await?;+ match relay+ .clone()+ .with_device_session(account.device_session.clone())+ .delete(&token, &self.machine_id)+ .await+ {+ Ok(()) | Err(Error::NotFound(_)) => Ok(()),+ Err(e) => Err(e),+ }+ }+}++/// The signed-in account a removal falls back to when the relay does not+/// take the computer's own token (or it has none).+pub struct RemovalAccount<'a> {+ /// The account's tokens.+ pub tokens: &'a dyn AccountTokens,+ /// This device's relay session, on a relay that requires an enrolled+ /// device.+ pub device_session: Option<String>,+}+/// Options for [`Host::setup`].#[derive(Clone, Debug)]pub struct SetupOptions {@@ -1533,6 +1661,17 @@ impl Host {edges: Vec::new(),},)?;+ // Leftovers of earlier removals the relay missed go now (this+ // one is live and is never touched), so re-enabling cannot+ // leave a ghost behind.+ self.run_removals(+ Some(&RemovalAccount {+ tokens,+ device_session: opts.device_session.clone(),+ }),+ Some((relay.base().to_string(), reg.machine.id.clone())),+ )+ .await;config.mode = "relay".into();config.relay_url = Some(relay.base().to_string());config.machine_id = Some(reg.machine.id);@@ -2024,6 +2163,7 @@ impl Host {/// Current state: config, service, and (relay mode) the relay's view/// with the connected clients.pub async fn status(&self) -> Result<HostStatus> {+ self.retry_pending_removals().await;let Some(config) = self.config()? else {return Ok(HostStatus::default());};@@ -2426,13 +2566,14 @@ impl Host {read_secret(&self.paths.machine_token()),){- kept.insert(- policy.owner.clone(),- StoredRegistration {- machine_id: id,- machine_token,- },- );+ let left = StoredRegistration {+ machine_id: id,+ machine_token,+ };+ if let Some(email) = policy.owner_email.as_deref().filter(|e| !e.is_empty()) {+ kept.insert(email_key(email), left.clone());+ }+ kept.insert(policy.owner.clone(), left);}let request = |id: String| RegisterRequest {id,@@ -2442,35 +2583,39 @@ impl Host {meta: host_meta(config.provide_spaces),};// This account's earlier registration of this computer, if any (the- // token says whose it is); else, or when the relay no longer takes- // it, a new machine id. Another account's id is never tried: if its- // record is gone from the relay it would register here and clash- // with the saved one.- let earlier: Vec<StoredRegistration> = crate::device::token_subject(&token)- .and_then(|sub| kept.get(&sub).cloned())- .into_iter()- .collect();- let mut reg = None;- for r in earlier {- match relay- .register_as_machine(&token, Some(&r.machine_token), &request(r.machine_id))- .await- {- Ok(r) => {- reg = Some(r);- break;+ // token says whose it is: its subject, else its email). Another+ // account's id is never tried: if its record is gone from the relay+ // it would register here and clash with the saved one.+ //+ // A saved registration is never dropped for a new random id: that+ // would leave the old computer listed on the relay (a duplicate row+ // nobody can retire from here) and cut this computer off from+ // whatever is tied to its id. When the relay refuses it, the reason+ // is the answer, and the next check tries the same id again.+ let reg = match saved_registration(&kept, &token) {+ Some(earlier) => {+ let id = earlier.machine_id.clone();+ match relay+ .register_as_machine(&token, Some(&earlier.machine_token), &request(id.clone()))+ .await+ {+ Ok(r) => r,+ // The relay lost the record: the id is free, so the same+ // computer takes it again (no machine token to show).+ Err(Error::NotFound(_)) => {+ relay+ .register_as_machine(&token, None, &request(id.clone()))+ .await?+ }+ Err(e @ (Error::Unauthenticated(_) | Error::PermissionDenied(_))) => {+ return Err(refused_saved_registration(&id, e));+ }+ Err(e @ Error::Conflict(_)) => {+ return Err(refused_saved_registration(&id, e));+ }+ Err(e) => return Err(e),}- Err(- Error::Unauthenticated(_)- | Error::PermissionDenied(_)- | Error::NotFound(_)- | Error::Conflict(_),- ) => {}- Err(e) => return Err(e),}- }- let reg = match reg {- Some(r) => r,None => {relay.register_as_machine(&token, None, &request(random_hex(16)))@@ -2479,13 +2624,14 @@ impl Host {};// The new registration is kept before anything else can fail, so a// retry reuses it instead of making another machine.- kept.insert(- reg.machine.owner.id.clone(),- StoredRegistration {- machine_id: reg.machine.id.clone(),- machine_token: reg.machine_token.clone(),- },- );+ let current = StoredRegistration {+ machine_id: reg.machine.id.clone(),+ machine_token: reg.machine_token.clone(),+ };+ if let Some(email) = reg.machine.owner.email.as_deref().filter(|e| !e.is_empty()) {+ kept.insert(email_key(email), current.clone());+ }+ kept.insert(reg.machine.owner.id.clone(), current);self.save_registrations(&kept)?;// The relay's sharing state follows this computer's own choice// (a reused registration keeps whatever it had under its account;@@ -2525,6 +2671,9 @@ impl Host {// (until here it stays kept, so a crash or a failed write retries// with it instead of making another machine).kept.remove(®.machine.owner.id);+ if let Some(email) = reg.machine.owner.email.as_deref() {+ kept.remove(&email_key(email));+ }self.save_registrations(&kept)?;// Registered for the new account and paused: resuming installs and// starts the service with the new registration (and keeps a stopped@@ -2612,7 +2761,16 @@ impl Host {/// and deletes `<home>/host`. The machine id is kept so a later setup/// reuses it.pub async fn remove(&self) -> Result<()> {- self.remove_inner(false).await+ self.remove_inner(false, None).await+ }++ /// [`Self::remove`] that also takes the computer off the relay as its+ /// owner (`account`) when the relay refuses the computer's own token or+ /// the computer has none: removal never depends on the computer being+ /// able to prove itself. A relay that cannot be reached at all is+ /// retried later ([`Self::finish_removals`], and on every status).+ pub async fn remove_with_account(&self, account: &RemovalAccount<'_>) -> Result<()> {+ self.remove_inner(false, Some(account)).await}/// [`Self::remove`] for an uninstall of the app: the Spaces this machine@@ -2621,7 +2779,7 @@ impl Host {/// through the relay; the Spaces themselves are left as they are for/// the caller to turn off ([`Self::provided_spaces`]).pub async fn remove_for_uninstall(&self) -> Result<()> {- self.remove_inner(true).await+ self.remove_inner(true, None).await}/// The Spaces this host provides to the owner's other devices.@@ -2884,7 +3042,11 @@ impl Host {);}- async fn remove_inner(&self, uninstalling: bool) -> Result<()> {+ async fn remove_inner(+ &self,+ uninstalling: bool,+ account: Option<&RemovalAccount<'_>>,+ ) -> Result<()> {let Some(config) = self.config()? else {return Ok(());};@@ -2904,59 +3066,209 @@ impl Host {crate::cli(),)));}- let mut relay_error = None;- let mut note = |e: Error| match e {- // Already gone: nothing to tell the relay.- Error::NotFound(_) => {}- // A refused machine token leaves the entry listed under My- // machines; report it (after the local cleanup) rather than- // pretending the unregister worked.- e => relay_error = Some(e),+ // Everything of this computer that is listed on a relay. Written+ // down before anything is deleted, outside the directory removed+ // below, so a relay that cannot be reached (or refuses the+ // computer's token) never leaves a row nobody can retire: the+ // removal is retried, and by the account when the token is refused.+ let mut targets: Vec<PendingRemoval> = Vec::new();+ let mut want = |url: &str, id: &str, token: String| {+ if url.is_empty() || id.is_empty() || targets.iter().any(|t| t.same(url, id)) {+ return;+ }+ targets.push(PendingRemoval::new(url, id, token));};if uninstalling {for space in &provided {- if space.machine_token.is_empty() || space.relay_url.is_empty() {- continue;- }- if let Err(e) = RelayClient::new(&space.relay_url)?- .delete(&space.machine_token, &space.relay_machine)- .await- {- note(e);- }+ want(+ &space.relay_url,+ &space.relay_machine,+ space.machine_token.clone(),+ );}}- if let (Some(url), Some(id)) = (&config.relay_url, &config.machine_id)- && let Ok(token) = read_secret(&self.paths.machine_token())- && let Err(e) = RelayClient::new(url)?.delete(&token, id).await- {- note(e);+ if let (Some(url), Some(id)) = (&config.relay_url, &config.machine_id) {+ want(+ url,+ id,+ read_secret(&self.paths.machine_token()).unwrap_or_default(),+ );}// Its registrations under other accounts go too: nothing of this// computer stays listed anywhere.if let Some(url) = &config.relay_url {for r in self.registrations().values() {- if let Err(e) = RelayClient::new(url)?- .delete(&r.machine_token, &r.machine_id)- .await- {- note(e);- }+ want(url, &r.machine_id, r.machine_token.clone());}}+ for t in &targets {+ // A bad relay URL is the caller's mistake, not a relay failure.+ RelayClient::new(&t.relay_url)?;+ }+ self.add_pending_removals(&targets)?;+ let left = self.run_removals(account, None).await;self.manager_for_config(&config).uninstall()?;if config.runner == RunnerKind::AppHelper.as_str() {// Whatever an interrupted move left of the old agent.let _ = self.retire_legacy();}remove_dir_retrying(&self.paths.dir).await?;- match relay_error {- Some(e) => Err(Error::Relay(format!(- "removed locally, but the relay could not be told: {e}"+ match left+ .into_iter()+ .find(|l| targets.iter().any(|t| t.same(&l.relay_url, &l.machine_id)))+ {+ Some(l) => Err(Error::Relay(format!(+ "removed locally, but the relay could not be told: {}. Cua will take it off \+ your account the next time it reaches the relay.",+ l.last_error+ .as_deref()+ .unwrap_or("the relay did not answer"),))),None => Ok(()),}}++ // ------------------------------------------- removals the relay missed++ fn pending_removals_path(&self) -> PathBuf {+ // Beside the machine id, not under `<home>/host`, which a removal+ // deletes.+ self.paths.driver_data.join(PENDING_REMOVALS_FILE)+ }++ fn read_pending_removals(&self) -> Vec<PendingRemoval> {+ read_json(&self.pending_removals_path())+ .ok()+ .flatten()+ .unwrap_or_default()+ }++ fn save_pending_removals(&self, pending: &[PendingRemoval]) -> Result<()> {+ let path = self.pending_removals_path();+ if pending.is_empty() {+ let _ = std::fs::remove_file(&path);+ return Ok(());+ }+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir)?;+ }+ write_json(&path, &pending)+ }++ fn add_pending_removals(&self, targets: &[PendingRemoval]) -> Result<()> {+ if targets.is_empty() {+ return Ok(());+ }+ let mut pending = self.read_pending_removals();+ for t in targets {+ match pending+ .iter_mut()+ .find(|p| p.same(&t.relay_url, &t.machine_id))+ {+ // The newest token wins.+ Some(p) => {+ if !t.machine_token.is_empty() {+ p.machine_token = t.machine_token.clone();+ }+ }+ None => pending.push(t.clone()),+ }+ }+ self.save_pending_removals(&pending)+ }++ /// The computers (relay URL, machine id) whose removal from a relay is+ /// still waiting to reach it.+ pub fn pending_removals(&self) -> Vec<(String, String)> {+ self.read_pending_removals()+ .into_iter()+ .map(|p| (p.relay_url, p.machine_id))+ .collect()+ }++ /// Takes off the relay every computer a removal could not reach it for+ /// (this computer's earlier registrations whose delete failed because+ /// the relay was unreachable or refused its token): first with the+ /// computer's own token, then, with `account`, as the owner. One that+ /// this computer has since registered again is never touched. Returns+ /// the removals still waiting.+ pub async fn finish_removals(+ &self,+ account: Option<&RemovalAccount<'_>>,+ ) -> Vec<PendingRemoval> {+ let live = self+ .config()+ .ok()+ .flatten()+ .and_then(|c| match (c.relay_url, c.machine_id) {+ (Some(u), Some(i)) => Some((u, i)),+ _ => None,+ });+ self.run_removals(account, live).await+ }++ async fn run_removals(+ &self,+ account: Option<&RemovalAccount<'_>>,+ live: Option<(String, String)>,+ ) -> Vec<PendingRemoval> {+ let pending = self.read_pending_removals();+ if pending.is_empty() {+ return pending;+ }+ let mut left = Vec::new();+ for mut p in pending {+ // Registered again since (setup reuses the id): it is live, not+ // a leftover.+ if live.as_ref().is_some_and(|(url, id)| p.same(url, id)) {+ continue;+ }+ match p.try_delete(account).await {+ Ok(()) => {}+ Err(e) => {+ tracing::warn!(machine = %p.machine_id, "relay removal still pending: {e}");+ p.last_error = Some(e.to_string());+ // A year of refusals is an answer: stop asking.+ if now_ms().saturating_sub(p.since_ms) < PENDING_REMOVAL_GIVE_UP_MS {+ left.push(p);+ }+ }+ }+ }+ if let Err(e) = self.save_pending_removals(&left) {+ tracing::warn!("could not save the pending relay removals: {e}");+ }+ left+ }++ /// [`Host::finish_removals`] from [`Host::status`]: with the computer's+ /// own tokens only, at most once a minute, and only when something is+ /// waiting (a status is asked for often).+ async fn retry_pending_removals(&self) {+ static LAST: std::sync::Mutex<+ Option<std::collections::HashMap<PathBuf, std::time::Instant>>,+ > = std::sync::Mutex::new(None);+ let path = self.pending_removals_path();+ if !path.is_file() {+ return;+ }+ {+ let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner());+ let last = last.get_or_insert_with(Default::default);+ if last+ .get(&path)+ .is_some_and(|at| at.elapsed() < std::time::Duration::from_secs(60))+ {+ return;+ }+ last.insert(path, std::time::Instant::now());+ }+ let _ = tokio::time::timeout(+ std::time::Duration::from_secs(10),+ self.finish_removals(None),+ )+ .await;+ }}/// Renames `from` to `to`, copying across volumes.diff --git a/libs/cua/crates/cua-host/src/lib.rs b/libs/cua/crates/cua-host/src/lib.rsindex 7aa5d5d956..9ec6eeb63d 100644--- a/libs/cua/crates/cua-host/src/lib.rs+++ b/libs/cua/crates/cua-host/src/lib.rs@@ -66,8 +66,9 @@ pub use host::SetupStage;pub use host::{DirectHosting, Host, HostConfig, HostMode, HostPaths, HostPolicy, HostSettingsChange,HostStatus, META_ARCH, META_CLOUD, META_OS, META_PHONE_FEED, META_PROVIDES_SPACES,- PermissionHint, RELAY_HICCUP_GRACE, SetupOptions, ShareEdgeJoin, SpacesDaemon, StaticRelay,- default_provide_spaces, local_network_hint, permission_hints,+ PendingRemoval, PermissionHint, RELAY_HICCUP_GRACE, RemovalAccount, SetupOptions,+ ShareEdgeJoin, SpacesDaemon, StaticRelay, default_provide_spaces, local_network_hint,+ permission_hints,};pub use machine::machine_id;pub use pairing::{diff --git a/libs/cua/crates/cua-host/src/testing.rs b/libs/cua/crates/cua-host/src/testing.rsindex f7c33213e5..6425f42700 100644--- a/libs/cua/crates/cua-host/src/testing.rs+++ b/libs/cua/crates/cua-host/src/testing.rs@@ -73,6 +73,8 @@ struct State_ {/// Statuses the next machine registrations answer with, in order/// (a relay mid-deploy, a proxy in front of it).fail_register: std::collections::VecDeque<u16>,+ /// Statuses the next machine deletes answer with, in order.+ fail_deletes: std::collections::VecDeque<u16>,/// Statuses the next machine reads (GET) answer with, in order.fail_reads: std::collections::VecDeque<u16>,/// Every machine read answers 503, as the proxy in front of the@@ -666,6 +668,12 @@ async fn patch(async fn delete(State(s): State<S>, headers: HeaderMap, Path(id): Path<String>) -> Response {let mut st = s.lock().unwrap();+ if let Some(code) = st.fail_deletes.pop_front() {+ return err(+ StatusCode::from_u16(code).unwrap_or(StatusCode::BAD_GATEWAY),+ "delete failed",+ );+ }if let Err(r) = authorize(&st, &headers, &id, true) {return r;}@@ -1406,6 +1414,17 @@ impl FakeRelay {.extend(statuses.iter().copied());}+ /// The next machine deletes answer with `statuses`, in order, before the+ /// relay deletes normally again (a relay mid-deploy: 503; a refused+ /// token: 401 or 403).+ pub fn fail_deletes(&self, statuses: &[u16]) {+ self.state+ .lock()+ .unwrap()+ .fail_deletes+ .extend(statuses.iter().copied());+ }+/// The next machine reads (the list, or one machine) answer with/// `statuses`, in order, before the relay answers normally again.pub fn fail_reads(&self, statuses: &[u16]) {diff --git a/libs/cua/crates/cua-host/src/tests.rs b/libs/cua/crates/cua-host/src/tests.rsindex 407e285a70..f177b85bcc 100644--- a/libs/cua/crates/cua-host/src/tests.rs+++ b/libs/cua/crates/cua-host/src/tests.rs@@ -2756,3 +2756,256 @@ async fn setup_says_so_when_no_port_is_free() {);assert!(f.manager.calls.lock().unwrap().is_empty());}++// ---------------------------------------------------------------------+// One id per computer: turning remote access off and on, removal that the+// relay missed, and signing in as another account and back.++/// A JWT-shaped token with a `sub` and an `email` claim.+fn jwt_with_email(sub: &str, email: &str) -> String {+ use base64::Engine as _;+ let b = |v: &str| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(v);+ format!(+ "{}.{}.sig",+ b("{}"),+ b(&format!(r#"{{"sub":"{sub}","email":"{email}"}}"#))+ )+}++/// The ids of the computers `token`'s account has on the relay.+async fn listed(relay: &FakeRelay, token: &str) -> Vec<String> {+ let mut ids: Vec<String> = RelayClient::new(&relay.url)+ .unwrap()+ .machines(token)+ .await+ .unwrap()+ .into_iter()+ .map(|m| m.id)+ .collect();+ ids.sort();+ ids+}++/// Off and on again (remove the host setup, set it up again) is the same+/// computer: the same id, one row on the relay, however often it is done.+#[tokio::test]+async fn turning_remote_access_off_and_on_keeps_one_computer() {+ let relay = FakeRelay::start().await;+ relay.add_account("acct", "user-1", Some("[email protected]"));+ let f = fixture();+ let host = f.host();+ let first = host+ .setup(f.relay_opts(&relay.url), &StaticToken("acct".into()))+ .await+ .unwrap();+ let id = first.machine_id.clone().unwrap();+ for _ in 0..3 {+ host.remove().await.unwrap();+ assert!(listed(&relay, "acct").await.is_empty(), "off: gone");+ let again = host+ .setup(f.relay_opts(&relay.url), &StaticToken("acct".into()))+ .await+ .unwrap();+ assert_eq!(again.machine_id.as_deref(), Some(id.as_str()));+ assert_eq!(listed(&relay, "acct").await, vec![id.clone()], "on: one");+ }+}++/// A removal the relay could not take (it was mid-deploy) is remembered+/// outside the directory a removal deletes, and finished once the relay+/// answers: the computer does not stay listed with nothing left here to+/// retry it from.+#[tokio::test]+async fn a_removal_the_relay_missed_is_remembered_and_finished() {+ let relay = FakeRelay::start().await;+ relay.add_account("acct", "user-1", Some("[email protected]"));+ let f = fixture();+ let host = f.host();+ let id = host+ .setup(f.relay_opts(&relay.url), &StaticToken("acct".into()))+ .await+ .unwrap()+ .machine_id+ .unwrap();++ relay.fail_deletes(&[503]);+ let err = host.remove().await.unwrap_err().to_string();+ assert!(err.contains("removed locally"), "{err}");+ assert!(+ err.contains("next time"),+ "it says it will be retried: {err}"+ );+ assert!(relay.machine(&id).is_some(), "still listed for now");+ assert_eq!(+ host.pending_removals(),+ vec![(relay.url.clone(), id.clone())]+ );++ // The next time the relay answers it goes: a status asks (at most once+ // a minute), and so does anything that finishes removals.+ assert!(!host.status().await.unwrap().configured);+ assert!(relay.machine(&id).is_none(), "the status finished it");+ assert!(host.pending_removals().is_empty());+}++/// A relay that refuses the computer's own token (rotated, or lost) still+/// lets the owner take it off, so removing never needs the computer to+/// prove itself.+#[tokio::test]+async fn a_refused_computer_token_falls_back_to_the_owner_on_remove() {+ let relay = FakeRelay::start().await;+ relay.add_account("acct", "user-1", Some("[email protected]"));+ let f = fixture();+ let host = f.host();+ let id = host+ .setup(f.relay_opts(&relay.url), &StaticToken("acct".into()))+ .await+ .unwrap()+ .machine_id+ .unwrap();++ // Without the account the refusal is reported and remembered.+ relay.fail_deletes(&[403]);+ assert!(host.remove().await.is_err());+ assert!(relay.machine(&id).is_some());+ // The owner finishes it.+ let tokens = StaticToken("acct".into());+ let left = host+ .finish_removals(Some(&RemovalAccount {+ tokens: &tokens,+ device_session: None,+ }))+ .await;+ assert!(left.is_empty(), "{left:?}");+ assert!(relay.machine(&id).is_none());++ // And at once, when the account is there for the removal itself.+ host.setup(f.relay_opts(&relay.url), &StaticToken("acct".into()))+ .await+ .unwrap();+ relay.fail_deletes(&[401]);+ host.remove_with_account(&RemovalAccount {+ tokens: &tokens,+ device_session: None,+ })+ .await+ .unwrap();+ assert!(listed(&relay, "acct").await.is_empty());+ assert!(host.pending_removals().is_empty());+}++/// Setting up again after a removal the relay missed registers the same id+/// (so it is one row), and the pending removal never deletes the live+/// registration.+#[tokio::test]+async fn setting_up_again_after_a_missed_removal_reuses_the_row() {+ let relay = FakeRelay::start().await;+ relay.add_account("acct", "user-1", Some("[email protected]"));+ let f = fixture();+ let host = f.host();+ let id = host+ .setup(f.relay_opts(&relay.url), &StaticToken("acct".into()))+ .await+ .unwrap()+ .machine_id+ .unwrap();+ relay.fail_deletes(&[503]);+ assert!(host.remove().await.is_err());+ assert_eq!(host.pending_removals().len(), 1);++ let again = host+ .setup(f.relay_opts(&relay.url), &StaticToken("acct".into()))+ .await+ .unwrap();+ assert_eq!(again.machine_id.as_deref(), Some(id.as_str()));+ assert!(host.pending_removals().is_empty(), "nothing left to retry");+ assert_eq!(listed(&relay, "acct").await, vec![id.clone()]);+ assert!(relay.machine(&id).is_some(), "the live row was not deleted");+}++/// Signing in as another account and back is the same two computers every+/// time, and a relay that refuses the saved registration is an error that+/// says why, never a third, new computer.+#[tokio::test]+async fn switching_accounts_reuses_each_registration_and_never_mints_a_new_id() {+ let relay = FakeRelay::start().await;+ let (a, b) = (jwt("user-1"), jwt("user-2"));+ relay.add_account(&a, "user-1", Some("[email protected]"));+ relay.add_account(&b, "user-2", Some("[email protected]"));+ let f = fixture();+ let host = f.host();+ let id_a = host+ .setup(f.relay_opts(&relay.url), &StaticToken(a.clone()))+ .await+ .unwrap()+ .machine_id+ .unwrap();+ let id_b = host+ .resume_or_switch_account("user-2", &StaticToken(b.clone()))+ .await+ .unwrap()+ .machine_id+ .unwrap();+ assert_ne!(id_a, id_b, "another account has its own computer id");+ for _ in 0..2 {+ let s = host+ .resume_or_switch_account("user-1", &StaticToken(a.clone()))+ .await+ .unwrap();+ assert_eq!(s.machine_id.as_deref(), Some(id_a.as_str()));+ let s = host+ .resume_or_switch_account("user-2", &StaticToken(b.clone()))+ .await+ .unwrap();+ assert_eq!(s.machine_id.as_deref(), Some(id_b.as_str()));+ }+ assert_eq!(listed(&relay, &a).await, vec![id_a.clone()]);+ assert_eq!(listed(&relay, &b).await, vec![id_b.clone()]);++ // The relay refuses the saved registration of the first account.+ let registered = relay.register_calls();+ relay.fail_registrations(&[403]);+ let err = host+ .resume_or_switch_account("user-1", &StaticToken(a.clone()))+ .await+ .unwrap_err();+ assert!(matches!(err, Error::PermissionDenied(_)), "{err}");+ assert!(err.to_string().contains("saved registration"), "{err}");+ assert_eq!(relay.register_calls(), registered + 1, "asked once");+ assert_eq!(listed(&relay, &a).await, vec![id_a.clone()], "no new row");+ // Next time it goes through with the same id.+ let s = host+ .resume_or_switch_account("user-1", &StaticToken(a.clone()))+ .await+ .unwrap();+ assert_eq!(s.machine_id.as_deref(), Some(id_a.as_str()));+}++/// A relay whose account id is not the token's `sub` (it takes another+/// claim) still finds the saved registration, by the token's email.+#[tokio::test]+async fn the_saved_registration_is_found_by_email_when_the_account_id_is_not_the_subject() {+ let relay = FakeRelay::start().await;+ let a = jwt_with_email("sub-a", "[email protected]");+ let b = jwt_with_email("sub-b", "[email protected]");+ // The relay's account ids are not the subjects.+ relay.add_account(&a, "acct-ada", Some("[email protected]"));+ relay.add_account(&b, "acct-bob", Some("[email protected]"));+ let f = fixture();+ let host = f.host();+ let id_a = host+ .setup(f.relay_opts(&relay.url), &StaticToken(a.clone()))+ .await+ .unwrap()+ .machine_id+ .unwrap();+ host.resume_or_switch_account("acct-bob", &StaticToken(b.clone()))+ .await+ .unwrap();+ let back = host+ .resume_or_switch_account("acct-ada", &StaticToken(a.clone()))+ .await+ .unwrap();+ assert_eq!(back.machine_id.as_deref(), Some(id_a.as_str()));+ assert_eq!(listed(&relay, &a).await, vec![id_a]);+}diff --git a/libs/cua/crates/cua-sdk/src/native/host.rs b/libs/cua/crates/cua-sdk/src/native/host.rsindex fab44a9943..20341bb88e 100644--- a/libs/cua/crates/cua-sdk/src/native/host.rs+++ b/libs/cua/crates/cua-sdk/src/native/host.rs@@ -905,7 +905,28 @@ impl Host {pub async fn remove(&self) -> Result<()> {let home = self.home.clone();run(async move {- cua_host::Host::new(home).remove().await?;+ let host = cua_host::Host::new(home);+ // The relay is told with this computer's own token; when that is+ // refused (or it has none) as the signed-in owner, so a+ // computer that cannot prove itself is still taken off the+ // account, and one the relay could not be reached for is+ // retried later.+ let tokens = SessionTokens(Arc::new(cua_auth::Session::from_env()));+ let device_session = match host.config()?.and_then(|c| c.relay_url) {+ Some(url) => tokio::time::timeout(+ std::time::Duration::from_secs(10),+ own_device_session(&url),+ )+ .await+ .ok()+ .flatten(),+ None => None,+ };+ host.remove_with_account(&cua_host::RemovalAccount {+ tokens: &tokens,+ device_session,+ })+ .await?;// Then the runtimes cua set up itself (the built-in Lume and the// built-in Linux runtime, set up again on the next create that// needs them); the user's own stay.@@ -1290,7 +1311,14 @@ impl Devices {).await?.into();- cua_host::Host::new(cua_daemon::cua_home()).adopt_name(&machine_id, &name)?;+ // Every copy of the name on this device (this computer's host+ // setup, the saved directory, the registry), by the machine id.+ cua_spaces::relay::adopt_machine_name(+ &cua_daemon::cua_home(),+ auth.relay_url(),+ &machine_id,+ &name,+ );Ok(m)}).awaitdiff --git a/libs/cua/crates/cua-spaces/src/relay.rs b/libs/cua/crates/cua-spaces/src/relay.rsindex 69c513feb2..6f899282a7 100644--- a/libs/cua/crates/cua-spaces/src/relay.rs+++ b/libs/cua/crates/cua-spaces/src/relay.rs@@ -100,6 +100,10 @@ pub(crate) struct RelayBearer {pub(crate) account: RelayAccount,}+/// How long a computer the relay lists as connected has to answer before+/// removing it from the account counts it as a stale entry.+const LIVE_PROBE: std::time::Duration = std::time::Duration::from_secs(6);+type BoxError = Box<dyn std::error::Error + Send + Sync>;impl cua_spacesd_client::BearerProvider for RelayBearer {@@ -159,6 +163,68 @@ pub(crate) fn is_registered_space(m: &RelayMachine) -> bool {&& m.id.starts_with("space-")}+/// Makes `name` the name of relay computer `machine_id` in every copy this+/// device keeps, after the relay took it (`PATCH /v1/machines/{id}`): the+/// host setup's own name when it is this computer, the saved directory+/// listing (read first when the app starts), the `relay:<id>` record in the+/// registry, and the host entries named like the computer was, which the+/// "Run on" list matches by name. The computer is found by its id+/// everywhere, so a rename never makes it a different or an offline one.+/// Best effort: a copy that cannot be written is logged.+pub fn adopt_machine_name(home: &std::path::Path, relay_url: &str, machine_id: &str, name: &str) {+ let name = name.trim();+ if name.is_empty() {+ return;+ }+ if let Err(e) = cua_host::Host::new(home).adopt_name(machine_id, name) {+ tracing::debug!(error = %e, "host name not updated");+ }+ let mut old: Vec<String> = Vec::new();+ let mut saved = crate::listing::load_directory(home, relay_url);+ let mut changed = false;+ for m in saved.iter_mut().filter(|m| m.id == machine_id) {+ if m.name != name {+ old.push(std::mem::replace(&mut m.name, name.to_string()));+ changed = true;+ }+ }+ if changed {+ crate::listing::save_directory(home, relay_url, &saved);+ }+ let registry = crate::registry::Registry::new(home);+ let space = format!("relay:{machine_id}");+ match registry.get(&space) {+ Ok(Some(mut record)) => {+ if record.name != name {+ old.push(record.name.clone());+ record.name = name.to_string();+ let credential = registry+ .credential(&space)+ .ok()+ .flatten()+ .unwrap_or_default();+ if let Err(e) = registry.upsert(record, credential) {+ tracing::debug!(error = %e, "{space} record not renamed");+ }+ }+ }+ Ok(None) => {}+ Err(e) => tracing::debug!(error = %e, "{space} record not read"),+ }+ if !old.is_empty()+ && let Err(e) = registry.update_direct_hosts(|hosts| {+ for h in hosts.iter_mut().filter(|h| {+ !h.space.starts_with("relay:")+ && old.iter().any(|o| o.eq_ignore_ascii_case(&h.name))+ }) {+ h.name = name.to_string();+ }+ })+ {+ tracing::debug!(error = %e, "host entries not renamed");+ }+}+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@@ -199,19 +265,28 @@ impl crate::Spaces {))));}// 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.+ // host keeps providing it, or it is a stale entry): it goes. A Space+ // in your cloud that is connected now does not (the cloud ends it).+ // A computer the relay lists as connected goes only when it does not+ // answer: the listing can outlive a computer that is gone (a relay+ // that handed over, a crash behind a proxy), and such a row would+ // otherwise be a ghost nobody can remove. One that answers is+ // connected for real and is taken off from that computer.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!(+ if crate::cloud::is_cloud_machine(&m) {+ return Err(Error::invalid(format!(+ "{id} ({name}) is a running Space; delete it with `cua spaces delete {id}`"+ )));+ }+ if self.answers_through_relay(machine_id).await {+ return Err(Error::invalid(format!("{id} ({name}) is one of your computers and is connected now; take it off \the relay with `cua host remove` on that computer"- )- }));+ )));+ }+ tracing::info!(machine = %machine_id, "listed connected but not answering: removing the stale entry");}#[cfg(feature = "spaces-agents")]self.detach_attached_driver(machine_id).await;@@ -223,6 +298,38 @@ impl crate::Spaces {Ok(Some(m))}+ /// [`adopt_machine_name`] for this runtime: its cached directory too.+ pub(crate) fn adopt_relay_machine_name(&self, machine_id: &str, name: &str) {+ if let Some(account) = self.relay_account() {+ adopt_machine_name(self.home_dir(), &account.url, machine_id, name);+ }+ for m in self+ .inner+ .relay_cache+ .lock()+ .expect("relay cache")+ .iter_mut()+ .filter(|m| m.id == machine_id)+ {+ m.name = name.trim().to_string();+ }+ }++ /// Whether `relay:<machine_id>`, which the relay lists as connected,+ /// answers a fresh connection within [`LIVE_PROBE`]. A computer that+ /// refuses because its owner stopped sharing it is alive (that is how+ /// it refused).+ pub(crate) async fn answers_through_relay(&self, machine_id: &str) -> bool {+ let id = format!("relay:{machine_id}");+ // Never an old connection: that is what may be stale.+ let _ = self.forget_connection(&id).await;+ match tokio::time::timeout(LIVE_PROBE, self.space(&id)).await {+ Ok(Ok(_)) => true,+ Ok(Err(e)) => crate::host_spaces::is_stopped_sharing(&e.to_string()),+ Err(_) => false,+ }+ }+/// 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.diff --git a/libs/cua/crates/cua-spaces/src/share.rs b/libs/cua/crates/cua-spaces/src/share.rsindex 07e6883e45..a78286b514 100644--- a/libs/cua/crates/cua-spaces/src/share.rs+++ b/libs/cua/crates/cua-spaces/src/share.rs@@ -514,26 +514,8 @@ impl Spaces {cua_host::Error::PermissionDenied(_) => refused(),e => e.into(),})?;- for m in self- .inner- .relay_cache- .lock()- .expect("relay cache")- .iter_mut()- .filter(|m| m.id == machine)- {- m.name = name.to_string();- }- // A `relay:` Space added to this device's registry lists its record.- if relay_space && let Some(mut record) = self.inner.registry.get(&info.id)? {- record.name = name.to_string();- let credential = self- .inner- .registry- .credential(&info.id)?- .unwrap_or_default();- self.inner.registry.upsert(record, credential)?;- }+ // Every copy of the name on this device, found by the machine id.+ self.adopt_relay_machine_name(&machine, name);Ok(())}diff --git a/libs/cua/crates/cua-spaces/tests/computer_identity.rs b/libs/cua/crates/cua-spaces/tests/computer_identity.rsnew file mode 100644index 0000000000..b259963f05--- /dev/null+++ b/libs/cua/crates/cua-spaces/tests/computer_identity.rs@@ -0,0 +1,307 @@+//! A computer is one row, found by its id: removing a ghost the relay lists+//! as connected, and renaming a computer (this one or another) without it+//! changing id or going offline in any list. Hermetic: a throwaway cua home+//! per computer and the fake relay directory+//! (`cua_host::testing::FakeRelay`); nothing touches the real home, the+//! network, or the desktop.++use cua_host::testing::FakeRelay;+use cua_spaces::relay::StaticToken;+use cua_spaces::{RelayAccount, Spaces};+use cua_spacesd_client::testing::{MockAuth, MockServer};+use std::path::Path;+use std::sync::Arc;++const MACHINE: &str = "0123abcd4567ef89";+const TOKEN: &str = "owner-token";++fn signed_in(home: &Path, relay: &FakeRelay) -> Spaces {+ Spaces::builder()+ .home(home)+ .relay(RelayAccount::new(+ &relay.url,+ Arc::new(StaticToken(TOKEN.into())),+ ))+ .build()+}++async fn register(relay: &FakeRelay, id: &str, name: &str) {+ cua_host::RelayClient::new(&relay.url)+ .unwrap()+ .register(+ TOKEN,+ &cua_host::relay::RegisterRequest {+ id: id.into(),+ name: name.into(),+ allow: vec![],+ host: None,+ meta: Default::default(),+ },+ )+ .await+ .unwrap();+}++/// Writes the host setup of `home` the way `cua host setup` leaves it.+fn host_setup(home: &Path, relay: &FakeRelay, id: &str, name: &str) {+ std::fs::create_dir_all(home.join("host")).unwrap();+ std::fs::write(+ home.join("host/config.json"),+ serde_json::json!({+ "mode": "relay",+ "relay_url": relay.url,+ "name": name,+ "machine_id": id,+ "runner": "process",+ "driver_bin": "/nonexistent/cua-spacesd",+ })+ .to_string(),+ )+ .unwrap();+}++/// `(name, status)` of the `relay:<id>` row in `spaces`' cached list.+fn row(spaces: &Spaces, id: &str) -> Option<(String, String)> {+ spaces+ .list()+ .unwrap()+ .into_iter()+ .find(|i| i.id == format!("relay:{id}"))+ .map(|i| (i.shown_name().to_string(), i.status))+}++/// A computer the relay lists as connected that does not answer (a stale+/// entry: a relay that handed over, a crash behind a proxy) is a ghost the+/// owner can remove from the app; one that answers is connected for real+/// and is taken off from that computer.+#[tokio::test]+async fn a_ghost_listed_as_connected_can_be_removed_but_a_live_computer_cannot() {+ let relay = FakeRelay::start().await;+ relay.add_account(TOKEN, "user-1", Some("[email protected]"));+ let live = "aaaa111122223333";+ let ghost = "bbbb111122223333";+ register(&relay, live, "studio").await;+ register(&relay, ghost, "old-studio").await;+ relay.set_online(live, true, "1.0.0");+ relay.set_online(ghost, true, "1.0.0");+ // `live` answers through the relay; `ghost` does not (the fake relay+ // answers 502 for a machine with nothing behind it).+ let srv = MockServer::start(MockAuth {+ token: None,+ gateway: None,+ prefix: None,+ })+ .await;+ relay.tunnel(live, &srv.url());++ let home = tempfile::tempdir().unwrap();+ let app = signed_in(home.path(), &relay);+ app.list_all().await.unwrap();++ let err = app+ .relay_unregister(&format!("relay:{live}"))+ .await+ .unwrap_err()+ .to_string();+ assert!(+ err.contains("connected now") && err.contains("cua host remove"),+ "{err}"+ );+ assert!(relay.machine(live).is_some(), "a live computer stays");++ assert!(+ app.relay_unregister(&format!("relay:{ghost}"))+ .await+ .unwrap()+ );+ assert!(+ relay.machine(ghost).is_none(),+ "the ghost is gone on the relay"+ );+ assert!(row(&app, ghost).is_none(), "and in this list");+ assert!(row(&app, live).is_some());+}++/// A computer that is offline is removed, as before.+#[tokio::test]+async fn an_offline_computer_is_removed_from_the_account() {+ let relay = FakeRelay::start().await;+ relay.add_account(TOKEN, "user-1", Some("[email protected]"));+ register(&relay, MACHINE, "studio").await;+ let home = tempfile::tempdir().unwrap();+ let app = signed_in(home.path(), &relay);+ app.list_all().await.unwrap();+ assert!(+ app.relay_unregister(&format!("relay:{MACHINE}"))+ .await+ .unwrap()+ );+ assert!(relay.machine(MACHINE).is_none());+}++/// Renaming a computer from the Machines page patches the relay and then+/// every copy this device keeps by the machine id: this computer's host+/// setup, the saved directory (what the lists show first), the cached list.+/// It stays the same computer, online, in this computer's lists and in the+/// lists of the account's other computers.+#[tokio::test]+async fn renaming_a_computer_keeps_its_id_and_it_stays_online_in_every_list() {+ let relay = FakeRelay::start().await;+ relay.add_account(TOKEN, "user-1", Some("[email protected]"));+ register(&relay, MACHINE, "alpha").await;+ relay.set_online(MACHINE, true, "1.0.0");++ // This computer (a host), and another computer of the account.+ let this = tempfile::tempdir().unwrap();+ host_setup(this.path(), &relay, MACHINE, "alpha");+ let other = tempfile::tempdir().unwrap();+ let on_this = signed_in(this.path(), &relay);+ let on_other = signed_in(other.path(), &relay);+ on_this.list_all().await.unwrap();+ on_other.list_all().await.unwrap();+ assert_eq!(row(&on_other, MACHINE).unwrap().0, "alpha");++ // What the app's Machines page does (`Relay::rename_machine`).+ cua_host::RelayClient::new(&relay.url)+ .unwrap()+ .patch(+ TOKEN,+ MACHINE,+ &cua_host::MachinePatch {+ name: Some("beta".into()),+ ..Default::default()+ },+ )+ .await+ .unwrap();+ cua_spaces::relay::adopt_machine_name(this.path(), &relay.url, MACHINE, "beta");++ // This computer's host setup follows.+ let cfg = cua_host::Host::new(this.path()).config().unwrap().unwrap();+ assert_eq!(cfg.name, "beta");+ assert_eq!(cfg.machine_id.as_deref(), Some(MACHINE));+ // A fresh start of the app reads the saved directory before the relay+ // answers: it already says Beta, not the old name.+ let restarted = Spaces::builder().home(this.path()).build();+ restarted.set_relay(Some(RelayAccount::new(+ &relay.url,+ Arc::new(StaticToken(TOKEN.into())),+ )));+ assert_eq!(row(&restarted, MACHINE).unwrap().0, "beta");++ // Both lists, once read again: same id, new name, still online.+ for app in [&on_this, &on_other] {+ let all = app.list_all().await.unwrap();+ let listed: Vec<_> = all.iter().filter(|i| i.id.starts_with("relay:")).collect();+ assert_eq!(listed.len(), 1, "one computer");+ assert_eq!(listed[0].id, format!("relay:{MACHINE}"));+ assert_eq!(listed[0].shown_name(), "beta");+ assert_ne!(listed[0].status, "offline");+ assert!(app.relay_machines().await.unwrap()[0].online);+ }+ // The old name no longer names it; the new one does.+ assert!(on_this.resolve("alpha").is_err());+ assert_eq!(+ on_this.resolve("beta").unwrap().to_string(),+ format!("relay:{MACHINE}")+ );+}++/// The Space rename path updates the same copies (and the in-memory list at+/// once), by the same function.+#[tokio::test]+async fn renaming_a_relay_computer_as_a_space_updates_the_same_copies() {+ let relay = FakeRelay::start().await;+ relay.add_account(TOKEN, "user-1", Some("[email protected]"));+ register(&relay, MACHINE, "alpha").await;+ relay.set_online(MACHINE, true, "1.0.0");+ let this = tempfile::tempdir().unwrap();+ host_setup(this.path(), &relay, MACHINE, "alpha");+ let app = signed_in(this.path(), &relay);+ app.list_all().await.unwrap();++ app.rename(&format!("relay:{MACHINE}"), "gamma")+ .await+ .unwrap();+ assert_eq!(row(&app, MACHINE).unwrap().0, "gamma");+ let cfg = cua_host::Host::new(this.path()).config().unwrap().unwrap();+ assert_eq!(cfg.name, "gamma", "this computer's own setup follows");+ assert_eq!(relay.machine(MACHINE).unwrap().name, "gamma");+ assert!(relay.machine(MACHINE).unwrap().online);+}++/// The `relay:` record in the registry and the host entries the "Run on"+/// list matches by name follow a rename, so the same computer is not listed+/// twice under two names.+#[tokio::test]+async fn a_rename_reaches_the_registry_record_and_the_host_entry_named_like_it() {+ use cua_proto::daemon::v1 as dpb;+ use cua_spaces::registry::Credential;+ let home = tempfile::tempdir().unwrap();+ let registry = cua_spaces::registry::Registry::new(home.path());+ registry+ .upsert(+ dpb::Space {+ id: format!("relay:{MACHINE}"),+ name: "alpha".into(),+ ..Default::default()+ },+ Credential::default(),+ )+ .unwrap();+ registry+ .upsert_direct_host("Alpha", "direct:100.64.0.9:3211")+ .unwrap();+ registry+ .upsert_direct_host("elsewhere", "direct:100.64.0.10:3211")+ .unwrap();++ cua_spaces::relay::adopt_machine_name(home.path(), "http://relay.test", MACHINE, "beta");++ let record = registry.get(&format!("relay:{MACHINE}")).unwrap().unwrap();+ assert_eq!(record.name, "beta");+ let hosts: Vec<_> = registry+ .direct_hosts()+ .unwrap()+ .into_iter()+ .map(|h| (h.space, h.name))+ .collect();+ assert!(+ hosts.contains(&("direct:100.64.0.9:3211".into(), "beta".into())),+ "{hosts:?}"+ );+ assert!(+ hosts.contains(&("direct:100.64.0.10:3211".into(), "elsewhere".into())),+ "{hosts:?}"+ );+}++/// "Run on" lists a computer set up both ways (on the relay and added by+/// address) once, matching them by name. A rename must take both names+/// along, or the address entry (unreachable from another network) is listed+/// again as an offline copy of the renamed computer.+#[tokio::test]+async fn a_renamed_computer_is_not_listed_again_as_an_offline_host() {+ let relay = FakeRelay::start().await;+ relay.add_account(TOKEN, "user-1", Some("[email protected]"));+ register(&relay, MACHINE, "alpha").await;+ relay.set_online(MACHINE, true, "1.0.0");+ let home = tempfile::tempdir().unwrap();+ let app = signed_in(home.path(), &relay);+ // The same computer, added by an address this network cannot reach.+ app.registry()+ .upsert_direct_host("alpha", "direct:127.0.0.1:1")+ .unwrap();+ app.list_all().await.unwrap();+ let names = |hosts: Vec<cua_spaces::host_spaces::HostOffer>| {+ let mut n: Vec<String> = hosts.into_iter().map(|h| h.name).collect();+ n.sort();+ n+ };+ assert_eq!(names(app.hosts().await.unwrap()), ["alpha"]);++ app.rename(&format!("relay:{MACHINE}"), "beta")+ .await+ .unwrap();+ assert_eq!(names(app.hosts().await.unwrap()), ["beta"]);+}diff --git a/libs/cua/crates/cua-spaces/tests/share.rs b/libs/cua/crates/cua-spaces/tests/share.rsindex fc93558162..1b303a5d50 100644--- a/libs/cua/crates/cua-spaces/tests/share.rs+++ b/libs/cua/crates/cua-spaces/tests/share.rs@@ -654,10 +654,10 @@ async fn rm_and_relay_unregister_leave_no_stale_relay_record() {}/// 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`.+/// `relay_unregister` of a machine that is no longer connected (or listed+/// as connected but not answering) remove it from the relay directory, and+/// a live Space registration is untouched by `rm`. A host that answers is+/// refused with `cua host remove` (covered in `computer_identity.rs`).#[tokio::test]async fn stale_relay_records_can_be_removed() {let (relay, ada, _bob, _homes) = two_accounts().await;@@ -683,18 +683,13 @@ async fn stale_relay_records_can_be_removed() {);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.+ // A host: one that is connected and answers is refused with a remedy+ // that can be carried out (see `computer_identity.rs`; the fake relay+ // here has nothing behind the id, so a listed-connected host is a+ // ghost that can be removed). `rm` and `delete` never remove a host.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, "");