Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(sandbox): report the live status of local VMs in sandbox ls (#4657)
Francesco Bonacci9db2208f9424
diff --git a/libs/cua/crates/cua-sandbox-core/src/sandbox.rs b/libs/cua/crates/cua-sandbox-core/src/sandbox.rsindex 0f7d7c8d47..c08e19b72f 100644--- a/libs/cua/crates/cua-sandbox-core/src/sandbox.rs+++ b/libs/cua/crates/cua-sandbox-core/src/sandbox.rs@@ -2149,21 +2149,27 @@ impl Sandboxes {}if let Some(rt) = &self.inner.local {let listed = rt.list().await?;- // Local state files whose VM or container is gone: `missing`,- // so `ls` shows the stale record and `rm` clears it. Only a- // definite not-found counts; an unreachable engine keeps the- // recorded status.+ // Local state files the backend listing leaves out (a Lume VM,+ // or a VM or container that is gone) get their live status: the+ // recorded one is what the last lifecycle call wrote, and a host+ // reboot stops a VM without updating it. A definite not-found is+ // `missing`, so `ls` shows the stale record and `rm` clears it;+ // an unreachable engine keeps the recorded status.for s in self.inner.state.list_all() {if provider_of(&s) != ProviderKind::Local|| listed.iter().any(|i| i.name == s.name()){continue;}- if let Err(crate::RuntimeError::NotFound(_)) =- rt.status_on(s.name(), s.runtime_type()).await- && let Some(row) = out.get_mut(&state_ref(&s).to_string())- {- row.status = Status::Unknown(MISSING.into());+ let Some(row) = out.get_mut(&state_ref(&s).to_string()) else {+ continue;+ };+ match rt.status_on(s.name(), s.runtime_type()).await {+ Ok(live) => row.status = live.into(),+ Err(crate::RuntimeError::NotFound(_)) => {+ row.status = Status::Unknown(MISSING.into());+ }+ Err(_) => {}}}for i in listed {diff --git a/libs/cua/crates/cua-sandbox-core/tests/stale_records.rs b/libs/cua/crates/cua-sandbox-core/tests/stale_records.rsindex 349e6248fc..d3ca10b2da 100644--- a/libs/cua/crates/cua-sandbox-core/tests/stale_records.rs+++ b/libs/cua/crates/cua-sandbox-core/tests/stale_records.rs@@ -19,6 +19,8 @@ use std::{struct Runtime {instances: Mutex<HashMap<String, InstanceStatus>>,unreachable: Vec<String>,+ /// Instances `list` leaves out (the daemon's listing has no Lume VMs).+ unlisted: Vec<String>,}#[async_trait]@@ -45,6 +47,7 @@ impl LocalRuntime for Runtime {.lock().unwrap().iter()+ .filter(|(n, _)| !self.unlisted.contains(n)).map(|(n, s)| LocalSummary {name: n.clone(),backend: "qemu".into(),@@ -150,6 +153,32 @@ async fn an_unreachable_engine_is_not_reported_missing() {assert_eq!(status_of(&list, "cua-e2e-maybe"), Status::Running);}+/// After a host reboot the state file still says `running`, but the VM is+/// stopped. A VM the backend listing leaves out (Lume) is listed with the+/// status its engine reports, not the recorded one.+#[tokio::test]+async fn a_vm_stopped_by_a_reboot_is_listed_stopped() {+ let dir = tempfile::tempdir().unwrap();+ let rt = Arc::new(Runtime {+ unlisted: vec!["cua-e2e-mac".into()],+ ..Default::default()+ });+ rt.instances+ .lock()+ .unwrap()+ .insert("cua-e2e-mac".into(), InstanceStatus::Stopped);+ let sbx = Sandboxes::builder().local(rt).state_dir(dir.path()).build();+ sbx.state().save(&record("cua-e2e-mac")).unwrap();+ assert_eq!(sbx.state().load("cua-e2e-mac").unwrap().status(), "running");++ let list = sbx.list().await.unwrap();+ assert_eq!(status_of(&list, "cua-e2e-mac"), Status::Stopped);+ assert_eq!(+ sbx.get("cua-e2e-mac").await.unwrap().status,+ Status::Stopped+ );+}+#[tokio::test]async fn an_orphan_instance_without_a_record_deletes() {let dir = tempfile::tempdir().unwrap();diff --git a/libs/cua/crates/cua-vmm/src/lume/mod.rs b/libs/cua/crates/cua-vmm/src/lume/mod.rsindex eaf93935ed..89443dcfc8 100644--- a/libs/cua/crates/cua-vmm/src/lume/mod.rs+++ b/libs/cua/crates/cua-vmm/src/lume/mod.rs@@ -1096,6 +1096,64 @@ pub async fn apply_macos_env(})}+/// How long `lume get` may take when no `lume serve` answers.+const CLI_STATUS_TIMEOUT: Duration = Duration::from_secs(15);++/// A VM's status from `lume get <name> --format json`, for when `lume serve`+/// is not running.+async fn cli_status(bin: &std::path::Path, name: &str) -> Result<Status> {+ let mut cmd = tokio::process::Command::new(bin);+ cmd.args(["get", name, "--format", "json"])+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped())+ .kill_on_drop(true);+ let out = tokio::time::timeout(CLI_STATUS_TIMEOUT, cmd.output())+ .await+ .map_err(|_| VmmError::Timeout {+ name: name.to_string(),+ secs: CLI_STATUS_TIMEOUT.as_secs(),+ detail: format!("lume get {name}"),+ })??;+ parse_cli_get(+ name,+ out.status.success(),+ out.status.code(),+ &String::from_utf8_lossy(&out.stdout),+ &String::from_utf8_lossy(&out.stderr),+ )+}++/// The status in `lume get --format json` output (a one-element array, or+/// an object), or not found when Lume says it has no such VM.+fn parse_cli_get(+ name: &str,+ success: bool,+ code: Option<i32>,+ stdout: &str,+ stderr: &str,+) -> Result<Status> {+ if !success {+ if format!("{stdout}\n{stderr}").contains("not found") {+ return Err(VmmError::NotFound(name.into()));+ }+ return Err(VmmError::Command {+ cmd: format!("lume get {name}"),+ code,+ stderr: crate::exec::tail(stderr, 2000),+ });+ }+ let v: serde_json::Value = serde_json::from_str(stdout.trim())+ .map_err(|e| VmmError::other(format!("lume get {name}: unreadable output: {e}")))?;+ let vm = match &v {+ serde_json::Value::Array(a) => a.iter().find(|vm| vm["name"] == name).or(a.first()),+ o => Some(o),+ };+ vm.and_then(|vm| vm["status"].as_str())+ .map(map_status)+ .ok_or_else(|| VmmError::other(format!("lume get {name}: no status in its output")))+}+fn map_status(s: &str) -> Status {match s {"running" => Status::Running,@@ -1539,12 +1597,19 @@ impl Runtime for LumeRuntime {}async fn status(&self, name: &str) -> Result<Status> {- let vm = self- .client- .get(name)- .await?- .ok_or_else(|| VmmError::NotFound(name.into()))?;- Ok(map_status(&vm.status))+ match self.client.get(name).await {+ Ok(Some(vm)) => Ok(map_status(&vm.status)),+ Ok(None) => Err(VmmError::NotFound(name.into())),+ // No `lume serve` answers (after a reboot it is not running until+ // something starts it). The `lume` CLI reads the VM's state from+ // its directory without a server, so a status check does not have+ // to start one.+ Err(e @ VmmError::Missing { .. }) => match lume_bin() {+ Some(bin) => cli_status(&bin, name).await,+ None => Err(e),+ },+ Err(e) => Err(e),+ }}async fn delete(&self, name: &str) -> Result<()> {@@ -1609,6 +1674,48 @@ impl Runtime for LumeRuntime {mod tests {use super::*;+ #[test]+ fn cli_get_reads_the_status_lume_reports() {+ let stopped = r#"[{"name":"cua-box","status":"stopped","os":"macOS"}]"#;+ assert_eq!(+ parse_cli_get("cua-box", true, Some(0), stopped, "").unwrap(),+ Status::Stopped+ );+ let running = r#"{"name":"cua-box","status":"running"}"#;+ assert_eq!(+ parse_cli_get("cua-box", true, Some(0), running, "").unwrap(),+ Status::Running+ );+ let gone = "Error: Virtual machine not found: cua-box";+ assert!(matches!(+ parse_cli_get("cua-box", false, Some(1), gone, ""),+ Err(VmmError::NotFound(_))+ ));+ assert!(matches!(+ parse_cli_get("cua-box", false, Some(1), "", "permission denied"),+ Err(VmmError::Command { .. })+ ));+ assert!(parse_cli_get("cua-box", true, Some(0), "[]", "").is_err());+ }++ /// A VM stopped by a reboot, asked through the `lume` CLI (a stand-in+ /// script) because no `lume serve` runs.+ #[cfg(unix)]+ #[tokio::test]+ async fn cli_status_runs_lume_get() {+ use std::os::unix::fs::PermissionsExt;+ let dir = tempfile::tempdir().unwrap();+ let bin = dir.path().join("lume");+ std::fs::write(+ &bin,+ "#!/bin/sh\n[ \"$1 $2 $3 $4\" = 'get cua-box --format json' ] || exit 2\n\+ echo '[{\"name\":\"cua-box\",\"status\":\"stopped\"}]'\n",+ )+ .unwrap();+ std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();+ assert_eq!(cli_status(&bin, "cua-box").await.unwrap(), Status::Stopped);+ }+#[test]fn base_names_match_the_python_runtime() {// hashlib.sha256(b"ghcr.io/trycua/macos-sequoia-cua:latest").hexdigest()[:12]