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): signing in to Claude Code, Codex and Hermes from the chat says what happened (#6576)
Francesco Bonacci0c5e26f86e16
diff --git a/apps/cua-spaces-web/src/__tests__/connectors-redesign.test.tsx b/apps/cua-spaces-web/src/__tests__/connectors-redesign.test.tsxindex ff0d84ac53..98c924f98a 100644--- a/apps/cua-spaces-web/src/__tests__/connectors-redesign.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/connectors-redesign.test.tsx@@ -13,7 +13,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { wasmBuilt } from "@/bridge/__tests__/testCore";import { resetConnectedAppsState } from "@/hooks/use-connected-apps";-import { resetConnectState } from "@/hooks/use-connectors";+import { connectFailureLine, resetConnectState } from "@/hooks/use-connectors";import { mountApp, stubBrowserApis } from "./app-harness";stubBrowserApis();@@ -187,6 +187,19 @@ describe.skipIf(!wasmBuilt)("Settings, Connections", () => {expect(calls.some((c) => c.op === "agents.signInStart" && (c.args as { agent: string }).agent === "codex")).toBe(true);});+ it("a sign-in that can't start says why, in the words the host gave", async () => {+ const calls: { op: string; args: unknown }[] = [];+ const h = { ...host(calls), intercept: (op: string) => {+ if (op === "agents.signInStart") throw new Error("Codex isn't installed on This Mac.");+ return undefined;+ } };+ await mountApp("/settings/connections", h);+ await disconnect("openai");+ await waitFor(() => expect(q("[data-connector-app=codex]")!.dataset.state).toBe("not-connected"));+ await click(q("[data-connector-app=codex] [data-connector-connect]")!);+ await waitFor(() => expect(connectFailureLine("codex")).toBe("Codex isn't installed on This Mac."));+ });+it("a key exported in your shell can be used; only its name is read first", async () => {const calls: { op: string; args: unknown }[] = [];await mountApp("/settings/connections", host(calls));diff --git a/apps/cua-spaces-web/src/components/ask-first/home.tsx b/apps/cua-spaces-web/src/components/ask-first/home.tsxindex 3d7ae91916..b8e3a4f527 100644--- a/apps/cua-spaces-web/src/components/ask-first/home.tsx+++ b/apps/cua-spaces-web/src/components/ask-first/home.tsx@@ -9,7 +9,8 @@ import { useChildren } from "@/components/children/use-children";import { CuaKey } from "@/components/cua-key";import { useAgentAttempts } from "@/hooks/use-agent-attempts";import { useAgentMenu } from "@/hooks/use-agent-menu";-import { useConnectors } from "@/hooks/use-connectors";+import { toast } from "@/components/ui/toast";+import { connectFailureLine, useConnectors } from "@/hooks/use-connectors";import { OsIcon } from "@/components/os-icon";import { currentWhere, SUGGESTIONS, thisMacConfirmed, useAskTasks, type AskTask, type TaskState } from "@/lib/ask-first";import { pickAccount, pickOf, rememberAgent, resolveAgent, usePickedAgent } from "@/lib/ask-first-model";@@ -112,6 +113,12 @@ export function AskFirstHome() {start({ prompt, agent: chosenAgent, where: w, model: selected.model.id, repo });setText("");};+ // A sign-in that did not work says so, in plain words, where the person clicked.+ const signInTo = async (app: string, label: string) => {+ if ((await connectors.connectApp(app)) === "failed") {+ toast(`Couldn't sign in to ${label}`, { description: connectFailureLine(app) || "Try again, or sign in from Settings, then Connections.", type: "error", group: `sign-in:${app}` });+ }+ };const useAccount = (group: AgentGroup, account: AgentAccount) => {rememberAgent(pickAccount(group, account, picked));if (!account.selected) void connectors.useCredential(group.app, { env: account.env, slot: account.slot });@@ -145,7 +152,7 @@ export function AskFirstHome() {selected={selected}onPickAccount={useAccount}onModel={(model) => selected && rememberAgent({ ...pickOf(selected), model })}- onSignIn={(g) => void connectors.connectApp(g.app)}+ onSignIn={(g) => void signInTo(g.app, g.label)}onConfigure={() => void navigate({ to: "/settings/connections" })}accounts={accountActions}repo={repo}@@ -166,7 +173,7 @@ export function AskFirstHome() {autoFocustree={tw}/>- <AgentStatus state={agentHome ? readiness : "none"} onReconnect={() => selected && void connectors.connectApp(selected.group.app)} />+ <AgentStatus state={agentHome ? readiness : "none"} onReconnect={() => selected && void signInTo(selected.group.app, selected.group.label)} />{fallback ? <FallbackLine fallback={fallback} /> : null}{/* Preparing is silent: only a failed prepare says so, with Try again. */}<PrepareLine view={prep.view} onRetry={onPrepareAction} />diff --git a/apps/cua-spaces-web/src/hooks/use-connectors.ts b/apps/cua-spaces-web/src/hooks/use-connectors.tsindex ac1d679705..a460c58934 100644--- a/apps/cua-spaces-web/src/hooks/use-connectors.ts+++ b/apps/cua-spaces-web/src/hooks/use-connectors.ts@@ -102,6 +102,9 @@ export function resetConnectState(): void {const message = (e: unknown) => (e instanceof Error ? e.message : String(e));+/** Why an app's last Connect failed, in the words it was told ("" when it did not). */+export const connectFailureLine = (agent: string): string => useConnectState.getState().failures.find((f) => f.id === `app:${agent}`)?.line ?? "";+/** How a connect ended: `connected`, waiting on the provider sheet (`sheet`), or `failed`. */export type ConnectOutcome = "connected" | "sheet" | "failed";@@ -176,13 +179,17 @@ export function useConnectors(): Connectors {set({ device: { app, provider, url: started.url, code: started.code } });const r = await data.call("agents.signInWait", { id: started.id });if (!r.imported) {- fail(id, r.line ?? "The sign-in didn't finish. Try again.");+ const line = r.line ?? "The sign-in didn't finish. Try again.";+ fail(id, line);+ fail(`app:${app}`, line);return false;}await reload();return true;} catch (e) {+ // The app's row shows its own failure line; the provider sheet shows the provider's.fail(id, message(e));+ fail(`app:${app}`, message(e));return false;} finally {set({ device: null });@@ -195,10 +202,16 @@ export function useConnectors(): Connectors {const connectApp = useCallback(async (agent: string): Promise<ConnectOutcome> => {- if (!data) return "failed";const id = `app:${agent}`;+ if (!data) {+ fail(id, "Cua Spaces isn't ready yet. Try again in a moment.");+ return "failed";+ }const plan = connectPlan(core, input, agent);- if (!plan) return "failed";+ if (!plan) {+ fail(id, "Cua couldn't tell how to sign in to this app. Open Settings, then Connections, to sign in there.");+ return "failed";+ }// Importing an app's own sign-in reads its files: ask first, in plain words.if (plan.appToken) {settleImport("sheet");diff --git a/libs/cua/crates/cua-agent-setup/src/lib.rs b/libs/cua/crates/cua-agent-setup/src/lib.rsindex 302812d131..892556417f 100644--- a/libs/cua/crates/cua-agent-setup/src/lib.rs+++ b/libs/cua/crates/cua-agent-setup/src/lib.rs@@ -177,6 +177,10 @@ pub struct HostEnv {pub channel: CuaChannel,}+/// How long [`AgentSetup::sign_in`] waits to see the agent's own login stop+/// at once with an error.+const SIGN_IN_EARLY_WAIT: std::time::Duration = std::time::Duration::from_secs(3);+const VARS: &[&str] = &["XDG_CONFIG_HOME","APPDATA",@@ -718,16 +722,18 @@ impl AgentSetup {.collect()}- /// Starts `agent`'s own sign-in on this computer (`codex login`: the- /// browser opens, and the agent keeps the sign-in in its own file). It- /// returns once the command is running; [`AgentSetup::detect`] reports- /// `signed_in` when it is done. cua never reads or copies the sign-in,- /// so every computer signs in on its own. A sign-in already waiting for- /// the browser is not started twice.+ /// Starts `agent`'s own sign-in on this computer (`codex login` and+ /// `claude auth login` open the browser; Hermes asks which provider, so+ /// it runs in Terminal). It returns once the command is running;+ /// [`AgentSetup::detect`] reports `signed_in` when it is done. cua never+ /// reads or copies the sign-in, so every computer signs in on its own.+ /// A sign-in already waiting is not started twice. A command that fails+ /// to start, or stops with an error within a few seconds, is an error+ /// in plain words (its own last line included), never silence.pub fn sign_in(&self, agent: &str) -> Result<()> {let a = registry::find(agent).ok_or_else(|| Error::InvalidArgument(format!("unknown agent {agent:?}")))?;- let login = a.login.ok_or_else(|| {+ let login = signin::login_command(a.id).ok_or_else(|| {Error::InvalidArgument(format!("{} has no sign-in cua can start", a.name))})?;if !self.env.run_agent_clis {@@ -748,6 +754,9 @@ impl AgentSetup {return Ok(());}let program = cmd_shim_target(&bin).unwrap_or_else(|| bin.clone());+ if login.terminal {+ return self.sign_in_in_terminal(a.name, &program, login.args);+ }let mut cmd = std::process::Command::new(&program);#[cfg(windows)]{@@ -763,10 +772,69 @@ impl AgentSetup {let mut child = cmd.args(login.args).stdin(std::process::Stdio::null())- .stdout(std::process::Stdio::null())- .stderr(std::process::Stdio::null())+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped()).spawn().map_err(|e| Error::io(&bin, e))?;+ // What it prints, kept (the last lines) so a failure can say why.+ let tail = std::sync::Arc::new(std::sync::Mutex::new(String::new()));+ for pipe in [+ child+ .stdout+ .take()+ .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),+ child+ .stderr+ .take()+ .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),+ ]+ .into_iter()+ .flatten()+ {+ let tail = tail.clone();+ std::thread::spawn(move || {+ use std::io::Read as _;+ let mut pipe = pipe;+ let mut buf = [0u8; 1024];+ while let Ok(n) = pipe.read(&mut buf) {+ if n == 0 {+ break;+ }+ let mut t = tail.lock().unwrap_or_else(|e| e.into_inner());+ t.push_str(&String::from_utf8_lossy(&buf[..n]));+ if t.len() > 4096 {+ let cut = t.len() - 4096;+ let cut = (cut..t.len()).find(|i| t.is_char_boundary(*i)).unwrap_or(0);+ t.drain(..cut);+ }+ }+ });+ }+ // A login that is going to fail usually does so at once (no browser,+ // an old version, a refused flag): wait briefly so the person hears it.+ let early = std::time::Instant::now() + SIGN_IN_EARLY_WAIT;+ let status = loop {+ match child.try_wait() {+ Ok(Some(s)) => break Some(s),+ Ok(None) if std::time::Instant::now() < early => {+ std::thread::sleep(std::time::Duration::from_millis(25))+ }+ _ => break None,+ }+ };+ if let Some(s) = status {+ // Let the readers finish what the process printed.+ std::thread::sleep(std::time::Duration::from_millis(100));+ if !s.success() {+ let said = tail.lock().unwrap_or_else(|e| e.into_inner()).clone();+ return Err(Error::InvalidArgument(signin::sign_in_failure(+ a.name,+ s.code(),+ &said,+ )));+ }+ return Ok(());+ }waiting.push(a.id);let id = a.id;// Reaped in the background: the sign-in waits for the browser.@@ -780,6 +848,47 @@ impl AgentSetup {Ok(())}+ /// Runs `program args` in Terminal (macOS), where the agent asks its own+ /// questions.+ fn sign_in_in_terminal(&self, name: &str, program: &Path, args: &[&str]) -> Result<()> {+ if self.env.os != Os::MacOs {+ return Err(Error::InvalidArgument(format!(+ "{name} signs in by asking questions: open a terminal and run `{} {}`.",+ program+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("hermes"),+ args.join(" ")+ )));+ }+ let osascript = self+ .env+ .which("osascript")+ .unwrap_or_else(|| PathBuf::from("/usr/bin/osascript"));+ let quote = |s: &str| format!("'{}'", s.replace('\'', "'\\''"));+ let line = std::iter::once(quote(&program.display().to_string()))+ .chain(args.iter().map(|a| quote(a)))+ .collect::<Vec<_>>()+ .join(" ");+ let script = format!(+ "tell application \"Terminal\"\nactivate\ndo script \"{}\"\nend tell",+ line.replace('\\', "\\\\").replace('"', "\\\"")+ );+ let out = std::process::Command::new(&osascript)+ .args(["-e", &script])+ .stdin(std::process::Stdio::null())+ .output()+ .map_err(|e| Error::io(&osascript, e))?;+ if out.status.success() {+ return Ok(());+ }+ Err(Error::InvalidArgument(signin::sign_in_failure(+ "Terminal",+ out.status.code(),+ &String::from_utf8_lossy(&out.stderr),+ )))+ }+/// Alias of [`AgentSetup::detect`].pub fn status(&self) -> Vec<AgentStatus> {self.detect()diff --git a/libs/cua/crates/cua-agent-setup/src/signin.rs b/libs/cua/crates/cua-agent-setup/src/signin.rsindex 78283a890d..cd1807fcb1 100644--- a/libs/cua/crates/cua-agent-setup/src/signin.rs+++ b/libs/cua/crates/cua-agent-setup/src/signin.rs@@ -666,9 +666,41 @@ pub fn importable(agent: &str) -> bool {matches!(agent, "codex" | "claude-code")}-/// Whether Cua can start the agent's own sign-in (`codex login`).+/// Whether Cua can start the agent's own sign-in.pub fn can_start_sign_in(agent: &str) -> bool {- registry::find(agent).is_some_and(|a| a.login.is_some())+ login_command(agent).is_some()+}++/// How an agent's own sign-in starts.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct LoginCommand {+ /// Arguments to the agent's binary.+ pub args: &'static [&'static str],+ /// The command asks questions, so it runs in Terminal (the agent's own+ /// screen) rather than in the background (it opens the browser itself).+ pub terminal: bool,+}++/// The agent's own sign-in command, when it has one Cua can start:+/// `codex login` and `claude auth login` open the browser on their own;+/// Hermes picks a provider by asking, so `hermes model` runs in Terminal.+pub fn login_command(agent: &str) -> Option<LoginCommand> {+ let id = registry::find(agent)?.id;+ match id {+ "codex" => Some(LoginCommand {+ args: &["login"],+ terminal: false,+ }),+ "claude-code" => Some(LoginCommand {+ args: &["auth", "login"],+ terminal: false,+ }),+ "hermes" => Some(LoginCommand {+ args: &["model"],+ terminal: true,+ }),+ _ => None,+ }}/// What the row's indented tick copies ("ChatGPT sign-in"), when any.@@ -690,6 +722,23 @@ pub fn copy_source(_env: &HostEnv, agent: &str) -> Option<String> {}}+/// A sign-in command that stopped with an error, in plain words: what it+/// last said (without terminal colors), else its exit code.+pub fn sign_in_failure(name: &str, code: Option<i32>, said: &str) -> String {+ let last = plain(said)+ .lines()+ .map(str::trim)+ .rfind(|l| !l.is_empty())+ .map(|l| l.chars().take(200).collect::<String>());+ match (last, code) {+ (Some(l), _) => format!("{name}'s sign-in stopped: {l}"),+ (None, Some(c)) => {+ format!("{name}'s sign-in stopped (exit code {c}). Try signing in from its own app.")+ }+ (None, None) => format!("{name}'s sign-in was stopped. Try again."),+ }+}+// ------------------------------------------------------- device sign-in/// How long the device code waits for the person to enter it (Codex's own is 15 minutes).@@ -849,9 +898,15 @@ pub fn start_device_sign_in(Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,}}- Err(CopyRefusal::Failed(- "Codex didn't show a sign-in code. Try again.".into(),- ))+ let said = plain(&seen);+ let last = said.lines().map(str::trim).rfind(|l| !l.is_empty());+ Err(CopyRefusal::Failed(match last {+ Some(l) => format!(+ "Codex didn't show a sign-in code. It said: {}",+ l.chars().take(200).collect::<String>()+ ),+ None => "Codex didn't show a sign-in code. Try again.".into(),+ }))}use std::io::Read as _;diff --git a/libs/cua/crates/cua-agent-setup/tests/agents.rs b/libs/cua/crates/cua-agent-setup/tests/agents.rsindex 7df0f788be..43db0dc883 100644--- a/libs/cua/crates/cua-agent-setup/tests/agents.rs+++ b/libs/cua/crates/cua-agent-setup/tests/agents.rs@@ -1442,7 +1442,7 @@ fn sign_in_is_refused_without_a_sign_in_an_install_or_agent_commands() {let mut t = T::new();let err = |s: &AgentSetup, id: &str| s.sign_in(id).unwrap_err().to_string();assert!(err(&t.setup(), "nope").contains("unknown agent"));- assert!(err(&t.setup(), "claude-code").contains("no sign-in"));+ assert!(err(&t.setup(), "cursor").contains("no sign-in"));// Isolated environments never run an agent's CLI.assert!(err(&t.setup(), "codex").contains("off in this environment"));t.env.run_agent_clis = true;@@ -1482,6 +1482,75 @@ fn sign_in_runs_the_agents_own_login_and_detect_sees_it() {assert!(a.installed && a.signed_in, "{a:?}");}+#[cfg(unix)]+#[test]+fn claude_code_signs_in_with_its_own_login_and_a_failing_one_says_why() {+ let mut t = T::new();+ let bin = t.home.join("bin");+ let log = t.home.join("claude-argv.log");+ common::write_script(+ &bin,+ "claude",+ &format!(+ "printf '%s\\n' \"$*\" >> '{}'\nsleep 0.3\nexit 0",+ log.display()+ ),+ );+ t.env.path = vec![bin.clone(), "/bin".into(), "/usr/bin".into()];+ t.env.run_agent_clis = true;+ t.setup().sign_in("claude-code").unwrap();+ assert_eq!(t.read(&log).trim(), "auth login");+ // A login that stops with an error at once: its own last line, in words.+ common::write_script(+ &bin,+ "claude",+ "echo 'opening the browser' >&2\necho '\x1b[31mNo browser found\x1b[0m' >&2\nexit 1",+ );+ let e = t.setup().sign_in("claude-code").unwrap_err().to_string();+ assert!(+ e.contains("Claude Code's sign-in stopped: No browser found"),+ "{e}"+ );+ // No output: the exit code.+ common::write_script(&bin, "claude", "exit 7");+ let e = t.setup().sign_in("claude-code").unwrap_err().to_string();+ assert!(e.contains("exit code 7"), "{e}");+ // One still waiting for the browser is not started twice (last: it stays+ // registered while it runs).+ let runs = t.home.join("claude-runs.log");+ common::write_script(+ &bin,+ "claude",+ &format!("echo run >> '{}'\nsleep 5", runs.display()),+ );+ t.setup().sign_in("claude-code").unwrap();+ t.setup().sign_in("claude-code").unwrap();+ std::thread::sleep(std::time::Duration::from_millis(300));+ assert_eq!(t.read(&runs).lines().count(), 1);+}++#[cfg(target_os = "macos")]+#[test]+fn hermes_signs_in_in_terminal() {+ let mut t = T::new();+ let bin = t.home.join("bin");+ let log = t.home.join("osascript.log");+ common::write_script(&bin, "hermes", "exit 0");+ common::write_script(+ &bin,+ "osascript",+ &format!("printf '%s' \"$*\" > '{}'", log.display()),+ );+ t.env.path = vec![bin];+ t.env.run_agent_clis = true;+ t.setup().sign_in("hermes").unwrap();+ let said = t.read(&log);+ assert!(+ said.contains("Terminal") && said.contains("hermes") && said.contains("model"),+ "{said}"+ );+}+/// Cua's own setup (its entry in a new `~/.claude.json`, its skills under/// `~/.claude/skills`) is no sign Claude Code is installed: the first run/// showed "Ready" on a Mac without it (CUA-3063).diff --git a/libs/cua/crates/cua-agent-setup/tests/common/mod.rs b/libs/cua/crates/cua-agent-setup/tests/common/mod.rsindex 649297bb56..ad944d49ff 100644--- a/libs/cua/crates/cua-agent-setup/tests/common/mod.rs+++ b/libs/cua/crates/cua-agent-setup/tests/common/mod.rs@@ -41,3 +41,11 @@ pub fn write_executable(path: &std::path::Path, contents: impl AsRef<[u8]>) {let tmp_path = tmp.into_temp_path();tmp_path.persist(path).unwrap();}++/// Writes an executable shell script `name` into `dir` (a fake agent binary) and returns its path.+#[cfg(unix)]+pub fn write_script(dir: &std::path::Path, name: &str, body: &str) -> std::path::PathBuf {+ let p = dir.join(name);+ write_executable(&p, format!("#!/bin/sh\n{body}\n"));+ p+}diff --git a/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs b/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rsindex 36acaaeffe..8b111e733a 100644--- a/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs+++ b/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs@@ -433,8 +433,9 @@ fn installed_signed_in_or_not_connected_or_not() {fn connected_but_not_signed_in_says_so_and_offers_sign_in_where_cua_can_start_it() {for (id, action) in [("codex", ProblemAction::SignIn),- ("claude-code", ProblemAction::None),- ("hermes", ProblemAction::None),+ // Claude Code and Hermes sign in from here too since CUA-3549 (`claude auth login`; Hermes in Terminal).+ ("claude-code", ProblemAction::SignIn),+ ("hermes", ProblemAction::SignIn),] {let w = World::new();w.install(id, "1.0.0");diff --git a/libs/cua/crates/cua-cli/tests/connect_status.rs b/libs/cua/crates/cua-cli/tests/connect_status.rsindex bc1a726b73..32a64d1add 100644--- a/libs/cua/crates/cua-cli/tests/connect_status.rs+++ b/libs/cua/crates/cua-cli/tests/connect_status.rs@@ -260,7 +260,8 @@ async fn cli_mcp_and_app_report_the_same_connection_in_every_state() {assert_eq!(row(&r, "codex")["state"], "connected", "{r}");assert_eq!(row(&r, "codex")["signin_import"], "ok");assert_eq!(row(&r, "hermes")["state"], "attention");- assert_eq!(row(&r, "hermes")["problem"]["action"], "none");+ // Hermes has its own `hermes login`, so the row offers Sign in.+ assert_eq!(row(&r, "hermes")["problem"]["action"], "sign_in");assert_eq!(row(&r, "cursor")["state"], "connected");assert_eq!(row(&r, "cursor")["signed_in"], "unknown");