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): refuse a Windows VM create without QEMU before the 6 GB pull (CUA-1761) (#5294)

Francesco Bonaccie16a462d854b
diff --git a/apps/cua-spaces/src/components/desktop/NewSpaceWizard.test.tsx b/apps/cua-spaces/src/components/desktop/NewSpaceWizard.test.tsx
index 14fbe6255a..b06b4f5678 100644
--- a/apps/cua-spaces/src/components/desktop/NewSpaceWizard.test.tsx
+++ b/apps/cua-spaces/src/components/desktop/NewSpaceWizard.test.tsx
@@ -156,7 +156,7 @@ describe("the image field", () => {
describe("New Space wizard", () => {
it("walks System, Resources, Options, Summary and creates a local VM with its resources", () => {
- const { onCreate } = renderWizard();
+ const { onCreate } = renderWizard({ localBackends: ["docker", "lume", "qemu"] });
expect(screen.getByRole("list", { name: "Steps" })).toHaveTextContent(
"1System2Resources3Options4Summary",
);
@@ -339,7 +339,7 @@ describe("the Resources step", () => {
});
it("grows a Linux VM's disk with a slider and creates with it", () => {
- const { onCreate } = renderWizard({ hostArch: "arm64", storage: storage() });
+ const { onCreate } = renderWizard({ hostArch: "arm64", storage: storage(), localBackends: ["docker", "lume", "qemu"] });
fireEvent.change(imageField(), { target: { value: "ghcr.io/trycua/linux:24.04-disk" } });
runOn("local");
next();
@@ -369,7 +369,7 @@ describe("the Resources step", () => {
});
it("warns that an image without a build for this Mac runs emulated, locally only", () => {
- renderWizard({ hostArch: "arm64", storage: storage() });
+ renderWizard({ hostArch: "arm64", storage: storage(), localBackends: ["docker", "lume", "qemu"] });
fireEvent.change(imageField(), { target: { value: "ghcr.io/trycua/omarchy:edge" } });
runOn("local");
next();
@@ -441,6 +441,44 @@ describe("local runtime readiness", () => {
});
});
+describe("QEMU VMs", () => {
+ const continueButton = () => screen.getByRole("button", { name: "Continue" });
+ const pick = (ref: string) => fireEvent.change(imageField(), { target: { value: ref } });
+
+ it("are not offered while the runtimes are unknown; containers and Lume still are", () => {
+ renderWizard();
+ runOn("local");
+ pick("ghcr.io/trycua/windows:2022");
+ expect(continueButton()).toBeDisabled();
+ expect(screen.getByRole("alert")).toHaveTextContent("cannot run QEMU Spaces");
+ pick("ghcr.io/trycua/linux:24.04-disk");
+ expect(continueButton()).toBeDisabled();
+ pick("ghcr.io/trycua/linux:24.04");
+ expect(continueButton()).toBeEnabled();
+ pick("ghcr.io/trycua/macos:26");
+ expect(continueButton()).toBeEnabled();
+ });
+
+ it("need QEMU among the ready runtimes", () => {
+ renderWizard({ localBackends: ["docker", "lume"] });
+ runOn("local");
+ pick("ghcr.io/trycua/windows:2022");
+ expect(continueButton()).toBeDisabled();
+ expect(screen.getByRole("alert")).toHaveTextContent("cannot run QEMU Spaces");
+ pick("ghcr.io/trycua/macos:26");
+ expect(continueButton()).toBeEnabled();
+ pick("ghcr.io/trycua/linux:24.04");
+ expect(continueButton()).toBeEnabled();
+ });
+
+ it("are offered once QEMU is ready", () => {
+ renderWizard({ localBackends: ["docker", "qemu"] });
+ runOn("local");
+ pick("ghcr.io/trycua/windows:2022");
+ expect(continueButton()).toBeEnabled();
+ });
+});
+
describe("default placement", () => {
it("starts on This Mac when not signed in but a local runtime is ready, even if that is known late", () => {
const props: NewSpaceWizardProps = {
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/create-resources.json b/libs/cua/crates/cua-spaces-app-core/parity/create-resources.json
index b75a827454..ceb9f9809e 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/create-resources.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/create-resources.json
@@ -6,7 +6,7 @@
"cloudAvailable": true,
"localAvailable": true,
"localReason": null,
- "localBackends": null,
+ "localBackends": ["docker", "lume", "qemu"],
"nameSeed": 42,
"maxCpus": 8,
"hostArch": "arm64",
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 b3ac0d9932..8de32c9af8 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
@@ -764,6 +764,9 @@ pub enum FailureCause {
/// The image download stopped partway: Lume's pull failed or was
/// cancelled, or Lume stopped. Another try resumes it.
PullStopped,
+ /// The VM's runtime is not on this machine (QEMU for a Windows or Linux
+ /// VM on a PC without it): trying again does not help.
+ RuntimeMissing,
}
impl FailureCause {
@@ -779,6 +782,7 @@ impl FailureCause {
Self::Unauthenticated => "Unauthenticated",
Self::ServiceTimeout | Self::PullTimeout => "Timeout",
Self::PullStopped => "ImagePull",
+ Self::RuntimeMissing => "RuntimeMissing",
}
}
}
@@ -827,6 +831,12 @@ pub fn failure_cause(raw: &str, phase: Option<&str>, gpu: bool) -> Option<Failur
if l.contains(PULL_STOPPED) {
return Some(FailureCause::PullStopped);
}
+ // The SDK's `VmmError::Missing` for QEMU: "QEMU (qemu-system-x86_64,
+ // qemu-img) is not available: ...", or older SDKs' "qemu-img is not
+ // available: ..." after the image was pulled.
+ if l.contains("qemu") && (l.contains("is not available") || l.contains("not found on path")) {
+ return Some(FailureCause::RuntimeMissing);
+ }
let timed_out =
l.contains("timed out") || l.contains("timeout") || l.contains("not ready after");
if l.contains("cua-spacesd did not answer within ") {
@@ -943,7 +953,7 @@ pub fn failure_text_on(
Some(FailureCause::PullTimeout) => "The image download did not finish in the time \
allowed. Check your internet connection, then try again."
.into(),
- None => plain,
+ Some(FailureCause::RuntimeMissing) | None => plain,
}
}
@@ -2468,6 +2478,24 @@ mod tests {
failure_variant(stopped, Some("pulling"), false, "Runtime"),
"ImagePull"
);
+ // QEMU missing on a Windows PC: 0.9.2's after the pull, and the
+ // refusal before it. Not `other` in telemetry, and the SDK's words.
+ for raw in [
+ "local runtime: [local] qemu-img is not available: install QEMU (macOS: `brew \
+ install qemu`; Debian/Ubuntu: `apt install qemu-utils`)",
+ "local runtime: [local] QEMU (qemu-system-x86_64, qemu-img) is not available: \
+ Windows VMs on a Windows PC need QEMU, which Cua does not install for you.",
+ ] {
+ assert_eq!(
+ failure_cause(raw, Some("pulling"), false),
+ Some(FailureCause::RuntimeMissing),
+ "{raw}"
+ );
+ assert_eq!(
+ failure_variant(raw, Some("pulling"), false, "Other"),
+ "RuntimeMissing"
+ );
+ }
// Local Network privacy on the Mac that runs the VM.
let sdk = "Local Network access is not available: cua cannot reach the VM at \
192.168.64.45:3211 (No route to host (os error 65)). macOS blocks an app's \
diff --git a/libs/cua/crates/cua-spaces-app-core/src/wizard.rs b/libs/cua/crates/cua-spaces-app-core/src/wizard.rs
index 1879db54f4..03afb1937a 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/wizard.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/wizard.rs
@@ -834,14 +834,17 @@ fn local_engine_detail(image: &SandboxImage, env: &WizardEnv) -> Option<String>
})
}
-/// This Mac can run `image` now: a local runtime answers, and (when the
-/// doctor's list is known) one of the image's engines is among them.
+/// This Mac can run `image` now: a local runtime answers, and one of the
+/// image's engines is among the doctor's ready ones. While that list is not
+/// known, every engine counts as ready except QEMU: the app never installs
+/// it (a Windows PC has no way to), and a Windows VM's image is gigabytes
+/// that would download only for the create to fail.
fn local_ready(image: &SandboxImage, env: &WizardEnv) -> bool {
env.local_available
- && env
- .local_backends
- .as_ref()
- .is_none_or(|b| local_runtime_ready(image, b))
+ && match env.local_backends.as_ref() {
+ Some(b) => local_runtime_ready(image, b),
+ None => image.local != Some(LocalEngine::Qemu),
+ }
}
/// The first machine of yours that can run `image` now (online, not at a
@@ -3612,6 +3615,69 @@ mod tests {
}
}
+ /// A Windows VM runs on QEMU, which the app never installs: on a PC
+ /// without it (or before the doctor answered) the Windows image is not
+ /// offered here, so nothing downloads gigabytes only to fail.
+ #[test]
+ fn a_windows_vm_needs_qemu_ready_here() {
+ let image = "ghcr.io/trycua/windows:2022";
+ let blocked = |e: &WizardEnv| {
+ let s = reduce(
+ &initial(e),
+ &WizardAction::ChooseImage {
+ image_ref: image.into(),
+ },
+ e,
+ );
+ let s = reduce(&s, &WizardAction::ChoosePlacement { on: "local".into() }, e);
+ let v = view_on(&s, e, SpaceOs::Windows);
+ assert_eq!(v.image.image_ref, image);
+ (!v.can_continue).then(|| v.placement_error.unwrap_or_default())
+ };
+ let unknown = WizardEnv {
+ local_backends: None,
+ ..env()
+ };
+ assert_eq!(
+ blocked(&unknown).as_deref(),
+ Some("This PC cannot run QEMU Spaces.")
+ );
+ // Docker Desktop is up, QEMU is not: the doctor's reason.
+ let docker_only = WizardEnv {
+ local_backends: Some(vec!["container".into()]),
+ local_details: Some(
+ [(
+ "qemu".to_string(),
+ "QEMU not found; missing: qemu-system-x86_64 / qemu-img".to_string(),
+ )]
+ .into(),
+ ),
+ ..env()
+ };
+ assert_eq!(
+ blocked(&docker_only).as_deref(),
+ Some(
+ "This PC cannot run QEMU Spaces: QEMU not found; missing: qemu-system-x86_64 \
+ / qemu-img."
+ )
+ );
+ // A Linux container is still offered with the same env.
+ let linux = reduce(
+ &initial(&unknown),
+ &WizardAction::ChooseImage {
+ image_ref: "ghcr.io/trycua/linux:24.04".into(),
+ },
+ &unknown,
+ );
+ assert!(view_on(&linux, &unknown, SpaceOs::Windows).can_continue);
+ // QEMU ready: Windows is offered.
+ let qemu = WizardEnv {
+ local_backends: Some(vec!["qemu".into()]),
+ ..env()
+ };
+ assert_eq!(blocked(&qemu), None);
+ }
+
/// A container image on a Mac whose container engine is not ready says
/// why (the runtime doctor's detail), not only that it cannot.
#[test]
@@ -3870,7 +3936,10 @@ mod tests {
#[test]
fn a_linux_vm_disk_grows_with_the_slider() {
- let e = storage_env();
+ let e = WizardEnv {
+ local_backends: Some(vec!["qemu".into()]),
+ ..storage_env()
+ };
let mut s = on("ghcr.io/trycua/linux:24.04-disk", &e);
let v = view(&s, &e);
let p = sizes("ghcr.io/trycua/linux:24.04-disk", "arm64");
diff --git a/libs/cua/crates/cua-vmm/src/qemu/mod.rs b/libs/cua/crates/cua-vmm/src/qemu/mod.rs
index 785007626f..100600219d 100644
--- a/libs/cua/crates/cua-vmm/src/qemu/mod.rs
+++ b/libs/cua/crates/cua-vmm/src/qemu/mod.rs
@@ -53,6 +53,10 @@ pub struct QemuConfig {
pub vnc: bool,
/// Override the accelerator (`hvf`/`kvm`/`whpx`/`tcg`); auto when `None`.
pub accel: Option<String>,
+ /// Refuse a new instance before its image is pulled when
+ /// `qemu-system-<arch>` or `qemu-img` is missing (a VM image can be
+ /// gigabytes, and neither tool is optional).
+ pub preflight_tools: bool,
}
impl Default for QemuConfig {
@@ -64,6 +68,7 @@ impl Default for QemuConfig {
graceful_stop: Duration::from_secs(30),
vnc: true,
accel: None,
+ preflight_tools: true,
}
}
}
@@ -279,6 +284,19 @@ impl QemuRuntime {
))
}
+ /// `qemu-system-<arch>` and `qemu-img` are on this host (installed
+ /// first when allowed), checked before a new instance pulls anything.
+ async fn ensure_tools(&self, arch: Arch) -> Result<()> {
+ let os = host::HostOs::current();
+ if missing_tools(arch, os, host::which).is_none() {
+ return Ok(());
+ }
+ if self.cfg.allow_install {
+ install_qemu().await?;
+ }
+ missing_tools(arch, os, host::which).map_or(Ok(()), Err)
+ }
+
fn accel_for(&self, arch: Arch, kvm: &std::io::Result<()>) -> Result<String> {
if let Some(accel) = &self.cfg.accel {
return Ok(accel.clone());
@@ -893,6 +911,40 @@ fn unique_suffix() -> String {
format!("{nanos:x}")
}
+/// How QEMU gets onto a Windows host: cua does not install it there.
+pub const WINDOWS_QEMU_HINT: &str = "Windows VMs on a Windows PC need QEMU, which Cua does not \
+ install for you. Install QEMU for Windows from https://qemu.weilnetz.de/ and add it to PATH, \
+ or create a Linux Space instead";
+
+/// What a QEMU VM needs that `which` does not find on an `os` host, as the
+/// error a create returns before pulling its image; `None` when both
+/// `qemu-system-<arch>` and `qemu-img` are there.
+fn missing_tools(
+ arch: Arch,
+ os: host::HostOs,
+ which: impl Fn(&str) -> Option<PathBuf>,
+) -> Option<VmmError> {
+ let system = format!("qemu-system-{}", arch.qemu());
+ let missing: Vec<&str> = [system.as_str(), "qemu-img"]
+ .into_iter()
+ .filter(|t| which(t).is_none())
+ .collect();
+ if missing.is_empty() {
+ return None;
+ }
+ let hint = match os {
+ host::HostOs::Windows => WINDOWS_QEMU_HINT.to_string(),
+ _ => format!(
+ "install QEMU (macOS: `brew install qemu`; {})",
+ QemuPackageManager::linux_hint()
+ ),
+ };
+ Some(VmmError::missing(
+ format!("QEMU ({})", missing.join(", ")),
+ hint,
+ ))
+}
+
/// Install QEMU through the host package manager (explicit opt-in).
pub async fn install_qemu() -> Result<()> {
match host::HostOs::current() {
@@ -917,10 +969,7 @@ pub async fn install_qemu() -> Result<()> {
}
}
host::HostOs::Windows => {
- return Err(VmmError::missing(
- "QEMU",
- "download QEMU for Windows from https://qemu.weilnetz.de/ and put it on PATH",
- ));
+ return Err(VmmError::missing("QEMU", WINDOWS_QEMU_HINT));
}
}
Ok(())
@@ -1026,6 +1075,9 @@ impl Runtime for QemuRuntime {
crate::disk::GIB,
&format!("create VM {}", spec.name),
)?;
+ if self.cfg.preflight_tools {
+ self.ensure_tools(spec.effective_arch()).await?;
+ }
let (backing, iso) = match &spec.image {
ImageSource::Existing => return Err(VmmError::NotFound(spec.name.clone())),
ImageSource::Disk { path }
@@ -1506,6 +1558,7 @@ mod tests {
let r = QemuRuntime::new(QemuConfig {
root: tmp.path().to_path_buf(),
resolver: Some(seen.clone()),
+ preflight_tools: false,
..Default::default()
});
let mut spec = StartSpec::new("p1", ImageSource::oci("ghcr.io/me/private:1"));
@@ -1607,6 +1660,7 @@ mod tests {
let r = QemuRuntime::new(QemuConfig {
root: tmp.path().to_path_buf(),
resolver: Some(resolver.clone()),
+ preflight_tools: false,
..Default::default()
});
let min_free = crate::disk::CacheConfig::load().min_free;
@@ -1644,6 +1698,56 @@ mod tests {
);
}
+ #[test]
+ fn missing_qemu_tools_name_what_is_missing_with_a_host_hint() {
+ use host::HostOs;
+ let none = |_: &str| None;
+ let all = |t: &str| Some(PathBuf::from(t));
+ assert!(missing_tools(Arch::X86_64, HostOs::Windows, all).is_none());
+ // A Windows PC: nothing cua can install; says how, and the way out.
+ let err = missing_tools(Arch::X86_64, HostOs::Windows, none).unwrap();
+ assert!(matches!(err, VmmError::Missing { .. }), "{err}");
+ assert_eq!(
+ err.to_string(),
+ format!("QEMU (qemu-system-x86_64, qemu-img) is not available: {WINDOWS_QEMU_HINT}")
+ );
+ assert!(err.to_string().contains("create a Linux Space"));
+ // Only qemu-img missing (a bare qemu-system on PATH).
+ let no_img = |t: &str| (t != "qemu-img").then(|| PathBuf::from(t));
+ let err = missing_tools(Arch::X86_64, HostOs::Linux, no_img).unwrap();
+ assert!(
+ err.to_string()
+ .starts_with("QEMU (qemu-img) is not available: install QEMU")
+ );
+ assert!(err.to_string().contains("brew install qemu"));
+ }
+
+ #[tokio::test]
+ async fn a_new_vm_without_qemu_fails_before_its_image_is_pulled() {
+ let os = host::HostOs::current();
+ if missing_tools(Arch::host(), os, host::which).is_none() {
+ eprintln!("QEMU is installed here; the refusal is covered by missing_tools");
+ return;
+ }
+ let tmp = tempfile::tempdir().unwrap();
+ let resolver = Arc::new(CountingResolver(Default::default()));
+ let r = QemuRuntime::new(QemuConfig {
+ root: tmp.path().to_path_buf(),
+ resolver: Some(resolver.clone()),
+ ..Default::default()
+ });
+ let mut spec = StartSpec::new("win", ImageSource::oci("ghcr.io/trycua/windows:2022"));
+ spec.os = GuestOs::Windows;
+ let err = r.start(&spec).await.unwrap_err();
+ assert!(matches!(err, VmmError::Missing { .. }), "{err}");
+ assert_eq!(
+ resolver.0.load(std::sync::atomic::Ordering::SeqCst),
+ 0,
+ "nothing is pulled"
+ );
+ assert!(matches!(r.load("win"), Err(VmmError::NotFound(_))));
+ }
+
#[test]
fn missing_qemu_hints_show_the_install_plan() {
assert_eq!(