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
feat(cli): cua machines rm removes a computer that is gone (#6092)
injaneity6660c7d56ba7
diff --git a/docs/content/docs/cua-cli/reference/cli/index.mdx b/docs/content/docs/cua-cli/reference/cli/index.mdxindex 6aaee0390d..654c4a49a5 100644--- a/docs/content/docs/cua-cli/reference/cli/index.mdx+++ b/docs/content/docs/cua-cli/reference/cli/index.mdx@@ -25,6 +25,7 @@ Your Spaces and machines, unattended access on this machine, devices, teams, you| Command | Description | Subcommands || --- | --- | --- || <span id="cua-spaces"></span><span id="cua-spaces-ls"></span><span id="cua-spaces-add"></span><span id="cua-spaces-create"></span><span id="cua-spaces-prewarm"></span><span id="cua-spaces-egress"></span><span id="cua-spaces-cancel"></span><span id="cua-spaces-gpus"></span><span id="cua-spaces-delete"></span><span id="cua-spaces-stop"></span><span id="cua-spaces-suspend"></span><span id="cua-spaces-resize"></span><span id="cua-spaces-start"></span><span id="cua-spaces-rm"></span><span id="cua-spaces-rename"></span><span id="cua-spaces-share"></span><span id="cua-spaces-unshare"></span><span id="cua-spaces-shares"></span><span id="cua-spaces-relay-register"></span><span id="cua-spaces-relay-unregister"></span>[`cua spaces`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces) | Spaces: registered ones and your computers on the relay. | [`ls`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-ls), [`add`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-add), [`create`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-create), [`prewarm`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-prewarm), [`egress`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-egress), [`cancel`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-cancel), [`gpus`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-gpus), [`delete`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-delete), [`stop`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-stop), [`suspend`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-suspend), [`resize`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-resize), [`start`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-start), [`rm`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-rm), [`rename`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-rename), [`share`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-share), [`unshare`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-unshare), [`shares`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-shares), [`relay-register`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-relay-register), [`relay-unregister`](/cua-cli/reference/cli/spaces-and-computers#cua-spaces-relay-unregister) |+| <span id="cua-machines"></span><span id="cua-machines-rm"></span>[`cua machines`](/cua-cli/reference/cli/spaces-and-computers#cua-machines) | Your computers on the relay: remove one that is gone. | [`rm`](/cua-cli/reference/cli/spaces-and-computers#cua-machines-rm) || <span id="cua-host"></span><span id="cua-host-setup"></span><span id="cua-host-pair"></span><span id="cua-host-config"></span><span id="cua-host-status"></span><span id="cua-host-stop"></span><span id="cua-host-start"></span><span id="cua-host-share"></span><span id="cua-host-unshare"></span><span id="cua-host-migrate"></span><span id="cua-host-remove"></span>[`cua host`](/cua-cli/reference/cli/spaces-and-computers#cua-host) | Unattended access to this computer (setup, status, stop, start, remove). | [`setup`](/cua-cli/reference/cli/spaces-and-computers#cua-host-setup), [`pair`](/cua-cli/reference/cli/spaces-and-computers#cua-host-pair), [`config`](/cua-cli/reference/cli/spaces-and-computers#cua-host-config), [`status`](/cua-cli/reference/cli/spaces-and-computers#cua-host-status), [`stop`](/cua-cli/reference/cli/spaces-and-computers#cua-host-stop), [`start`](/cua-cli/reference/cli/spaces-and-computers#cua-host-start), [`share`](/cua-cli/reference/cli/spaces-and-computers#cua-host-share), [`unshare`](/cua-cli/reference/cli/spaces-and-computers#cua-host-unshare), [`migrate`](/cua-cli/reference/cli/spaces-and-computers#cua-host-migrate), [`remove`](/cua-cli/reference/cli/spaces-and-computers#cua-host-remove) || <span id="cua-devices"></span><span id="cua-devices-status"></span><span id="cua-devices-enroll"></span><span id="cua-devices-approve"></span><span id="cua-devices-ls"></span><span id="cua-devices-rename"></span><span id="cua-devices-revoke"></span><span id="cua-devices-audit"></span>[`cua devices`](/cua-cli/reference/cli/spaces-and-computers#cua-devices) | This device as a client of your cua.ai account on the relay: enroll (second factor), approve other devices, list, rename, revoke, and the audit log of who accessed what. | [`status`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-status), [`enroll`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-enroll), [`approve`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-approve), [`ls`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-ls), [`rename`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-rename), [`revoke`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-revoke), [`audit`](/cua-cli/reference/cli/spaces-and-computers#cua-devices-audit) || <span id="cua-team"></span><span id="cua-team-create"></span><span id="cua-team-ls"></span><span id="cua-team-show"></span><span id="cua-team-invite"></span><span id="cua-team-join"></span><span id="cua-team-leave"></span><span id="cua-team-remove-member"></span><span id="cua-team-set-role"></span><span id="cua-team-devices"></span><span id="cua-team-approve"></span><span id="cua-team-deny"></span><span id="cua-team-request"></span><span id="cua-team-add-machine"></span><span id="cua-team-remove-machine"></span><span id="cua-team-audit"></span><span id="cua-team-delete"></span>[`cua team`](/cua-cli/reference/cli/spaces-and-computers#cua-team) | Teams (organizations of your cua.ai account) share computers with every member and their agents. | [`create`](/cua-cli/reference/cli/spaces-and-computers#cua-team-create), [`ls`](/cua-cli/reference/cli/spaces-and-computers#cua-team-ls), [`show`](/cua-cli/reference/cli/spaces-and-computers#cua-team-show), [`invite`](/cua-cli/reference/cli/spaces-and-computers#cua-team-invite), [`join`](/cua-cli/reference/cli/spaces-and-computers#cua-team-join), [`leave`](/cua-cli/reference/cli/spaces-and-computers#cua-team-leave), [`remove-member`](/cua-cli/reference/cli/spaces-and-computers#cua-team-remove-member), [`set-role`](/cua-cli/reference/cli/spaces-and-computers#cua-team-set-role), [`devices`](/cua-cli/reference/cli/spaces-and-computers#cua-team-devices), [`approve`](/cua-cli/reference/cli/spaces-and-computers#cua-team-approve), [`deny`](/cua-cli/reference/cli/spaces-and-computers#cua-team-deny), [`request`](/cua-cli/reference/cli/spaces-and-computers#cua-team-request), [`add-machine`](/cua-cli/reference/cli/spaces-and-computers#cua-team-add-machine), [`remove-machine`](/cua-cli/reference/cli/spaces-and-computers#cua-team-remove-machine), [`audit`](/cua-cli/reference/cli/spaces-and-computers#cua-team-audit), [`delete`](/cua-cli/reference/cli/spaces-and-computers#cua-team-delete) |diff --git a/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx b/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdxindex d5ec280972..20fcfb9986 100644--- a/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx+++ b/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx@@ -32,6 +32,8 @@ description: "Your Spaces and machines, unattended access on this machine, devic| [`cua spaces shares`](#cua-spaces-shares) | Who a Space is shared with, and who of them is connected now. || [`cua spaces relay-register`](#cua-spaces-relay-register) | Publish a Space on the relay for your other devices (a phone off this network): its own driver dials out, as `cua host setup` does for this computer. || [`cua spaces relay-unregister`](#cua-spaces-relay-unregister) | Take a Space off the relay (every share with it ends). |+| [`cua machines`](#cua-machines) | Your computers on the relay: remove one that is gone. |+| [`cua machines rm`](#cua-machines-rm) | Remove a computer that is gone: its row leaves your relay directory, then the signed-in device with exactly its name is revoked (never this device; nothing when several match). || [`cua host`](#cua-host) | Unattended access to this computer (setup, status, stop, start, remove). || [`cua host setup`](#cua-host-setup) | Set this computer up for unattended access: install cua-spacesd as a service that joins the cua.ai relay as your account (default) or serves on a direct ip:port. || [`cua host pair`](#cua-host-pair) | Make a one-time code (with a link and the install command) that adds another computer to your account: run the command it prints on that computer. |@@ -569,6 +571,37 @@ cua spaces relay-unregister local:studiocua spaces relay-unregister relay:space-0123abcd4567ef89```+## `cua machines`++Your computers on the relay: remove one that is gone.++```text output+cua machines [OPTIONS] <COMMAND>+```++### `cua machines rm`++Remove a computer that is gone: its row leaves your relay directory, then the signed-in device with exactly its name is revoked (never this device; nothing when several match). A computer that is connected now is refused: run `cua host remove` on it.++```text output+cua machines rm [OPTIONS] <NAME>+```++| Argument | Type | Default | Description |+| --- | --- | --- | --- |+| `<NAME>` | string | required | The computer's name, machine id or `relay:<id>` (`cua spaces ls`). |++| Flag | Short | Type | Default | Description |+| --- | --- | --- | --- | --- |+| <span id="cua-machines-rm--yes"></span>`--yes` | `-y` | boolean | `false` | Remove without asking. |++**Examples**++```bash test="cli-shape" id="ref-cua-machines-rm"+cua machines rm old-laptop+cua machines rm relay:0123abcd4567ef89 --yes --json+```+## `cua host`Unattended access to this computer (setup, status, stop, start, remove).diff --git a/docs/content/docs/spaces/guides/add-a-computer.mdx b/docs/content/docs/spaces/guides/add-a-computer.mdxindex edcee7cc37..57f328ddbf 100644--- a/docs/content/docs/spaces/guides/add-a-computer.mdx+++ b/docs/content/docs/spaces/guides/add-a-computer.mdx@@ -148,6 +148,8 @@ cua devices audit # who opened which machine, from which device, and whencua devices revoke dev_0123456789abcdef01234567```+A computer that is gone: `cua machines rm <name>` removes it from your relay directory and revokes its device.+In the app, **Settings > Devices** shows this device's enrollment, your deviceswith Rename and Revoke, and Recent Access (which device opened which computer,and when). When another device asks to join, the app shows an approval sheet:diff --git a/libs/cua/crates/cua-cli/src/devices_cmd.rs b/libs/cua/crates/cua-cli/src/devices_cmd.rsindex 16744e62fd..60a79394da 100644--- a/libs/cua/crates/cua-cli/src/devices_cmd.rs+++ b/libs/cua/crates/cua-cli/src/devices_cmd.rs@@ -255,6 +255,19 @@ fn view_json(d: &DeviceView) -> serde_json::Value {serde_json::to_value(d).unwrap_or_default()}+/// Revokes device `id` and stops the agents it connected to Spaces.+pub(crate) async fn revoke_device(auth: &DeviceAuth, id: &str) -> Result<DeviceView, CuaError> {+ let this = auth.device_id().ok().flatten();+ let d = auth.revoke(id).await.map_err(crate::host::host_err)?;+ // The agents that computer connected to Spaces stop at once.+ if this.as_deref() == Some(id) {+ crate::member_cmd::forget_this_computer().await;+ } else {+ crate::member_cmd::revoke_device_members(id).await;+ }+ Ok(d)+}+/// Runs `cmd` for the device `auth` (`confirm` answers the consent/// prompts; tests pass a fixed answer).pub async fn run_with(@@ -508,14 +521,7 @@ pub async fn run_with("not revoked (pass --yes to revoke without a prompt)".into(),));}- let this = auth.device_id().ok().flatten();- let d = auth.revoke(&id).await.map_err(err)?;- // The agents that computer connected to Spaces stop at once.- if this.as_deref() == Some(id.as_str()) {- crate::member_cmd::forget_this_computer().await;- } else {- crate::member_cmd::revoke_device_members(&id).await;- }+ let d = revoke_device(auth, &id).await?;if json {line(out, view_json(&d).to_string());} else {diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rsindex 3cfa2f7fa4..ed00f59333 100644--- a/libs/cua/crates/cua-cli/src/host.rs+++ b/libs/cua/crates/cua-cli/src/host.rs@@ -291,6 +291,26 @@ pub enum HostCmd {},}+/// `cua machines`: your computers on the relay.+#[derive(Subcommand, Debug)]+pub enum MachinesCmd {+ /// Remove a computer that is gone: its row leaves your relay directory,+ /// then the signed-in device with exactly its name is revoked (never this+ /// device; nothing when several match). A computer that is connected now+ /// is refused: run `cua host remove` on it.+ #[command(after_help = "Examples:+ cua machines rm old-laptop+ cua machines rm relay:0123abcd4567ef89 --yes --json")]+ Rm {+ /// The computer's name, machine id or `relay:<id>` (`cua spaces ls`).+ #[arg(value_name = "NAME")]+ name: String,+ /// Remove without asking.+ #[arg(long, short = 'y')]+ yes: bool,+ },+}+#[derive(Subcommand, Debug)]pub enum SpacesCmd {/// Registered Spaces and your computers on the relay.@@ -1628,6 +1648,188 @@ impl AccountTokens for SessionTokens {}}+/// `cua machines rm`: removes a computer that is gone (its relay row, then+/// the one signed-in device named like it). The caller folds `--yes` into+/// `confirm`.+pub async fn remove_machine(+ cua: &cua_sdk::Cua,+ auth: &DeviceAuth,+ tokens: &dyn AccountTokens,+ name: &str,+ confirm: &dyn Fn(&str) -> bool,+ json: bool,+ out: &mut dyn Write,+) -> Result<i32, CuaError> {+ use cua_host::DeviceState;+ // The row is removed through `cua`, the lookup and the device through+ // `auth`: they must be one relay (a daemon keeps its own).+ let bound = cua+ .embedded_runtime()+ .and_then(|r| r.spaces().relay_account())+ .map(|a| a.url);+ let same = |a: &str, b: &str| a.trim_end_matches('/') == b.trim_end_matches('/');+ if !bound.is_some_and(|u| same(&u, auth.relay_url())) {+ return Err(CuaError::InvalidArgument(format!(+ "this runtime is not bound to the relay {} that your account uses; run it with --embedded",+ auth.relay_url()+ )));+ }+ // Fresh from the relay: the Space resolver reads a possibly cold cache.+ let relay = RelayClient::new(auth.relay_url()).map_err(host_err)?;+ let token = tokens.access_token().await.map_err(host_err)?;+ let machines = auth.machines_for(&relay, &token).await.map_err(host_err)?;+ let mut hits: Vec<_> = machines+ .iter()+ .filter(|m| m.id == name || format!("relay:{}", m.id) == name || m.name == name)+ .collect();+ hits.sort_by(|a, b| a.id.cmp(&b.id));+ let m = match hits.as_slice() {+ [] => {+ return Err(CuaError::NotFound(format!(+ "no computer named {name:?} in your relay directory (`cua spaces ls` lists them)"+ )));+ }+ [m] => *m,+ many => {+ let ids: Vec<_> = many.iter().map(|m| format!("relay:{}", m.id)).collect();+ return Err(CuaError::InvalidArgument(format!(+ "several computers are named {name:?}: pass one of {}",+ ids.join(", ")+ )));+ }+ };+ let rid = format!("relay:{}", m.id);+ if m.role != "owner" {+ return Err(CuaError::PermissionDenied(format!(+ "{rid} is shared with you; only its owner can remove it"+ )));+ }+ let hosted = m.host.as_deref().is_some_and(|h| !h.is_empty());+ let cloud = m+ .meta+ .get(cua_sandbox_core::byoc::meta::PROVIDER)+ .is_some_and(|p| !p.is_empty());+ let registered = !hosted+ && !m.meta.contains_key(cua_host::META_PROVIDES_SPACES)+ && m.id.starts_with("space-");+ if hosted || cloud || registered {+ return Err(CuaError::InvalidArgument(format!(+ "{rid} is a Space, not a computer; manage it with `cua spaces`"+ )));+ }+ if m.online {+ return Err(CuaError::InvalidArgument(format!(+ "{rid} ({}) is connected now; run `cua host remove` on that computer",+ m.name+ )));+ }+ if !confirm(&format!(+ "Remove {} ({rid}) from your relay directory and revoke the signed-in device named {}?",+ m.name, m.name+ )) {+ return Err(CuaError::PermissionDenied(+ "not removed (pass --yes to remove without a prompt)".into(),+ ));+ }+ // Refuses again if the computer connected meanwhile.+ let removed = cua.spaces().relay_unregister(rid.clone()).await?;+ let report = |out: &mut dyn Write, status: &str, ids: &[String], text: String| {+ if json {+ let v = serde_json::json!({+ "machine": { "id": rid, "name": m.name },+ "removed": removed,+ "device": { "status": status, "ids": ids, "message": text },+ });+ line(out, v.to_string());+ } else {+ if removed {+ line(+ out,+ format!("Removed {} ({rid}) from your relay directory.", m.name),+ );+ } else {+ line(+ out,+ format!("{rid} was already gone from your relay directory."),+ );+ }+ line(out, text);+ }+ };+ if !removed {+ report(out, "not_attempted", &[], "No device was touched.".into());+ return Ok(0);+ }+ let this = auth.device_id().ok().flatten();+ let found = auth.devices().await.map(|all| {+ let mut ids: Vec<_> = all+ .into_iter()+ .filter(|d| {+ !m.name.is_empty()+ && d.name == m.name+ && !d.current+ && Some(&d.id) != this.as_ref()+ && d.state != DeviceState::Revoked+ })+ .map(|d| d.id)+ .collect();+ ids.sort();+ ids+ });+ let fail = |out: &mut dyn Write, e: cua_host::Error| {+ report(+ out,+ "failed",+ &[],+ "Finish with `cua devices ls` and `cua devices revoke <id>`.".into(),+ );+ host_err(e)+ };+ let ids = match found {+ Ok(ids) => ids,+ Err(e) => return Err(fail(out, e)),+ };+ match ids.as_slice() {+ [] => report(+ out,+ "not_found",+ &[],+ format!(+ "No signed-in device named {}; no device was revoked.",+ m.name+ ),+ ),+ [id] => match crate::devices_cmd::revoke_device(auth, id).await {+ Ok(d) => report(+ out,+ "revoked",+ &ids,+ format!("Revoked {} ({}).", d.name, d.id),+ ),+ Err(e) => {+ report(+ out,+ "failed",+ &ids,+ "Finish with `cua devices ls` and `cua devices revoke <id>`.".into(),+ );+ return Err(e);+ }+ },+ many => report(+ out,+ "ambiguous",+ many,+ format!(+ "Several devices are named {} ({}): revoke the right one with `cua devices revoke <id>`.",+ m.name,+ many.join(", ")+ ),+ ),+ }+ Ok(0)+}+pub fn host_err(e: cua_host::Error) -> CuaError {let message = e.to_string();host_error(e, message)@@ -4739,6 +4941,362 @@ mod tests {);}+ mod machines_rm {+ use super::*;+ use cua_host::MemoryKeySlot;+ use cua_host::relay::{DeviceState, RegisterRequest};+ use std::cell::Cell;++ const ID: &str = "0123abcd4567ef89";++ struct Fx {+ _env: crate::util::test_env::Guard,+ relay: FakeRelay,+ cua: Arc<cua_sdk::Cua>,+ _dir: tempfile::TempDir,+ auth: Arc<DeviceAuth>,+ laptop: String,+ remote: Vec<String>,+ }++ async fn device(relay: &FakeRelay, name: &str, i: usize) -> (Arc<DeviceAuth>, String) {+ let d = Arc::new(+ DeviceAuth::new(+ &relay.url,+ Arc::new(StaticToken("acct".into())),+ Arc::new(MemoryKeySlot::default()),+ name,+ )+ .unwrap()+ .with_machine_id(Some(format!("machine-of-{i}"))),+ );+ relay.fresh_sign_in("user-1");+ d.enroll().await.unwrap();+ let id = d.device_id().unwrap().unwrap();+ (d, id)+ }++ async fn register(+ relay: &FakeRelay,+ id: &str,+ name: &str,+ host: Option<&str>,+ meta: std::collections::BTreeMap<String, String>,+ ) {+ RelayClient::new(&relay.url)+ .unwrap()+ .register(+ "acct",+ &RegisterRequest {+ id: id.into(),+ name: name.into(),+ allow: vec![],+ host: host.map(Into::into),+ meta,+ },+ )+ .await+ .unwrap();+ }++ async fn fx(remote_names: &[&str]) -> Fx {+ let env = crate::util::test_env::isolated();+ let relay = FakeRelay::start().await;+ relay.add_account("acct", "user-1", Some("[email protected]"));+ relay.require_devices(true);+ relay.fresh_sign_in("user-1");+ let (auth, laptop) = device(&relay, "laptop", 0).await;+ let mut remote = vec![];+ for (i, n) in remote_names.iter().enumerate() {+ remote.push(device(&relay, n, i + 1).await.1);+ }+ register(&relay, ID, "old-laptop", None, Default::default()).await;+ let dir = tempfile::tempdir().unwrap();+ let cua = cua_sdk::Cua::embedded(cua_sdk::CuaConfig {+ state_dir: Some(dir.path().join("sandboxes").display().to_string()),+ spaces_home: Some(dir.path().join("cua").display().to_string()),+ ..Default::default()+ })+ .unwrap();+ let (url, dev) = (relay.url.clone(), auth.clone());+ attach_relay_account(&cua, || {+ cua_spaces::RelayAccount::new(url, Arc::new(StaticToken("acct".into())))+ .with_device(dev)+ });+ Fx {+ _env: env,+ relay,+ cua,+ _dir: dir,+ auth,+ laptop,+ remote,+ }+ }++ /// Runs `rm`; returns the result, the output and the prompt count.+ async fn rm(+ f: &Fx,+ arg: &str,+ json: bool,+ answer: impl Fn() -> bool,+ ) -> (Result<i32, CuaError>, String, u32) {+ let asked = Cell::new(0);+ let mut out = Vec::new();+ let r = remove_machine(+ &f.cua,+ &f.auth,+ &StaticToken("acct".into()),+ arg,+ &|_| {+ asked.set(asked.get() + 1);+ answer()+ },+ json,+ &mut out,+ )+ .await;+ (r, String::from_utf8(out).unwrap(), asked.get())+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn machines_rm_removes_a_gone_computer_then_revokes_its_device() {+ let f = fx(&["old-laptop"]).await;+ let (r, text, _) = rm(&f, "old-laptop", false, || true).await;+ assert_eq!(r.unwrap(), 0, "{text}");+ assert!(f.relay.machine(ID).is_none());+ assert_eq!(+ f.relay.device_state(&f.remote[0]),+ Some(DeviceState::Revoked)+ );+ assert_eq!(f.relay.device_state(&f.laptop), Some(DeviceState::Enrolled));+ assert!(+ text.contains("Removed old-laptop (relay:0123abcd4567ef89)"),+ "{text}"+ );+ assert!(text.contains("Revoked old-laptop ("), "{text}");+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn machines_rm_by_bare_id_reports_json() {+ let f = fx(&["old-laptop"]).await;+ let (r, text, _) = rm(&f, ID, true, || true).await;+ assert_eq!(r.unwrap(), 0, "{text}");+ let v: serde_json::Value = serde_json::from_str(&text).unwrap();+ assert_eq!(v["removed"], true, "{text}");+ assert_eq!(v["machine"]["id"], "relay:0123abcd4567ef89");+ assert_eq!(v["device"]["status"], "revoked", "{text}");+ assert_eq!(v["device"]["ids"], serde_json::json!([f.remote[0]]));+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn machines_rm_refuses_a_connected_computer() {+ let f = fx(&["old-laptop"]).await;+ f.relay.set_online(ID, true, "1.0");+ let (r, _, asked) = rm(&f, "old-laptop", false, || true).await;+ let Err(CuaError::InvalidArgument(m)) = r else {+ panic!("{r:?}")+ };+ assert!(+ m.contains("is connected now") && m.contains("cua host remove"),+ "{m}"+ );+ assert_eq!(asked, 0);+ assert!(f.relay.machine(ID).is_some());+ assert_eq!(+ f.relay.device_state(&f.remote[0]),+ Some(DeviceState::Enrolled)+ );+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn machines_rm_unknown_name_is_not_found() {+ let f = fx(&["old-laptop"]).await;+ let (r, text, asked) = rm(&f, "no-such-box", false, || true).await;+ let Err(CuaError::NotFound(m)) = r else {+ panic!("{r:?}")+ };+ assert!(m.contains("no-such-box"), "{m}");+ assert_eq!(asked, 0);+ assert!(text.is_empty());+ assert!(f.relay.machine(ID).is_some());+ assert_eq!(+ f.relay.device_state(&f.remote[0]),+ Some(DeviceState::Enrolled)+ );+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn machines_rm_rechecks_after_confirmation() {+ let f = fx(&["old-laptop"]).await;+ let (r, _, asked) = rm(&f, "old-laptop", false, || {+ f.relay.set_online(ID, true, "1.0");+ true+ })+ .await;+ assert!(matches!(r, Err(CuaError::InvalidArgument(_))), "{r:?}");+ assert_eq!(asked, 1);+ assert!(f.relay.machine(ID).is_some());+ assert_eq!(+ f.relay.device_state(&f.remote[0]),+ Some(DeviceState::Enrolled)+ );+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn machines_rm_never_revokes_this_device_or_guesses() {+ // (a) A machine named like this device: this device stays.+ let f = fx(&[]).await;+ let other = "fedcba9876543210";+ register(&f.relay, other, "laptop", None, Default::default()).await;+ let (r, text, _) = rm(&f, "laptop", false, || true).await;+ assert_eq!(r.unwrap(), 0, "{text}");+ assert!(f.relay.machine(other).is_none());+ assert_eq!(f.relay.device_state(&f.laptop), Some(DeviceState::Enrolled));+ assert!(text.contains("no device was revoked"), "{text}");+ drop(f); // releases the isolated environment++ // (b) Two devices share the name: neither is revoked.+ let f = fx(&["old-laptop", "old-laptop"]).await;+ let (r, text, _) = rm(&f, "old-laptop", false, || true).await;+ assert_eq!(r.unwrap(), 0, "{text}");+ assert!(f.relay.machine(ID).is_none());+ for id in &f.remote {+ assert_eq!(f.relay.device_state(id), Some(DeviceState::Enrolled));+ assert!(text.contains(id.as_str()), "{text}");+ }+ assert!(text.contains("cua devices revoke <id>"), "{text}");+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn machines_rm_refuses_a_runtime_bound_to_another_relay() {+ // A daemon-like runtime on relay B, the caller's account on A.+ let f = fx(&["old-laptop"]).await;+ let other = FakeRelay::start().await;+ let dir = tempfile::tempdir().unwrap();+ let cua = cua_sdk::Cua::embedded(cua_sdk::CuaConfig {+ state_dir: Some(dir.path().join("sandboxes").display().to_string()),+ spaces_home: Some(dir.path().join("cua").display().to_string()),+ ..Default::default()+ })+ .unwrap();+ let url = other.url.clone();+ attach_relay_account(&cua, || {+ cua_spaces::RelayAccount::new(url, Arc::new(StaticToken("acct".into())))+ });+ let g = Fx { cua, ..f };+ let (r, text, asked) = rm(&g, "old-laptop", false, || true).await;+ let Err(CuaError::InvalidArgument(m)) = r else {+ panic!("{r:?}")+ };+ assert!(m.contains("--embedded"), "{m}");+ assert_eq!(asked, 0);+ assert!(text.is_empty(), "{text}");+ assert!(g.relay.machine(ID).is_some());+ assert_eq!(+ g.relay.device_state(&g.remote[0]),+ Some(DeviceState::Enrolled)+ );+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn machines_rm_device_failure_keeps_recovery_steps() {+ // This device is revoked while the prompt is open (and the relay+ // stops requiring devices): the row goes, the revoke is refused.+ for json in [false, true] {+ let f = fx(&["old-laptop"]).await;+ let dir = tempfile::tempdir().unwrap();+ let cua = cua_sdk::Cua::embedded(cua_sdk::CuaConfig {+ state_dir: Some(dir.path().join("sandboxes").display().to_string()),+ spaces_home: Some(dir.path().join("cua").display().to_string()),+ ..Default::default()+ })+ .unwrap();+ let url = f.relay.url.clone();+ attach_relay_account(&cua, || {+ cua_spaces::RelayAccount::new(url, Arc::new(StaticToken("acct".into())))+ });+ let g = Fx { cua, ..f };+ let (admin, _) = device(&g.relay, "admin", 9).await;+ let mut out = Vec::new();+ let r = remove_machine(+ &g.cua,+ &g.auth,+ &StaticToken("acct".into()),+ "old-laptop",+ &|_| {+ g.relay.require_devices(false);+ std::thread::scope(|s| {+ s.spawn(|| {+ tokio::runtime::Runtime::new()+ .unwrap()+ .block_on(admin.revoke(&g.laptop))+ .unwrap()+ });+ });+ true+ },+ json,+ &mut out,+ )+ .await;+ let text = String::from_utf8(out).unwrap();+ assert!(+ matches!(r, Err(CuaError::PermissionDenied(_))),+ "{r:?} {text}"+ );+ assert!(g.relay.machine(ID).is_none(), "{text}");+ assert_eq!(+ g.relay.device_state(&g.remote[0]),+ Some(DeviceState::Enrolled)+ );+ assert!(text.contains("cua devices revoke <id>"), "{text}");+ if json {+ assert!(text.contains(r#""status":"failed""#), "{text}");+ }+ }+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn machines_rm_declined_changes_nothing() {+ let f = fx(&["old-laptop"]).await;+ let (r, _, asked) = rm(&f, "old-laptop", false, || false).await;+ let Err(CuaError::PermissionDenied(m)) = r else {+ panic!("{r:?}")+ };+ assert!(m.contains("pass --yes"), "{m}");+ assert_eq!(asked, 1);+ assert!(f.relay.machine(ID).is_some());+ assert_eq!(+ f.relay.device_state(&f.remote[0]),+ Some(DeviceState::Enrolled)+ );+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn machines_rm_refuses_spaces() {+ let f = fx(&[]).await;+ let none = Default::default;+ register(&f.relay, "space-hosted1", "hosted", Some(ID), none()).await;+ let meta = [("cua.cloud.provider".to_string(), "hetzner".to_string())].into();+ register(&f.relay, "space-cloud001", "cloudy", None, meta).await;+ register(&f.relay, "space-selfreg1", "selfreg", None, none()).await;+ for (id, name) in [+ ("space-hosted1", "hosted"),+ ("space-cloud001", "cloudy"),+ ("space-selfreg1", "selfreg"),+ ] {+ let (r, _, asked) = rm(&f, name, false, || true).await;+ let Err(CuaError::InvalidArgument(m)) = r else {+ panic!("{name}: {r:?}")+ };+ assert!(m.contains("not a computer"), "{m}");+ assert_eq!(asked, 0);+ assert!(f.relay.machine(id).is_some());+ }+ }+ }+/// `cua mcp` without a daemon (embedded) sees the account's relay/// machines, as the daemon's Spaces do; it attaches only once and never/// to a daemon-backed `cua`.diff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rsindex 6a1d74132d..05febcc42b 100644--- a/libs/cua/crates/cua-cli/src/lib.rs+++ b/libs/cua/crates/cua-cli/src/lib.rs@@ -311,6 +311,9 @@ enum Command {cua computerscua computers --json")]Computers,+ /// Your computers on the relay: remove one that is gone.+ #[command(subcommand)]+ Machines(host::MachinesCmd),/// Unattended access to this computer (setup, status, stop, start, remove).#[command(subcommand)]Host(host::HostCmd),@@ -1860,6 +1863,33 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {host::attach_relay_account(&cua, || host::daemon_relay_account(&util::cua_home()));return cloud_cmd::run(&cua, cmd, json, out).await;}+ Command::Machines(host::MachinesCmd::Rm { name, yes }) => {+ // Embedded: the row, the lookup and the device all use this+ // process's relay, never a daemon's.+ let rest = Cli {+ command: Command::Spaces(host::SpacesCmd::Ls {+ relay: None,+ label: vec![],+ no_size: false,+ }),+ embedded: true,+ ..cli+ };+ let cua = open(&rest, false).await?;+ let home = util::cua_home();+ host::attach_relay_account(&cua, || host::daemon_relay_account(&home));+ let auth = devices_cmd::device_auth(&host::relay_url(None, &home))?;+ return host::remove_machine(+ &cua,+ &auth,+ &host::SessionTokens,+ &name,+ &|q| yes || (util::interactive() && util::confirm(q, false)),+ json,+ out,+ )+ .await;+ }Command::Spaces(cmd) => {// Relay machines only when signed in; the registry either way.let tokens: Option<Arc<dyn cua_host::AccountTokens>> =@@ -2218,6 +2248,7 @@ async fn run_sdk(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {| Command::Build(_)| Command::Jobs(_)| Command::Computers+ | Command::Machines(_)| Command::Spaces(_)| Command::Cloud(_)| Command::Devices(_)@@ -3412,7 +3443,7 @@ mod tests {/// `cua computers` is the one command that lists the pool's computers;/// `cua machines` and `cua sb runs --machines` (old spellings) are gone, not aliases.#[test]- fn computers_is_its_own_command_and_machines_is_gone() {+ fn computers_is_its_own_command_and_machines_only_removes() {let parse =|a: &[&str]| Cli::try_parse_from(std::iter::once("cua").chain(a.iter().copied()));assert!(matches!(@@ -3422,7 +3453,19 @@ mod tests {let j = parse(&["computers", "--json"]).unwrap();assert!(j.json && matches!(j.command, Command::Computers));assert!(parse(&["computers", "extra"]).is_err());- assert!(parse(&["machines"]).is_err());+ assert_eq!(+ parse(&["machines"]).unwrap_err().kind(),+ clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand+ );+ let Command::Machines(host::MachinesCmd::Rm { name, yes }) =+ parse(&["machines", "rm", "old-laptop", "--yes"])+ .unwrap()+ .command+ else {+ panic!()+ };+ assert!(name == "old-laptop" && yes);+ assert!(parse(&["machines", "ls"]).is_err());for sb in ["sb", "sandbox"] {let e = parse(&[sb, "runs", "--machines"]).unwrap_err();assert_eq!(diff --git a/libs/cua/crates/cua-telemetry/src/cli_commands.in b/libs/cua/crates/cua-telemetry/src/cli_commands.inindex 259ba5f3bb..474c6843d3 100644--- a/libs/cua/crates/cua-telemetry/src/cli_commands.in+++ b/libs/cua/crates/cua-telemetry/src/cli_commands.in@@ -151,6 +151,7 @@"keyvault.requests","keyvault.status","keyvault.unlock",+ "machines.rm","mcp","pools","run",diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.jsonindex 236c883a7f..9987ebc05f 100644--- a/scripts/docs-generators/cli-specs/cua.json+++ b/scripts/docs-generators/cli-specs/cua.json@@ -12937,6 +12937,57 @@"subcommands": [],"usage": "cua computers [OPTIONS]"},+ {+ "abstract": "Your computers on the relay: remove one that is gone",+ "aliases": [],+ "arguments": [],+ "flags": [],+ "hidden": false,+ "hidden_aliases": [],+ "name": "machines",+ "options": [],+ "subcommand_optional": false,+ "subcommands": [+ {+ "abstract": "Remove a computer that is gone: its row leaves your relay directory, then the signed-in device with exactly its name is revoked (never this device; nothing when several match). A computer that is connected now is refused: run `cua host remove` on it",+ "after_help": "Examples:\n cua machines rm old-laptop\n cua machines rm relay:0123abcd4567ef89 --yes --json",+ "aliases": [],+ "arguments": [+ {+ "default_value": null,+ "help": "The computer's name, machine id or `relay:<id>` (`cua spaces ls`)",+ "hidden": false,+ "is_optional": false,+ "name": "NAME",+ "possible_values": [],+ "repeatable": false,+ "type": "string"+ }+ ],+ "flags": [+ {+ "aliases": [],+ "default_value": false,+ "env": null,+ "help": "Remove without asking",+ "hidden": false,+ "name": "yes",+ "repeatable": false,+ "short_name": "y",+ "takes_value": false+ }+ ],+ "hidden": false,+ "hidden_aliases": [],+ "name": "rm",+ "options": [],+ "subcommand_optional": false,+ "subcommands": [],+ "usage": "cua machines rm [OPTIONS] <NAME>"+ }+ ],+ "usage": "cua machines [OPTIONS] <COMMAND>"+ },{"abstract": "Unattended access to this computer (setup, status, stop, start, remove)","aliases": [],diff --git a/scripts/docs-generators/cua-cli.ts b/scripts/docs-generators/cua-cli.tsindex 8605839488..a5dbfb4a96 100644--- a/scripts/docs-generators/cua-cli.ts+++ b/scripts/docs-generators/cua-cli.ts@@ -98,7 +98,7 @@ export const CLI_GROUPS: CliGroup[] = [title: 'Spaces, computers and teams',summary:'Your Spaces and machines, unattended access on this machine, devices, teams, your remote use this month, and a cua-spacesd by URL',- commands: ['spaces', 'host', 'devices', 'team', 'usage', 'spacesd', 'share'],+ commands: ['spaces', 'machines', 'host', 'devices', 'team', 'usage', 'spacesd', 'share'],},{slug: 'files-teleport-and-keys',