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(spaces): recognize configured Claude Code without PATH evidence (#5749)
injaneity4ecb58e45b9a
diff --git a/apps/cua-spaces-web/src/__tests__/first-run.test.tsx b/apps/cua-spaces-web/src/__tests__/first-run.test.tsxindex 23de27e4ea..c1961c694d 100644--- a/apps/cua-spaces-web/src/__tests__/first-run.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/first-run.test.tsx@@ -7,14 +7,16 @@// it is ready; a fix left turns Done into Finish later and Home keeps the// to-do list.-import { cleanup, fireEvent, screen, waitFor } from "@testing-library/react";+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { testCore, wasmBuilt } from "@/bridge/__tests__/testCore";+import { BridgeProvider } from "@/bridge";+import { createDemoAdapter } from "@/bridge/adapters/demo";+import { noCore, testCore, wasmBuilt } from "@/bridge/__tests__/testCore";import type { AgentSetupRow } from "@/bridge/contracts/agents";import type { HostStatus } from "@/bridge/contracts/host";import type { NewSpaceOptions } from "@/bridge/contracts/new-space";-import { readFirstRun, resetFirstRunCache, writeFirstRun } from "@/bridge/first-run";+import { readFirstRun, resetFirstRunCache, useFirstRun, writeFirstRun } from "@/bridge/first-run";import { CLOSED_NEW_SPACE, updateNewSpaceSession } from "@/bridge/new-space";import { resetSavedOnboardingCache } from "@/bridge/onboarding";import { mountApp, stubBrowserApis } from "./app-harness";@@ -59,6 +61,42 @@ async function mount(opts: { host?: (h: HostStatus) => HostStatus; local?: (l: Nconst heading = () => document.querySelector("[data-onboarding-heading]")?.textContent ?? "";const primary = () => document.querySelector<HTMLButtonElement>("[data-first-run-primary]");+describe("first-run detection on window focus", () => {+ it("refreshes connected agents without waiting for polling and stops after unmount", async () => {+ writeFirstRun({ step: "setup", agent: "claude-code" });+ const demo = createDemoAdapter({ latencyMs: 0 });+ let reads = 0;+ let latest: AgentSetupRow[] = [];+ const adapter: typeof demo = {+ ...demo,+ call: (async (op, args) => {+ if (op === "agents.setup") {+ reads++;+ return [{ agent: "claude-code", name: "Claude Code", installed: reads < 3, configured: true, detail: "MCP configured", skillsInstalled: 1, skillsTotal: 1, mcpConfig: ".claude.json", skillsDir: ".claude/skills" }];+ }+ return demo.call(op, args);+ }) as typeof demo.call,+ };+ function Probe() {+ latest = useFirstRun(true, 60_000).agents;+ return null;+ }+ const mounted = render(<BridgeProvider adapter={adapter} core={noCore}><Probe /></BridgeProvider>);+ await waitFor(() => expect(latest[0]?.installed).toBe(true));+ const before = reads;+ fireEvent.focus(window);+ await waitFor(() => expect(reads).toBe(before + 1));+ fireEvent.focus(window);+ await waitFor(() => expect(reads).toBe(before + 2));+ await waitFor(() => expect(latest[0]?.installed).toBe(false));+ mounted.unmount();+ const stopped = reads;+ await act(async () => { fireEvent.focus(window); });+ expect(reads).toBe(stopped);+ demo.dispose?.();+ });+});+describe.skipIf(!wasmBuilt)("the first run (real route, wasm core)", () => {it("connects the ticked agents, then says they can use this computer, with Done on", async () => {// Nothing set up yet: every installed agent is ticked.diff --git a/apps/cua-spaces-web/src/__tests__/settings-agents.test.tsx b/apps/cua-spaces-web/src/__tests__/settings-agents.test.tsxindex 8e828693ea..1aacd5f470 100644--- a/apps/cua-spaces-web/src/__tests__/settings-agents.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/settings-agents.test.tsx@@ -6,9 +6,14 @@// all detected agents" in the header (the core's `agents` section over the// host's `agents.setup`); the cua-driver card follows in its own group.-import { cleanup, fireEvent, waitFor, within } from "@testing-library/react";+import { createMemoryHistory, createRootRoute, createRouter, RouterProvider } from "@tanstack/react-router";+import { cleanup, fireEvent, render, waitFor, within } from "@testing-library/react";import { afterEach, describe, expect, it } from "vitest";-import { wasmBuilt } from "@/bridge/__tests__/testCore";+import { BridgeProvider } from "@/bridge";+import { createDemoAdapter } from "@/bridge/adapters/demo";+import { noCore, wasmBuilt } from "@/bridge/__tests__/testCore";+import { ConnectAgentDialog } from "@/components/agents/connect-dialog";+import { RunAgentDialog } from "@/components/agents/run-agent-dialog";import { mountApp, stubBrowserApis } from "./app-harness";afterEach(cleanup);@@ -17,6 +22,33 @@ stubBrowserApis();const section = () => document.querySelector<HTMLElement>('[data-settings-section="agents"]');const row = (agent: string) => section()?.querySelector<HTMLElement>(`[data-setting-row="agent:${agent}"]`) ?? null;+describe("configured agents without binary evidence", () => {+ it.each(["connect", "run"])("shows a configured agent as ready in the %s dialog", async (dialog) => {+ const demo = createDemoAdapter({ latencyMs: 0 });+ const adapter: typeof demo = {+ ...demo,+ call: (async (op, args) => {+ if (op === "agents.setup") return [{ agent: "claude-code", name: "Claude Code", installed: false, configured: true, detail: "skills and MCP configured", skillsInstalled: 1, skillsTotal: 1, mcpConfig: "C:/Users/test/.claude.json", skillsDir: "C:/Users/test/.claude/skills" }];+ return demo.call(op, args);+ }) as typeof demo.call,+ };+ const routeTree = createRootRoute({ component: () => dialog === "connect"+ ? <ConnectAgentDialog open onOpenChange={() => {}} />+ : <RunAgentDialog open onOpenChange={() => {}} space={{ id: "local:test", name: "Test Space", os: "windows", status: "running", detail: "", lastUsedAt: 0, scene: "blank" }} /> });+ const router = createRouter({ routeTree, history: createMemoryHistory({ initialEntries: ["/"] }) });+ const mounted = render(<BridgeProvider adapter={adapter} core={noCore}><RouterProvider router={router} /></BridgeProvider>);+ if (dialog === "connect") {+ await waitFor(() => expect(document.querySelector("li")?.textContent).toContain("Set up"));+ expect(document.querySelector("li")?.textContent).toContain("C:/Users/test/.claude.json");+ expect(document.querySelector("li")?.textContent).not.toContain("Not installed");+ } else {+ await waitFor(() => expect(document.querySelector("[data-run-agent]")?.getAttribute("data-run-agent")).toBe("ready"));+ }+ mounted.unmount();+ demo.dispose?.();+ });+});+describe.skipIf(!wasmBuilt)("Settings, AI agents", () => {it("lists each detected agent with its status, configures one, removes it, and configures all", { timeout: 20_000 }, async () => {await mountApp("/settings", { failsCreates: false, listsGhost: false });diff --git a/apps/cua-spaces-web/src/bridge/first-run.ts b/apps/cua-spaces-web/src/bridge/first-run.tsindex 5089083bce..dea7e77608 100644--- a/apps/cua-spaces-web/src/bridge/first-run.ts+++ b/apps/cua-spaces-web/src/bridge/first-run.ts@@ -349,13 +349,13 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRunif (!active || !adapter) return;let live = true;let n = 0;- const read = () => {+ const read = (forceAgents = false) => {// The agent setup runs a command on the host: once connected, it's read now and then// (every time while an agent's own sign-in waits for the browser).const saved = readFirstRun();const want = saved.picked ?? (saved.agent ? [saved.agent] : []);const connected = saved.step === "setup" && Boolean(agentsRef.current) && want.every((id) => agentsRef.current!.some((a) => a.agent === id && a.configured));- if (signingRef.current || !connected || n++ % 6 === 0) {+ if (forceAgents || signingRef.current || !connected || n++ % 6 === 0) {void adapter.call("agents.setup", {}).then((rows) => live && setAgents(rows))@@ -369,10 +369,13 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRun}};read();- const timer = setInterval(read, pollMs);+ const focus = () => read(true);+ window.addEventListener("focus", focus);+ const timer = setInterval(() => read(), pollMs);return () => {live = false;clearInterval(timer);+ window.removeEventListener("focus", focus);};}, [active, adapter, s.step, s.finishedLater, tick, pollMs]);diff --git a/apps/cua-spaces-web/src/components/agents/connect-dialog.tsx b/apps/cua-spaces-web/src/components/agents/connect-dialog.tsxindex 32dba12585..62bcdb7540 100644--- a/apps/cua-spaces-web/src/components/agents/connect-dialog.tsx+++ b/apps/cua-spaces-web/src/components/agents/connect-dialog.tsx@@ -148,11 +148,11 @@ function SetupRow({ row }: { row: AgentSetupRow }) {<li className="flex items-center gap-3 px-3 py-2"><div className="min-w-0 flex-1"><div className={cn("text-[13px]", !row.installed && "text-muted-foreground")}>{row.name}</div>- {row.installed && row.mcpConfig ? <div className="truncate font-mono text-2xs text-muted-foreground">{row.mcpConfig}</div> : null}+ {(row.installed || row.configured) && row.mcpConfig ? <div className="truncate font-mono text-2xs text-muted-foreground">{row.mcpConfig}</div> : null}</div><span className={cn("inline-flex shrink-0 items-center gap-1 text-xs", row.configured ? "text-foreground" : "text-muted-foreground")}>{row.configured ? <CheckIcon className="size-3.5 text-success" aria-hidden /> : null}- {!row.installed ? "Not installed" : row.configured ? "Set up" : "Not set up"}+ {row.configured ? "Set up" : !row.installed ? "Not installed" : "Not set up"}</span></li>);diff --git a/apps/cua-spaces-web/src/components/agents/run-agent-dialog.tsx b/apps/cua-spaces-web/src/components/agents/run-agent-dialog.tsxindex 35753b3014..10cc104247 100644--- a/apps/cua-spaces-web/src/components/agents/run-agent-dialog.tsx+++ b/apps/cua-spaces-web/src/components/agents/run-agent-dialog.tsx@@ -41,7 +41,7 @@ export function RunAgentDialog({ open, space, onOpenChange, onManual, onConnecte// eslint-disable-next-line react-hooks/exhaustive-deps}, [open]);- const ready = (rows ?? []).filter((r) => r.installed && r.configured);+ const ready = (rows ?? []).filter((r) => r.configured);const pending = (rows ?? []).filter((r) => r.installed && !r.configured);const prompt = asked ?? runAgentPrompt(space.name);const first = ready[0];@@ -52,7 +52,7 @@ export function RunAgentDialog({ open, space, onOpenChange, onManual, onConnecteconfigureAgents().then((r) => {setRows(r);- if (r.some((x) => x.installed && x.configured)) onConnected?.();+ if (r.some((x) => x.configured)) onConnected?.();}).catch((e: unknown) => toast("Couldn't connect your agent", { description: e instanceof Error ? e.message : String(e) })).finally(() => setBusy(false));diff --git a/libs/cua/crates/cua-agent-setup/src/lib.rs b/libs/cua/crates/cua-agent-setup/src/lib.rsindex b938b5753d..41e5dfd3c2 100644--- a/libs/cua/crates/cua-agent-setup/src/lib.rs+++ b/libs/cua/crates/cua-agent-setup/src/lib.rs@@ -137,19 +137,6 @@ pub struct HostEnv {pub run_agent_clis: bool,}-/// Where coding-agent CLIs usually install, searched after `$PATH`.-fn well_known_bin_dirs(home: &Path) -> Vec<PathBuf> {- vec![- home.join(".local/bin"),- home.join(".claude/local"),- home.join(".npm-global/bin"),- home.join(".bun/bin"),- home.join(".cargo/bin"),- PathBuf::from("/opt/homebrew/bin"),- PathBuf::from("/usr/local/bin"),- ]-}-const VARS: &[&str] = &["XDG_CONFIG_HOME","APPDATA",@@ -167,6 +154,32 @@ const VARS: &[&str] = &[];impl HostEnv {+ /// Ordered fallback binary directories for this environment's OS, searched after PATH.+ pub fn well_known_bin_dirs(&self) -> Vec<PathBuf> {+ if self.os == Os::Windows {+ let appdata = self+ .var("APPDATA")+ .map(PathBuf::from)+ .unwrap_or_else(|| self.home.join("AppData/Roaming"));+ vec![+ self.home.join(".local/bin"),+ appdata.join("npm"),+ self.home.join(".bun/bin"),+ self.home.join(".cargo/bin"),+ ]+ } else {+ vec![+ self.home.join(".local/bin"),+ self.home.join(".claude/local"),+ self.home.join(".npm-global/bin"),+ self.home.join(".bun/bin"),+ self.home.join(".cargo/bin"),+ PathBuf::from("/opt/homebrew/bin"),+ PathBuf::from("/usr/local/bin"),+ ]+ }+ }+/// The real environment: `$HOME` (or `%USERPROFILE%`), `$PATH`, the/// agent override variables, `/Applications` and `~/Applications`/// (or `$CUA_AGENT_APP_DIRS`).@@ -180,19 +193,9 @@ impl HostEnv {.filter_map(|k| std::env::var(k).ok().map(|v| (k.to_string(), v))).collect();let os = Os::current();- let mut path: Vec<PathBuf> = std::env::var_os("PATH")+ let path: Vec<PathBuf> = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();- // A GUI app (Cua Spaces from the Dock) runs without the user's- // shell PATH, so an agent installed under a user bin dir would look- // missing. Search the usual install dirs after the real PATH.- if os != Os::Windows {- for d in well_known_bin_dirs(&home) {- if !path.contains(&d) {- path.push(d);- }- }- }// `CUA_AGENT_APP_DIRS` (a path list, empty for none) replaces the// app folders, so hermetic runs do not see the host's apps.let app_dirs = match std::env::var_os("CUA_AGENT_APP_DIRS") {@@ -204,14 +207,23 @@ impl HostEnv {}None => vec![],};- HostEnv {+ let mut env = HostEnv {home,vars,path,app_dirs,os,run_agent_clis: true,+ };+ // A GUI app (Cua Spaces from the Dock) runs without the user's+ // shell PATH, so an agent installed under a user bin dir would look+ // missing. Search the usual install dirs after the real PATH.+ for dir in env.well_known_bin_dirs() {+ if !env.path.contains(&dir) {+ env.path.push(dir);+ }}+ env}/// A hermetic environment rooted at `home`: no variables, no PATH, apps@@ -1418,7 +1430,7 @@ fn run_cli(bin: &Path, args: &[String]) -> Result<()> {#[cfg(test)]mod cmd_shim_tests {- use super::{HostEnv, Os, cmd_shim_target};+ use super::{HostEnv, cmd_shim_target};/// What `npm i -g @anthropic-ai/claude-code` writes (cmd-shim).const NATIVE_SHIM: &str = "@ECHO off\r\nGOTO start\r\n:find_dp0\r\nSET dp0=%~dp0\r\nEXIT /b\r\n:start\r\nSETLOCAL\r\nCALL :find_dp0\r\n\"%dp0%\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe\" %*\r\n";@@ -1439,13 +1451,8 @@ mod cmd_shim_tests {#[test]fn the_current_env_also_searches_the_usual_install_dirs() {let env = HostEnv::current();- if env.os != Os::Windows {- let home = env.home.clone();- assert!(env.path.contains(&home.join(".local/bin")));- assert!(- env.path- .contains(&std::path::PathBuf::from("/opt/homebrew/bin"))- );+ for dir in env.well_known_bin_dirs() {+ assert!(env.path.contains(&dir), "{}", dir.display());}}diff --git a/libs/cua/crates/cua-agent-setup/tests/agents.rs b/libs/cua/crates/cua-agent-setup/tests/agents.rsindex 4174b72a66..8e49c304a7 100644--- a/libs/cua/crates/cua-agent-setup/tests/agents.rs+++ b/libs/cua/crates/cua-agent-setup/tests/agents.rs@@ -55,6 +55,78 @@ impl T {}}+#[test]+fn windows_gui_finds_claude_in_user_install_dirs_without_path() {+ use cua_agent_setup::Os;+ let mut t = T::new();+ t.env.os = Os::Windows;+ assert!(t.env.path.is_empty());+ let exe = t.write(".local/bin/claude.exe", "MZ");+ for suffix in ["exe", "cmd", "bat"] {+ let p = t.write(&format!(".local/bin/claude.{suffix}"), "MZ");+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ assert!(p.is_file());+ }+ assert_eq!(+ t.env.well_known_bin_dirs(),+ vec![+ t.home.join(".local/bin"),+ t.home.join("AppData/Roaming/npm"),+ t.home.join(".bun/bin"),+ t.home.join(".cargo/bin"),+ ]+ );+ let roaming = t.home.join("roaming");+ t.env+ .vars+ .insert("APPDATA".into(), roaming.to_string_lossy().into_owned());+ assert_eq!(t.env.well_known_bin_dirs()[1], roaming.join("npm"));+ t.env.path.extend(t.env.well_known_bin_dirs());+ let claude = t+ .setup()+ .detect()+ .into_iter()+ .find(|a| a.id == "claude-code")+ .unwrap();+ assert!(claude.evidence.contains(&format!("bin:{}", exe.display())));+ assert_eq!(t.env.which("claude"), Some(exe.clone()));+ std::fs::remove_file(exe).unwrap();+ assert_eq!(+ t.env.which("claude"),+ Some(t.home.join(".local/bin/claude.cmd"))+ );+ std::fs::remove_file(t.home.join(".local/bin/claude.cmd")).unwrap();+ assert_eq!(+ t.env.which("claude"),+ Some(t.home.join(".local/bin/claude.bat"))+ );+ t.env.path.insert(0, t.home.join("inherited"));+ let inherited = t.write("inherited/claude.exe", "MZ");+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&inherited, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ assert_eq!(t.env.which("claude"), Some(inherited));+ t.env.os = Os::Linux;+ assert_eq!(+ t.env.well_known_bin_dirs(),+ vec![+ t.home.join(".local/bin"),+ t.home.join(".claude/local"),+ t.home.join(".npm-global/bin"),+ t.home.join(".bun/bin"),+ t.home.join(".cargo/bin"),+ PathBuf::from("/opt/homebrew/bin"),+ PathBuf::from("/usr/local/bin"),+ ]+ );+}+fn server() -> McpServer {McpServer::new("/opt/cua/bin/cua")}diff --git a/libs/cua/crates/cua-spaces-app-core/src/agents.rs b/libs/cua/crates/cua-spaces-app-core/src/agents.rsindex 8c7100ef3e..9256de0fbd 100644--- a/libs/cua/crates/cua-spaces-app-core/src/agents.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/agents.rs@@ -276,10 +276,10 @@ pub fn agent_settings_row(a: &AgentSetupStatus, total: u32) -> AgentSettingsRowlet skills_ok = a.skills_dir.is_none()|| (a.skills_installed.len() as u32 >= total && a.skills_outdated.is_empty());let mcp_ok = a.mcp_config.is_none() || a.cua_configured;- let configured = a.installed && skills_ok && mcp_ok;+ let configured = (a.installed || a.cua_configured) && skills_ok && mcp_ok;let detail = if let Some(e) = a.error.as_ref().filter(|e| !e.is_empty()) {e.clone()- } else if !a.installed {+ } else if !a.installed && !a.cua_configured {"not installed".into()} else if configured {match (a.skills_dir.is_some(), a.mcp_config.is_some()) {@@ -318,7 +318,7 @@ pub fn agent_settings_rows(statuses: &[AgentSetupStatus], total: u32) -> Vec<Age.iter().map(|a| agent_settings_row(a, total)).collect();- rows.sort_by_key(|r| !r.installed);+ rows.sort_by_key(|r| !(r.installed || r.configured));rows}@@ -425,6 +425,41 @@ mod tests {use super::*;use serde_json::json;+ #[test]+ fn configured_mcp_does_not_require_a_discoverable_binary() {+ let mut status = AgentSetupStatus {+ id: "claude-code".into(),+ name: "Claude Code".into(),+ mcp_config: Some(".claude.json".into()),+ skills_dir: Some(".claude/skills".into()),+ cua_configured: true,+ skills_installed: vec!["cua".into()],+ ..Default::default()+ };+ let row = agent_settings_row(&status, 1);+ assert!(row.configured);+ assert!(!row.installed);+ assert_eq!(row.detail, "skills and MCP configured");+ let absent = AgentSetupStatus {+ id: "absent".into(),+ ..Default::default()+ };+ let rows = agent_settings_rows(&[absent, status.clone()], 1);+ assert_eq!(rows[0].agent, "claude-code");+ status.skills_outdated = vec!["cua".into()];+ let row = agent_settings_row(&status, 1);+ assert!(!row.configured);+ assert_eq!(row.detail, "skills 1/1");+ status.skills_outdated.clear();+ status.skills_installed.clear();+ assert_eq!(agent_settings_row(&status, 1).detail, "skills 0/1");+ status.skills_installed = vec!["cua".into()];+ status.cua_configured = false;+ let row = agent_settings_row(&status, 1);+ assert!(!row.configured);+ assert_eq!(row.detail, "not installed");+ }+#[test]fn summaries_are_one_bounded_line() {assert_eq!(one_line("fix\n the build"), "fix the build");diff --git a/libs/cua/crates/cua-spaces-app-core/src/first_run.rs b/libs/cua/crates/cua-spaces-app-core/src/first_run.rsindex dd4a509b84..65b097a87a 100644--- a/libs/cua/crates/cua-spaces-app-core/src/first_run.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/first_run.rs@@ -1490,6 +1490,47 @@ mod tests {v.setup.as_ref().unwrap()}+ #[test]+ fn configured_claude_is_ready_without_binary_evidence_but_folders_are_not() {+ use crate::agents::{AgentSetupStatus, agent_settings_row};+ for configured in [true, false] {+ let row = agent_settings_row(+ &AgentSetupStatus {+ id: "claude-code".into(),+ name: "Claude Code".into(),+ cua_configured: configured,+ mcp_config: Some(".claude.json".into()),+ skills_dir: Some(".claude/skills".into()),+ skills_installed: vec!["cua".into()],+ ..Default::default()+ },+ 1,+ );+ let agent = FirstRunAgent {+ agent: row.agent,+ name: row.name,+ installed: row.installed,+ configured: row.configured,+ ..Default::default()+ };+ let c = connect(vec![agent.clone()], None);+ let pick = c.agents.iter().find(|a| a.agent == "claude-code").unwrap();+ assert_eq!(pick.checked, configured);+ assert_eq!(pick.locked, configured);+ if configured {+ let v = view(&FirstRunInput {+ agents: Some(vec![agent]),+ ..setup()+ });+ let row = s(&v).rows.iter().find(|r| r.id == "agent").unwrap();+ assert_eq!(row.state, RowState::Ok);+ assert_eq!(row.title, "Claude Code can use Cua");+ } else {+ assert_eq!(pick.note.as_deref(), Some("Not found on this Mac"));+ }+ }+ }+#[test]fn every_agent_is_listed_once_and_installed_ones_are_ticked() {let all = vec![