Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(spaces): preflight checks before creating a local Space (CUA-1916) (#5553)
Francesco Bonacci7bfb8e17e5a1
diff --git a/apps/cua-spaces/core-wasm/Cargo.lock b/apps/cua-spaces/core-wasm/Cargo.lockindex 78593c3143..258ed89af8 100644--- a/apps/cua-spaces/core-wasm/Cargo.lock+++ b/apps/cua-spaces/core-wasm/Cargo.lock@@ -17,6 +17,9 @@ checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"[[package]]name = "cua-create-failure"version = "0.1.0"+dependencies = [+ "serde",+][[package]]name = "cua-home"diff --git a/apps/cua-spaces/src-tauri/Cargo.lock b/apps/cua-spaces/src-tauri/Cargo.lockindex cd92d954e5..ebcdabb117 100644--- a/apps/cua-spaces/src-tauri/Cargo.lock+++ b/apps/cua-spaces/src-tauri/Cargo.lock@@ -1274,6 +1274,9 @@ dependencies = [[[package]]name = "cua-create-failure"version = "0.1.0"+dependencies = [+ "serde",+][[package]]name = "cua-daemon"@@ -1283,6 +1286,7 @@ dependencies = ["axum","base64 0.22.1","bytes",+ "cua-create-failure","cua-disk","cua-home","cua-host",@@ -1828,6 +1832,7 @@ dependencies = ["base64 0.22.1","bollard","bytes",+ "cua-create-failure","filetime","futures","libc",diff --git a/docs/content/docs/cua-sdk/concepts/telemetry-error-kinds.mdx b/docs/content/docs/cua-sdk/concepts/telemetry-error-kinds.mdxindex a66f4a4d2f..f8f28806f5 100644--- a/docs/content/docs/cua-sdk/concepts/telemetry-error-kinds.mdx+++ b/docs/content/docs/cua-sdk/concepts/telemetry-error-kinds.mdx@@ -22,6 +22,10 @@ error text.| `vm_boot_timeout` | The VM did not finish booting in time. || `services_unreachable` | The Space booted but its services never answered. || `local_network` | macOS Local Network privacy blocked the connection to the new VM. |+| `out_of_memory` | The machine ran out of memory for the guest. |+| `port_in_use` | A port the Space needs is already taken. |+| `file_access` | A file or folder could not be written (access denied, in use, path too long). |+| `network` | The machine could not reach the network (DNS, proxy, certificate) outside the image download. || `quota_exceeded` | The account's quota, plan limit or credits ran out. || `cancelled` | You cancelled the create. |diff --git a/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock b/examples/openkoalabot-example-tauri/src-tauri/Cargo.lockindex c2f2c8b999..5189b3c4db 100644--- a/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock+++ b/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock@@ -1265,6 +1265,9 @@ dependencies = [[[package]]name = "cua-create-failure"version = "0.1.0"+dependencies = [+ "serde",+][[package]]name = "cua-daemon"@@ -1274,6 +1277,7 @@ dependencies = ["axum","base64 0.22.1","bytes",+ "cua-create-failure","cua-disk","cua-home","cua-host",@@ -1757,6 +1761,7 @@ dependencies = ["base64 0.22.1","bollard","bytes",+ "cua-create-failure","filetime","futures","libc",diff --git a/examples/streaming/rust/Cargo.lock b/examples/streaming/rust/Cargo.lockindex 09b79cabc4..cb1cf195b8 100644--- a/examples/streaming/rust/Cargo.lock+++ b/examples/streaming/rust/Cargo.lock@@ -1291,6 +1291,9 @@ dependencies = [[[package]]name = "cua-create-failure"version = "0.1.0"+dependencies = [+ "serde",+][[package]]name = "cua-daemon"@@ -1300,6 +1303,7 @@ dependencies = ["base64 0.22.1","bytes","cua-byoc",+ "cua-create-failure","cua-disk","cua-home","cua-host",@@ -1660,6 +1664,7 @@ dependencies = ["base64 0.22.1","bollard","bytes",+ "cua-create-failure","filetime","futures","libc",diff --git a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lockindex 52f3ad02d8..81de94cc75 100644--- a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock+++ b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock@@ -2069,6 +2069,9 @@ dependencies = [[[package]]name = "cua-create-failure"version = "0.1.0"+dependencies = [+ "serde",+][[package]]name = "cua-cursor-motion"@@ -2086,6 +2089,7 @@ dependencies = ["base64 0.22.1","bytes","cua-byoc",+ "cua-create-failure","cua-disk","cua-home","cua-host",@@ -2833,6 +2837,7 @@ dependencies = ["base64 0.22.1","bollard","bytes",+ "cua-create-failure","filetime","futures","libc",diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lockindex 610fe6358f..6781e71300 100644--- a/libs/cua/Cargo.lock+++ b/libs/cua/Cargo.lock@@ -2436,6 +2436,8 @@ name = "cua-create-failure"version = "0.1.0"dependencies = ["cua-telemetry",+ "serde",+ "serde_json",][[package]]@@ -2448,6 +2450,7 @@ dependencies = ["bytes","cua-byoc","cua-contrib",+ "cua-create-failure","cua-disk","cua-home","cua-host",@@ -3203,6 +3206,7 @@ dependencies = ["base64 0.22.1","bollard","bytes",+ "cua-create-failure","cua-spacesd-client","filetime","futures",diff --git a/libs/cua/crates/cua-create-failure/Cargo.toml b/libs/cua/crates/cua-create-failure/Cargo.tomlindex 4fc9b3ce3c..3289aeb447 100644--- a/libs/cua/crates/cua-create-failure/Cargo.toml+++ b/libs/cua/crates/cua-create-failure/Cargo.toml@@ -1,6 +1,6 @@[package]name = "cua-create-failure"-description = "Why a sandbox or Space create failed, as a fixed telemetry word (`image_pull_not_found`, `vm_boot_timeout`, ...) read from the error text inside the process; the text never leaves. No dependencies, so the Spaces app core's wasm build uses it too."+description = "Why a sandbox or Space create failed, as a fixed telemetry word (`image_pull_not_found`, `vm_boot_timeout`, ...) read from the error text inside the process; the text never leaves. Also the preflight checks before a create and their plain-language results. Only serde, so the Spaces app core's wasm build uses it too."version.workspace = trueedition.workspace = truerust-version = "1.95"@@ -9,5 +9,9 @@ license.workspace = truerepository.workspace = truepublish = false+[dependencies]+serde.workspace = true+[dev-dependencies]+serde_json.workspace = truecua-telemetry.workspace = truediff --git a/libs/cua/crates/cua-create-failure/src/lib.rs b/libs/cua/crates/cua-create-failure/src/lib.rsindex e8fdfd28a8..9d06088b8c 100644--- a/libs/cua/crates/cua-create-failure/src/lib.rs+++ b/libs/cua/crates/cua-create-failure/src/lib.rs@@ -9,6 +9,8 @@//! the same cause the same way. Callers pass the result through//! `cua_telemetry::events::error_kind`, which keeps only schema words.+pub mod preflight;+/// Enum cases that say little on their own (compared lowercase, without/// underscores): the error text decides instead.const GENERIC: &[&str] = &[@@ -93,6 +95,10 @@ fn from_text(message: &str, phase: &str, local: bool) -> Option<&'static str> {) {return Some("cancelled");}+ // A preflight sentence (`preflight::evaluate`) a create carried on.+ if let Some(kind) = preflight::IssueKind::of_text(&l) {+ return Some(kind.error_kind());+ }if has(&l,&[@@ -183,6 +189,62 @@ fn from_text(message: &str, phase: &str, local: bool) -> Option<&'static str> {if l.contains("unauthenticated") {return Some("unauthenticated");}+ // Causes that used to land in `other`: they name the problem but not+ // the runtime, so they apply to every phase.+ if has(+ &l,+ &[+ "not enough memory",+ "out of memory",+ "cannot allocate memory",+ "failed to allocate memory",+ ],+ ) {+ return Some("out_of_memory");+ }+ if has(+ &l,+ &[+ "address already in use",+ "port is already allocated",+ "port is already in use",+ "only one usage of each socket address",+ ],+ ) {+ return Some("port_in_use");+ }+ if has(+ &l,+ &[+ "access is denied",+ "os error 5)",+ "being used by another process",+ "path too long",+ "file name too long",+ "filename too long",+ "read-only file system",+ ],+ ) {+ return Some("file_access");+ }+ if has(+ &l,+ &[+ "could not resolve host",+ "dns error",+ "name or service not known",+ "no such host",+ "temporary failure in name resolution",+ "network is unreachable",+ "no internet",+ "tls handshake",+ "certificate verify failed",+ "proxyconnect",+ "failed to lookup address",+ ],+ ) {+ return Some("network");+ }// The Space booted but its service (cua-spacesd, the computer server)// did not answer.if l.contains("cua-spacesd did not answer within ")@@ -323,6 +385,10 @@ pub const TEXT_KINDS: &[&str] = &["runtime_not_running","runtime_missing","unauthenticated",+ "out_of_memory",+ "port_in_use",+ "file_access",+ "network","services_unreachable","vm_boot_timeout","timeout",@@ -346,6 +412,40 @@ mod tests {}}+ #[test]+ fn former_other_texts_get_a_kind() {+ fn k(m: &str) -> &str {+ kind(m, "preparing", "Runtime")+ }+ assert_eq!(k("Cannot allocate memory (os error 12)"), "out_of_memory");+ assert_eq!(k("QEMU: not enough memory for the guest"), "out_of_memory");+ assert_eq!(+ k("bind: address already in use on 127.0.0.1:5900"),+ "port_in_use"+ );+ assert_eq!(+ k("Bind for 0.0.0.0:8080 failed: port is already allocated"),+ "port_in_use"+ );+ assert_eq!(k("Access is denied. (os error 5)"), "file_access");+ assert_eq!(+ k("the file is being used by another process"),+ "file_access"+ );+ assert_eq!(+ k("error sending request: dns error: failed to lookup address information"),+ "network"+ );+ assert_eq!(k("x509: certificate verify failed"), "network");+ // A pull keeps its own, finer kinds.+ assert_eq!(+ kind("dns error: no such host", "pulling", "Runtime"),+ "image_pull_network"+ );+ assert_eq!(k("something nobody has seen"), "Runtime");+ assert_eq!(kind("something nobody has seen", "", ""), "other");+ }+#[test]fn image_pulls_split_by_cause() {let p = "pulling";diff --git a/libs/cua/crates/cua-create-failure/src/preflight.rs b/libs/cua/crates/cua-create-failure/src/preflight.rsnew file mode 100644index 0000000000..c5db09dc9e--- /dev/null+++ b/libs/cua/crates/cua-create-failure/src/preflight.rs@@ -0,0 +1,595 @@+//! Preflight: what to check before a local Space is created, and what to+//! tell the person when a check fails.+//!+//! This is the pure half. A host gathers [`Facts`] about the machine (free+//! disk space, the container engine, macOS Local Network access, hardware+//! virtualization; `cua_vmm::preflight` does it) and [`evaluate`] turns+//! them into [`Issue`]s: one plain sentence a parent would understand and,+//! where one exists, a single [`Fix`] for a button or link. Every shell+//! (the macOS, Windows and Linux apps, the CLI) shows the same words.+//!+//! No dependencies besides serde, so the Spaces app core's wasm build uses+//! it too. The sentences are fixed text on purpose: [`IssueKind::of_text`]+//! recognises them again, so a create that failed with one of them is+//! classified the same way as the preflight that predicted it.++use serde::{Deserialize, Serialize};++const GIB: u64 = 1 << 30;++/// The machine the Space is created on.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Host {+ Macos,+ Windows,+ Linux,+}++impl Host {+ /// This machine.+ pub fn current() -> Self {+ if cfg!(target_os = "macos") {+ Self::Macos+ } else if cfg!(windows) {+ Self::Windows+ } else {+ Self::Linux+ }+ }++ /// How a sentence names the machine.+ fn subject(self) -> &'static str {+ match self {+ Self::Macos => "Your Mac",+ Self::Windows => "Your PC",+ Self::Linux => "Your computer",+ }+ }+}++/// The operating system of the Space to create.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Guest {+ Linux,+ Macos,+ Windows,+}++/// How the Space runs.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Runs {+ /// A container, on a container engine (Docker).+ Container,+ /// A virtual machine.+ Vm,+}++/// What is about to be created.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct Request {+ pub host: Host,+ pub guest: Guest,+ pub runs: Runs,+ /// Bytes the create writes (the image, the VM's disk).+ pub needed_bytes: u64,+ /// Bytes cua keeps free on the volume besides that.+ pub min_free_bytes: u64,+}++/// The container engine, as found.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Engine {+ /// Answering.+ Ready,+ /// Not installed.+ Missing,+ /// Installed, not running.+ NotRunning,+ /// This user may not use it.+ PermissionDenied,+ /// Not checked (not needed, or this build cannot).+ #[default]+ NotChecked,+}++/// What stops this machine from running virtual machines.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum VirtGap {+ /// Windows: the Windows Hypervisor Platform feature is off.+ HypervisorPlatformOff,+ /// Linux: no `/dev/kvm` (virtualization off in the firmware, or none).+ KvmMissing,+ /// Linux: `/dev/kvm` exists but this user may not open it.+ KvmPermission,+}++/// What the host found, `None` / `NotChecked` for what it did not check.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct Facts {+ /// Free bytes on the volume the Space is written to.+ pub free_bytes: Option<u64>,+ pub engine: Engine,+ /// macOS Local Network privacy blocked a connect to a running VM.+ pub local_network_blocked: bool,+ pub virtualization: Option<VirtGap>,+}++/// What a failed check is about. Also the error kind a create that fails+/// the same way records ([`IssueKind::error_kind`]).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum IssueKind {+ InsufficientDisk,+ EngineMissing,+ EngineNotRunning,+ EnginePermission,+ LocalNetwork,+ VirtualizationUnavailable,+}++impl IssueKind {+ /// The telemetry word (`cua_telemetry::schema::ERROR_KINDS`).+ pub fn error_kind(self) -> &'static str {+ match self {+ Self::InsufficientDisk => "insufficient_disk",+ Self::EngineMissing => "runtime_missing",+ Self::EngineNotRunning => "runtime_not_running",+ Self::EnginePermission => "runtime_permission",+ Self::LocalNetwork => "local_network",+ Self::VirtualizationUnavailable => "virtualization_unavailable",+ }+ }++ /// The kind whose preflight sentence `text` is (compared lowercase), if+ /// it is one.+ pub fn of_text(text: &str) -> Option<Self> {+ let l = text.to_ascii_lowercase();+ let has = |s: &str| l.contains(s);+ if has("free to create this computer") {+ Some(Self::InsufficientDisk)+ } else if has("to run linux computers.") {+ Some(Self::EngineMissing)+ } else if has("isn't running. ") && has("docker") {+ Some(Self::EngineNotRunning)+ } else if has("isn't allowed to use docker") {+ Some(Self::EnginePermission)+ } else if has("find devices on your network") {+ Some(Self::LocalNetwork)+ } else if has("hypervisor platform")+ || has("virtualization is turned off")+ || has("isn't allowed to use this computer's virtualization")+ {+ Some(Self::VirtualizationUnavailable)+ } else {+ None+ }+ }+}++/// A System Settings page or Windows dialog a fix opens.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Pane {+ /// macOS: Privacy & Security > Local Network.+ LocalNetwork,+ /// Windows: Turn Windows features on or off.+ WindowsFeatures,+}++/// What the fix button does.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(tag = "type", content = "value", rename_all = "snake_case")]+pub enum FixAction {+ /// Open this web page.+ OpenUrl(String),+ /// Open this settings page.+ OpenSettings(Pane),+ /// Run this command (the CLI prints it; an app runs it for the user).+ RunCommand(String),+}++/// One button or link that fixes the problem.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct Fix {+ pub label: String,+ pub action: FixAction,+}++/// One failed check.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct Issue {+ pub kind: IssueKind,+ /// One plain sentence or two: what is wrong and what to do.+ pub message: String,+ /// The single fix, where one is possible.+ pub fix: Option<Fix>,+}++impl Issue {+ fn new(kind: IssueKind, message: impl Into<String>, fix: Option<Fix>) -> Self {+ Self {+ kind,+ message: message.into(),+ fix,+ }+ }+}++fn fix(label: &str, action: FixAction) -> Option<Fix> {+ Some(Fix {+ label: label.into(),+ action,+ })+}++/// Whole gigabytes, rounded up, for a sentence.+fn gb(bytes: u64) -> u64 {+ bytes.div_ceil(GIB).max(1)+}++/// The checks that fail, most important first. Empty: go ahead.+pub fn evaluate(req: &Request, facts: &Facts) -> Vec<Issue> {+ let mut out = Vec::new();++ if let Some(free) = facts.free_bytes {+ let need = req.needed_bytes.saturating_add(req.min_free_bytes);+ if free < need {+ out.push(Issue::new(+ IssueKind::InsufficientDisk,+ format!(+ "{} needs about {} GB free to create this computer. Free up space and try \+ again.",+ req.host.subject(),+ gb(need)+ ),+ fix(+ "Free up space",+ FixAction::RunCommand("cua cache prune".into()),+ ),+ ));+ }+ }++ if req.runs == Runs::Container {+ let desktop = req.host != Host::Linux;+ match facts.engine {+ Engine::Missing if desktop => out.push(Issue::new(+ IssueKind::EngineMissing,+ "Install Docker Desktop to run Linux computers.",+ fix(+ "Get Docker",+ FixAction::OpenUrl("https://www.docker.com/products/docker-desktop/".into()),+ ),+ )),+ Engine::Missing => out.push(Issue::new(+ IssueKind::EngineMissing,+ "Install Docker to run Linux computers.",+ fix(+ "Get Docker",+ FixAction::OpenUrl("https://docs.docker.com/engine/install/".into()),+ ),+ )),+ Engine::NotRunning if desktop => out.push(Issue::new(+ IssueKind::EngineNotRunning,+ "Docker Desktop isn't running. Open it, wait until it says it's running, then \+ try again.",+ None,+ )),+ Engine::NotRunning => out.push(Issue::new(+ IssueKind::EngineNotRunning,+ "Docker isn't running. Start it, then try again.",+ None,+ )),+ Engine::PermissionDenied => out.push(Issue::new(+ IssueKind::EnginePermission,+ "Cua isn't allowed to use Docker on this computer. Give your account access to \+ Docker, then try again.",+ fix(+ "How to fix",+ FixAction::OpenUrl(+ "https://docs.docker.com/engine/install/linux-postinstall/".into(),+ ),+ ),+ )),+ Engine::Ready | Engine::NotChecked => {}+ }+ }++ if req.host == Host::Macos && req.guest == Guest::Macos && facts.local_network_blocked {+ out.push(Issue::new(+ IssueKind::LocalNetwork,+ "Cua needs permission to find devices on your network to reach this Mac computer. \+ Turn on Cua in Local Network settings, then try again.",+ fix("Open Settings", FixAction::OpenSettings(Pane::LocalNetwork)),+ ));+ }++ if req.runs == Runs::Vm+ && let Some(gap) = facts.virtualization+ {+ match (gap, req.host, req.guest) {+ (VirtGap::HypervisorPlatformOff, Host::Windows, _) => out.push(Issue::new(+ IssueKind::VirtualizationUnavailable,+ "Turn on the Windows Hypervisor Platform feature so this PC can run virtual \+ computers, then restart it.",+ fix(+ "Open Windows Features",+ FixAction::OpenSettings(Pane::WindowsFeatures),+ ),+ )),+ // Without KVM a Linux guest still runs, slowly; Windows does not.+ (VirtGap::KvmMissing, Host::Linux, Guest::Windows) => out.push(Issue::new(+ IssueKind::VirtualizationUnavailable,+ "Virtualization is turned off on this computer, so it can't run Windows \+ computers. Turn it on in the computer's BIOS settings.",+ None,+ )),+ // Like a missing KVM, a Linux guest still starts without it.+ (VirtGap::KvmPermission, Host::Linux, Guest::Windows) => out.push(Issue::new(+ IssueKind::VirtualizationUnavailable,+ "Cua isn't allowed to use this computer's virtualization. Add your account to \+ the kvm group, then log out and back in.",+ None,+ )),+ _ => {}+ }+ }++ out+}++#[cfg(test)]+mod tests {+ use super::*;++ fn req(host: Host, guest: Guest, runs: Runs) -> Request {+ Request {+ host,+ guest,+ runs,+ needed_bytes: 7 * GIB,+ min_free_bytes: 5 * GIB,+ }+ }++ fn first(req: &Request, facts: &Facts) -> Issue {+ evaluate(req, facts).remove(0)+ }++ #[test]+ fn a_healthy_machine_has_no_issues() {+ let facts = Facts {+ free_bytes: Some(100 * GIB),+ engine: Engine::Ready,+ ..Default::default()+ };+ for r in [+ req(Host::Macos, Guest::Linux, Runs::Container),+ req(Host::Windows, Guest::Windows, Runs::Vm),+ req(Host::Linux, Guest::Linux, Runs::Container),+ ] {+ assert!(evaluate(&r, &facts).is_empty());+ }+ assert!(evaluate(&req(Host::Linux, Guest::Linux, Runs::Vm), &Facts::default()).is_empty());+ }++ #[test]+ fn a_full_disk_says_how_much_is_needed() {+ let facts = Facts {+ free_bytes: Some(3 * GIB),+ ..Default::default()+ };+ let i = first(&req(Host::Macos, Guest::Macos, Runs::Vm), &facts);+ assert_eq!(i.kind, IssueKind::InsufficientDisk);+ assert_eq!(+ i.message,+ "Your Mac needs about 12 GB free to create this computer. Free up space and try again."+ );+ assert_eq!(i.fix.unwrap().label, "Free up space");+ let w = first(&req(Host::Windows, Guest::Windows, Runs::Vm), &facts);+ assert!(w.message.starts_with("Your PC needs about 12 GB"));+ // Exactly enough is enough; an unknown size never blocks.+ let ok = Facts {+ free_bytes: Some(12 * GIB),+ ..Default::default()+ };+ assert!(evaluate(&req(Host::Macos, Guest::Macos, Runs::Vm), &ok).is_empty());+ assert!(evaluate(&req(Host::Macos, Guest::Macos, Runs::Vm), &Facts::default()).is_empty());+ }++ #[test]+ fn the_container_engine_has_three_ways_to_fail() {+ let r = req(Host::Macos, Guest::Linux, Runs::Container);+ let with = |engine| Facts {+ engine,+ ..Default::default()+ };+ let missing = first(&r, &with(Engine::Missing));+ assert_eq!(+ missing.message,+ "Install Docker Desktop to run Linux computers."+ );+ assert_eq!(+ missing.fix,+ Some(Fix {+ label: "Get Docker".into(),+ action: FixAction::OpenUrl(+ "https://www.docker.com/products/docker-desktop/".into()+ )+ })+ );+ let linux = first(+ &req(Host::Linux, Guest::Linux, Runs::Container),+ &with(Engine::Missing),+ );+ assert_eq!(linux.message, "Install Docker to run Linux computers.");+ let down = first(&r, &with(Engine::NotRunning));+ assert_eq!(down.kind, IssueKind::EngineNotRunning);+ assert!(down.fix.is_none());+ let denied = first(&r, &with(Engine::PermissionDenied));+ assert_eq!(denied.kind, IssueKind::EnginePermission);+ // A VM does not need an engine.+ let vm = req(Host::Macos, Guest::Linux, Runs::Vm);+ assert!(evaluate(&vm, &with(Engine::Missing)).is_empty());+ }++ #[test]+ fn local_network_only_matters_for_a_macos_guest_on_a_mac() {+ let facts = Facts {+ local_network_blocked: true,+ ..Default::default()+ };+ let i = first(&req(Host::Macos, Guest::Macos, Runs::Vm), &facts);+ assert_eq!(i.kind, IssueKind::LocalNetwork);+ assert_eq!(+ i.fix.unwrap().action,+ FixAction::OpenSettings(Pane::LocalNetwork)+ );+ assert!(evaluate(&req(Host::Macos, Guest::Linux, Runs::Container), &facts).is_empty());+ assert!(evaluate(&req(Host::Windows, Guest::Windows, Runs::Vm), &facts).is_empty());+ }++ #[test]+ fn virtualization_prerequisites_by_host() {+ let gap = |g| Facts {+ virtualization: Some(g),+ ..Default::default()+ };+ let win = first(+ &req(Host::Windows, Guest::Windows, Runs::Vm),+ &gap(VirtGap::HypervisorPlatformOff),+ );+ assert_eq!(win.kind, IssueKind::VirtualizationUnavailable);+ assert_eq!(+ win.fix.unwrap().action,+ FixAction::OpenSettings(Pane::WindowsFeatures)+ );+ let linux_win = req(Host::Linux, Guest::Windows, Runs::Vm);+ assert!(first(&linux_win, &gap(VirtGap::KvmMissing)).fix.is_none());+ // A Linux guest without KVM still runs (slowly).+ let linux_linux = req(Host::Linux, Guest::Linux, Runs::Vm);+ assert!(evaluate(&linux_linux, &gap(VirtGap::KvmMissing)).is_empty());+ assert!(evaluate(&linux_linux, &gap(VirtGap::KvmPermission)).is_empty());+ assert_eq!(+ first(&linux_win, &gap(VirtGap::KvmPermission)).kind,+ IssueKind::VirtualizationUnavailable+ );+ // Containers do not need it.+ let c = req(Host::Windows, Guest::Linux, Runs::Container);+ assert!(evaluate(&c, &gap(VirtGap::HypervisorPlatformOff)).is_empty());+ }++ #[test]+ fn every_sentence_is_recognised_again() {+ let everything = Facts {+ free_bytes: Some(0),+ engine: Engine::Missing,+ local_network_blocked: true,+ virtualization: Some(VirtGap::HypervisorPlatformOff),+ };+ let mut seen = Vec::new();+ for (host, guest, runs, engine, gap) in [+ (Host::Macos, Guest::Macos, Runs::Vm, Engine::Ready, None),+ (+ Host::Macos,+ Guest::Linux,+ Runs::Container,+ Engine::Missing,+ None,+ ),+ (+ Host::Macos,+ Guest::Linux,+ Runs::Container,+ Engine::NotRunning,+ None,+ ),+ (+ Host::Linux,+ Guest::Linux,+ Runs::Container,+ Engine::NotRunning,+ None,+ ),+ (+ Host::Linux,+ Guest::Linux,+ Runs::Container,+ Engine::Missing,+ None,+ ),+ (+ Host::Linux,+ Guest::Linux,+ Runs::Container,+ Engine::PermissionDenied,+ None,+ ),+ (+ Host::Windows,+ Guest::Windows,+ Runs::Vm,+ Engine::Ready,+ Some(VirtGap::HypervisorPlatformOff),+ ),+ (+ Host::Linux,+ Guest::Windows,+ Runs::Vm,+ Engine::Ready,+ Some(VirtGap::KvmMissing),+ ),+ (+ Host::Linux,+ Guest::Windows,+ Runs::Vm,+ Engine::Ready,+ Some(VirtGap::KvmPermission),+ ),+ ] {+ let facts = Facts {+ engine,+ virtualization: gap,+ ..everything+ };+ for i in evaluate(&req(host, guest, runs), &facts) {+ assert_eq!(+ IssueKind::of_text(&i.message),+ Some(i.kind),+ "{}",+ i.message+ );+ seen.push(i.kind);+ }+ }+ for k in [+ IssueKind::InsufficientDisk,+ IssueKind::EngineMissing,+ IssueKind::EngineNotRunning,+ IssueKind::EnginePermission,+ IssueKind::LocalNetwork,+ IssueKind::VirtualizationUnavailable,+ ] {+ assert!(seen.contains(&k), "{k:?} never produced");+ }+ assert_eq!(IssueKind::of_text("something else"), None);+ }++ #[test]+ fn issues_round_trip_as_json() {+ let i = first(+ &req(Host::Macos, Guest::Linux, Runs::Container),+ &Facts {+ engine: Engine::Missing,+ ..Default::default()+ },+ );+ let json = serde_json::to_string(&i).unwrap();+ assert_eq!(serde_json::from_str::<Issue>(&json).unwrap(), i);+ }+}diff --git a/libs/cua/crates/cua-daemon/Cargo.toml b/libs/cua/crates/cua-daemon/Cargo.tomlindex 080d678378..379402bc22 100644--- a/libs/cua/crates/cua-daemon/Cargo.toml+++ b/libs/cua/crates/cua-daemon/Cargo.toml@@ -40,6 +40,7 @@ cua-spacesd-client.workspace = truecua-sandbox-core.workspace = truecua-contrib = { workspace = true, optional = true }cua-vmm = { path = "../cua-vmm" }+cua-create-failure.workspace = truecua-image = { path = "../cua-image" }# Disk accounting, cache GC and orphan reaping.cua-disk.workspace = truediff --git a/libs/cua/crates/cua-daemon/src/local.rs b/libs/cua/crates/cua-daemon/src/local.rsindex 57b22bfbb8..82e83c1971 100644--- a/libs/cua/crates/cua-daemon/src/local.rs+++ b/libs/cua/crates/cua-daemon/src/local.rs@@ -853,6 +853,7 @@ impl LocalRuntime for VmmLocal {});}refuse_gpu(&spec.image, spec.gpu.is_some(), &r)?;+ preflight_refusal(os_of(&spec.os), p.backend).await?;let rt = self.runtime(p.backend).await.map_err(rt_err)?;let mut s = StartSpec::new(&spec.name, p.image).os(os_of(&spec.os))@@ -1215,6 +1216,31 @@ impl VmmLocal {}}+// ------------------------------------------------------------------ preflight++/// Refuses a create the machine cannot run, in plain words (the first+/// failed check of [`cua_vmm::preflight`]), before anything is pulled. The+/// disk is left to the guards of the create itself, which know the image's+/// real size.+async fn preflight_refusal(os: cua_vmm::GuestOs, backend: BackendKind) -> RuntimeResult<()> {+ use cua_create_failure::preflight::Runs;+ let runs = if backend == BackendKind::Container {+ Runs::Container+ } else {+ Runs::Vm+ };+ let req = cua_vmm::preflight::request(cua_vmm::preflight::guest_of(os), runs, None);+ let mut facts = cua_vmm::preflight::gather(&req).await;+ facts.free_bytes = None;+ match cua_create_failure::preflight::evaluate(&req, &facts)+ .into_iter()+ .next()+ {+ Some(issue) => Err(RuntimeError::Other(issue.message)),+ None => Ok(()),+ }+}+// ------------------------------------------------------------------ doctor/// `cua runtime doctor`: the `cua-vmm` report (read-only).@@ -1239,6 +1265,14 @@ pub async fn doctor_response() -> cua_proto::daemon::v1::DoctorResponse {serde_json::to_value(ln).unwrap_or_default(),);}+ if let Some(map) = json.as_object_mut() {+ // What would stop a create here, per Space the host can run, in+ // words the apps and the CLI show as they are.+ map.insert(+ "preflight".into(),+ serde_json::to_value(cua_vmm::preflight::report().await).unwrap_or_default(),+ );+ }cua_proto::daemon::v1::DoctorResponse {checks: doctor_checks(&report),report_json: json.to_string(),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.rsindex 924e82be05..b1a1e084cb 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@@ -691,6 +691,24 @@ fn short_duration(secs: f64) -> String {}}+/// The first thing that would stop a create of `space` (`linux_container`,+/// `linux_vm`, `macos_vm`, `windows_vm`), from the `preflight` entry of the+/// daemon's runtime doctor report (`report_json`), to show before Create:+/// its plain sentence and the single fix button, when there is one. `None`:+/// nothing in the way, or the report has no verdict for it (an older+/// daemon), so Create goes ahead.+pub fn preflight_issue(+ report_json: &str,+ space: &str,+) -> Option<cua_create_failure::preflight::Issue> {+ let report: serde_json::Value = serde_json::from_str(report_json).ok()?;+ let issues = report.get("preflight")?.get(space)?.clone();+ serde_json::from_value::<Vec<cua_create_failure::preflight::Issue>>(issues)+ .ok()?+ .into_iter()+ .next()+}+/// The SDK's disk refusal ("not enough disk space to pull ...: it needs/// about 30.0 GB and cua keeps 5.0 GB free, but only 12.0 GB is available/// on /Users/me/.lume (...)") in plain words, with its numbers when present.@@ -1476,6 +1494,36 @@ pub fn compose(registry: &[Space], state: &CreatesState) -> Vec<Space> {mod tests {use super::*;+ #[test]+ fn preflight_issue_reads_the_daemons_report() {+ let report = r#"{"preflight":{+ "linux_container":[{"kind":"engine_missing",+ "message":"Install Docker Desktop to run Linux computers.",+ "fix":{"label":"Get Docker","action":{"type":"open_url","value":"https://www.docker.com/products/docker-desktop/"}}}],+ "linux_vm":[]}}"#;+ let issue = preflight_issue(report, "linux_container").unwrap();+ assert_eq!(+ issue.message,+ "Install Docker Desktop to run Linux computers."+ );+ assert_eq!(issue.fix.unwrap().label, "Get Docker");+ assert!(preflight_issue(report, "linux_vm").is_none());+ assert!(preflight_issue(report, "windows_vm").is_none());+ // An older daemon has no verdict; garbage never blocks a create.+ assert!(preflight_issue("{}", "linux_vm").is_none());+ assert!(preflight_issue("not json", "linux_vm").is_none());+ }++ #[test]+ fn a_failed_create_with_a_preflight_sentence_keeps_its_cause() {+ let raw = "Install Docker Desktop to run Linux computers.";+ assert_eq!(failure_text(raw, Some("preparing"), None, false), raw);+ assert_eq!(+ failure_variant(raw, Some("preparing"), false, "Runtime", None),+ "runtime_missing"+ );+ }+/// 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() {diff --git a/libs/cua/crates/cua-telemetry/src/schema.rs b/libs/cua/crates/cua-telemetry/src/schema.rsindex 176923ca04..c3893b7c5e 100644--- a/libs/cua/crates/cua-telemetry/src/schema.rs+++ b/libs/cua/crates/cua-telemetry/src/schema.rs@@ -179,6 +179,14 @@ pub const ERROR_KINDS: &[&str] = &["local_network","vm_limit","requires_cua_app",+ // A failed create's text, read into a cause: the guest asked for more+ // memory than the machine has, a port the Space needs is taken, a file+ // or folder could not be written, the machine could not reach the+ // network.+ "out_of_memory",+ "port_in_use",+ "file_access",+ "network","cancelled",// An agent run: cua_spaces `Error::Agent`, a run that recorded a// failure, a run whose process went away mid-turn.diff --git a/libs/cua/crates/cua-vmm/Cargo.toml b/libs/cua/crates/cua-vmm/Cargo.tomlindex 05a7aaa478..353306d8fa 100644--- a/libs/cua/crates/cua-vmm/Cargo.toml+++ b/libs/cua/crates/cua-vmm/Cargo.toml@@ -18,6 +18,7 @@ container = ["dep:bollard", "dep:bytes"]# Scratch file for the disk-architecture probe (qemu-img dd).tempfile = "3"async-trait = "0.1"+cua-create-failure.workspace = truebase64 = "0.22"bollard = { version = "0.21", optional = true }bytes = { version = "1", optional = true }diff --git a/libs/cua/crates/cua-vmm/src/lib.rs b/libs/cua/crates/cua-vmm/src/lib.rsindex f3521f4123..222643bc1f 100644--- a/libs/cua/crates/cua-vmm/src/lib.rs+++ b/libs/cua/crates/cua-vmm/src/lib.rs@@ -34,6 +34,7 @@ pub mod local_network;#[cfg(feature = "lume")]pub mod lume;pub mod managed;+pub mod preflight;pub mod probe;pub mod progress;#[cfg(feature = "qemu")]diff --git a/libs/cua/crates/cua-vmm/src/preflight.rs b/libs/cua/crates/cua-vmm/src/preflight.rsnew file mode 100644index 0000000000..ccad8c48bc--- /dev/null+++ b/libs/cua/crates/cua-vmm/src/preflight.rs@@ -0,0 +1,205 @@+//! Preflight for a local create: gathers what the machine has and hands it+//! to [`cua_create_failure::preflight::evaluate`], which words the result.+//!+//! Read-only and quick (a free-space call, a socket connect, a file+//! check, and on a Mac one connect to a running macOS VM). Nothing here+//! installs, starts or changes anything.++use std::collections::BTreeMap;++use cua_create_failure::preflight::{+ self as pf, Engine, Facts, Guest, Host, Issue, Request, Runs, VirtGap,+};++use crate::disk::{CONTAINER_PULL_ESTIMATE, GIB, LUME_PULL_ESTIMATE, VM_CREATE_ESTIMATE};+use crate::types::GuestOs;++/// A Windows VM image and its disk: bigger than a Linux VM's.+pub const WINDOWS_VM_ESTIMATE: u64 = 20 * GIB;++/// Bytes a create writes when the image's size is not known up front.+pub fn estimate(guest: Guest, runs: Runs) -> u64 {+ match (guest, runs) {+ (Guest::Macos, _) => LUME_PULL_ESTIMATE,+ (Guest::Windows, _) => WINDOWS_VM_ESTIMATE,+ (Guest::Linux, Runs::Container) => CONTAINER_PULL_ESTIMATE,+ (Guest::Linux, Runs::Vm) => VM_CREATE_ESTIMATE,+ }+}++/// The guest as the preflight words it.+pub fn guest_of(os: GuestOs) -> Guest {+ match os {+ GuestOs::Linux => Guest::Linux,+ GuestOs::Macos => Guest::Macos,+ GuestOs::Windows => Guest::Windows,+ }+}++/// Whether a missing or stopped container engine stops a Linux container+/// create here. On a Mac the built-in Linux runtime stands in, unless the+/// setting says to use only the Mac's own engine.+pub fn engine_required() -> bool {+ !cfg!(target_os = "macos")+ || crate::managed::LinuxSource::current() == crate::managed::LinuxSource::System+}++/// What is about to be created. `needed_bytes`: the image's size when known,+/// else [`estimate`].+pub fn request(guest: Guest, runs: Runs, needed_bytes: Option<u64>) -> Request {+ Request {+ host: Host::current(),+ guest,+ runs,+ needed_bytes: needed_bytes.unwrap_or_else(|| estimate(guest, runs)),+ min_free_bytes: crate::disk::CacheConfig::load().min_free,+ }+}++/// Finds what `req` needs to know about this machine.+pub async fn gather(req: &Request) -> Facts {+ let mut facts = Facts {+ free_bytes: crate::disk::space(&crate::host::cua_home())+ .ok()+ .map(|s| s.available),+ ..Default::default()+ };+ if req.runs == Runs::Container && engine_required() {+ facts.engine = engine().await;+ }+ if req.runs == Runs::Vm {+ facts.virtualization = virtualization(req.host);+ }+ if req.host == Host::Macos && req.guest == Guest::Macos {+ facts.local_network_blocked = local_network_blocked().await;+ }+ facts+}++/// The failed checks for creating `req` here, most important first. Empty:+/// go ahead.+pub async fn check(req: &Request) -> Vec<Issue> {+ pf::evaluate(req, &gather(req).await)+}++/// [`check`] for the Spaces a shell can offer, by name (`linux_container`,+/// `linux_vm`, `macos_vm`, `windows_vm`), with the image sizes estimated.+/// Hosts that cannot run a Space (a macOS guest off a Mac) are left out.+/// The daemon puts this in its runtime doctor report under `preflight`, so+/// every app and the CLI read it from one place.+pub async fn report() -> BTreeMap<String, Vec<Issue>> {+ let mut out = BTreeMap::new();+ for (name, guest, runs) in [+ ("linux_container", Guest::Linux, Runs::Container),+ ("linux_vm", Guest::Linux, Runs::Vm),+ ("macos_vm", Guest::Macos, Runs::Vm),+ ("windows_vm", Guest::Windows, Runs::Vm),+ ] {+ if guest == Guest::Macos && Host::current() != Host::Macos {+ continue;+ }+ let req = request(guest, runs, None);+ // The image's real size is unknown here and it may already be on+ // disk, so a guess must not block a create that would work: the+ // create's own disk guards decide.+ let mut facts = gather(&req).await;+ facts.free_bytes = None;+ out.insert(name.to_string(), pf::evaluate(&req, &facts));+ }+ out+}++async fn engine() -> Engine {+ #[cfg(feature = "container")]+ {+ use crate::container::engine::{SocketCheck, check_socket, discover, stopped_context};+ let Some(ep) = discover() else {+ return if stopped_context().is_some() {+ Engine::NotRunning+ } else {+ Engine::Missing+ };+ };+ match check_socket(&ep.uri).await {+ Some(SocketCheck::Missing | SocketCheck::NotListening) => Engine::NotRunning,+ Some(SocketCheck::PermissionDenied) => Engine::PermissionDenied,+ Some(SocketCheck::Accepting | SocketCheck::Other(_)) | None => Engine::Ready,+ }+ }+ #[cfg(not(feature = "container"))]+ {+ Engine::NotChecked+ }+}++fn virtualization(host: Host) -> Option<VirtGap> {+ match host {+ Host::Windows => {+ windows_hypervisor_platform_off().then_some(VirtGap::HypervisorPlatformOff)+ }+ Host::Linux => match crate::host::kvm_usable() {+ Ok(()) => None,+ Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {+ Some(VirtGap::KvmPermission)+ }+ Err(_) => Some(VirtGap::KvmMissing),+ },+ Host::Macos => None,+ }+}++/// QEMU's `whpx` accelerator needs the Windows Hypervisor Platform feature,+/// whose library (`WinHvPlatform.dll`) is only in System32 when it is on.+fn windows_hypervisor_platform_off() -> bool {+ if !cfg!(windows) {+ return false;+ }+ let root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());+ !std::path::Path::new(&root)+ .join("System32")+ .join("WinHvPlatform.dll")+ .exists()+}++async fn local_network_blocked() -> bool {+ #[cfg(feature = "lume")]+ {+ matches!(+ crate::local_network::probe(&crate::local_network::lume_base()).await,+ crate::local_network::Probe::Blocked { .. }+ )+ }+ #[cfg(not(feature = "lume"))]+ {+ false+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn estimates_grow_with_the_guest() {+ assert!(estimate(Guest::Macos, Runs::Vm) > estimate(Guest::Windows, Runs::Vm));+ assert!(estimate(Guest::Windows, Runs::Vm) > estimate(Guest::Linux, Runs::Vm));+ assert!(estimate(Guest::Linux, Runs::Vm) > estimate(Guest::Linux, Runs::Container));+ }++ #[test]+ fn the_request_uses_the_images_size_when_known() {+ let r = request(Guest::Linux, Runs::Container, Some(3 * GIB));+ assert_eq!(r.needed_bytes, 3 * GIB);+ assert_eq!(+ request(Guest::Linux, Runs::Container, None).needed_bytes,+ CONTAINER_PULL_ESTIMATE+ );+ }++ #[tokio::test]+ async fn the_report_names_every_space_this_host_can_run() {+ let r = report().await;+ assert!(r.contains_key("linux_container") && r.contains_key("windows_vm"));+ assert_eq!(r.contains_key("macos_vm"), cfg!(target_os = "macos"));+ }+}diff --git a/libs/images/tools/cua-image-pack/Cargo.lock b/libs/images/tools/cua-image-pack/Cargo.lockindex 7054a1d506..2f151dc89a 100644--- a/libs/images/tools/cua-image-pack/Cargo.lock+++ b/libs/images/tools/cua-image-pack/Cargo.lock@@ -336,6 +336,13 @@ dependencies = ["hybrid-array",]+[[package]]+name = "cua-create-failure"+version = "0.1.0"+dependencies = [+ "serde",+]+[[package]]name = "cua-image"version = "0.1.0"@@ -378,6 +385,7 @@ dependencies = ["base64 0.22.1","bollard","bytes",+ "cua-create-failure","filetime","futures","libc",diff --git a/tests/e2e/cua-sdk/rust/Cargo.lock b/tests/e2e/cua-sdk/rust/Cargo.lockindex 722a832124..27dc4d1d4f 100644--- a/tests/e2e/cua-sdk/rust/Cargo.lock+++ b/tests/e2e/cua-sdk/rust/Cargo.lock@@ -1291,6 +1291,9 @@ dependencies = [[[package]]name = "cua-create-failure"version = "0.1.0"+dependencies = [+ "serde",+][[package]]name = "cua-daemon"@@ -1300,6 +1303,7 @@ dependencies = ["base64 0.22.1","bytes","cua-byoc",+ "cua-create-failure","cua-disk","cua-home","cua-host",@@ -1660,6 +1664,7 @@ dependencies = ["base64 0.22.1","bollard","bytes",+ "cua-create-failure","filetime","futures","libc",diff --git a/tests/e2e/local-runtimes/Cargo.lock b/tests/e2e/local-runtimes/Cargo.lockindex 108af6ba4d..9e6f807320 100644--- a/tests/e2e/local-runtimes/Cargo.lock+++ b/tests/e2e/local-runtimes/Cargo.lock@@ -666,6 +666,9 @@ dependencies = [[[package]]name = "cua-create-failure"version = "0.1.0"+dependencies = [+ "serde",+][[package]]name = "cua-daemon"@@ -674,6 +677,7 @@ dependencies = ["async-trait","base64 0.22.1","bytes",+ "cua-create-failure","cua-disk","cua-home","cua-image",@@ -1001,6 +1005,7 @@ dependencies = ["base64 0.22.1","bollard","bytes",+ "cua-create-failure","filetime","futures","libc",