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(spaces): name the app blocked from the Local Network in cua doctor, the daemon log and Turn on (CUA-1819) (#5378)

ddupont075add55cf93
diff --git a/apps/cua-spaces/src-tauri/Cargo.lock b/apps/cua-spaces/src-tauri/Cargo.lock
index 7b08ca13df..203ae383d5 100644
--- a/apps/cua-spaces/src-tauri/Cargo.lock
+++ b/apps/cua-spaces/src-tauri/Cargo.lock
@@ -1664,6 +1664,7 @@ dependencies = [
"cua-spaces-contract",
"cua-spacesd-client",
"cua-telemetry",
+ "cua-vmm",
"futures-util",
"hex",
"http",
diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
index 4a982c884a..a2146c8dc4 100644
--- a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
+++ b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
@@ -991,6 +991,17 @@ pub enum Health {
}
```
+### `reattach::Note`
+
+Whether to log a failure at `warn`.
+
+```rust
+pub enum Note {
+ Log { repeated: u32 },
+ Quiet,
+}
+```
+
### `reattach::Policy`
Timing of `supervise`.
@@ -1003,6 +1014,18 @@ pub struct Policy {
}
```
+### `reattach::RepeatLimiter`
+
+Rate-limits identical failure messages across every ...
+
+```rust
+pub struct RepeatLimiter { /* private fields */ }
+impl RepeatLimiter {
+ const fn new() -> Self;
+ fn note(&self, why: &str, now: Instant) -> Note;
+}
+```
+
### `RecoveredCreate`
`container:ghcr.io/x:1` -> `ghcr.io/x:1` (the local ...
@@ -1474,6 +1497,7 @@ impl Space {
fn provider(&self) -> Provider;
fn spacesd(&self) -> Result<&SpacesdClient>;
fn has_spacesd(&self) -> bool;
+ fn spacesd_unreachable_cause(&self) -> Option<String>;
fn capabilities(&self) -> &GetCapabilitiesResponse;
fn declared_services(&self) -> &BTreeMap<String, SpaceService>;
fn env_token(&self) -> Option<&str>;
@@ -2382,6 +2406,10 @@ pub const SNAP_DISTANCE: f64 = 0.25;
/// Render delay on the 20 Hz `Join` stream.
pub const STREAM_DELAY_MS: f64 = 100.0;
+// mod reattach
+/// How often the same re-attach failure is ...
+pub const REPEAT_LOG_EVERY: Duration = _;
+
// mod registry
/// File name of the 0600 credential store.
pub const CREDENTIALS_FILE: &str = "spaces-credentials.json";
diff --git a/examples/streaming/rust/Cargo.lock b/examples/streaming/rust/Cargo.lock
index c5f3e07eea..1c1b729608 100644
--- a/examples/streaming/rust/Cargo.lock
+++ b/examples/streaming/rust/Cargo.lock
@@ -1605,6 +1605,7 @@ dependencies = [
"cua-spaces-contract",
"cua-spacesd-client",
"cua-telemetry",
+ "cua-vmm",
"futures-util",
"hex",
"http",
diff --git a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
index b891382beb..ea1119eb9a 100644
--- a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
+++ b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
@@ -2549,6 +2549,7 @@ dependencies = [
"cua-spaces-contract",
"cua-spacesd-client",
"cua-telemetry",
+ "cua-vmm",
"futures-util",
"hex",
"http",
diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lock
index dd394fbc21..af57c34e1a 100644
--- a/libs/cua/Cargo.lock
+++ b/libs/cua/Cargo.lock
@@ -2898,6 +2898,7 @@ dependencies = [
"cua-spaces-contract",
"cua-spacesd-client",
"cua-telemetry",
+ "cua-vmm",
"futures-util",
"hex",
"http",
diff --git a/libs/cua/crates/cua-cli/src/doctor/host.rs b/libs/cua/crates/cua-cli/src/doctor/host.rs
index 9423de38ac..f9243cc607 100644
--- a/libs/cua/crates/cua-cli/src/doctor/host.rs
+++ b/libs/cua/crates/cua-cli/src/doctor/host.rs
@@ -256,13 +256,19 @@ pub async fn host_checks(cua: &Arc<Cua>, runtime_type: Option<&str>, arch: &str)
}
}
checks.extend(host_sharing_checks());
- checks.push(local_network_check(&report.checks).await);
+ checks.push(local_network_check(&report.checks, &vmm).await);
checks
}
/// `host.local_network`: on a Mac that runs macOS VMs (lume answers, or
-/// it provides Spaces), one bounded connect to a running VM.
-async fn local_network_check(runtime: &[cua_sdk::RuntimeCheck]) -> Check {
+/// it provides Spaces), the daemon's own probe from its runtime doctor
+/// report (it talks to the VMs, under its own app's grant), else one
+/// bounded connect from this process for a daemon that predates it.
+async fn local_network_check(
+ runtime: &[cua_sdk::RuntimeCheck],
+ report_json: &serde_json::Value,
+) -> Check {
+ use super::local_network as ln;
let os = std::env::consts::OS;
let lume = runtime
.iter()
@@ -274,11 +280,14 @@ async fn local_network_check(runtime: &[cua_sdk::RuntimeCheck]) -> Check {
);
let macos_vms = lume || provides;
let probe = if os == "macos" && macos_vms {
- Some(super::local_network::probe(&super::local_network::lume_base()).await)
+ match ln::from_daemon(report_json) {
+ Some(p) => Some(p),
+ None => Some(ln::from_this_process().await),
+ }
} else {
None
};
- super::local_network::check(os, macos_vms, probe)
+ ln::check(os, macos_vms, probe)
}
/// This machine's `cua host` readiness: a GUI (Aqua) session for the
diff --git a/libs/cua/crates/cua-cli/src/doctor/local_network.rs b/libs/cua/crates/cua-cli/src/doctor/local_network.rs
index 5a2aee11d6..8b64adb9b5 100644
--- a/libs/cua/crates/cua-cli/src/doctor/local_network.rs
+++ b/libs/cua/crates/cua-cli/src/doctor/local_network.rs
@@ -1,52 +1,68 @@
-//! `host.local_network`: whether this Mac can reach its own macOS VMs.
+//! `host.local_network`: whether the cua daemon can reach this Mac's own
+//! macOS VMs.
//!
//! A macOS Space is a VM on Apple's shared network (192.168.64.x); the cua
//! daemon talks to it there. macOS blocks that until Local Network access
-//! is on for the app responsible for the process, and then a connect fails
-//! at once with "No route to host" (`EHOSTUNREACH`), the probe the SDK and
-//! the app core read (`cua_vmm::probe::is_unreachable`). The check connects
-//! once to a running VM `lume serve` lists, with short time limits, from
-//! this process (the terminal app that ran `cua doctor`). It is never
-//! required: a blocked VM network warns; no VM to try, or not a Mac, skips
-//! with the reason.
-
-use std::time::Duration;
+//! is on for the app macOS holds responsible for the daemon (the Spaces
+//! app for the daemon it starts), and then a connect fails at once with
+//! "No route to host" (`EHOSTUNREACH`). The grant is per app, so a connect
+//! from this CLI would test the terminal's grant, not the daemon's: the
+//! daemon probes (`cua_vmm::local_network::report`, in its runtime doctor
+//! report) and names the app. A daemon that predates that report is tested
+//! from this process instead, and the check says so. It is never required:
+//! a blocked VM network warns; no VM to try, or not a Mac, skips with the
+//! reason.
use cua_spacesd_client::diagnose::{Check, Severity, Status};
+pub use cua_vmm::local_network::{Probe, ResponsibleApp};
const ID: &str = "host.local_network";
-/// Listing the VMs (`lume serve` is local).
-const LIST_TIMEOUT: Duration = Duration::from_secs(2);
-/// One connect to the VM. A blocked network fails at once; a VM that is
-/// there answers (accepts or refuses) well within this.
-const CONNECT_TIMEOUT: Duration = Duration::from_millis(1500);
-/// Any port works: a refusal comes back over the same network.
-const PROBE_PORT: u16 = 22;
/// Where the setting is, as the user reads it in System Settings.
pub const SETTINGS_PATH: &str = "System Settings > Privacy & Security > Local Network";
const SETTINGS_URL: &str =
"x-apple.systempreferences:com.apple.preference.security?Privacy_LocalNetwork";
-/// What the probe found.
+/// Who probed.
#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum Probe {
- /// `lume serve` did not list its VMs in time (or answered an error).
- NoList(String),
- /// No macOS VM is running with an address.
- NoRunningVm,
- /// The VM answered (accepted or refused the connection).
- Reached { vm: String, ip: String },
- /// No route to the VM: Local Network access is off for this app.
- Blocked { vm: String, ip: String },
- /// No answer in time, or another error: inconclusive.
- Unclear { vm: String, ip: String, why: String },
+pub enum Prober {
+ /// The cua daemon (the process that talks to the VMs), as the app
+ /// macOS holds responsible for it.
+ Daemon(Option<ResponsibleApp>),
+ /// This CLI process: the daemon predates the daemon-side probe.
+ ThisProcess(Option<ResponsibleApp>),
+}
+
+impl Prober {
+ fn app(&self) -> Option<&ResponsibleApp> {
+ match self {
+ Self::Daemon(a) | Self::ThisProcess(a) => a.as_ref(),
+ }
+ }
+
+ /// "the cua daemon" / "this terminal (Terminal)".
+ fn who(&self) -> String {
+ match self {
+ Self::Daemon(_) => "the cua daemon".into(),
+ Self::ThisProcess(Some(a)) => format!("this process ({})", a.name),
+ Self::ThisProcess(None) => "this process".into(),
+ }
+ }
+
+ /// The app to allow, as the user finds it in System Settings.
+ fn app_words(&self) -> String {
+ match (self, self.app()) {
+ (_, Some(a)) if a.bundle => format!("{} ({})", a.name, a.path.display()),
+ (Self::Daemon(_), _) => "the app that started the cua daemon".into(),
+ (Self::ThisProcess(_), _) => "the app you ran cua from (your terminal app)".into(),
+ }
+ }
}
/// The check for what this machine is and what the probe found (pure).
/// `macos_vms`: this Mac runs local macOS VMs (lume answers, or it
/// provides Spaces).
-pub fn check(os: &str, macos_vms: bool, probe: Option<Probe>) -> Check {
+pub fn check(os: &str, macos_vms: bool, probe: Option<(Probe, Prober)>) -> Check {
let skip = |message: String, reason: &str| {
info(Check::new(ID, Status::Skip, message).skip_reason(reason))
};
@@ -63,42 +79,78 @@ pub fn check(os: &str, macos_vms: bool, probe: Option<Probe>) -> Check {
"not_applicable",
);
}
+ let generic_allow = format!(
+ "open {SETTINGS_PATH} and turn on Cua Spaces (or cua-spacesd), which starts the cua \
+ daemon, and the app you ran cua from; then run `cua doctor` again"
+ );
+ let Some((probe, by)) = probe else {
+ return skip(
+ "no macOS VM is running, so Local Network access can't be tested; start a macOS Space and run `cua doctor` again".into(),
+ "no_running_vm",
+ )
+ .fix(format!("if macOS Spaces fail with \"No route to host\": {generic_allow}"));
+ };
+ let app = by.app_words();
let allow = format!(
- "open {SETTINGS_PATH} and turn on the app you ran cua from (Terminal, or your terminal app), \
- and Cua Spaces or cua-spacesd, which start the cua daemon; then run `cua doctor` again"
+ "open {SETTINGS_PATH} and turn on {app}; if it isn't listed, quit and reopen it on \
+ this Mac (macOS asks again); then run `cua doctor` again"
);
- match probe {
- None | Some(Probe::NoRunningVm) => skip(
+ let mut check = match probe {
+ Probe::NoRunningVm => skip(
"no macOS VM is running, so Local Network access can't be tested; start a macOS Space and run `cua doctor` again".into(),
"no_running_vm",
)
.fix(format!("if macOS Spaces fail with \"No route to host\": {allow}")),
- Some(Probe::NoList(why)) => skip(
+ Probe::NoList { why } => skip(
format!("couldn't list this Mac's VMs ({why})"),
"no_vm_list",
),
- Some(Probe::Reached { vm, ip }) => info(Check::new(
+ Probe::Reached { vm, ip } => info(Check::new(
ID,
Status::Pass,
- format!("reached the macOS VM {vm} at {ip}: Local Network access is on"),
+ match &by {
+ Prober::Daemon(_) => format!(
+ "the cua daemon reached the macOS VM {vm} at {ip}: Local Network access is on for {app}"
+ ),
+ Prober::ThisProcess(_) => format!(
+ "{} reached the macOS VM {vm} at {ip}; the cua daemon is too old to check its own access, \
+ so this does not show that the daemon has Local Network access",
+ by.who()
+ ),
+ },
)),
- Some(Probe::Blocked { vm, ip }) => info(
+ Probe::Blocked { vm, ip } => info(
Check::new(
ID,
Status::Warn,
format!(
- "can't reach the macOS VM {vm} at {ip} (No route to host): Local Network access is off. \
- macOS Spaces on this Mac fail until it is on"
+ "{} can't reach the macOS VM {vm} at {ip} (No route to host): Local Network access is off \
+ for {app}. macOS Spaces on this Mac fail until it is on",
+ by.who()
),
)
.fix(format!("{allow} ({SETTINGS_URL})")),
),
- Some(Probe::Unclear { vm, ip, why }) => skip(
+ Probe::Unclear { vm, ip, why } => skip(
format!("couldn't tell whether the macOS VM {vm} at {ip} is reachable ({why})"),
"inconclusive",
)
.fix(format!("if macOS Spaces fail with \"No route to host\": {allow}")),
+ };
+ check.facts.insert(
+ "probed_by".into(),
+ match by {
+ Prober::Daemon(_) => "daemon".into(),
+ Prober::ThisProcess(_) => "cli".into(),
+ },
+ );
+ if let Some(a) = by.app() {
+ check.facts.insert("responsible_app".into(), a.name.clone());
+ check
+ .facts
+ .insert("responsible_app_path".into(), a.path.display().to_string());
}
+ check
}
fn info(mut c: Check) -> Check {
@@ -106,72 +158,62 @@ fn info(mut c: Check) -> Check {
c
}
-/// What one connect says about the network (pure).
-pub fn classify(vm: &str, ip: &str, result: Result<std::io::Result<()>, ()>) -> Probe {
- let (vm, ip) = (vm.to_owned(), ip.to_owned());
- match result {
- Ok(Ok(())) => Probe::Reached { vm, ip },
- Ok(Err(e)) if e.kind() == std::io::ErrorKind::ConnectionRefused => {
- Probe::Reached { vm, ip }
- }
- Ok(Err(e)) if cua_vmm::probe::is_unreachable(&e) => Probe::Blocked { vm, ip },
- Ok(Err(e)) => Probe::Unclear {
- vm,
- ip,
- why: e.to_string(),
- },
- Err(()) => Probe::Unclear {
- vm,
- ip,
- why: format!("no answer in {} ms", CONNECT_TIMEOUT.as_millis()),
- },
- }
+/// The daemon's own probe from its runtime doctor report (`report_json`'s
+/// `local_network`), when it has one.
+pub fn from_daemon(report_json: &serde_json::Value) -> Option<(Probe, Prober)> {
+ let r: cua_vmm::local_network::Report =
+ serde_json::from_value(report_json.get("local_network")?.clone()).ok()?;
+ Some((r.probe, Prober::Daemon(r.app)))
}
-/// Lists the VMs `lume serve` runs and connects once to the first running
-/// one with an address. Bounded: about 3.5 s at most.
-pub async fn probe(lume_base: &str) -> Probe {
- let client = cua_vmm::lume::LumeClient::new(lume_base);
- let vms = match tokio::time::timeout(LIST_TIMEOUT, client.list()).await {
- Ok(Ok(vms)) => vms,
- Ok(Err(e)) => return Probe::NoList(e.to_string()),
- Err(_) => return Probe::NoList(format!("no answer in {} s", LIST_TIMEOUT.as_secs())),
- };
- let Some((vm, ip)) = vms.iter().find_map(|v| {
- (v.status == "running" && v.os.eq_ignore_ascii_case("macos"))
- .then(|| v.ip().map(|ip| (v.name.clone(), ip.to_owned())))
- .flatten()
- }) else {
- return Probe::NoRunningVm;
- };
- let addr = format!("{ip}:{PROBE_PORT}");
- let result = tokio::time::timeout(CONNECT_TIMEOUT, tokio::net::TcpStream::connect(&addr))
- .await
- .map(|r| r.map(drop))
- .map_err(drop);
- classify(&vm, &ip, result)
+/// Probes from this process (a daemon that predates its own probe).
+pub async fn from_this_process() -> (Probe, Prober) {
+ let probe = cua_vmm::local_network::probe(&lume_base()).await;
+ (
+ probe,
+ Prober::ThisProcess(ResponsibleApp::of_this_process()),
+ )
}
/// The `lume serve` the runtime doctor talks to.
pub fn lume_base() -> String {
- std::env::var("LUME_API").unwrap_or_else(|_| "http://127.0.0.1:7777".into())
+ cua_vmm::local_network::lume_base()
}
#[cfg(test)]
mod tests {
use super::*;
- use std::io::{Error, ErrorKind};
+ use std::path::PathBuf;
- fn ok_vm() -> Option<Probe> {
- Some(Probe::Reached {
+ fn app(name: &str) -> ResponsibleApp {
+ ResponsibleApp {
+ name: name.into(),
+ path: PathBuf::from(format!("/Users/x/apps/{name}.app")),
+ bundle: true,
+ }
+ }
+
+ fn daemon(probe: Probe) -> Option<(Probe, Prober)> {
+ Some((probe, Prober::Daemon(Some(app("Cua1807 Main")))))
+ }
+
+ fn blocked() -> Probe {
+ Probe::Blocked {
vm: "m1".into(),
ip: "192.168.64.5".into(),
- })
+ }
+ }
+
+ fn reached() -> Probe {
+ Probe::Reached {
+ vm: "m1".into(),
+ ip: "192.168.64.5".into(),
+ }
}
#[test]
fn not_a_mac_or_no_vms_skips_with_the_reason() {
- let c = check("linux", true, ok_vm());
+ let c = check("linux", true, daemon(reached()));
assert_eq!(c.status, Status::Skip);
assert_eq!(
c.facts.get("skip_reason").map(String::as_str),
@@ -184,86 +226,131 @@ mod tests {
assert_eq!(c.severity, Severity::Info);
}
+ /// CUA-1807: the daemon is blocked while the terminal is allowed. The
+ /// daemon's probe decides, and names the app to turn on.
#[test]
- fn a_blocked_vm_network_warns_and_says_where_to_turn_it_on() {
- let c = check(
- "macos",
- true,
- Some(Probe::Blocked {
- vm: "m1".into(),
- ip: "192.168.64.5".into(),
- }),
- );
+ fn a_blocked_daemon_warns_and_names_its_app() {
+ let c = check("macos", true, daemon(blocked()));
assert_eq!(c.status, Status::Warn);
assert_eq!(c.severity, Severity::Info, "never required");
+ assert!(
+ c.message.contains("the cua daemon can't reach"),
+ "{}",
+ c.message
+ );
assert!(c.message.contains("No route to host"), "{}", c.message);
assert!(
- c.remediation
- .contains("System Settings > Privacy & Security > Local Network"),
+ c.message
+ .contains("Cua1807 Main (/Users/x/apps/Cua1807 Main.app)"),
+ "{}",
+ c.message
+ );
+ assert!(
+ c.remediation.contains(
+ "System Settings > Privacy & Security > Local Network and turn on Cua1807 Main"
+ ),
"{}",
c.remediation
);
- assert!(c.remediation.contains("turn on"), "{}", c.remediation);
assert!(
c.remediation.contains("Privacy_LocalNetwork"),
"{}",
c.remediation
);
+ assert_eq!(c.facts["probed_by"], "daemon");
+ assert_eq!(c.facts["responsible_app"], "Cua1807 Main");
}
#[test]
- fn a_reached_vm_passes_and_no_vm_skips_with_the_fix() {
- let c = check("macos", true, ok_vm());
+ fn a_reached_vm_passes_and_says_for_which_app() {
+ let c = check("macos", true, daemon(reached()));
assert_eq!(c.status, Status::Pass);
- assert!(c.message.contains("192.168.64.5"));
- let c = check("macos", true, Some(Probe::NoRunningVm));
+ assert!(
+ c.message.contains("the cua daemon reached"),
+ "{}",
+ c.message
+ );
+ assert!(c.message.contains("on for Cua1807 Main"), "{}", c.message);
+ let c = check("macos", true, daemon(Probe::NoRunningVm));
assert_eq!(c.status, Status::Skip);
assert_eq!(
c.facts.get("skip_reason").map(String::as_str),
Some("no_running_vm")
);
assert!(c.remediation.contains("Local Network"), "{}", c.remediation);
- let c = check("macos", true, Some(Probe::NoList("not reachable".into())));
+ let c = check("macos", true, daemon(Probe::NoList { why: "x".into() }));
assert_eq!(c.status, Status::Skip);
+ assert!(
+ check("macos", true, None)
+ .remediation
+ .contains("Cua Spaces")
+ );
}
+ /// An older daemon: the CLI's own pass must not read as the daemon's.
#[test]
- fn connect_results_classify() {
- let unreachable = Error::from(ErrorKind::HostUnreachable);
- assert!(matches!(
- classify("m", "1.2.3.4", Ok(Err(unreachable))),
- Probe::Blocked { .. }
- ));
- let net = Error::from(ErrorKind::NetworkUnreachable);
- assert!(matches!(
- classify("m", "1.2.3.4", Ok(Err(net))),
- Probe::Blocked { .. }
- ));
- // A refusal comes back over the network: reachable.
- let refused = Error::from(ErrorKind::ConnectionRefused);
- assert!(matches!(
- classify("m", "1.2.3.4", Ok(Err(refused))),
- Probe::Reached { .. }
- ));
- assert!(matches!(
- classify("m", "1.2.3.4", Ok(Ok(()))),
- Probe::Reached { .. }
- ));
- assert!(matches!(
- classify("m", "1.2.3.4", Err(())),
- Probe::Unclear { .. }
- ));
- // An Unclear probe skips (never a warning on a guess).
- assert_eq!(
- check("macos", true, Some(classify("m", "1.2.3.4", Err(())))).status,
- Status::Skip
+ fn a_pass_from_this_process_says_the_daemon_was_not_checked() {
+ let by = Prober::ThisProcess(Some(app("Terminal")));
+ let c = check("macos", true, Some((reached(), by.clone())));
+ assert_eq!(c.status, Status::Pass);
+ assert!(
+ c.message.contains("this process (Terminal)"),
+ "{}",
+ c.message
+ );
+ assert!(
+ c.message.contains("does not show that the daemon"),
+ "{}",
+ c.message
+ );
+ assert_eq!(c.facts["probed_by"], "cli");
+ let c = check("macos", true, Some((blocked(), by)));
+ assert_eq!(c.status, Status::Warn);
+ assert!(
+ c.remediation.contains("turn on Terminal"),
+ "{}",
+ c.remediation
);
}
+ #[test]
+ fn a_bare_daemon_names_the_app_that_started_it() {
+ let bare = ResponsibleApp {
+ name: "cua".into(),
+ path: PathBuf::from("/usr/local/bin/cua"),
+ bundle: false,
+ };
+ let c = check("macos", true, Some((blocked(), Prober::Daemon(Some(bare)))));
+ assert!(
+ c.remediation
+ .contains("turn on the app that started the cua daemon"),
+ "{}",
+ c.remediation
+ );
+ }
+
+ #[test]
+ fn the_daemon_report_is_read_from_its_json() {
+ let json = serde_json::json!({
+ "backends": [],
+ "local_network": {
+ "probe": {"result": "blocked", "vm": "m1", "ip": "192.168.64.5"},
+ "app": {"name": "Cua Spaces", "path": "/Applications/Cua Spaces.app", "bundle": true},
+ "pid": 42
+ }
+ });
+ let (probe, by) = from_daemon(&json).unwrap();
+ assert_eq!(probe, blocked());
+ assert!(matches!(by, Prober::Daemon(Some(a)) if a.name == "Cua Spaces"));
+ // An older daemon has none.
+ assert!(from_daemon(&serde_json::json!({"backends": []})).is_none());
+ }
+
/// A fake `lume serve` listing one running macOS VM at 127.0.0.1: the
/// probe lists it and reaches it (a refusal on port 22 counts).
#[tokio::test]
async fn probe_lists_lume_vms_and_connects_once_within_its_limits() {
+ use std::time::Duration;
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
@@ -282,7 +369,7 @@ mod tests {
}
});
let started = std::time::Instant::now();
- let p = probe(&base).await;
+ let p = cua_vmm::local_network::probe(&base).await;
assert!(started.elapsed() < Duration::from_secs(4));
match p {
Probe::Reached { vm, ip } | Probe::Unclear { vm, ip, .. } => {
@@ -291,7 +378,7 @@ mod tests {
other => panic!("{other:?}"),
}
// Nothing listening: the list fails fast and the check skips.
- let p = probe("http://127.0.0.1:9").await;
- assert!(matches!(p, Probe::NoList(_)), "{p:?}");
+ let p = cua_vmm::local_network::probe("http://127.0.0.1:9").await;
+ assert!(matches!(p, Probe::NoList { .. }), "{p:?}");
}
}
diff --git a/libs/cua/crates/cua-daemon/src/local.rs b/libs/cua/crates/cua-daemon/src/local.rs
index 822c2f392b..b8bf326a6d 100644
--- a/libs/cua/crates/cua-daemon/src/local.rs
+++ b/libs/cua/crates/cua-daemon/src/local.rs
@@ -1224,6 +1224,29 @@ pub async fn doctor_report() -> DoctorReport {
auto::doctor().await
}
+/// `RuntimeService.Doctor`'s answer: the runtime report, plus on macOS
+/// Local Network access as this process has it and which app macOS holds
+/// responsible for it (`local_network`). This process is the one that
+/// talks to the VMs (the daemon, or the SDK embedding it); a CLI's own
+/// connect would test the terminal's grant instead (CUA-1807).
+pub async fn doctor_response() -> cua_proto::daemon::v1::DoctorResponse {
+ let report = doctor_report().await;
+ let mut json = serde_json::to_value(&report).unwrap_or_default();
+ if cfg!(target_os = "macos")
+ && let Some(map) = json.as_object_mut()
+ {
+ let ln = cua_vmm::local_network::report(&cua_vmm::local_network::lume_base()).await;
+ map.insert(
+ "local_network".into(),
+ serde_json::to_value(ln).unwrap_or_default(),
+ );
+ }
+ cua_proto::daemon::v1::DoctorResponse {
+ checks: doctor_checks(&report),
+ report_json: json.to_string(),
+ }
+}
+
/// The report as `cua.daemon.v1` checks (one per backend).
pub fn doctor_checks(r: &DoctorReport) -> Vec<cua_proto::daemon::v1::RuntimeCheck> {
use cua_proto::daemon::v1::{CheckStatus, RuntimeCheck};
diff --git a/libs/cua/crates/cua-daemon/src/server.rs b/libs/cua/crates/cua-daemon/src/server.rs
index 70ac9dfbf3..075df42781 100644
--- a/libs/cua/crates/cua-daemon/src/server.rs
+++ b/libs/cua/crates/cua-daemon/src/server.rs
@@ -1128,11 +1128,7 @@ impl SandboxService for Svc {
#[tonic::async_trait]
impl RuntimeService for Svc {
async fn doctor(&self, _: tonic::Request<pb::DoctorRequest>) -> R<pb::DoctorResponse> {
- let report = crate::local::doctor_report().await;
- ok(pb::DoctorResponse {
- checks: crate::local::doctor_checks(&report),
- report_json: serde_json::to_string(&report).unwrap_or_default(),
- })
+ ok(crate::local::doctor_response().await)
}
async fn setup(&self, req: tonic::Request<pb::SetupRequest>) -> R<pb::SetupResponse> {
diff --git a/libs/cua/crates/cua-sdk/src/native/local.rs b/libs/cua/crates/cua-sdk/src/native/local.rs
index edf169f932..7774ef72e5 100644
--- a/libs/cua/crates/cua-sdk/src/native/local.rs
+++ b/libs/cua/crates/cua-sdk/src/native/local.rs
@@ -156,13 +156,7 @@ impl Local {
let backend = self.backend.clone();
run(async move {
let r = match &backend {
- Backend::Embedded(_) => {
- let report = cua_daemon::local::doctor_report().await;
- cua_proto::daemon::v1::DoctorResponse {
- checks: cua_daemon::local::doctor_checks(&report),
- report_json: serde_json::to_string(&report)?,
- }
- }
+ Backend::Embedded(_) => cua_daemon::local::doctor_response().await,
Backend::Daemon(d) => d.doctor().await?,
};
Ok(DoctorReport {
diff --git a/libs/cua/crates/cua-spaces-app-core/src/spaces/creating.rs b/libs/cua/crates/cua-spaces-app-core/src/spaces/creating.rs
index 792de24a2a..00e104ffdc 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/spaces/creating.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/spaces/creating.rs
@@ -1215,13 +1215,44 @@ pub fn reduce(state: &CreatesState, action: &CreateAction) -> CreatesState {
/// The inline line a failed power action shows: "Could not turn it on:
/// <why>".
+///
+/// The known causes ([`failure_cause`], as for a failed create) read in
+/// plain words: a Local Network block names the app to turn on, instead of
+/// the SDK's raw error (CUA-1807).
pub fn power_failed_text(on: bool, error: &str) -> String {
let what = if on { "turn it on" } else { "turn it off" };
if error.trim().is_empty() {
- format!("Could not {what}")
- } else {
- format!("Could not {what}: {}", crate::errors::plain_error(error))
+ return format!("Could not {what}");
}
+ let plain = crate::errors::plain_error(error);
+ let why = match failure_cause(error, None, false) {
+ Some(FailureCause::LocalNetwork) => {
+ let app = local_network_app(&plain).unwrap_or("Cua Spaces (or cua-spacesd)");
+ format!(
+ "Cua can't reach the Space's VM because it doesn't have Local Network access on \
+ the Mac running it. On that Mac, open System Settings > Privacy & Security > \
+ Local Network, turn on {app}, then try again."
+ )
+ }
+ Some(FailureCause::Disk) => "there isn't enough disk space on the Mac running it. Free \
+ up space there (or run `cua cache prune` in Terminal), then try again."
+ .into(),
+ Some(FailureCause::VmLimit) => "the Mac running it is already running two macOS VMs, \
+ the most Apple's macOS license allows at once. Stop one, then try again."
+ .into(),
+ _ => plain,
+ };
+ format!("Could not {what}: {why}")
+}
+
+/// The app the SDK's Local Network error names ("Local Network access is
+/// not available: <App> (<path>) cannot reach ..."), when it names one.
+fn local_network_app(plain: &str) -> Option<&str> {
+ const LEAD: &str = "Local Network access is not available: ";
+ let rest = &plain[plain.find(LEAD)? + LEAD.len()..];
+ let (name, _) = rest.split_once(" (")?;
+ let name = name.trim();
+ (!name.is_empty() && name != "cua" && !name.contains("cannot reach")).then_some(name)
}
/// Drops finished creates whose Space the registry now lists, and finished
@@ -1432,6 +1463,41 @@ pub fn compose(registry: &[Space], state: &CreatesState) -> Vec<Space> {
mod tests {
use super::*;
+ /// CUA-1807: Turn on showed the SDK's raw Local Network error.
+ #[test]
+ fn a_failed_turn_on_says_the_known_cause_in_plain_words() {
+ let raw = "local runtime: Local Network access is not available: Cua Spaces \
+ (/Applications/Cua Spaces.app) cannot reach the VM at 192.168.64.191:3211 \
+ (No route to host (os error 65)). macOS blocks Cua Spaces's local network \
+ connections until they are allowed: ...";
+ let t = power_failed_text(true, raw);
+ assert!(
+ t.starts_with("Could not turn it on: Cua can't reach"),
+ "{t}"
+ );
+ assert!(t.contains("turn on Cua Spaces, then try again"), "{t}");
+ assert!(!t.contains("os error"), "{t}");
+ // An older SDK's bare EHOSTUNREACH to a vmnet address.
+ let t = power_failed_text(
+ true,
+ "connect 192.168.64.5:3211: No route to host (os error 65)",
+ );
+ assert!(t.contains("turn on Cua Spaces (or cua-spacesd)"), "{t}");
+ // A bare binary is not an app to turn on.
+ let t = power_failed_text(
+ true,
+ "Local Network access is not available: cua cannot reach the VM at 192.168.64.5:3211",
+ );
+ assert!(t.contains("turn on Cua Spaces (or cua-spacesd)"), "{t}");
+ // Unknown causes stay as they were.
+ assert_eq!(
+ power_failed_text(false, "Docker is not running"),
+ "Could not turn it off: Docker is not running"
+ );
+ assert_eq!(power_failed_text(true, " "), "Could not turn it on");
+ assert!(power_failed_text(true, "No space left on device").contains("disk space"));
+ }
+
fn start(id: &str, name: &str, os: SpaceOs) -> CreateAction {
CreateAction::Start {
id: id.into(),
diff --git a/libs/cua/crates/cua-spaces-ext/src/drive_runtime.rs b/libs/cua/crates/cua-spaces-ext/src/drive_runtime.rs
index 0a0e0dbbd7..d73b9e0420 100644
--- a/libs/cua/crates/cua-spaces-ext/src/drive_runtime.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/drive_runtime.rs
@@ -270,9 +270,16 @@ impl SpacesDrive for Spaces {
// capabilities, not a guest without the volume. Connect
// afresh next time, and fail so the supervisor retries.
let _ = self.forget_connection(&id).await;
- let why = "its cua-spacesd is not answering yet (the Space is still starting); \
- Cua Volume mounts once it does";
- ext.runtime.note_unavailable(&id, Some(why.into()));
+ // No route to the VM is not "still starting": macOS Local
+ // Network privacy blocks this process, and waiting does not
+ // help until the named app is allowed (CUA-1807).
+ let why = match s.spacesd_unreachable_cause() {
+ Some(cause) => format!("its cua-spacesd can't be reached: {cause}"),
+ None => "its cua-spacesd is not answering yet (the Space is still starting); \
+ Cua Volume mounts once it does"
+ .into(),
+ };
+ ext.runtime.note_unavailable(&id, Some(why.clone()));
return Err(Error::extension("precondition_failed", why));
}
let why = s
diff --git a/libs/cua/crates/cua-spaces/Cargo.toml b/libs/cua/crates/cua-spaces/Cargo.toml
index 160df5fd67..dcaac664ae 100644
--- a/libs/cua/crates/cua-spaces/Cargo.toml
+++ b/libs/cua/crates/cua-spaces/Cargo.toml
@@ -62,6 +62,7 @@ cua-auth = { workspace = true, optional = true }
cua-fleet.workspace = true
cua-image.workspace = true
cua-sandbox-core.workspace = true
+cua-vmm.workspace = true
# The cua-relay machine directory (`space://relay/<id>`) and AccountTokens.
cua-host.workspace = true
# `relay:` Spaces over the WireGuard®-based mesh.
diff --git a/libs/cua/crates/cua-spaces/src/reattach.rs b/libs/cua/crates/cua-spaces/src/reattach.rs
index 663ac3c048..2ad888306a 100644
--- a/libs/cua/crates/cua-spaces/src/reattach.rs
+++ b/libs/cua/crates/cua-spaces/src/reattach.rs
@@ -82,6 +82,62 @@ impl Backoff {
}
}
+/// How often the same re-attach failure is logged at `warn`. A Space that
+/// cannot be reached (macOS Local Network privacy, say) fails the same way
+/// every few seconds, from every supervisor that watches it; once per
+/// cause in this window keeps the log readable and the cause visible.
+pub const REPEAT_LOG_EVERY: Duration = Duration::from_secs(10 * 60);
+
+/// Whether to log a failure at `warn`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Note {
+ /// Log it; `repeated` identical failures were kept quiet since the
+ /// last time.
+ Log { repeated: u32 },
+ /// Logged within [`REPEAT_LOG_EVERY`]: debug only.
+ Quiet,
+}
+
+/// Rate-limits identical failure messages across every supervisor in this
+/// process. Bounded: at most [`RepeatLimiter::MAX`] distinct messages are
+/// remembered; the oldest go first.
+#[derive(Debug, Default)]
+pub struct RepeatLimiter {
+ seen: std::sync::Mutex<Vec<(String, std::time::Instant, u32)>>,
+}
+
+impl RepeatLimiter {
+ const MAX: usize = 64;
+
+ pub const fn new() -> Self {
+ Self {
+ seen: std::sync::Mutex::new(Vec::new()),
+ }
+ }
+
+ /// Notes a failure `why` at `now`.
+ pub fn note(&self, why: &str, now: std::time::Instant) -> Note {
+ let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(entry) = seen.iter_mut().find(|(m, _, _)| m == why) {
+ if now.saturating_duration_since(entry.1) < REPEAT_LOG_EVERY {
+ entry.2 = entry.2.saturating_add(1);
+ return Note::Quiet;
+ }
+ let repeated = entry.2;
+ entry.1 = now;
+ entry.2 = 0;
+ return Note::Log { repeated };
+ }
+ if seen.len() >= Self::MAX {
+ seen.remove(0);
+ }
+ seen.push((why.to_string(), now, 0));
+ Note::Log { repeated: 0 }
+ }
+}
+
+static FAILURES: RepeatLimiter = RepeatLimiter::new();
+
/// Checks a link every `policy.poll` and calls `reattach` while it is
/// [`Health::Down`], waiting out an exponential backoff after each failure.
/// The first check is immediate, so a link that was never made is made at
@@ -113,7 +169,20 @@ where
Ok(Attempt::Unsupported) => return,
Err(why) => {
let wait = backoff.fail();
- tracing::warn!(error = %why, retry_in = ?wait, "re-attach failed");
+ match FAILURES.note(&why, std::time::Instant::now()) {
+ Note::Log { repeated } if repeated > 0 => tracing::warn!(
+ error = %why,
+ retry_in = ?wait,
+ repeated,
+ "re-attach still failing"
+ ),
+ Note::Log { .. } => {
+ tracing::warn!(error = %why, retry_in = ?wait, "re-attach failed")
+ }
+ Note::Quiet => {
+ tracing::debug!(error = %why, retry_in = ?wait, "re-attach failed")
+ }
+ }
retry_at = Some(tokio::time::Instant::now() + wait);
}
}
@@ -138,6 +207,39 @@ mod tests {
}
}
+ /// CUA-1807: a blocked Space failed the same way 213 times in the log.
+ #[test]
+ fn the_same_failure_is_logged_once_per_window_and_a_new_one_at_once() {
+ let l = RepeatLimiter::new();
+ let t0 = std::time::Instant::now();
+ let blocked = "Cua Volume not mounted: Local Network access is not available";
+ assert_eq!(l.note(blocked, t0), Note::Log { repeated: 0 });
+ for i in 1..=200 {
+ assert_eq!(
+ l.note(blocked, t0 + Duration::from_secs(2 * i)),
+ Note::Quiet
+ );
+ }
+ // Another cause is news.
+ assert_eq!(
+ l.note(
+ "Cua Volume not mounted: still starting",
+ t0 + Duration::from_secs(5)
+ ),
+ Note::Log { repeated: 0 }
+ );
+ // After the window, once more, with how many were kept quiet.
+ assert_eq!(
+ l.note(blocked, t0 + REPEAT_LOG_EVERY + Duration::from_secs(1)),
+ Note::Log { repeated: 200 }
+ );
+ // Bounded.
+ for i in 0..(RepeatLimiter::MAX * 2) {
+ l.note(&format!("m{i}"), t0);
+ }
+ assert!(l.seen.lock().unwrap().len() <= RepeatLimiter::MAX);
+ }
+
#[test]
fn backoff_doubles_to_the_cap_and_resets() {
let mut b = Backoff::new(&policy());
diff --git a/libs/cua/crates/cua-spaces/src/space.rs b/libs/cua/crates/cua-spaces/src/space.rs
index e60781af5e..821aa8a134 100644
--- a/libs/cua/crates/cua-spaces/src/space.rs
+++ b/libs/cua/crates/cua-spaces/src/space.rs
@@ -159,6 +159,9 @@ pub(crate) struct SpaceInner {
pub(crate) image: std::sync::OnceLock<(String, String)>,
/// `(kind, arch)` from the local sandbox's record, when it has one.
pub(crate) platform: std::sync::OnceLock<(String, String)>,
+ /// Why no cua-spacesd answered when this connected (`endpoint`,
+ /// `reason`), for a Space connected without one.
+ pub(crate) spacesd_unavailable: std::sync::OnceLock<(String, String)>,
}
/// A connected Space. Cheap to clone; every clone shares one spacesd
@@ -209,6 +212,7 @@ impl Space {
mcp: Default::default(),
image: Default::default(),
platform: Default::default(),
+ spacesd_unavailable: Default::default(),
}),
}
}
@@ -355,6 +359,22 @@ impl Space {
self.inner.env.is_some()
}
+ pub(crate) fn set_spacesd_unavailable(&self, endpoint: String, reason: String) {
+ let _ = self.inner.spacesd_unavailable.set((endpoint, reason));
+ }
+
+ /// When no cua-spacesd answered because this host has no route to a
+ /// local VM (on macOS: Local Network privacy blocks this process), the
+ /// cause in words, naming the app to allow. `None` for any other reason
+ /// (still starting, nothing listening) or a Space that is not local.
+ pub fn spacesd_unreachable_cause(&self) -> Option<String> {
+ if !matches!(self.inner.id, SpaceId::Local { .. }) {
+ return None;
+ }
+ let (endpoint, reason) = self.inner.spacesd_unavailable.get()?;
+ unreachable_cause(endpoint, reason)
+ }
+
fn no_spacesd(&self) -> Error {
Error::CapabilityMissing {
space: self.inner.id.to_string(),
@@ -699,3 +719,38 @@ mod tests {
);
}
}
+
+/// [`Space::spacesd_unreachable_cause`] from the endpoint and the
+/// connect's reason (pure).
+pub(crate) fn unreachable_cause(endpoint: &str, reason: &str) -> Option<String> {
+ let l = reason.to_ascii_lowercase();
+ let cause = if l.contains("no route to host") {
+ "No route to host"
+ } else if l.contains("network is unreachable") {
+ "Network is unreachable"
+ } else {
+ return None;
+ };
+ let addr = endpoint
+ .trim_start_matches("http://")
+ .trim_start_matches("https://")
+ .trim_end_matches('/');
+ Some(cua_vmm::probe::unreachable_error(addr, &cause).to_string())
+}
+
+#[cfg(test)]
+mod unreachable_tests {
+ use super::unreachable_cause;
+
+ #[test]
+ fn no_route_to_a_local_vm_names_local_network_access() {
+ let reason = "nothing answered at http://192.168.64.191:3211/ (it may still be starting; \
+ retry in a few seconds): grpc: transport error (No route to host (os error 65))";
+ let c = unreachable_cause("http://192.168.64.191:3211/", reason).unwrap();
+ assert!(c.contains("192.168.64.191:3211"), "{c}");
+ if cfg!(target_os = "macos") {
+ assert!(c.contains("Local Network access is not available"), "{c}");
+ }
+ assert!(unreachable_cause("http://x:1", "nothing answered: connection refused").is_none());
+ }
+}
diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rs
index 9a9b5a9886..ab41f6dd6e 100644
--- a/libs/cua/crates/cua-spaces/src/spaces.rs
+++ b/libs/cua/crates/cua-spaces/src/spaces.rs
@@ -1651,11 +1651,12 @@ impl Spaces {
}
}
};
+ let mut unavailable: Option<(String, String)> = None;
let env = match options {
None => None,
Some(options) => match SpacesdClient::connect(options.probe_timeout(probe)).await {
Ok(env) => Some(env),
- Err(cua_spacesd_client::Error::SpacesdNotAvailable { reason, .. }) => {
+ Err(cua_spacesd_client::Error::SpacesdNotAvailable { endpoint, reason }) => {
let generic_ok = matches!(id, SpaceId::Local { .. } | SpaceId::Cloud { .. })
|| !services.is_empty();
if let SpaceId::Relay { machine_id } = &id
@@ -1683,6 +1684,7 @@ impl Spaces {
});
}
tracing::debug!(space = %id, %reason, "no cua-spacesd; a Space of declared services");
+ unavailable = Some((endpoint, reason));
None
}
Err(e) => return Err(e.into()),
@@ -1710,6 +1712,9 @@ impl Spaces {
if let Some((kind, arch)) = platform {
space.set_platform(kind, arch);
}
+ if let Some((endpoint, reason)) = unavailable {
+ space.set_spacesd_unavailable(endpoint, reason);
+ }
Ok(space)
}
diff --git a/libs/cua/crates/cua-vmm/src/lib.rs b/libs/cua/crates/cua-vmm/src/lib.rs
index 4a86410977..f3521f4123 100644
--- a/libs/cua/crates/cua-vmm/src/lib.rs
+++ b/libs/cua/crates/cua-vmm/src/lib.rs
@@ -30,6 +30,7 @@ pub mod error;
pub mod exec;
pub mod gpu;
pub mod host;
+pub mod local_network;
#[cfg(feature = "lume")]
pub mod lume;
pub mod managed;
diff --git a/libs/cua/crates/cua-vmm/src/local_network.rs b/libs/cua/crates/cua-vmm/src/local_network.rs
new file mode 100644
index 0000000000..6afe984ee4
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/src/local_network.rs
@@ -0,0 +1,295 @@
+//! Whether *this process* can reach this Mac's own macOS VMs, and which app
+//! macOS holds responsible for it.
+//!
+//! A macOS VM lives on Apple's shared network (192.168.64.x). macOS Local
+//! Network privacy blocks a process from it until the app macOS holds
+//! responsible for that process is allowed; a blocked connect fails at once
+//! with "No route to host" ([`crate::probe::is_unreachable`]). The grant
+//! belongs to the responsible app, not to the binary: a `cua` run from
+//! Terminal is Terminal's, the daemon the Spaces app starts is the app's. So
+//! the check has to run in the process that talks to the VMs (the cua
+//! daemon), and it says which app that is ([`ResponsibleApp`]).
+
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+use serde::{Deserialize, Serialize};
+
+/// Listing the VMs (`lume serve` is local).
+pub const LIST_TIMEOUT: Duration = Duration::from_secs(2);
+/// One connect to the VM. A blocked network fails at once; a VM that is
+/// there answers (accepts or refuses) well within this.
+pub const CONNECT_TIMEOUT: Duration = Duration::from_millis(1500);
+/// Any port works: a refusal comes back over the same network.
+pub const PROBE_PORT: u16 = 22;
+
+/// What one probe found.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "result", rename_all = "snake_case")]
+pub enum Probe {
+ /// `lume serve` did not list its VMs in time (or answered an error).
+ NoList { why: String },
+ /// No macOS VM is running with an address.
+ NoRunningVm,
+ /// The VM answered (accepted or refused the connection).
+ Reached { vm: String, ip: String },
+ /// No route to the VM: Local Network access is off for the responsible
+ /// app.
+ Blocked { vm: String, ip: String },
+ /// No answer in time, or another error: inconclusive.
+ Unclear { vm: String, ip: String, why: String },
+}
+
+/// The app macOS holds responsible for a process (whose Local Network
+/// grant applies to it).
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ResponsibleApp {
+ /// What System Settings lists: the bundle's name without `.app`, else
+ /// the executable's file name.
+ pub name: String,
+ /// The `.app` bundle, else the executable.
+ pub path: PathBuf,
+ /// Whether `path` is a `.app` bundle (System Settings lists apps; a
+ /// bare executable shows up under the app that started it, if at all).
+ pub bundle: bool,
+}
+
+/// The daemon-side probe as the daemon reports it (`cua doctor` reads it
+/// from the daemon's runtime doctor report under `local_network`).
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Report {
+ /// What the probe found.
+ pub probe: Probe,
+ /// The app macOS holds responsible for the probing process, when known.
+ #[serde(default)]
+ pub app: Option<ResponsibleApp>,
+ /// The probing process.
+ #[serde(default)]
+ pub pid: u32,
+}
+
+/// What one connect says about the network (pure).
+pub fn classify(vm: &str, ip: &str, result: Result<std::io::Result<()>, ()>) -> Probe {
+ let (vm, ip) = (vm.to_owned(), ip.to_owned());
+ match result {
+ Ok(Ok(())) => Probe::Reached { vm, ip },
+ Ok(Err(e)) if e.kind() == std::io::ErrorKind::ConnectionRefused => {
+ Probe::Reached { vm, ip }
+ }
+ Ok(Err(e)) if crate::probe::is_unreachable(&e) => Probe::Blocked { vm, ip },
+ Ok(Err(e)) => Probe::Unclear {
+ vm,
+ ip,
+ why: e.to_string(),
+ },
+ Err(()) => Probe::Unclear {
+ vm,
+ ip,
+ why: format!("no answer in {} ms", CONNECT_TIMEOUT.as_millis()),
+ },
+ }
+}
+
+/// Lists the VMs `lume serve` runs and connects once, from this process,
+/// to the first running macOS one with an address. Bounded: about 3.5 s.
+#[cfg(feature = "lume")]
+pub async fn probe(lume_base: &str) -> Probe {
+ let client = crate::lume::LumeClient::new(lume_base);
+ let vms = match tokio::time::timeout(LIST_TIMEOUT, client.list()).await {
+ Ok(Ok(vms)) => vms,
+ Ok(Err(e)) => return Probe::NoList { why: e.to_string() },
+ Err(_) => {
+ return Probe::NoList {
+ why: format!("no answer in {} s", LIST_TIMEOUT.as_secs()),
+ };
+ }
+ };
+ let Some((vm, ip)) = vms.iter().find_map(|v| {
+ (v.status == "running" && v.os.eq_ignore_ascii_case("macos"))
+ .then(|| v.ip().map(|ip| (v.name.clone(), ip.to_owned())))
+ .flatten()
+ }) else {
+ return Probe::NoRunningVm;
+ };
+ let addr = format!("{ip}:{PROBE_PORT}");
+ let result = tokio::time::timeout(CONNECT_TIMEOUT, tokio::net::TcpStream::connect(&addr))
+ .await
+ .map(|r| r.map(drop))
+ .map_err(drop);
+ classify(&vm, &ip, result)
+}
+
+/// [`probe`] plus who probed: what the daemon reports.
+#[cfg(feature = "lume")]
+pub async fn report(lume_base: &str) -> Report {
+ Report {
+ probe: probe(lume_base).await,
+ app: ResponsibleApp::of_this_process(),
+ pid: std::process::id(),
+ }
+}
+
+/// The `lume serve` this host's runtimes talk to.
+pub fn lume_base() -> String {
+ std::env::var("LUME_API").unwrap_or_else(|_| "http://127.0.0.1:7777".into())
+}
+
+impl ResponsibleApp {
+ /// The app macOS holds responsible for this process: the responsible
+ /// process's `.app` (for a daemon an app started, the app; for a CLI,
+ /// the terminal), else this executable's own `.app`, else the
+ /// executable. `None` off macOS.
+ pub fn of_this_process() -> Option<Self> {
+ if !cfg!(target_os = "macos") {
+ return None;
+ }
+ let exe = std::env::current_exe().ok();
+ let responsible = responsible_exe();
+ Self::pick(responsible.as_deref(), exe.as_deref())
+ }
+
+ /// The responsible executable's bundle, else this one's bundle, else
+ /// the responsible executable, else this one (pure).
+ fn pick(responsible: Option<&Path>, exe: Option<&Path>) -> Option<Self> {
+ responsible
+ .and_then(Self::bundle_of)
+ .or_else(|| exe.and_then(Self::bundle_of))
+ .or_else(|| responsible.or(exe).map(Self::bare))
+ }
+
+ /// The `.app` bundle `exe` runs from.
+ pub fn bundle_of(exe: &Path) -> Option<Self> {
+ exe.ancestors().find_map(|dir| {
+ let name = dir.file_name()?.to_str()?;
+ let stem = name.strip_suffix(".app")?;
+ Some(Self {
+ name: stem.to_string(),
+ path: dir.to_path_buf(),
+ bundle: true,
+ })
+ })
+ }
+
+ fn bare(exe: &Path) -> Self {
+ Self {
+ name: exe
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_else(|| exe.display().to_string()),
+ path: exe.to_path_buf(),
+ bundle: false,
+ }
+ }
+}
+
+/// The executable of the process macOS holds responsible for this one
+/// (`responsibility_get_pid_responsible_for_pid`, which TCC and Local
+/// Network privacy use), when it is another process.
+#[cfg(target_os = "macos")]
+fn responsible_exe() -> Option<PathBuf> {
+ unsafe extern "C" {
+ // libquarantine, part of libSystem. Not in the SDK headers, but
+ // stable since macOS 10.14 and what `launchctl procinfo` shows.
+ fn responsibility_get_pid_responsible_for_pid(pid: libc::pid_t) -> libc::pid_t;
+ }
+ // SAFETY: takes and returns a pid; no memory is shared.
+ let pid = unsafe { responsibility_get_pid_responsible_for_pid(libc::getpid()) };
+ if pid <= 0 {
+ return None;
+ }
+ let mut buf = vec![0u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];
+ // SAFETY: `buf` is valid for `buf.len()` bytes; proc_pidpath writes at
+ // most that many and returns the length written.
+ let n = unsafe { libc::proc_pidpath(pid, buf.as_mut_ptr().cast(), buf.len() as u32) };
+ if n <= 0 {
+ return None;
+ }
+ buf.truncate(n as usize);
+ String::from_utf8(buf).ok().map(PathBuf::from)
+}
+
+#[cfg(not(target_os = "macos"))]
+fn responsible_exe() -> Option<PathBuf> {
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::{Error, ErrorKind};
+
+ #[test]
+ fn connect_results_classify() {
+ let blocked = |k| classify("m", "1.2.3.4", Ok(Err(Error::from(k))));
+ assert!(matches!(
+ blocked(ErrorKind::HostUnreachable),
+ Probe::Blocked { .. }
+ ));
+ assert!(matches!(
+ blocked(ErrorKind::NetworkUnreachable),
+ Probe::Blocked { .. }
+ ));
+ // A refusal comes back over the network: reachable.
+ assert!(matches!(
+ blocked(ErrorKind::ConnectionRefused),
+ Probe::Reached { .. }
+ ));
+ assert!(matches!(
+ classify("m", "1.2.3.4", Ok(Ok(()))),
+ Probe::Reached { .. }
+ ));
+ assert!(matches!(
+ classify("m", "1.2.3.4", Err(())),
+ Probe::Unclear { .. }
+ ));
+ }
+
+ #[test]
+ fn the_responsible_apps_bundle_wins_then_this_ones() {
+ let app = Path::new("/Applications/Cua Spaces.app/Contents/MacOS/CuaSpacesMac");
+ let cli = Path::new("/Applications/Cua Spaces.app/Contents/MacOS/cua");
+ let bare = Path::new("/usr/local/bin/cua");
+ let terminal =
+ Path::new("/System/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal");
+ // The daemon the app started: the app.
+ let a = ResponsibleApp::pick(Some(app), Some(cli)).unwrap();
+ assert_eq!(a.name, "Cua Spaces");
+ assert!(a.bundle);
+ // A bare binary run from Terminal: Terminal.
+ let a = ResponsibleApp::pick(Some(terminal), Some(bare)).unwrap();
+ assert_eq!(a.name, "Terminal");
+ // Unknown responsible process, but this binary sits in an app.
+ let a = ResponsibleApp::pick(None, Some(cli)).unwrap();
+ assert_eq!(a.name, "Cua Spaces");
+ // Nothing in a bundle: the responsible executable, not a bundle.
+ let a = ResponsibleApp::pick(Some(bare), Some(bare)).unwrap();
+ assert_eq!((a.name.as_str(), a.bundle), ("cua", false));
+ assert!(ResponsibleApp::pick(None, None).is_none());
+ }
+
+ #[test]
+ fn the_report_round_trips_as_json() {
+ let r = Report {
+ probe: Probe::Blocked {
+ vm: "m1".into(),
+ ip: "192.168.64.5".into(),
+ },
+ app: ResponsibleApp::bundle_of(Path::new("/A/Cua Spaces.app/Contents/MacOS/cua")),
+ pid: 7,
+ };
+ let json = serde_json::to_value(&r).unwrap();
+ assert_eq!(json["probe"]["result"], "blocked");
+ assert_eq!(json["app"]["name"], "Cua Spaces");
+ let back: Report = serde_json::from_value(json).unwrap();
+ assert_eq!(back, r);
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn this_process_has_a_responsible_app() {
+ // Whatever ran the tests (a terminal, an IDE, launchd for CI): an
+ // executable that exists.
+ let a = ResponsibleApp::of_this_process().expect("on macOS");
+ assert!(a.path.exists(), "{a:?}");
+ }
+}
diff --git a/libs/cua/crates/cua-vmm/src/probe.rs b/libs/cua/crates/cua-vmm/src/probe.rs
index 12115ce22a..7199e1a2bf 100644
--- a/libs/cua/crates/cua-vmm/src/probe.rs
+++ b/libs/cua/crates/cua-vmm/src/probe.rs
@@ -158,21 +158,40 @@ pub fn is_unreachable(e: &std::io::Error) -> bool {
/// The error for a guest this process cannot reach: on macOS, what to allow
/// in Local Network privacy and for which app (the `.app` bundle this
/// process runs from, by name and path, since two builds can share a name).
-pub fn unreachable_error(addr: &str, error: &std::io::Error) -> VmmError {
- unreachable_error_for(addr, error, std::env::current_exe().ok().as_deref())
+///
+/// A bare executable (not in an `.app`) is named by the app macOS holds
+/// responsible for it when that is an app
+/// ([`crate::local_network::ResponsibleApp`]): the daemon a shell app
+/// started reads as that app, not as "cua".
+pub fn unreachable_error(addr: &str, error: &dyn std::fmt::Display) -> VmmError {
+ let exe = std::env::current_exe().ok();
+ let bundle = exe.as_deref().and_then(app_bundle).or_else(|| {
+ crate::local_network::ResponsibleApp::of_this_process()
+ .filter(|a| a.bundle)
+ .map(|a| (a.name, a.path))
+ });
+ unreachable_error_named(addr, error, bundle)
}
+#[cfg(test)]
fn unreachable_error_for(
addr: &str,
- error: &std::io::Error,
+ error: &dyn std::fmt::Display,
exe: Option<&std::path::Path>,
+) -> VmmError {
+ unreachable_error_named(addr, error, exe.and_then(app_bundle))
+}
+
+fn unreachable_error_named(
+ addr: &str,
+ error: &dyn std::fmt::Display,
+ bundle: Option<(String, std::path::PathBuf)>,
) -> VmmError {
if cfg!(target_os = "macos") {
// macOS asks once per boot, on this Mac's own screen, the first time
// the app reaches the local network, and lists the app under Local
// Network only after it has asked. Someone using this Mac from
// another device may never see the prompt, so say all three ways.
- let bundle = exe.and_then(app_bundle);
let hint = match &bundle {
Some((name, path)) => format!(
"{name} ({}) cannot reach the VM at {addr} ({error}). macOS blocks {name}'s \
diff --git a/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock b/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock
index df83bfb766..15417d64e6 100644
--- a/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock
+++ b/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock
@@ -1654,6 +1654,7 @@ dependencies = [
"cua-spaces-contract",
"cua-spacesd-client",
"cua-telemetry",
+ "cua-vmm",
"futures-util",
"hex",
"http",
diff --git a/tests/e2e/cua-sdk/rust/Cargo.lock b/tests/e2e/cua-sdk/rust/Cargo.lock
index 9ee9b73542..24e78df376 100644
--- a/tests/e2e/cua-sdk/rust/Cargo.lock
+++ b/tests/e2e/cua-sdk/rust/Cargo.lock
@@ -1616,6 +1616,7 @@ dependencies = [
"cua-spaces-contract",
"cua-spacesd-client",
"cua-telemetry",
+ "cua-vmm",
"futures-util",
"hex",
"http",
diff --git a/tests/e2e/local-runtimes/Cargo.lock b/tests/e2e/local-runtimes/Cargo.lock
index 8f1e21ff05..1c43f6097f 100644
--- a/tests/e2e/local-runtimes/Cargo.lock
+++ b/tests/e2e/local-runtimes/Cargo.lock
@@ -1034,6 +1034,7 @@ dependencies = [
"cua-spaces-contract",
"cua-spacesd-client",
"cua-telemetry",
+ "cua-vmm",
"futures-util",
"hex",
"http",