Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix cli: share confirmation errors, team create on free, stale relay record (#6167)

Francesco Bonaccie6128ed7d788
diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rs
index a56f53cb23..06298d7764 100644
--- a/libs/cua/crates/cua-cli/src/host.rs
+++ b/libs/cua/crates/cua-cli/src/host.rs
@@ -785,6 +785,40 @@ pub fn daemon_share_gate(yes: bool, terminal: bool) -> std::result::Result<(), C
))
}
+/// Says how to confirm when a share was stopped because nobody confirmed it
+/// on this computer (CUA-2837). The confirmation is a security gate: sharing
+/// hands a desktop to another account, so no flag skips it. A cancelled,
+/// denied or timed-out prompt used to end with only "biometric authorization
+/// was cancelled".
+pub fn explain_share_presence_failure(err: CuaError) -> CuaError {
+ let msg = match &err {
+ CuaError::PermissionDenied(m) => m.clone(),
+ other => other.to_string(),
+ };
+ // A free account: "Start a team" used to lead nowhere (CUA-2791).
+ if msg.contains(cua_spaces::share::NO_TEAM) && !msg.contains("app.cua.ai") {
+ return CuaError::PermissionDenied(format!(
+ "{msg} Start Teams at {} (from 1 seat), then run `cua auth login` again.",
+ cua_host::spaces_api::BUY_TEAMS_URL
+ ));
+ }
+ if !msg.contains("user presence was not confirmed") || msg.contains("To share:") {
+ return err;
+ }
+ CuaError::PermissionDenied(format!(
+ "{msg}. To share: run the command again at this computer and confirm the prompt with \
+ {}, or share from the Cua app. A script or agent cannot confirm for you; \
+ `--yes` only says someone is there to answer.",
+ if cfg!(target_os = "macos") {
+ "Touch ID or your password"
+ } else if cfg!(target_os = "windows") {
+ "Windows Hello or your password"
+ } else {
+ "your password (the desktop's polkit prompt)"
+ }
+ ))
+}
+
/// What the daemon asks the person at this computer for, in this OS's words
/// (it was always "Touch ID", also on a Linux server that has none).
pub fn share_confirm_prompt() -> &'static str {
@@ -4369,6 +4403,32 @@ mod tests {
}
}
+ #[test]
+ fn share_presence_failure_says_how_to_confirm() {
+ let raw = CuaError::PermissionDenied(
+ "not shared: user presence was not confirmed: biometric authorization was cancelled"
+ .into(),
+ );
+ let e = explain_share_presence_failure(raw).to_string();
+ assert!(
+ e.contains("To share: run the command again at this computer"),
+ "{e}"
+ );
+ assert!(e.contains("Cua app"), "{e}");
+ // Applied twice, or to an unrelated error, it changes nothing more.
+ let again =
+ explain_share_presence_failure(CuaError::PermissionDenied(e.clone())).to_string();
+ assert_eq!(again.matches("To share:").count(), 1, "{again}");
+ let free = explain_share_presence_failure(CuaError::PermissionDenied(
+ cua_spaces::share::NO_TEAM.into(),
+ ))
+ .to_string();
+ assert!(free.contains("https://app.cua.ai/buy/teams"), "{free}");
+ assert!(free.contains("cua auth login"), "{free}");
+ let other = CuaError::NotFound("space".into());
+ assert_eq!(explain_share_presence_failure(other.clone()), other);
+ }
+
#[test]
fn daemon_share_fails_fast_without_a_terminal_or_yes() {
let err = daemon_share_gate(false, false).unwrap_err().to_string();
diff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rs
index 403f7bdf0f..116a46d149 100644
--- a/libs/cua/crates/cua-cli/src/lib.rs
+++ b/libs/cua/crates/cua-cli/src/lib.rs
@@ -1832,19 +1832,26 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
// an embedded runtime confirms on the terminal.
host::attach_relay_account(&cua, || host::daemon_relay_account(&util::cua_home()));
let yes = matches!(cmd, host::SpacesCmd::Share { yes: true, .. });
- if let Some(rt) = cua.embedded_runtime() {
- if !rt.spaces().has_share_consent() {
- rt.spaces()
- .set_share_consent(Some(Arc::new(host::TerminalConsent { yes })));
- }
- } else if matches!(cmd, host::SpacesCmd::Share { .. }) {
- // The daemon asks for user presence on this computer.
+ let is_share = matches!(cmd, host::SpacesCmd::Share { .. });
+ let mut presence_asks = is_share;
+ if let Some(rt) = cua.embedded_runtime()
+ && !rt.spaces().has_share_consent()
+ {
+ rt.spaces()
+ .set_share_consent(Some(Arc::new(host::TerminalConsent { yes })));
+ presence_asks = false;
+ }
+ if presence_asks {
+ // The daemon, or an embedded runtime that carries the
+ // daemon's extensions, asks for user presence on this
+ // computer; `--yes` cannot skip that.
use std::io::IsTerminal as _;
host::daemon_share_gate(yes, std::io::stdin().is_terminal())?;
eprintln!("{}", host::share_confirm_prompt());
}
}
- return host::run_spaces_sdk(&cua, cmd, json, out).await;
+ let res = host::run_spaces_sdk(&cua, cmd, json, out).await;
+ res.map_err(host::explain_share_presence_failure)
}
Command::Build(a) => {
let rest = Cli {
diff --git a/libs/cua/crates/cua-cli/src/team_cmd.rs b/libs/cua/crates/cua-cli/src/team_cmd.rs
index efe967054e..6ccbd047f8 100644
--- a/libs/cua/crates/cua-cli/src/team_cmd.rs
+++ b/libs/cua/crates/cua-cli/src/team_cmd.rs
@@ -297,6 +297,48 @@ fn audit_notice(json: bool, out: &mut dyn Write) -> i32 {
0
}
+/// A line of what `team create` prints.
+enum Created {
+ Plain(String),
+ Hint(String),
+}
+
+/// What `cua team create` tells the person (CUA-2791). The API makes the
+/// team waiting for payment (`status: pending`): it stays hidden, and
+/// `team ls`, `team show` and `team invite` do not know it, until Teams is
+/// started at app.cua.ai. So it never prints those as next steps for it.
+fn created_text(t: &cua_host::spaces_api::ApiOrg) -> Vec<Created> {
+ use Created::{Hint, Plain};
+ if t.status == "pending" {
+ return vec![
+ Plain(format!(
+ "Reserved the team {}. It is not active yet: a team starts when you start Teams.",
+ t.label()
+ )),
+ Plain("Next:".into()),
+ Hint(format!(
+ " start Teams at {} (from 1 seat; the team appears once it is bought)",
+ cua_host::spaces_api::BUY_TEAMS_URL
+ )),
+ Hint(" cua auth login (your session lists the team after a new sign-in)".into()),
+ Hint(" cua team invite <team> <email>".into()),
+ ];
+ }
+ vec![
+ Plain(format!("Created team {} ({}).", t.label(), t.id)),
+ Plain("Next:".into()),
+ Hint(
+ " cua auth login (your session lists the team after a new sign-in)"
+ .into(),
+ ),
+ Plain(
+ " buy Teams for it at app.cua.ai (team computers and device approval need it)".into(),
+ ),
+ Hint(format!(" cua team invite {} <email>", t.id)),
+ Hint(format!(" cua team add-machine {} <space>", t.id)),
+ ]
+}
+
/// Runs `cmd` (all but `add-machine`, which goes through Spaces).
/// `confirm` answers the delete prompt.
pub async fn run_with(
@@ -324,18 +366,12 @@ pub async fn run_with(
if json {
emit_json(out, &t);
} else {
- line(out, format!("Created team {} ({}).", t.label(), t.id));
- line(out, "Next:");
- hint_line(
- out,
- " cua auth login (your session lists the team after a new sign-in)",
- );
- line(
- out,
- " buy Teams for it at app.cua.ai (team computers and device approval need it)",
- );
- hint_line(out, format!(" cua team invite {} <email>", t.id));
- hint_line(out, format!(" cua team add-machine {} <space>", t.id));
+ for l in created_text(&t) {
+ match l {
+ Created::Plain(l) => line(out, l),
+ Created::Hint(l) => hint_line(out, l),
+ }
+ }
}
}
TeamCmd::Ls => {
@@ -684,6 +720,38 @@ mod tests {
Ok(String::from_utf8(out).unwrap())
}
+ #[test]
+ fn a_team_waiting_for_payment_does_not_suggest_steps_that_fail() {
+ let pending = cua_host::spaces_api::ApiOrg {
+ id: "0f1e2d3c".into(),
+ name: "Acme".into(),
+ status: "pending".into(),
+ ..Default::default()
+ };
+ let text: String = created_text(&pending)
+ .into_iter()
+ .map(|l| match l {
+ Created::Plain(l) | Created::Hint(l) => l,
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(text.contains("not active yet"), "{text}");
+ assert!(text.contains("https://app.cua.ai/buy/teams"), "{text}");
+ assert!(!text.contains("add-machine"), "{text}");
+ assert!(!text.contains("0f1e2d3c"), "{text}");
+ let active = cua_host::spaces_api::ApiOrg {
+ status: "active".into(),
+ ..pending
+ };
+ let text: String = created_text(&active)
+ .into_iter()
+ .map(|l| match l {
+ Created::Plain(l) | Created::Hint(l) => l,
+ })
+ .collect();
+ assert!(text.contains("Created team Acme"), "{text}");
+ }
+
#[tokio::test]
async fn teams_are_organizations_with_machines_and_approved_devices() {
let api = FakeSpacesApi::start().await;
diff --git a/libs/cua/crates/cua-spaces/src/share.rs b/libs/cua/crates/cua-spaces/src/share.rs
index 1bddba6ba7..c53fa8f2ab 100644
--- a/libs/cua/crates/cua-spaces/src/share.rs
+++ b/libs/cua/crates/cua-spaces/src/share.rs
@@ -984,6 +984,15 @@ impl Spaces {
/// 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> {
+ // A Space that is already gone here but was left on the relay (its
+ // delete could not reach the relay, CUA-2841): its machine is still
+ // remembered, so `relay-unregister local:<name>` removes it.
+ if matches!(self.resolve(space), Err(Error::NotFound(_)))
+ && let Some(machine) = self.attached().get(space).map(|a| a.machine.clone())
+ {
+ self.detach(space, &machine).await?;
+ return Ok(true);
+ }
let id = match self.resolve(space) {
// A bare relay machine id (`space-…`) is known once the
// directory was listed.
diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rs
index 4c06c53918..10ded0d929 100644
--- a/libs/cua/crates/cua-spaces/src/spaces.rs
+++ b/libs/cua/crates/cua-spaces/src/spaces.rs
@@ -1232,6 +1232,13 @@ impl Spaces {
{
self.forget_relay_machine(machine_id).await?;
}
+ // A Space this device attached to the relay as a machine of its own
+ // takes that machine with it (as `delete` does): `rm` must not leave
+ // a stale record the owner has to remove by hand (CUA-2841).
+ #[cfg(feature = "spaces-agents")]
+ if !matches!(id, SpaceId::Relay { .. }) {
+ let _ = self.release_attached(&id.to_string()).await;
+ }
// A direct host leaves the direct-host list with the Spaces it
// created here (nothing reaches them without it; a host that is
// gone leaves no rows behind), and a Space one created leaves its
diff --git a/libs/cua/crates/cua-spaces/tests/share.rs b/libs/cua/crates/cua-spaces/tests/share.rs
index fc1db04618..c8eef1563e 100644
--- a/libs/cua/crates/cua-spaces/tests/share.rs
+++ b/libs/cua/crates/cua-spaces/tests/share.rs
@@ -575,6 +575,49 @@ async fn deleting_a_relay_registered_space_removes_its_machine() {
assert!(!ada.list_all().await.unwrap().iter().any(|i| i.id == id));
}
+/// CUA-2841: `rm` of a relay-registered Space takes its machine off the
+/// relay too, and a Space whose delete could not reach the relay (it is
+/// gone here, its machine is still remembered) is removed by
+/// `relay-unregister local:<name>`.
+#[tokio::test]
+async fn rm_and_relay_unregister_leave_no_stale_relay_record() {
+ 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());
+ ada.remove(&info.id).await.unwrap();
+ assert!(
+ relay.machine(&r.machine).is_none(),
+ "rm removed the machine"
+ );
+
+ // A Space that is gone here, its machine still remembered.
+ let ghost = "space-00000000000000bb";
+ register(&relay, ghost, false).await;
+ let file = homes[0].path().join("shared-spaces.json");
+ std::fs::write(
+ &file,
+ serde_json::json!({"local:ghost": {"machine": ghost}}).to_string(),
+ )
+ .unwrap();
+ assert!(ada.relay_unregister("local:ghost").await.unwrap());
+ assert!(relay.machine(ghost).is_none(), "stale record removed");
+ assert!(!ada.relay_unregister("local:ghost").await.unwrap_or(false));
+}
+
/// 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