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(agents): an idle agent run on the Cua Volume starts again, and a start that fails says what is missing (CUA-2830) (#6174)
ddupont1e8a8082fdfd
diff --git a/libs/cua/crates/cua-agents/runner/acp-runner.mjs b/libs/cua/crates/cua-agents/runner/acp-runner.mjsindex 6430f63c2c..2a7bbe81da 100644--- a/libs/cua/crates/cua-agents/runner/acp-runner.mjs+++ b/libs/cua/crates/cua-agents/runner/acp-runner.mjs@@ -653,6 +653,41 @@ const keyCheck = checkKey(cfg.keyCheck).catch(() => null);const agentLog = fs.openSync(P("agent.log"), "a");const logStart = fs.fstatSync(agentLog).size;+// Node reports a missing working folder, a missing program and a missing+// shebang interpreter all as `spawn <program> ENOENT`. Say which it is, in+// words a person can act on (the surfaces show this line first).+function spawnProblem(error) {+ if (error?.code !== "ENOENT" && error?.code !== "ENOTDIR") return "";+ let isDir = false;+ try {+ isDir = fs.statSync(cfg.cwd).isDirectory();+ } catch {}+ if (!isDir) {+ return `The working folder ${cfg.cwd} is not available in this Space (a folder on the Cua Volume is missing until the Volume is attached again).`;+ }+ let head = "";+ try {+ const fd = fs.openSync(command, "r");+ try {+ const b = Buffer.alloc(256);+ head = b.toString("utf8", 0, fs.readSync(fd, b, 0, 256, 0));+ } finally {+ fs.closeSync(fd);+ }+ } catch {+ return `${cfg.agent.command} is not installed in this Space.`;+ }+ const m = /^#!\s*(\S+)(?:\s+(\S+))?/.exec(head);+ if (m) {+ const prog = path.basename(m[1]) === "env" && m[2] ? m[2] : m[1];+ const found = prog.includes("/")+ ? fs.existsSync(prog)+ : (env.PATH ?? "").split(path.delimiter).some((d) => d && fs.existsSync(path.join(d, prog)));+ if (!found) return `${prog === "node" ? "Node" : prog} is not installed in this Space.`;+ }+ return "";+}+function diagnostic(error, phase) {const size = fs.fstatSync(agentLog).size;const tail = Buffer.alloc(Math.min(4096, size - logStart));@@ -662,7 +697,10 @@ function diagnostic(error, phase) {} finally {fs.closeSync(fd);}- return redact(`${error?.message ?? error}`+ // macOS reports a missing shebang interpreter as exit 127 from env, not ENOENT.+ const why = phase === "spawn" ? spawnProblem(error) : error?.exit127 ? spawnProblem({ code: "ENOENT" }) : "";+ return redact((why ? `${why}\n` : "")+ + `${error?.message ?? error}`+ (error?.code != null ? ` (code ${error.code})` : "")+ (error?.data != null ? ` ${JSON.stringify(error.data)}` : "")+ ` (${phase}: ${cfg.agent.command})`@@ -686,6 +724,11 @@ let restarts = 0;// start, or closes its stdout (the ACP transport) while still alive.function startAgent() {const myGen = ++gen;+ // The working folder can be gone when a run starts again (it was on a+ // Volume that is not attached yet): make it, or say it is not there.+ try {+ fs.mkdirSync(cfg.cwd, { recursive: true });+ } catch {}const c = spawn(command, cfg.agent.args ?? [], {cwd: cfg.cwd,env,@@ -716,7 +759,7 @@ function startAgent() {function goneDiagnostic(g) {if (g.error) return diagnostic(g.error, "spawn");if (g.stdoutClosed) return diagnostic(new Error("agent stdout closed"), "transport");- return diagnostic(new Error(`the agent exited unexpectedly (code ${g.code}, signal ${g.signal})`), "transport");+ return diagnostic(Object.assign(new Error(`the agent exited unexpectedly (code ${g.code}, signal ${g.signal})`), { exit127: g.code === 127 }), "transport");}// End this run's cua-driver session on the guest MCP (cua-spacesd keys it bydiff --git a/libs/cua/crates/cua-agents/runner/test/spawn-enoent.test.mjs b/libs/cua/crates/cua-agents/runner/test/spawn-enoent.test.mjsnew file mode 100644index 0000000000..52171cbd16--- /dev/null+++ b/libs/cua/crates/cua-agents/runner/test/spawn-enoent.test.mjs@@ -0,0 +1,82 @@+// A run that cannot start says why. Node words a missing working folder, a+// missing program and a missing shebang interpreter all as+// `spawn <program> ENOENT`; the runner names which one it is.+//+// node --test libs/cua/crates/cua-agents/runner/test/+import { test } from "node:test";+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";++const here = path.dirname(fileURLToPath(import.meta.url));++async function startFailure(t, { cwd, command, args = [], env = {}, setup }) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "cua-enoent-"));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const sdk = path.join(root, "node_modules", "@agentclientprotocol", "sdk");+ fs.mkdirSync(sdk, { recursive: true });+ fs.writeFileSync(path.join(sdk, "package.json"), JSON.stringify({ name: "@agentclientprotocol/sdk", type: "module", main: "index.js" }));+ fs.writeFileSync(+ path.join(sdk, "index.js"),+ `const any = new Proxy(function () {}, { get: (_, k) => (k === "then" ? undefined : any), apply: () => any });+ export const ndJsonStream = any, methods = any, PROTOCOL_VERSION = 1, client = any;+ export default any;`,+ );+ fs.copyFileSync(path.join(here, "..", "acp-runner.mjs"), path.join(root, "runner.mjs"));+ const run = path.join(root, "run");+ fs.mkdirSync(run);+ setup?.(root);+ fs.writeFileSync(+ path.join(run, "run.json"),+ JSON.stringify({ cwd: cwd(root), agent: { command: command(root), args }, env: env && Object.fromEntries(Object.entries(env).map(([k, v]) => [k, typeof v === "function" ? v(root) : v])) }),+ );+ const child = spawn(process.execPath, [path.join(root, "runner.mjs"), run], { stdio: "ignore" });+ t.after(() => child.kill("SIGKILL"));+ await new Promise((resolve) => child.on("exit", resolve));+ return JSON.parse(fs.readFileSync(path.join(run, "state.json"), "utf8"));+}++test("a working folder that cannot be made is named, not the program", async (t) => {+ const st = await startFailure(t, {+ cwd: (root) => path.join(root, "gone", "work"),+ command: () => process.execPath,+ args: ["-e", "0"],+ // A file where the parent folder should be: mkdir -p fails.+ setup: (root) => fs.writeFileSync(path.join(root, "gone"), "x"),+ });+ assert.equal(st.status, "failed");+ assert.match(st.error, /^The working folder .*work is not available in this Space/);+});++test("a missing working folder is made again before the agent starts", async (t) => {+ const st = await startFailure(t, {+ cwd: (root) => path.join(root, "again", "work"),+ command: () => process.execPath,+ args: ["-e", "0"],+ });+ assert.doesNotMatch(st.error ?? "", /working folder/);+});++test("a script whose node is not installed says Node is not installed", async (t) => {+ const st = await startFailure(t, {+ cwd: (root) => path.join(root, "run"),+ command: (root) => path.join(root, "agent.js"),+ env: { PATH: (root) => path.join(root, "empty") },+ setup: (root) => {+ fs.mkdirSync(path.join(root, "empty"));+ fs.writeFileSync(path.join(root, "agent.js"), "#!/usr/bin/env node\nconsole.log(1)\n", { mode: 0o755 });+ },+ });+ assert.match(st.error, /^Node is not installed in this Space\./);+});++test("a program that is not there says it is not installed", async (t) => {+ const st = await startFailure(t, {+ cwd: (root) => path.join(root, "run"),+ command: (root) => path.join(root, "nope"),+ });+ assert.match(st.error, /nope is not installed in this Space\./);+});diff --git a/libs/cua/crates/cua-agents/src/failure.rs b/libs/cua/crates/cua-agents/src/failure.rsindex dc1bf63724..729d8a1b8c 100644--- a/libs/cua/crates/cua-agents/src/failure.rs+++ b/libs/cua/crates/cua-agents/src/failure.rs@@ -316,14 +316,60 @@ pub fn plain(f: &Failure, harness: &str) -> String {format!("{name} needs an API key for a provider it can use. Your Claude subscription sign-in only works in Claude Code.")}},- FailureClass::Error => "I couldn't finish that.".into(),+ FailureClass::Error => start_problem(&f.message, harness)+ .unwrap_or_else(|| "I couldn't finish that.".into()),}}+/// A start that failed for a reason the person can act on, from the runner's+/// first line ("Node is not installed in this Space.", "The working folder+/// ... is not available ..."): what is missing, and that Retry sets it up+/// again. `None` for any other error.+fn start_problem(message: &str, harness: &str) -> Option<String> {+ let first = message.lines().next()?.trim();+ let name = crate::harness::harness(harness).map_or("This agent", |h| h.name);+ if first.starts_with("The working folder ") {+ return Some(format!(+ "{name} couldn't start: its working folder isn't available in this Space yet (the Cua Volume isn't attached). Retry attaches it again."+ ));+ }+ if first.ends_with(" is not installed in this Space.") {+ return Some(format!(+ "{name} couldn't start: {first} Retry sets it up again."+ ));+ }+ None+}+#[cfg(test)]mod tests {use super::*;+ #[test]+ fn a_start_that_failed_for_something_missing_says_what() {+ let spawn = "spawn /home/cua/.cua/tools/x/dist/index.js ENOENT (code ENOENT)";+ for (first, want) in [+ (+ "The working folder /volume/agents/ada/work is not available in this Space (a folder on the Cua Volume is missing until the Volume is attached again).",+ "working folder isn't available",+ ),+ (+ "Node is not installed in this Space.",+ "Node is not installed in this Space. Retry sets it up again.",+ ),+ ] {+ let f = classify("claude-code", &format!("{first}\n{spawn}"));+ assert_eq!(f.class, FailureClass::Error);+ assert!(plain(&f, "claude-code").contains(want), "{first}");+ assert!(plain(&f, "claude-code").starts_with("Claude Code couldn't start"));+ }+ // Anything else stays the general sentence.+ assert_eq!(+ plain(&classify("claude-code", spawn), "claude-code"),+ "I couldn't finish that."+ );+ }+#[test]fn auth_failures_in_every_wording_need_a_connect() {for (h, t, p) in [diff --git a/libs/cua/crates/cua-agents/src/harness.rs b/libs/cua/crates/cua-agents/src/harness.rsindex b846412ee7..6cf809e745 100644--- a/libs/cua/crates/cua-agents/src/harness.rs+++ b/libs/cua/crates/cua-agents/src/harness.rs@@ -934,6 +934,51 @@ mod tests {}}+ /// Drift guard: the agent binaries are scripts (`#!/usr/bin/env node`) or+ /// Python entry points, so a Space only starts them when the interpreter+ /// is installed by the launcher itself, not assumed from the image. Every+ /// harness's install list must bring `node` (for npm items) or `uv` (for+ /// git-uv items) before the item, and the generated launcher must install+ /// them, so a public image without Node still starts every harness.+ #[test]+ fn every_harness_installs_the_interpreter_its_launcher_needs() {+ use crate::installables::{Source, get, resolve, script};+ for h in HARNESSES {+ let order = resolve(h.installs).unwrap();+ let pos = |id: &str| order.iter().position(|x| x == id);+ let mut needs_node = false;+ for (i, id) in order.iter().enumerate() {+ let it = get(id).unwrap();+ match &it.how {+ Source::Npm { .. } => {+ needs_node = true;+ assert!(+ pos("node").is_some_and(|n| n < i),+ "{}: {id} before node",+ h.id+ );+ }+ Source::GitUv { .. } => {+ assert!(pos("uv").is_some_and(|n| n < i), "{}: {id} before uv", h.id);+ }+ Source::Archive { .. } => {}+ }+ }+ let sh = script(h.installs).unwrap();+ if needs_node {+ assert!(+ sh.contains("node-v"),+ "{}: the launcher does not install node",+ h.id+ );+ assert!(+ get("node").unwrap().bins.contains_key("node"),+ "node links no `node` into ~/.cua/bin"+ );+ }+ }+ }+#[test]fn endpoints_are_applied_per_wire_and_refused_on_the_wrong_one() {let e = Endpoint {diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rsindex 9f4770eacf..dbfd5941ed 100644--- a/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs@@ -1153,6 +1153,25 @@ impl Persistent {}self.release_writer(&rec).await;}+ // An idle run whose home is not where this agent's home is+ // now (it was on the mounted Volume, which shows the agent's+ // view only while the agent holds it): sending would start+ // its runner again in a folder that is not there. The home+ // is taken first (the Volume shows this agent's view), and a+ // run on another home ends and starts again.+ Ok(st)+ if st.accepts_message+ && st.status == RunStatus::Idle+ && rec.k() == 1+ && self.home_moved(&rec, &st).await =>+ {+ tracing::info!(agent = name, "the run's home moved: starting a fresh run");+ let _ = self.save(name).await;+ if let Err(e) = agents.stop(run).await {+ tracing::warn!(agent = name, "the old run did not stop: {e}");+ }+ self.release_writer(&rec).await;+ }Ok(st) if st.accepts_message && st.status == RunStatus::Idle => {if rec.k() == 1 && !self.live.lock().await.leases.contains_key(name) {self.take_lease(&rec).await?;@@ -1172,6 +1191,28 @@ impl Persistent {Box::pin(self.start_session(&rec, text, entry, None)).await}+ /// Whether the idle run `st` of `rec` works on the mounted Volume in a+ /// home other than the one `rec` has now (or the Volume is not its to+ /// hold). Takes the Volume for the agent when it has one, so a+ /// run on the mounted home finds its folders where it left them.+ async fn home_moved(&self, rec: &AgentRecord, st: &ag::RunInfo) -> bool {+ let Some(cwd) = st.meta.as_ref().map(|m| m.cwd.as_str()) else {+ return false;+ };+ // Only a run on the mounted Volume can lose its folders this way.+ let on_volume = cwd.starts_with("/volume/");+ match self.mounted_home(rec).await {+ Some(m) => on_volume && !Self::in_home(cwd, &m),+ None => on_volume,+ }+ }++ /// Whether `cwd` is `home` or inside it.+ fn in_home(cwd: &str, home: &str) -> bool {+ let home = home.trim_end_matches('/');+ cwd == home || cwd.strip_prefix(home).is_some_and(|r| r.starts_with('/'))+ }+/// Whether the idle run `run` of `rec` must not take another message:/// it was started with other credentials than the ones forwarded now, or/// its last turn failed to authenticate.@@ -2281,6 +2322,20 @@ mod tests {ag::AgentEvent::parse(&line.to_string()).unwrap()}+ #[test]+ fn a_run_in_another_home_is_not_in_this_one() {+ // The run started on the mounted Volume; the Volume is not the+ // agent's now (or the home is copied in): its folders are not there.+ let vol = "/volume/agents/claude-2";+ assert!(Persistent::in_home("/volume/agents/claude-2/work", vol));+ assert!(Persistent::in_home(vol, "/volume/agents/claude-2/"));+ assert!(!Persistent::in_home(+ "/volume/agents/claude-2/work",+ "/home/cua/.cua/homes/claude-2"+ ));+ assert!(!Persistent::in_home("/volume/agents/claude-22/work", vol));+ }+#[test]fn a_failed_turn_is_one_error_not_finished_plus_an_error() {// The runner's failed turn: an error, then turn_ended (stop: error).diff --git a/libs/cua/crates/cua-spaces-ext/tests/thread_compat.rs b/libs/cua/crates/cua-spaces-ext/tests/thread_compat.rsindex 504f16df82..fb836b4396 100644--- a/libs/cua/crates/cua-spaces-ext/tests/thread_compat.rs+++ b/libs/cua/crates/cua-spaces-ext/tests/thread_compat.rs@@ -1322,6 +1322,34 @@ async fn a_changed_credential_ends_the_idle_run_instead_of_reusing_it() {assert!(!run_alive(&fx).await, "the old run was ended");}+/// CUA-2830: an idle run whose working folder is on the mounted Cua Volume+/// can only take a message while the Volume shows the agent's view. A Space+/// without the Volume to hold (it attached again, or has none) ends that run+/// and starts a new one instead of waking a runner in a folder that is gone.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn an_idle_run_on_a_volume_that_is_gone_is_not_woken() {+ let fx = setup().await;+ let (p, _proc) = member_with_idle_run(&fx).await;+ edit_record(&fx, "ada", |r| {+ r["env"] = json!({"ANTHROPIC_API_KEY": "sk-one"})+ });+ let meta = json!({"run_id": RUN, "harness": "claude-code", "prompt": "hi",+ "cwd": "/volume/agents/ada/work", "created_at": 0.0,+ "cred_hash": forwarded_hash("sk-one")});+ fx.srv.state.put_file(+ &format!("{RUNS}/{RUN}/meta.json"),+ meta.to_string().into_bytes(),+ );+ // The mock runs no shell, so the fresh start itself can't finish here.+ let _ = p.send("ada", "again").await;+ assert!(+ inbox(&fx).iter().all(|t| t.is_empty()),+ "the old run was not woken: {:?}",+ inbox(&fx)+ );+ assert!(!run_alive(&fx).await, "the old run was ended");+}+/// A run whose last turn failed to authenticate is not reused either, even/// with the same credentials (the provider rejected them).#[tokio::test(flavor = "multi_thread", worker_threads = 2)]