Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-cli): Cua Spaces Local's hints and errors name cua-local, not cua (#5892)
cua-agents[bot]5309f1edd49b
diff --git a/apps/cua-spaces-macos/README.md b/apps/cua-spaces-macos/README.mdindex 47a5837f8c..bb8c62332a 100644--- a/apps/cua-spaces-macos/README.md+++ b/apps/cua-spaces-macos/README.md@@ -379,7 +379,12 @@ not verify it puts the previous Local app back. It refuses to replace anythingat the Local path that is not a Cua Spaces Local bundle, and it never writes to`/Applications/Cua Spaces.app`, `~/.local/bin/cua`, `~/.cua` or `~/.lume`.`cua-local` is a link to the `cua` inside the app; no shell profile is edited,-so put `~/.local/bin` on your PATH.+so put `~/.local/bin` on your PATH. It names itself in what it prints: its help,+its hints and its error messages tell you to run `cua-local host setup`, never+`cua host setup` (which would run the released CLI). The code writes each hint+for the released CLI and `cua-cli` renames it where it is printed (`util::hint`,+and for a message that holds a name the user chose, `util::cli`); a message+that names a command goes through one of them.**Permissions survive a rebuild** when the app is signed with the stable localcertificate that Cua Driver's local install usesdiff --git a/libs/cua/crates/cua-cli/src/add_aws.rs b/libs/cua/crates/cua-cli/src/add_aws.rsindex fd82a238c3..8bcfcf0c55 100644--- a/libs/cua/crates/cua-cli/src/add_aws.rs+++ b/libs/cua/crates/cua-cli/src/add_aws.rs@@ -24,7 +24,7 @@ use cua_sdk::CuaError;use serde_json::json;use crate::onboard::AwsArgs;-use crate::util::line;+use crate::util::{hint_line, line};/// The TCP ports open between pool hosts (and only between them): all of/// them, since ranks of frameworks such as PyTorch (NCCL, Gloo) listen on@@ -121,7 +121,7 @@ async fn add(a: AwsArgs, hosts: &Hosts, json: bool, out: &mut dyn Write) -> Resuif json {line(out, json!({"hosts": rows(&made)}).to_string());} else {- line(+ hint_line(out,"They join your pool in a few minutes: cua cloud add aws --list, cua cloud hosts ls",);@@ -154,7 +154,7 @@ async fn add(a: AwsArgs, hosts: &Hosts, json: bool, out: &mut dyn Write) -> Resuline(out, l);}if joined == made.len() {- line(+ hint_line(out,format!("{joined} host{} in your pool: cua computers · cua sb run --on {} -- echo hi · \@@ -164,7 +164,7 @@ async fn add(a: AwsArgs, hosts: &Hosts, json: bool, out: &mut dyn Write) -> Resu),);} else {- line(+ hint_line(out,"Not all hosts joined within 20 minutes: see `cua cloud add aws --list`; its boot log \says why: aws ec2 get-console-output --latest --instance-id <instance>",diff --git a/libs/cua/crates/cua-cli/src/agent_cmd.rs b/libs/cua/crates/cua-cli/src/agent_cmd.rsindex 045e99de20..c555e74b83 100644--- a/libs/cua/crates/cua-cli/src/agent_cmd.rs+++ b/libs/cua/crates/cua-cli/src/agent_cmd.rs@@ -447,8 +447,11 @@ async fn start(}}eprintln!(- "{run_id} started ({harness}); follow with: cua agent logs {} {run_id} -f",- a.sandbox+ "{}",+ crate::util::hint(&format!(+ "{run_id} started ({harness}); follow with: cua agent logs {} {run_id} -f",+ a.sandbox+ )));}if !a.follow {@@ -522,11 +525,14 @@ async fn start_direct();} else {eprintln!(- "{} started ({}); follow with: cua agent logs {} {} -f",- run.run_id(),- run.harness(),- a.sandbox,- run.run_id()+ "{}",+ crate::util::hint(&format!(+ "{} started ({}); follow with: cua agent logs {} {} -f",+ run.run_id(),+ run.harness(),+ a.sandbox,+ run.run_id()+ )));}if a.follow {diff --git a/libs/cua/crates/cua-cli/src/agent_keys_cmd.rs b/libs/cua/crates/cua-cli/src/agent_keys_cmd.rsindex 8820824cb1..9053e032f9 100644--- a/libs/cua/crates/cua-cli/src/agent_keys_cmd.rs+++ b/libs/cua/crates/cua-cli/src/agent_keys_cmd.rs@@ -116,7 +116,9 @@ fn lines(report: &serde_json::Value) -> Vec<String> {}let keys = report["keys"].as_array().cloned().unwrap_or_default();if keys.is_empty() {- v.push("No agent keys saved. Add one with: pbpaste | cua agent keys set anthropic".into());+ v.push(crate::util::hint(+ "No agent keys saved. Add one with: pbpaste | cua agent keys set anthropic",+ ));}for k in keys {let last4 = k["last4"].as_str().unwrap_or("");diff --git a/libs/cua/crates/cua-cli/src/agent_session_cmd.rs b/libs/cua/crates/cua-cli/src/agent_session_cmd.rsindex 22cd5d0126..710f1bdba7 100644--- a/libs/cua/crates/cua-cli/src/agent_session_cmd.rs+++ b/libs/cua/crates/cua-cli/src/agent_session_cmd.rs@@ -271,8 +271,11 @@ pub async fn start(a: RunArgs, json: bool, out: &mut dyn Write) -> Result<i32, Cline(out, v.to_string());} else {eprintln!(- "{name} started as a durable session (epoch {}); follow with: cua agent logs session:{name} -f",- v["epoch"]+ "{}",+ crate::util::hint(&format!(+ "{name} started as a durable session (epoch {}); follow with: cua agent logs session:{name} -f",+ v["epoch"]+ )));}if !a.follow {diff --git a/libs/cua/crates/cua-cli/src/auth.rs b/libs/cua/crates/cua-cli/src/auth.rsindex 42bfa08734..84afa510ee 100644--- a/libs/cua/crates/cua-cli/src/auth.rs+++ b/libs/cua/crates/cua-cli/src/auth.rs@@ -195,7 +195,7 @@ pub async fn status(json: bool, out: &mut dyn Write) -> Result<i32, CuaError> {);}let Some(c) = c else {- line(out, "Not logged in. Run 'cua auth login'.");+ util::hint_line(out, "Not logged in. Run 'cua auth login'.");return Ok(1);};if c.expires().map_err(auth_err)? <= chrono::Utc::now() {@@ -234,7 +234,7 @@ pub async fn whoami(json: bool, out: &mut dyn Write) -> Result<i32, CuaError> {if json {util::json_line(out, &serde_json::json!({"authenticated": false}));} else {- line(out, "Not logged in. Run 'cua auth login'.");+ util::hint_line(out, "Not logged in. Run 'cua auth login'.");}return Ok(1);};diff --git a/libs/cua/crates/cua-cli/src/build_cmd.rs b/libs/cua/crates/cua-cli/src/build_cmd.rsindex 6ca3fc90fa..82e42086fb 100644--- a/libs/cua/crates/cua-cli/src/build_cmd.rs+++ b/libs/cua/crates/cua-cli/src/build_cmd.rs@@ -14,7 +14,7 @@ use std::time::Duration;use clap::Args;use cua_sdk::{BuildListener, BuildOptions, BuildProgress, Cua, CuaError};-use crate::util::line;+use crate::util::{hint_line, line};/// `cua build`.#[derive(Args, Debug, Clone)]@@ -207,7 +207,7 @@ pub async fn run(result.seconds),);- line(out, format!("Run it: cua spaces create build:{image}"));+ hint_line(out, format!("Run it: cua spaces create build:{image}"));Ok(0)}diff --git a/libs/cua/crates/cua-cli/src/cache.rs b/libs/cua/crates/cua-cli/src/cache.rsindex 46d1467b00..65cab7f7d8 100644--- a/libs/cua/crates/cua-cli/src/cache.rs+++ b/libs/cua/crates/cua-cli/src/cache.rs@@ -1,7 +1,7 @@//! `cua cache ls|du|prune|config`: what the SDK keeps on disk and its//! cleanup (`cua-disk`).-use crate::util::{self, line};+use crate::util::{self, hint_line, line};use clap::Subcommand;use cua_disk::{Budget, CacheConfig, Category, GcOptions, Layout, Scanner, format_size};use cua_sdk::CuaError;@@ -354,7 +354,7 @@ pub async fn run(),);if g.kept_referenced > 0 {- line(+ hint_line(out,format!("kept {} cache entr{} used by sandboxes (cua sb rm frees them)",@@ -376,7 +376,7 @@ pub async fn run();}if !g.kept_bases.is_empty() {- line(out, "cua cache prune --all removes bases no sandbox uses");+ hint_line(out, "cua cache prune --all removes bases no sandbox uses");}Ok(0)}diff --git a/libs/cua/crates/cua-cli/src/catalog.rs b/libs/cua/crates/cua-cli/src/catalog.rsindex 13aeab21c4..e524faedb0 100644--- a/libs/cua/crates/cua-cli/src/catalog.rs+++ b/libs/cua/crates/cua-cli/src/catalog.rs@@ -7,7 +7,7 @@ use cua_sdk::CuaError;use serde_json::{Value, json};use std::io::Write;-use crate::util::{self, line};+use crate::util::{self, hint_line, line};/// The catalog file, as built into this binary.pub const CATALOG_JSON: &str = include_str!("../../../../images/sandbox-images.json");@@ -63,12 +63,14 @@ fn row(image: &Value, all: &[Value]) -> Value {}v["browser_tools"] = json!(browser_tools(image));v["variants"] = Value::Array(variants);+ // Commands to run, for this build's CLI (`cua-local` on Local).+ let cli = crate::util::cli();let mut create = vec![];if image["local"].is_string() {- create.push(format!("cua sb create {r}"));+ create.push(format!("{cli} sb create {r}"));}if browser_tools(image) {- create.push(format!("cua sb create {r} --browser"));+ create.push(format!("{cli} sb create {r} --browser"));}v["create"] = json!(create);v@@ -89,6 +91,7 @@ pub fn list(f: &Filter) -> Vec<Value> {fn provider_rows(providers: &[std::sync::Arc<cua_sandbox_core::external::ExternalProvider>],) -> Vec<Value> {+ let cli = crate::util::cli();let mut out = vec![];for p in providers {for i in &p.manifest.images {@@ -107,7 +110,7 @@ fn provider_rows("browsers": [],"browser_tools": false,"variants": [],- "create": [format!("cua sb create {r} --runtime {}", p.name())],+ "create": [format!("{cli} sb create {r} --runtime {}", p.name())],}));}}@@ -226,7 +229,7 @@ pub fn print_list(f: &Filter, json: bool, out: &mut dyn Write) -> Result<i32, Cu],&table,);- line(+ hint_line(out,"\nWeb browsing: `cua sb create linux --browser` (Chromium, driven by the cua-driver browser tools).\nTiers: `cua sb create linux --tier slim` (full is the default; Linux also has --tier docker, a VM with dockerd; macOS --tier xcode).",);diff --git a/libs/cua/crates/cua-cli/src/cloud_cmd.rs b/libs/cua/crates/cua-cli/src/cloud_cmd.rsindex 6778de3b85..e31a39465f 100644--- a/libs/cua/crates/cua-cli/src/cloud_cmd.rs+++ b/libs/cua/crates/cua-cli/src/cloud_cmd.rs@@ -12,7 +12,7 @@ use std::sync::Arc;use clap::{Args, Subcommand};use cua_sdk::{CloudTarget, Cua, CuaError};-use crate::util::line;+use crate::util::{hint_line, line};/// Where in a cloud account Spaces go.#[derive(Args, Debug, Clone, Default)]@@ -423,7 +423,7 @@ pub async fn run(for c in &c.checks {line(out, check_line(c));}- line(+ hint_line(out,format!("Connected {}{}. Create a sandbox there: cua sb create linux --on {} (a Space: cua spaces create --on {})",@@ -492,7 +492,7 @@ pub async fn run(},);if !d.left.is_empty() {- line(+ hint_line(out,"Still recorded for that account (`cua cloud sweep --all --delete` after reconnecting removes them):",);@@ -627,7 +627,7 @@ pub async fn run(return Ok(0);}if hosts.is_empty() {- line(+ hint_line(out,"No elastic hosts (they are added when your machines are full, or with cua cloud hosts add).",);diff --git a/libs/cua/crates/cua-cli/src/compat_cmd.rs b/libs/cua/crates/cua-cli/src/compat_cmd.rsindex 0e3f255dfe..8554b90825 100644--- a/libs/cua/crates/cua-cli/src/compat_cmd.rs+++ b/libs/cua/crates/cua-cli/src/compat_cmd.rs@@ -148,7 +148,12 @@ pub async fn run(cmd: CompatCmd, json: bool, out: &mut dyn Write) -> Result<i32,let gw = if opts.no_warm {Gateway::start(g, None).await} else {- eprintln!("cua compat: warming (image pull and first boot; the first create is made now)...");+ eprintln!(+ "{}",+ crate::util::hint(+ "cua compat: warming (image pull and first boot; the first create is made now)..."+ )+ );Gateway::start_warmed(g, None).await}.map_err(|e| CuaError::InvalidArgument(e.to_string()))?;@@ -160,7 +165,7 @@ pub async fn run(cmd: CompatCmd, json: bool, out: &mut dyn Write) -> Result<i32,.collect();crate::util::line(out, serde_json::Value::Object(m).to_string());} else {- crate::util::line(+ crate::util::hint_line(out,format!("cua compat: serving the {} API on http://{} and sandbox hosts on {} (Spaces: --on {} --kind {}).\nClients export:\n{}",diff --git a/libs/cua/crates/cua-cli/src/devices_cmd.rs b/libs/cua/crates/cua-cli/src/devices_cmd.rsindex d839d9743e..1592685bb0 100644--- a/libs/cua/crates/cua-cli/src/devices_cmd.rs+++ b/libs/cua/crates/cua-cli/src/devices_cmd.rs@@ -6,7 +6,7 @@//! device; `cua auth login` does (see [`after_login`]).use crate::auth;-use crate::util::{self, line};+use crate::util::{self, hint_line, line};use clap::Subcommand;use cua_host::{DeviceAuth, DeviceState, DeviceView};use cua_sdk::CuaError;@@ -191,6 +191,8 @@ pub async fn after_login(home: &Path, out: &mut dyn Write) {),Ok(Ok(r)) => {if let Some(code) = r.code {+ // The command runs on another, enrolled device, which may have+ // either CLI: it is not renamed.line(out,format!(@@ -199,13 +201,13 @@ pub async fn after_login(home: &Path, out: &mut dyn Write) {);}}- Ok(Err(e)) => line(+ Ok(Err(e)) => hint_line(out,format!("Signed in, but this device could not be enrolled yet ({e}); run `cua devices enroll`."),),- Err(_) => line(+ Err(_) => hint_line(out,"Signed in, but the relay did not answer in time to enroll this device; run `cua devices enroll`.",),@@ -302,14 +304,14 @@ pub async fn run_with(}match (&id, &this) {(None, _) => {- line(+ hint_line(out,"This device is not enrolled (run `cua devices enroll`).",);return Ok(1);}(Some(id), None) => match state {- Ok(None) => line(+ Ok(None) => hint_line(out,format!("This device ({id}) is not registered on {} (run `cua devices enroll`).",@@ -399,7 +401,7 @@ pub async fn run_with(.unwrap_or_else(|| "in 10 minutes".into())),);- line(+ hint_line(out,"Or sign in again: `cua auth login` enrolls this device (older relays: only your first device).",);diff --git a/libs/cua/crates/cua-cli/src/do_cmd.rs b/libs/cua/crates/cua-cli/src/do_cmd.rsindex c437820a42..74d5ea6418 100644--- a/libs/cua/crates/cua-cli/src/do_cmd.rs+++ b/libs/cua/crates/cua-cli/src/do_cmd.rs@@ -591,7 +591,7 @@ pub async fn run(cua: &Arc<Cua>, args: DoArgs, out: &mut dyn Write) -> Result<i3}fn fail(msg: &str) -> Result<i32, CuaError> {- eprintln!("❌ {msg}");+ eprintln!("❌ {}", crate::util::hint(msg));Ok(1)}@@ -618,7 +618,10 @@ impl Run<'_> {"host" => {if !consent_path().exists() {eprintln!(- "❌ Warning: you are about to allow an AI to control your host PC directly.\n This grants full keyboard, mouse, and screen access to your local desktop.\n To continue, please run: cua do-host-consent"+ "{}",+ crate::util::hint(+ "❌ Warning: you are about to allow an AI to control your host PC directly.\n This grants full keyboard, mouse, and screen access to your local desktop.\n To continue, please run: cua do-host-consent"+ ),);return Ok(1);}diff --git a/libs/cua/crates/cua-cli/src/doctor/identity.rs b/libs/cua/crates/cua-cli/src/doctor/identity.rsindex 2b1145e156..2f36d39592 100644--- a/libs/cua/crates/cua-cli/src/doctor/identity.rs+++ b/libs/cua/crates/cua-cli/src/doctor/identity.rs@@ -88,7 +88,9 @@ pub fn checks(facts: BTreeMap<String, String>) -> Vec<Check> {stale.join(", ")),)- .fix("restart them (`cua sb overlay` stops stale copies)")+ .fix(crate::util::hint(+ "restart them (`cua sb overlay` stops stale copies)",+ ))});}let mut identity = Check::new(diff --git a/libs/cua/crates/cua-cli/src/doctor/mod.rs b/libs/cua/crates/cua-cli/src/doctor/mod.rsindex bab3b9c9f7..b456795e2f 100644--- a/libs/cua/crates/cua-cli/src/doctor/mod.rs+++ b/libs/cua/crates/cua-cli/src/doctor/mod.rs@@ -410,6 +410,12 @@ pub async fn run(if !args.no_host {extra.extend(host::host_checks(cua, runtime_type.as_deref(), &arch).await);}+ // These checks were written here, so their hints name this build's CLI+ // (`cua-local` on Local); the guest's own checks are the guest's words.+ for check in &mut extra {+ check.message = crate::util::hint(&check.message);+ check.remediation = crate::util::hint(&check.remediation);+ }let mut checks = extra;checks.append(&mut report.checks);report.checks = checks;diff --git a/libs/cua/crates/cua-cli/src/drive_cmd.rs b/libs/cua/crates/cua-cli/src/drive_cmd.rsindex 836fd2dbb9..80a82d0433 100644--- a/libs/cua/crates/cua-cli/src/drive_cmd.rs+++ b/libs/cua/crates/cua-cli/src/drive_cmd.rs@@ -13,7 +13,7 @@ use std::sync::Arc;use clap::{Args, Subcommand};use cua_sdk::{Cua, CuaError, DriveView};-use crate::util::line;+use crate::util::{hint_line, line};/// Whose view of the drive a command takes.#[derive(Args, Debug, Clone, Default)]@@ -332,7 +332,7 @@ pub async fn run(.collect();line(out, json!({ "volumes": v }).to_string());} else if vols.is_empty() {- line(+ hint_line(out,"No named volumes. Make one with `cua volume named create NAME`.",);diff --git a/libs/cua/crates/cua-cli/src/extension.rs b/libs/cua/crates/cua-cli/src/extension.rsindex fa053308eb..60d0aaae88 100644--- a/libs/cua/crates/cua-cli/src/extension.rs+++ b/libs/cua/crates/cua-cli/src/extension.rs@@ -360,7 +360,11 @@ async fn stop_daemon_within(.await.unwrap_or(false){- eprintln!("cua: the running cua daemon (pid {pid}) did not exit when asked; ended it");+ eprintln!(+ "{}: the running {} daemon (pid {pid}) did not exit when asked; ended it",+ crate::util::cli(),+ crate::util::cli()+ );if cua_daemon::client::live_address().is_none() {return Ok(());}diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rsindex d60da0b425..98fc1a70e3 100644--- a/libs/cua/crates/cua-cli/src/host.rs+++ b/libs/cua/crates/cua-cli/src/host.rs@@ -3,7 +3,7 @@//! machines; `add` / `rm`: register or forget a Space).use crate::auth;-use crate::util::line;+use crate::util::{hint_line, line};use clap::Subcommand;use cua_host::{AccountTokens, DeviceAuth, Host, HostStatus, MachinePatch, RelayClient, RunnerKind,@@ -1537,7 +1537,7 @@ fn host_error(e: cua_host::Error, m: String) -> CuaError {fn render(s: &HostStatus, out: &mut dyn Write) {if !s.configured {- line(+ hint_line(out,"This computer is not set up for access (run `cua host setup`).",);@@ -1545,7 +1545,7 @@ fn render(s: &HostStatus, out: &mut dyn Write) {}let name = s.name.clone().unwrap_or_default();if s.paused_signed_out {- line(+ hint_line(out,"Relay sharing is paused: the Cua app on this computer is signed out. \Sign in to it again (or run `cua host start`) to share it.",@@ -1589,12 +1589,12 @@ fn render(s: &HostStatus, out: &mut dyn Write) {),);if s.service.kind == "app-helper" && s.legacy_service {- line(+ hint_line(out," the old LaunchAgent (com.trycua.spacesd.host) is still there: run `cua host migrate` to remove it",);} else if s.service.kind == "launchd" && s.helper_available {- line(+ hint_line(out," tip: `cua host migrate` moves this service into the Cua Spaces app (its login item)",);@@ -1951,10 +1951,10 @@ pub async fn run_host(&& let Ok(Some((cpus, mem))) =cua_vmm::managed::dedicate_to_spaces(&cua_sandbox_core::settings::config_path()){- let note = format!(+ let note = crate::util::hint(&format!("Linux Spaces here share a {cpus}-CPU, {mem} GiB runtime VM \(cua config set runtime.linux_memory_gib N to change it)."- );+ ));if json {eprintln!("{note}");} else {@@ -2051,7 +2051,7 @@ pub async fn run_host(} else {line(out, format!("{}: {}", m.outcome, m.detail));if m.permissions_needed {- line(+ hint_line(out,"macOS will ask you once more for Screen Recording and Accessibility, \now for Cua Spaces: allow both in System Settings > Privacy & \@@ -2476,10 +2476,9 @@ async fn pair_codes(lines.push(format!(" Staging build (Linux): {st}"));}lines.push(format!(" Windows: {ps}"));- lines.push(- "It joins your pool as a host that provides Spaces; see it with `cua computers`."- .to_string(),- );+ lines.push(crate::util::hint(+ "It joins your pool as a host that provides Spaces; see it with `cua computers`.",+ ));for l in lines {line(out, l);}@@ -2487,7 +2486,10 @@ async fn pair_codes(let Some(org) = org else {return Ok(());};- let later = format!("cua team add-machine {} relay:<computer id>", org.id);+ let later = crate::util::hint(&format!(+ "cua team add-machine {} relay:<computer id>",+ org.id+ ));if no_wait {if !json {line(@@ -2890,11 +2892,14 @@ pub async fn run_add_host(serde_json::json!({ "host": host, "space": info.id, "via": "direct" }).to_string(),);} else {+ // The command is spelled with this build's CLI name here, not rewritten+ // afterwards: the host's name is the user's, and may read "cua host".line(out,format!(- "Added host {host:?} ({}, direct). Create Spaces on it with `cua spaces create --on \"host:{host}\"`.",- info.id+ "Added host {host:?} ({}, direct). Create Spaces on it with `{} spaces create --on \"host:{host}\"`.",+ info.id,+ crate::util::cli()),);}diff --git a/libs/cua/crates/cua-cli/src/jobs_cmd.rs b/libs/cua/crates/cua-cli/src/jobs_cmd.rsindex 504a0006ab..b6cd2cfd7f 100644--- a/libs/cua/crates/cua-cli/src/jobs_cmd.rs+++ b/libs/cua/crates/cua-cli/src/jobs_cmd.rs@@ -32,7 +32,7 @@ use cua_sdk::CuaError;use serde_json::{Value, json};use crate::runs::{request, target_of_run};-use crate::util::line;+use crate::util::{hint, hint_line, line};/// The jobs runtime every member runs with (`import cua`, `python -m/// _cua_entry`), by path inside `_cua_runtime/`.@@ -723,7 +723,7 @@ pub async fn run(a: RunArgs, json: bool, out: &mut dyn Write) -> Result<i32, Cualine(out, json!({"run": run_id}).to_string());} else {line(out, format!("{what}: submitted"));- line(out, format!("Follow it: cua jobs logs -f {run_id}"));+ hint_line(out, format!("Follow it: cua jobs logs -f {run_id}"));}return Ok(0);}@@ -1110,7 +1110,7 @@ async fn run_command(a: RunArgs, json: bool, out: &mut dyn Write) -> Result<i32,line(out, json!({"run": run_id}).to_string());} else {line(out, format!("{what}: submitted"));- line(out, format!("Follow it: cua jobs logs -f {run_id}"));+ hint_line(out, format!("Follow it: cua jobs logs -f {run_id}"));}return Ok(0);}@@ -1130,7 +1130,9 @@ async fn run_command(a: RunArgs, json: bool, out: &mut dyn Write) -> Result<i32,fn follow_hint(run_id: &str) -> [String; 2] {["Ctrl-C stops following; the run keeps going.".to_string(),- format!("(cancel: cua jobs cancel {run_id}; follow again: cua jobs logs -f {run_id})"),+ hint(&format!(+ "(cancel: cua jobs cancel {run_id}; follow again: cua jobs logs -f {run_id})"+ )),]}@@ -1649,7 +1651,7 @@ pub fn runs_table(v: &Value) -> Vec<String> {));}if runs.is_empty() {- rows.push("No runs yet: cua run train.py::finetune".into());+ rows.push(hint("No runs yet: cua run train.py::finetune"));}rows}diff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rsindex 2058b3a041..4ed4731b1a 100644--- a/libs/cua/crates/cua-cli/src/lib.rs+++ b/libs/cua/crates/cua-cli/src/lib.rs@@ -2667,27 +2667,54 @@ fn channel_command(cli: clap::Command, channel: cua_home::channel::CuaChannel) -if !channel.is_local() {return cli;}- let name = channel.cli_name();- localize_help(cli.bin_name(name), name)+ let verbs = util::verbs_of(&cli);+ localize_help(cli.bin_name(channel.cli_name()), channel, &verbs)}-/// `cmd` and its subcommands with the examples in their after-help run as-/// `name` (see [`localize_examples`]).-fn localize_help(cmd: clap::Command, name: &str) -> clap::Command {- let after = cmd- .get_after_help()- .map(|h| localize_examples(&h.to_string(), name));- let after_long = cmd- .get_after_long_help()- .map(|h| localize_examples(&h.to_string(), name));+/// `cmd` and its subcommands, their arguments included, with every command+/// their help tells the reader to run named for `channel`'s CLI: the+/// examples in the after-help (see [`localize_examples`]) and a `cua <verb>`+/// anywhere in the about, long about, after-help and argument help (see+/// [`util::hint`]). `verbs` are the CLI's command names.+fn localize_help(+ cmd: clap::Command,+ channel: cua_home::channel::CuaChannel,+ verbs: &std::collections::HashSet<String>,+) -> clap::Command {+ let name = channel.cli_name();+ let text = |s: &clap::builder::StyledStr| {+ util::localize_for(channel, &localize_examples(&s.to_string(), name), verbs)+ };+ let about = cmd.get_about().map(text);+ let long_about = cmd.get_long_about().map(text);+ let after = cmd.get_after_help().map(text);+ let after_long = cmd.get_after_long_help().map(text);let mut cmd = cmd;+ if let Some(h) = about {+ cmd = cmd.about(h);+ }+ if let Some(h) = long_about {+ cmd = cmd.long_about(h);+ }if let Some(h) = after {cmd = cmd.after_help(h);}if let Some(h) = after_long {cmd = cmd.after_long_help(h);}- cmd.mut_subcommands(|sub| localize_help(sub, name))+ cmd.mut_args(|arg| {+ let help = arg.get_help().map(text);+ let long_help = arg.get_long_help().map(text);+ let mut arg = arg;+ if let Some(h) = help {+ arg = arg.help(h);+ }+ if let Some(h) = long_help {+ arg = arg.long_help(h);+ }+ arg+ })+ .mut_subcommands(|sub| localize_help(sub, channel, verbs))}/// `text` with every line that is a `cua ...` example (it starts with `cua `@@ -2712,6 +2739,16 @@ fn localize_examples(text: &str, name: &str) -> String {out}+/// The text of `cua help advanced` for `channel`: Local's names its own CLI in+/// the examples and wherever a command is named in a sentence.+fn advanced_help_for(channel: cua_home::channel::CuaChannel) -> String {+ if !channel.is_local() {+ return ADVANCED_HELP.to_string();+ }+ let examples = localize_examples(ADVANCED_HELP, channel.cli_name());+ util::localize_for(channel, &examples, &util::verbs_of(&cli_command(true)))+}+/// `cua help advanced`, answered before clap: it is a help topic, not a/// command.fn is_advanced_help(args: &[std::ffi::OsString]) -> bool {@@ -2721,7 +2758,7 @@ fn is_advanced_help(args: &[std::ffi::OsString]) -> bool {/// Shows a fallback to the relay's HTTPS path on stderr (never stdout, so/// `--json` output and pipes stay clean).fn fallback_notice(n: &cua_spaces::mesh::FallbackNotice) {- eprintln!("cua: {}", n.message());+ eprintln!("{}: {}", util::cli(), n.message());}pub fn main() {@@ -2729,11 +2766,7 @@ pub fn main() {keep_stdio_out_of_children();let channel = cua_home::channel::CuaChannel::current();if is_advanced_help(&std::env::args_os().skip(1).collect::<Vec<_>>()) {- if channel.is_local() {- print!("{}", localize_examples(ADVANCED_HELP, channel.cli_name()));- } else {- print!("{ADVANCED_HELP}");- }+ print!("{}", advanced_help_for(channel));return;}promote_spacesd_env_vars();@@ -2854,7 +2887,7 @@ pub fn main() {Ok(c) => c,Err(e) => {let _ = out.flush();- eprintln!("cua: {e}");+ eprintln!("{}: {}", channel.cli_name(), util::hint(&e.to_string()));exit_code(&e)}}@@ -3695,6 +3728,56 @@ mod tests {);}+ /// Everything in Local's help that tells the reader to run a command is+ /// already named `cua-local`: running the hint rewriter over the rendered+ /// help (after-help, about, argument help) finds nothing left to change.+ /// A new help text that spells `cua host setup` in the middle of a line, or+ /// in backticks, is caught here, not by a user who pastes it.+ #[test]+ fn local_help_has_no_stable_command_left() {+ use cua_home::channel::CuaChannel;+ let verbs = util::verbs_of(&cli_command(true));+ let mut local = channel_command(cli_command(true), CuaChannel::Local);+ local.build();+ for (name, text) in all_help(&mut local) {+ assert_eq!(+ util::localize_for(CuaChannel::Local, &text, &verbs),+ text,+ "{name} still names the Stable `cua`"+ );+ }+ // And the rewrite is not a no-op: Stable's help still has them.+ let mut stable = cli_command(true);+ stable.build();+ assert!(+ all_help(&mut stable)+ .iter()+ .any(|(_, t)| t.contains("`cua ")),+ "Stable help has backticked commands"+ );+ }++ /// `cua help advanced` is a help topic printed before clap runs, so the help+ /// tree above does not cover it: Local's names `cua-local` in its examples+ /// and in its sentences, Stable's is the text as written.+ #[test]+ fn help_advanced_follows_the_channel() {+ use cua_home::channel::CuaChannel;+ assert_eq!(advanced_help_for(CuaChannel::Stable), ADVANCED_HELP);+ let local = advanced_help_for(CuaChannel::Local);+ assert!(local.contains("Works with cua-local host setup"), "{local}");+ let verbs = util::verbs_of(&cli_command(true));+ assert_eq!(+ util::localize_for(CuaChannel::Local, &local, &verbs),+ local,+ "nothing left that names the Stable `cua`"+ );+ assert!(+ !local.lines().any(|l| l.trim_start().starts_with("cua ")),+ "{local}"+ );+ }+/// Stable's command and its help are exactly what they were.#[test]fn stable_help_is_unchanged() {diff --git a/libs/cua/crates/cua-cli/src/mcp.rs b/libs/cua/crates/cua-cli/src/mcp.rsindex c7f853f71d..d15d3647c1 100644--- a/libs/cua/crates/cua-cli/src/mcp.rs+++ b/libs/cua/crates/cua-cli/src/mcp.rs@@ -128,7 +128,10 @@ pub fn parse_permissions(s: &str) -> BTreeSet<String> {continue;}unknown => {- eprintln!("cua mcp: unknown permission {unknown:?}");+ eprintln!(+ "{}",+ crate::util::hint(&format!("cua mcp: unknown permission {unknown:?}"))+ );continue;}};@@ -1579,9 +1582,9 @@ impl Server {jtext(json!({"success": true, "message": format!("Deleted skill: {n}")}))}),"skills_record" => jtext(json!({- "message": format!("To record skill '{n}', run 'cua skills record --name {n} --sandbox <name>' (or --viewer-url <url>) in a terminal"),+ "message": crate::util::hint(&format!("To record skill '{n}', run 'cua skills record --name {n} --sandbox <name>' (or --viewer-url <url>) in a terminal")),"instructions": [- format!("1. Run: cua skills record --name {n} --sandbox <name> (or --viewer-url <url>)"),+ crate::util::hint(&format!("1. Run: cua skills record --name {n} --sandbox <name> (or --viewer-url <url>)")),"2. Perform the actions you want to record in the viewer","3. Click 'Stop Recording' when done",],@@ -1740,7 +1743,7 @@ impl SdkTools {let space = arguments.get("space")?.as_str()?.to_string();Some(match self.0.space(space).await {Ok(s) => s.call_tool_here(tool, arguments.clone()).await,- Err(e) => ToolOutcome::error_message(error_kind(&e), e.to_string()),+ Err(e) => ToolOutcome::error_message(error_kind(&e), crate::util::hint(&e.to_string())),})}@@ -1767,7 +1770,7 @@ impl SdkTools {.as_deref().and_then(|s| serde_json::from_str(s).ok()),},- Err(e) => ToolOutcome::error_message(error_kind(&e), e.to_string()),+ Err(e) => ToolOutcome::error_message(error_kind(&e), crate::util::hint(&e.to_string())),}}}@@ -1824,7 +1827,8 @@ impl cua_spaces::mcp::ToolExtension for Server {cua_sandbox_core::external::annotate_runtime_schema(&mut schema, &providers);json!({"name": t.name,- "description": t.description,+ // Its commands are for this build's CLI (`cua-local` on Local).+ "description": crate::util::hint(t.description),"inputSchema": schema,})})@@ -1841,7 +1845,9 @@ impl cua_spaces::mcp::ToolExtension for Server {is_error: false,meta: None,},- Err(e) => ToolOutcome::error_message(error_kind(&e), e.to_string()),+ Err(e) => {+ ToolOutcome::error_message(error_kind(&e), crate::util::hint(&e.to_string()))+ }}};Some(bounded(tool, &arguments, run).await)diff --git a/libs/cua/crates/cua-cli/src/onboard.rs b/libs/cua/crates/cua-cli/src/onboard.rsindex a25bed6ab3..248bb93f22 100644--- a/libs/cua/crates/cua-cli/src/onboard.rs+++ b/libs/cua/crates/cua-cli/src/onboard.rs@@ -317,7 +317,9 @@ pub fn jobs_line(dedicated: bool, accelerators: &[String]) -> String {} else {"containers"};- format!("Jobs: run in {kind} here ({gpus}). `cua run` sends Python functions here.")+ crate::util::hint(&format!(+ "Jobs: run in {kind} here ({gpus}). `cua run` sends Python functions here."+ ))}fn pct(free: &Value, total: &Value) -> String {@@ -375,7 +377,9 @@ pub fn machines_table(v: &Value) -> Vec<String> {));}if machines.is_empty() {- rows.push("No hosts yet: `cua host setup --no-desktop --provide-spaces` here, `cua host pair` for another computer.".into());+ rows.push(crate::util::hint(+ "No hosts yet: `cua host setup --no-desktop --provide-spaces` here, `cua host pair` for another computer.",+ ));}rows}diff --git a/libs/cua/crates/cua-cli/src/persistent_cmd.rs b/libs/cua/crates/cua-cli/src/persistent_cmd.rsindex 9f634f7ede..0c5e42ec0a 100644--- a/libs/cua/crates/cua-cli/src/persistent_cmd.rs+++ b/libs/cua/crates/cua-cli/src/persistent_cmd.rs@@ -10,7 +10,7 @@//! cua agent notifications --unread//! ```-use crate::util::{json_line, line};+use crate::util::{hint_line, json_line, line};use clap::Subcommand;use cua_sdk::{Cua, CuaError, PersistentAgentOptions};use std::io::Write;@@ -241,7 +241,7 @@ pub async fn run(.collect();show(out, serde_json::json!({"agents": rows}));} else if all.is_empty() {- line(+ hint_line(out,"No persistent agents. Create one with `cua agent create`.",);diff --git a/libs/cua/crates/cua-cli/src/runs.rs b/libs/cua/crates/cua-cli/src/runs.rsindex e724656e3c..25aedc2217 100644--- a/libs/cua/crates/cua-cli/src/runs.rs+++ b/libs/cua/crates/cua-cli/src/runs.rs@@ -18,7 +18,7 @@ use clap::Args;use cua_sdk::CuaError;use serde_json::{Value, json};-use crate::util::line;+use crate::util::{hint_line, line};/// `cua sb run`.#[derive(Args, Debug)]@@ -237,7 +237,7 @@ pub async fn run(a: RunArgs, json: bool, out: &mut dyn Write) -> Result<i32, Cuaif json {line(out, json!({"run": run, "jobs": count}).to_string());} else {- line(+ hint_line(out,format!("{run}: {count} job{} submitted (cua sb runs {run})",@@ -329,7 +329,7 @@ pub async fn run(a: RunArgs, json: bool, out: &mut dyn Write) -> Result<i32, Cua),);if ok < u64::from(count) {- line(+ hint_line(out,format!("See what failed: cua sb runs {run} --state failed"),);@@ -446,10 +446,13 @@ fn keys_lines(k: &Value, width: Option<usize>) -> Vec<String> {.map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();let mut out = Vec::new();+ // The command is spelled with this build's CLI name, not rewritten with the+ // line: the device names in it are the user's.+ let cli = crate::util::cli();match k["waiting"].as_str() {Some(_) if !holders.is_empty() => {out.push(format!(- "Not shared with this device yet. Your pool keys are on: {}; at least one must be online to add a new device (open Cua on one of them), or revoke the ones you no longer have (`cua devices revoke <id>`).",+ "Not shared with this device yet. Your pool keys are on: {}; at least one must be online to add a new device (open Cua on one of them), or revoke the ones you no longer have (`{cli} devices revoke <id>`).",holders.join(", ")));}diff --git a/libs/cua/crates/cua-cli/src/sandbox.rs b/libs/cua/crates/cua-cli/src/sandbox.rsindex eac5d7fae5..52a4f5e1ee 100644--- a/libs/cua/crates/cua-cli/src/sandbox.rs+++ b/libs/cua/crates/cua-cli/src/sandbox.rs@@ -5,7 +5,7 @@use crate::{shell::{self, exit_code},- util::{self, internal, line},+ util::{self, hint_line, internal, line},};use clap::{Args, Subcommand};use cua_sandbox_core::placement::{Kind, On, Runtime};@@ -1727,12 +1727,15 @@ fn kept_message(i: &SandboxInfo) -> String {/// `--wait desktop`, `--browser`): deletes the sandbox unless `keep`, and returns `e`.async fn failed_after_create(sb: &Arc<cua_sdk::Sandbox>, keep: bool, e: CuaError) -> CuaError {if keep {- eprintln!("{}", kept_message(&sb.info()));+ eprintln!("{}", util::hint(&kept_message(&sb.info())));} else if let Err(d) = sb.delete().await {eprintln!(- "warning: could not delete sandbox {} after the failure: {d} (delete it with `cua sb rm {} --force`)",- sb.id(),- sb.id()+ "{}",+ util::hint(&format!(+ "warning: could not delete sandbox {} after the failure: {d} (delete it with `cua sb rm {} --force`)",+ sb.id(),+ sb.id()+ )));}e@@ -1898,7 +1901,7 @@ async fn create(&& let Some(n) = &requested_name&& let Ok(info) = cua.sandboxes().get(n.clone()).await{- eprintln!("{}", kept_message(&info));+ eprintln!("{}", util::hint(&kept_message(&info)));}let sb = created.map_err(|e| on_backend(e, &label))?;let i = sb.info();@@ -2021,7 +2024,7 @@ async fn create();if let Some(b) = &browser {let br = &b["browser"];- line(+ hint_line(out,format!("\nBrowser ready ({}): session {}, target_id {}, tab_id {}\n\@@ -2746,7 +2749,12 @@ pub async fn run(}SandboxCmd::View(v) => return view(cua, v, json_global, out).await,SandboxCmd::Vnc(v) => {- eprintln!("warning: `cua sb vnc` is deprecated; use `cua sb view` (the HTML5 viewer).");+ eprintln!(+ "{}",+ util::hint(+ "warning: `cua sb vnc` is deprecated; use `cua sb view` (the HTML5 viewer)."+ )+ );return view(cua, v, json_global, out).await;}SandboxCmd::StreamProbe { args, at } => {diff --git a/libs/cua/crates/cua-cli/src/sandbox/bake.rs b/libs/cua/crates/cua-cli/src/sandbox/bake.rsindex c412e0addf..306fb1f801 100644--- a/libs/cua/crates/cua-cli/src/sandbox/bake.rs+++ b/libs/cua/crates/cua-cli/src/sandbox/bake.rs@@ -152,7 +152,7 @@ pub async fn bake(.as_ref().map(|v| format!(", a fork came up live in {:.1}s", v.fork_s)).unwrap_or_default();- format!(+ crate::util::hint(&format!("Checkpoint '{}' baked in {:.1}s: {ready}compose up {:.1}s, checkpoint {:.1}s{fork}.\n{} containers running:\n {}\nFork it: cua sb fork {} <name>",s.checkpoint,s.total_s,@@ -161,7 +161,7 @@ pub async fn bake(s.containers.len(),s.containers.join("\n "),s.checkpoint- )+ ))});Ok(0)}diff --git a/libs/cua/crates/cua-cli/src/share_cmd.rs b/libs/cua/crates/cua-cli/src/share_cmd.rsindex a4ed15d77a..3d6feda27d 100644--- a/libs/cua/crates/cua-cli/src/share_cmd.rs+++ b/libs/cua/crates/cua-cli/src/share_cmd.rs@@ -204,7 +204,10 @@ async fn create(format!("Anyone with the link can open it, for {}.", ends(&s))}};- eprintln!("{note} Stop it with: cua share stop {}", s.id);+ eprintln!(+ "{}",+ crate::util::hint(&format!("{note} Stop it with: cua share stop {}", s.id))+ );}}Ok(0)@@ -221,7 +224,10 @@ async fn ls(json: bool, out: &mut dyn Write) -> Result<i32, CuaError> {return Ok(0);}if shares.is_empty() {- eprintln!("Nothing is shared. Share something with: cua share 3000");+ eprintln!(+ "{}",+ crate::util::hint("Nothing is shared. Share something with: cua share 3000")+ );return Ok(0);}line(diff --git a/libs/cua/crates/cua-cli/src/skills.rs b/libs/cua/crates/cua-cli/src/skills.rsindex e373e70188..d9e0789390 100644--- a/libs/cua/crates/cua-cli/src/skills.rs+++ b/libs/cua/crates/cua-cli/src/skills.rs@@ -7,7 +7,7 @@//! `[u32 BE json length][json {events, metadata}][mp4]`, extracts one frame//! per event with `ffmpeg` and captions it with a vision model.-use crate::util::{self, internal, line};+use crate::util::{self, hint_line, internal, line};use cua_sdk::CuaError;use std::{io::Write,@@ -108,7 +108,7 @@ pub fn cmd_list(json: bool, out: &mut dyn Write) -> Result<i32, CuaError> {}if skills.is_empty() {line(out, "No skills found.");- line(+ hint_line(out,"Record a skill with: cua skills record --sandbox <name>",);diff --git a/libs/cua/crates/cua-cli/src/team_cmd.rs b/libs/cua/crates/cua-cli/src/team_cmd.rsindex 47c38a3a3c..efe967054e 100644--- a/libs/cua/crates/cua-cli/src/team_cmd.rs+++ b/libs/cua/crates/cua-cli/src/team_cmd.rs@@ -10,7 +10,7 @@//! first, and asks you to confirm); see `lib.rs`. The relay's old//! `team-…` teams are not used: a server without Teams says so.-use crate::util::{self, line};+use crate::util::{self, hint_line, line};use clap::Subcommand;use cua_host::AccountTokens;use cua_host::spaces_api::{@@ -265,7 +265,7 @@ fn print_devices(org: &ApiOrg, devices: &[ApiDeviceApproval], out: &mut dyn Writline(out, format!(" {} {} {}", d.device_id, d.sub, d.state));}if org.manages() && devices.iter().any(|d| d.state == "pending") {- line(+ hint_line(out,format!("Approve one with `cua team approve {} <device>`.", org.id),);@@ -326,7 +326,7 @@ pub async fn run_with(} else {line(out, format!("Created team {} ({}).", t.label(), t.id));line(out, "Next:");- line(+ hint_line(out," cua auth login (your session lists the team after a new sign-in)",);@@ -334,8 +334,8 @@ pub async fn run_with(out," buy Teams for it at app.cua.ai (team computers and device approval need it)",);- line(out, format!(" cua team invite {} <email>", t.id));- line(out, format!(" cua team add-machine {} <space>", t.id));+ hint_line(out, format!(" cua team invite {} <email>", t.id));+ hint_line(out, format!(" cua team add-machine {} <space>", t.id));}}TeamCmd::Ls => {@@ -345,7 +345,7 @@ pub async fn run_with(return Ok(0);}if me.orgs.is_empty() {- line(+ hint_line(out,"You are in no team. Create one with `cua team create <name>` (or at app.cua.ai).",);@@ -417,7 +417,7 @@ pub async fn run_with(}line(out, format!("Computers ({}):", machines.len()));if machines.is_empty() {- line(+ hint_line(out," none yet: `cua team add-machine <team> <space>` (owner or admin)",);@@ -455,7 +455,7 @@ pub async fn run_with(&serde_json::json!({ "team": id, "email": email.trim(), "role": role }),);} else {- line(+ hint_line(out,format!("Invited {} to {} as {role}: cua.ai emails them an invitation. They accept it, sign in again (`cua auth login`), and run `cua team join {}`.",@@ -482,7 +482,7 @@ pub async fn run_with(out,format!("You are in {} ({}) as {role}.", org.label(), org.id),);- line(+ hint_line(out,format!("If the team approves devices, ask for this one: `cua team request {}`.",diff --git a/libs/cua/crates/cua-cli/src/telemetry_cmd.rs b/libs/cua/crates/cua-cli/src/telemetry_cmd.rsindex 8b87cf7120..d30750faab 100644--- a/libs/cua/crates/cua-cli/src/telemetry_cmd.rs+++ b/libs/cua/crates/cua-cli/src/telemetry_cmd.rs@@ -1,7 +1,7 @@//! `cua telemetry`: see and control anonymous usage telemetry//! (cua-telemetry).-use crate::util::{self, line};+use crate::util::{self, hint_line, line};use clap::Subcommand;use cua_sdk::CuaError;use std::io::Write;@@ -105,7 +105,7 @@ pub fn run(cmd: TelemetryCmd, json: bool, out: &mut dyn Write) -> Result<i32, Cuout,serde_json::to_string_pretty(&envelope).unwrap_or_default(),);- line(+ hint_line(out,format!("\n`cua telemetry schema` lists every event. Turn it off: cua telemetry off (or DO_NOT_TRACK=1). Details: {}",diff --git a/libs/cua/crates/cua-cli/src/trajectory.rs b/libs/cua/crates/cua-cli/src/trajectory.rsindex 0bcc68ae4a..599ad27df3 100644--- a/libs/cua/crates/cua-cli/src/trajectory.rs+++ b/libs/cua/crates/cua-cli/src/trajectory.rs@@ -3,7 +3,7 @@//! TrajectoryViewer format (`turn_NNN_agent_response.json` plus an optional//! `screenshot.png`). `cua trajectory` lists, zips, serves and cleans them.-use crate::util::{self, internal, line};+use crate::util::{self, hint_line, internal, line};use cua_sdk::CuaError;use std::{io::Write,@@ -388,7 +388,7 @@ pub fn cmd_view(target: Option<String>, port: u16, out: &mut dyn Write) -> Resul.unwrap_or_default();line(out, format!("Serving: {machine}/{ts}"));line(out, format!("Viewer: {viewer}"));- line(out, "Stop with: cua trajectory stop");+ hint_line(out, "Stop with: cua trajectory stop");util::open_browser(&viewer);Ok(0)}diff --git a/libs/cua/crates/cua-cli/src/util.rs b/libs/cua/crates/cua-cli/src/util.rsindex 060264a9d1..fe9220ea40 100644--- a/libs/cua/crates/cua-cli/src/util.rs+++ b/libs/cua/crates/cua-cli/src/util.rs@@ -1,7 +1,9 @@//! Shared helpers: paths, output, prompts, browser, HTTP.+use cua_home::channel::CuaChannel;use cua_sdk::CuaError;use std::{+ collections::HashSet,io::{IsTerminal, Write},path::PathBuf,time::Duration,@@ -67,6 +69,106 @@ pub fn line(out: &mut dyn Write, s: impl AsRef<str>) {let _ = writeln!(out, "{}", s.as_ref());}+/// The name of this build's CLI, for a message that holds one command's name+/// apart from its arguments (a `cua-local sb create ...` command in a JSON+/// list): `cua`, or `cua-local` on Local. Prose goes through [`hint`].+pub fn cli() -> &'static str {+ CuaChannel::current().cli_name()+}++/// Writes a hint line: [`line`] with each `cua <verb>` command it tells the+/// reader to run named for this build's CLI (`cua-local` on Local, see+/// [`hint`]). Stable's output is unchanged. For messages we wrote, never for+/// data (a Space's output, names, JSON).+pub fn hint_line(out: &mut dyn Write, s: impl AsRef<str>) {+ line(out, hint(s.as_ref()));+}++/// `s` with each command it tells the reader to run named for this build's+/// CLI, so "run `cua host setup`" says `cua-local host setup` on Local and a+/// pasted hint never runs the Stable CLI. Stable's text is returned as is.+/// Two spellings are rewritten: a backticked `` `cua <anything>` `` and a bare+/// `cua <verb>` ("Run it: cua spaces create ...") where `<verb>` is one of this+/// CLI's commands, so prose such as "cua will not ask again" is left alone.+/// Text inside double quotes is left alone too: that is where a message puts+/// a name the user chose (`{name:?}`), and a host called "cua host" is not a+/// command. For messages we wrote; where a message names a user's value next+/// to a command, spell the command with [`cli`] instead.+pub fn hint(s: &str) -> String {+ hint_for(CuaChannel::current(), s)+}++fn hint_for(channel: CuaChannel, s: &str) -> String {+ if !channel.is_local() {+ return s.to_string();+ }+ rename_commands(s, channel.cli_name(), cli_verbs(), true)+}++/// Help text we wrote (about, examples, argument help) for `channel`, given+/// the names of the CLI's commands: [`hint`] without the quote rule, since+/// there is no user's value in it (an example can quote an argument).+pub(crate) fn localize_for(channel: CuaChannel, s: &str, verbs: &HashSet<String>) -> String {+ if !channel.is_local() {+ return s.to_string();+ }+ rename_commands(s, channel.cli_name(), verbs, false)+}++/// The names (and aliases) of the CLI's commands, such as `host` and `sb`.+fn cli_verbs() -> &'static HashSet<String> {+ static VERBS: std::sync::OnceLock<HashSet<String>> = std::sync::OnceLock::new();+ VERBS.get_or_init(|| verbs_of(&crate::cli_command(true)))+}++/// The names (and aliases) of `cli`'s top-level commands.+pub(crate) fn verbs_of(cli: &clap::Command) -> HashSet<String> {+ cli.get_subcommands()+ .flat_map(|c| std::iter::once(c.get_name()).chain(c.get_all_aliases()))+ .map(str::to_string)+ .collect()+}++/// `text` with each command it names (a backticked `` `cua ...` ``, or a bare+/// `cua <verb>` that is not part of a longer word, path or name) starting with+/// `name` instead of `cua`. With `skip_quoted`, not inside double quotes.+fn rename_commands(text: &str, name: &str, verbs: &HashSet<String>, skip_quoted: bool) -> String {+ let mut out = String::with_capacity(text.len() + 16);+ let mut copied = 0;+ for (at, _) in text.match_indices("cua ") {+ let before = &text[..at];+ let prev = before.chars().next_back();+ let starts_word = prev.is_none_or(|c| !(c.is_alphanumeric() || "-_./~".contains(c)));+ let rest = &text[at + 4..];+ let verb_len = rest+ .find(|c: char| !(c.is_alphanumeric() || c == '-' || c == '_'))+ .unwrap_or(rest.len());+ let is_command = prev == Some('`') || verbs.contains(&rest[..verb_len]);+ if starts_word && is_command && !(skip_quoted && inside_double_quotes(before)) {+ out.push_str(&text[copied..at]);+ out.push_str(name);+ copied = at + 3;+ }+ }+ out.push_str(&text[copied..]);+ out+}++/// Whether the end of `before` is inside a double-quoted span (an unescaped+/// `"` opens one and the next closes it).+fn inside_double_quotes(before: &str) -> bool {+ let (mut open, mut escaped) = (false, false);+ for c in before.chars() {+ match c {+ _ if escaped => escaped = false,+ '\\' => escaped = true,+ '"' => open = !open,+ _ => {}+ }+ }+ open+}+/// Pretty JSON line.pub fn json_line(out: &mut dyn Write, v: &serde_json::Value) {let _ = writeln!(@@ -564,3 +666,91 @@ mod browser_tests {assert_eq!(args, vec![SIGN_IN.to_string()]);}}++#[cfg(test)]+mod hint_tests {+ use super::*;++ const HINT: &str = "run `cua host setup` (or `cua auth login`); then cua spaces ls, \+ cua sb view x, the cua daemon's log, cua will not ask, ~/.cua config, \+ `cua` and Cua spaces ls";++ #[test]+ fn stable_hints_are_unchanged() {+ assert_eq!(hint_for(CuaChannel::Stable, HINT), HINT);+ }++ #[test]+ fn local_hints_name_the_local_cli() {+ assert_eq!(+ hint_for(CuaChannel::Local, HINT),+ "run `cua-local host setup` (or `cua-local auth login`); then cua-local spaces ls, \+ cua-local sb view x, the cua-local daemon's log, cua will not ask, ~/.cua config, \+ `cua` and Cua spaces ls"+ );+ // A command named in prose is a command of this CLI too, and the word+ // after `cua` is the whole verb, not a prefix of one.+ assert_eq!(+ hint_for(CuaChannel::Local, "Not logged in. Run 'cua auth login'."),+ "Not logged in. Run 'cua-local auth login'."+ );+ assert_eq!(+ hint_for(CuaChannel::Local, "cua hostile, cua sbx, cua"),+ "cua hostile, cua sbx, cua"+ );+ // A value the user chose sits in double quotes (`{name:?}`): never a+ // command, whatever it says. The command next to it is renamed.+ assert_eq!(+ hint_for(+ CuaChannel::Local,+ r#"no team of yours is called "cua host" (`cua team ls`)"#+ ),+ r#"no team of yours is called "cua host" (`cua-local team ls`)"#+ );+ // An escaped quote inside the value does not end it.+ assert_eq!(+ hint_for(+ CuaChannel::Local,+ r#"host "say \"cua host\" now" added; run cua host status"#+ ),+ r#"host "say \"cua host\" now" added; run cua-local host status"#+ );+ // Help text we wrote has no user's value: an example's quotes do not+ // hide its command.+ let verbs = cli_verbs();+ assert_eq!(+ localize_for(+ CuaChannel::Local,+ r#"say "cua host setup" then cua sb ls"#,+ verbs+ ),+ r#"say "cua-local host setup" then cua-local sb ls"#+ );+ assert_eq!(+ localize_for(CuaChannel::Stable, r#"say "cua host setup""#, verbs),+ r#"say "cua host setup""#+ );+ // Not a command of this CLI, part of a longer name or path: untouched.+ for t in [+ "cua foo bar",+ "ai.cua spaces",+ "my-cua spaces",+ "/opt/cua spaces",+ "cua",+ "",+ ] {+ assert_eq!(hint_for(CuaChannel::Local, t), t, "{t}");+ }+ }++ #[test]+ fn the_verbs_are_the_cli_commands() {+ let verbs = cli_verbs();+ for v in [+ "host", "spaces", "sb", "auth", "jobs", "run", "do", "daemon",+ ] {+ assert!(verbs.contains(v), "{v}");+ }+ assert!(!verbs.contains("will"));+ }+}diff --git a/libs/cua/crates/cua-cli/tests/channel_name.rs b/libs/cua/crates/cua-cli/tests/channel_name.rsindex c7f6dc977c..87ff9da780 100644--- a/libs/cua/crates/cua-cli/tests/channel_name.rs+++ b/libs/cua/crates/cua-cli/tests/channel_name.rs@@ -102,6 +102,9 @@ fn says_local(text: &str) {!text.lines().any(|l| l.trim_start().starts_with("cua ")),"{text}");+ // A command named in the middle of a help text (in backticks) too.+ assert!(text.contains("`cua-local host pair`"), "{text}");+ assert!(!text.contains("`cua "), "{text}");}fn says_stable(text: &str) {@@ -112,6 +115,7 @@ fn says_stable(text: &str) {"{text}");assert!(!text.contains("cua-local"), "{text}");+ assert!(text.contains("`cua host pair`"), "{text}");}#[test]@@ -169,12 +173,108 @@ fn help_advanced_follows_the_channel() {assert!(!stable.contains("cua-local"), "{stable}");let local = rig.run("cua-local", None, None, &["help", "advanced"]);assert!(local.contains("cua-local host setup --relay"), "{local}");+ // And a command named in a sentence, not only the examples.+ assert!(local.contains("Works with cua-local host setup"), "{local}");+ assert!(stable.contains("Works with cua host setup"), "{stable}");assert!(!local.lines().any(|l| l.trim_start().starts_with("cua ")),"{local}");}+// ---- Hints and errors name the CLI that printed them --------------------------------++/// `program args...` in a fresh fake `HOME` with a clean environment (and the+/// file credential store: never the developer's Keychain). Returns the exit+/// code, stdout and stderr.+fn run_fresh(rig: &Rig, program: &str, args: &[&str]) -> (Option<i32>, String, String) {+ let home = tempfile::tempdir_in(rig.dir.path()).unwrap().keep();+ let out = Command::new(rig.bin(program))+ .args(args)+ .env_clear()+ .env("HOME", &home)+ .env("PATH", "")+ .env("CUA_TELEMETRY", "0")+ .env("CUA_CREDENTIAL_STORE", "file")+ .stdin(Stdio::null())+ .output()+ .expect("run cua");+ (+ out.status.code(),+ String::from_utf8(out.stdout).unwrap(),+ String::from_utf8(out.stderr).unwrap(),+ )+}++/// A hint that tells the reader to run a `cua` command names the CLI the+/// reader ran: `cua-local` for Local, so pasting it does not run Stable's+/// `cua`. Stable's output is unchanged.+#[test]+fn hints_and_errors_name_the_cli_that_printed_them() {+ let rig = Rig::new();++ // A hint on stdout: the status of a Mac that is not set up. (The rest of+ // what it prints, and its exit status, depend on this machine's disk.)+ let (_, out, _) = run_fresh(&rig, "cua", &["host", "status"]);+ assert!(+ out.contains("This computer is not set up for access (run `cua host setup`)."),+ "{out}"+ );+ assert!(!out.contains("cua-local"), "{out}");+ let (_, out, _) = run_fresh(&rig, "cua-local", &["host", "status"]);+ assert!(+ out.contains("This computer is not set up for access (run `cua-local host setup`)."),+ "{out}"+ );+ assert!(!out.contains("`cua "), "{out}");++ // An error on stderr: a command that needs the sign-in. The error line+ // starts with the name the user ran.+ let says = |err: &str, line: &str| err.lines().any(|l| l == line);+ let (stable_code, _, err) = run_fresh(&rig, "cua", &["host", "pair"]);+ assert!(+ says(+ &err,+ "cua: unauthenticated: not signed in to cua.ai; run `cua auth login` first"+ ),+ "{err}"+ );+ let (local_code, _, err) = run_fresh(&rig, "cua-local", &["host", "pair"]);+ assert!(+ says(+ &err,+ "cua-local: unauthenticated: not signed in to cua.ai; run `cua-local auth login` first"+ ),+ "{err}"+ );+ assert_eq!(+ local_code, stable_code,+ "the exit code does not depend on the name"+ );++ // An error made in `cua-host` (it is shared with the app), not in the CLI.+ let (stable_code, _, err) = run_fresh(&rig, "cua", &["host", "start"]);+ assert!(+ says(+ &err,+ "cua: not found: this computer is not set up for access (run `cua host setup`)"+ ),+ "{err}"+ );+ let (local_code, _, err) = run_fresh(&rig, "cua-local", &["host", "start"]);+ assert!(+ says(+ &err,+ "cua-local: not found: this computer is not set up for access (run `cua-local host setup`)"+ ),+ "{err}"+ );+ assert_eq!(+ local_code, stable_code,+ "the exit code does not depend on the name"+ );+}+// ---- Startup: the environment and the home -----------------------------------/// `cua auth status --json` of `program` in a fresh fake `HOME`, with thediff --git a/libs/cua/crates/cua-host/src/device.rs b/libs/cua/crates/cua-host/src/device.rsindex 4ff5b47141..f506149452 100644--- a/libs/cua/crates/cua-host/src/device.rs+++ b/libs/cua/crates/cua-host/src/device.rs@@ -546,10 +546,10 @@ impl DeviceAuth {return Ok(token.clone());}let key = self.key()?.ok_or_else(|| {- Error::PermissionDenied(- "this device is not enrolled for your cua.ai account (run `cua devices enroll`)"- .into(),- )+ Error::PermissionDenied(format!(+ "this device is not enrolled for your cua.ai account (run `{} devices enroll`)",+ crate::cli()+ ))})?;let token = self.tokens.access_token().await?;let session = self.open_session(&token, &key).await?;diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rsindex d74b13b489..48c42a6d53 100644--- a/libs/cua/crates/cua-host/src/host.rs+++ b/libs/cua/crates/cua-host/src/host.rs@@ -466,10 +466,11 @@ pub fn local_network_hint(os: &str, provide_spaces: bool, driver: &Path) -> Opti"macOS Spaces on this Mac need Local Network access for {d}. When \macOS asks \"Allow {short} to find devices on local networks?\" on this Mac's \screen, click Allow; or turn on {short} in System Settings → Privacy & \- Security → Local Network. If the cua daemon was started from Terminal or over SSH, \- run `cua daemon stop` so the host service starts it at the next create (over SSH \+ Security → Local Network. If the {cli} daemon was started from Terminal or over SSH, \+ run `{cli} daemon stop` so the host service starts it at the next create (over SSH \nothing can grant it). Without it, macOS Space creates fail with \"No route to \- host\"; Linux Spaces don't need it."+ host\"; Linux Spaces don't need it.",+ cli = crate::cli()),})}@@ -1228,11 +1229,11 @@ impl Host {self.helper_app().map(|app| service::app_helper_launcher(&app)).ok_or_else(|| {- Error::Service(+ Error::Service(format!("the host service runs inside the Cua Spaces app, which is not \- installed; install it, or run `cua host setup --runner launchd`"- .into(),- )+ installed; install it, or run `{} host setup --runner launchd`",+ crate::cli()+ ))})?,),_ => None,@@ -1529,18 +1530,22 @@ impl Host {/// changed.pub fn enable_shares(&self) -> Result<bool> {let config = self.config()?.ok_or_else(|| {- Error::NotFound(- "this machine is not on your cua.ai relay; set it up with `cua host setup`".into(),- )+ Error::NotFound(format!(+ "this machine is not on your cua.ai relay; set it up with `{} host setup`",+ crate::cli()+ ))})?;if config.mode != "relay" {- return Err(Error::InvalidArgument(- "this machine is not on your cua.ai relay (direct mode); links need the relay: `cua host setup`"- .into(),- ));+ return Err(Error::InvalidArgument(format!(+ "this machine is not on your cua.ai relay (direct mode); links need the relay: `{} host setup`",+ crate::cli()+ )));}let mut policy = self.policy()?.ok_or_else(|| {- Error::NotFound("this machine has no host policy; run `cua host setup`".into())+ Error::NotFound(format!(+ "this machine has no host policy; run `{} host setup`",+ crate::cli()+ ))})?;let gateway = self.shares_gateway();if policy.shares && policy.shares_gateway.as_deref() == Some(gateway.as_str()) {@@ -1814,7 +1819,10 @@ impl Host {fn require_config(&self) -> Result<HostConfig> {self.config()?.ok_or_else(|| {- Error::NotFound("this computer is not set up for access (run `cua host setup`)".into())+ Error::NotFound(format!(+ "this computer is not set up for access (run `{} host setup`)",+ crate::cli()+ ))})}@@ -1853,11 +1861,11 @@ impl Host {pub async fn start_sharing(&self) -> Result<HostStatus> {let mut config = self.require_config()?;if !config.share_desktop && !config.provide_spaces {- return Err(Error::InvalidArgument(+ return Err(Error::InvalidArgument(format!("there is nothing to share: turn on the desktop or Spaces first \- (`cua host config --desktop on` or `--provide-spaces on`)"- .into(),- ));+ (`{} host config --desktop on` or `--provide-spaces on`)",+ crate::cli()+ )));}match (&config.relay_url, &config.machine_id) {(Some(url), Some(id)) => {@@ -2088,8 +2096,11 @@ impl Host {MigrationPlan::Nothing(why) => Ok(ServiceMigration::new("not-needed", why, false)),MigrationPlan::KeepAfterFailure => Ok(ServiceMigration::new("kept",- "moving into the Cua Spaces app failed before with this version; the old host \- service keeps running (`cua host migrate --force` tries again)",+ format!(+ "moving into the Cua Spaces app failed before with this version; the old host \+ service keeps running (`{} host migrate --force` tries again)",+ crate::cli()+ ),false,)),MigrationPlan::RemoveLeftovers => {@@ -2300,7 +2311,7 @@ impl Host {let provided = crate::provided::load_provided(&self.paths.dir)?;if !provided.is_empty() && !uninstalling {return Err(Error::InvalidArgument(format!(- "this computer still provides {} Space{} ({}); delete {} first (`cua spaces delete <local:name>`)",+ "this computer still provides {} Space{} ({}); delete {} first (`{} spaces delete <local:name>`)",provided.len(),if provided.len() == 1 { "" } else { "s" },provided@@ -2309,6 +2320,7 @@ impl Host {.collect::<Vec<_>>().join(", "),if provided.len() == 1 { "it" } else { "them" },+ crate::cli(),)));}let mut relay_error = None;@@ -2449,8 +2461,9 @@ fn missing_libraries_message(missing: &[String]) -> String {""};format!(- "cua-spacesd cannot start: this machine lacks {}.{hint} Install them and run `cua host setup` again.",- missing.join(", ")+ "cua-spacesd cannot start: this machine lacks {}.{hint} Install them and run `{} host setup` again.",+ missing.join(", "),+ crate::cli())}diff --git a/libs/cua/crates/cua-host/src/lib.rs b/libs/cua/crates/cua-host/src/lib.rsindex 83860a7b53..5836748f63 100644--- a/libs/cua/crates/cua-host/src/lib.rs+++ b/libs/cua/crates/cua-host/src/lib.rs@@ -122,6 +122,13 @@ pub fn device_platform() -> &'static str {std::env::consts::OS}+/// The command a message tells the user to run: `cua`, or `cua-local` in a+/// Local build ("Cua Spaces Local", CUA-1776), so a pasted hint never runs the+/// Stable CLI. Messages write it as `` `{cli} host setup` ``.+pub(crate) fn cli() -> &'static str {+ cua_home::channel::CuaChannel::current().cli_name()+}+/// Errors.#[derive(Debug, thiserror::Error)]pub enum Error {diff --git a/libs/cua/crates/cua-host/src/pairing.rs b/libs/cua/crates/cua-host/src/pairing.rsindex 36a041b581..e14f82d02f 100644--- a/libs/cua/crates/cua-host/src/pairing.rs+++ b/libs/cua/crates/cua-host/src/pairing.rs@@ -249,7 +249,8 @@ impl RelayClient {.is_some_and(|h| !h.is_empty() && h.bytes().all(|b| b.is_ascii_alphanumeric()));if !valid {return Err(Error::InvalidArgument(format!(- "{id:?} is not a pairing code id (pc_…; see `cua host pair --list`)"+ "{id:?} is not a pairing code id (pc_…; see `{} host pair --list`)",+ crate::cli())));}let _: serde_json::Value = selfdiff --git a/libs/cua/crates/cua-host/src/preflight.rs b/libs/cua/crates/cua-host/src/preflight.rsindex 2cc39ec95f..496ec7fbc3 100644--- a/libs/cua/crates/cua-host/src/preflight.rs+++ b/libs/cua/crates/cua-host/src/preflight.rs@@ -254,7 +254,8 @@ pub fn check(probe: &dyn SessionProbe, driver_bin: &Path) -> Result<PreflightRepLaunchAgent needs one for screen sharing and input, and `launchctl bootstrap \gui/{uid}` would fail here. Log in at the console once, or turn on automatic \login (System Settings > Users & Groups > Login Options > Automatic login), \- then run `cua host setup` again."+ then run `{cli} host setup` again.",+ cli = crate::cli())));}let (screen_recording, accessibility) = match probe.permission_status(driver_bin) {diff --git a/libs/cua/crates/cua-host/src/relay.rs b/libs/cua/crates/cua-host/src/relay.rsindex 8b1dbfe0c6..033d0f9cd0 100644--- a/libs/cua/crates/cua-host/src/relay.rs+++ b/libs/cua/crates/cua-host/src/relay.rs@@ -86,9 +86,10 @@ pub struct NoAccount;#[async_trait::async_trait]impl AccountTokens for NoAccount {async fn access_token(&self) -> Result<String> {- Err(Error::Unauthenticated(- "not signed in to cua.ai (run `cua auth login` or sign in from the app)".into(),- ))+ Err(Error::Unauthenticated(format!(+ "not signed in to cua.ai (run `{} auth login` or sign in from the app)",+ crate::cli()+ )))}}diff --git a/libs/cua/crates/cua-host/src/service.rs b/libs/cua/crates/cua-host/src/service.rsindex a2fd2a14ca..5189d6c213 100644--- a/libs/cua/crates/cua-host/src/service.rs+++ b/libs/cua/crates/cua-host/src/service.rs@@ -1667,8 +1667,9 @@ impl ServiceManager for MissingAppHelper {fn missing_app() -> Error {Error::Service(format!("{name} lives in the Cua Spaces app, which is not installed; install it \- again, or run `cua host setup --runner launchd`",- name = app_helper_name()+ again, or run `{cli} host setup --runner launchd`",+ name = app_helper_name(),+ cli = crate::cli()))}diff --git a/libs/cua/crates/cua-host/src/spaces_api.rs b/libs/cua/crates/cua-host/src/spaces_api.rsindex 2b297f09e4..e02cc27395 100644--- a/libs/cua/crates/cua-host/src/spaces_api.rs+++ b/libs/cua/crates/cua-host/src/spaces_api.rs@@ -613,7 +613,8 @@ impl SpacesApiClient {if is_legacy_team_id(q) {return Err(Error::InvalidArgument(format!("{q} is a team id of the old Teams, which this version no longer uses: \- use the team's id from `cua team ls`"+ use the team's id from `{} team ls`",+ crate::cli())));}let me: ApiMe = self.org_get("/v1/me", token).await?;@@ -628,11 +629,13 @@ impl SpacesApiClient {match named.as_slice() {[o] => Ok((*o).clone()),[] => Err(Error::NotFound(format!(- "no team of yours is called {q:?} (`cua team ls`; a team made or joined a \- moment ago shows up after `cua auth login`)"+ "no team of yours is called {q:?} (`{cli} team ls`; a team made or joined a \+ moment ago shows up after `{cli} auth login`)",+ cli = crate::cli()))),_ => Err(Error::InvalidArgument(format!(- "several of your teams are called {q:?}: use the team id (`cua team ls`)"+ "several of your teams are called {q:?}: use the team id (`{} team ls`)",+ crate::cli()))),}}