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
Preserve polling after recoverable ACP turn failures (#5766)
injaneity27d8da9fd940
diff --git a/examples/cua-bots-macos/Package.swift b/examples/cua-bots-macos/Package.swiftindex 0b967f70f9..ff68fedca0 100644--- a/examples/cua-bots-macos/Package.swift+++ b/examples/cua-bots-macos/Package.swift@@ -52,7 +52,7 @@ let package = Package(.product(name: "Cua", package: "Cua")],path: "Sources/CuaBotsMac"),- .testTarget(name: "CuaBotsCoreTests", dependencies: ["CuaBotsCore", "CuaBotsUI"],+ .testTarget(name: "CuaBotsCoreTests", dependencies: ["CuaBotsCore", "CuaBotsUI", "CuaBotsCua"],path: "Tests/CuaBotsCoreTests"),],swiftLanguageModes: [.v5]diff --git a/examples/cua-bots-macos/Sources/CuaBotsCore/Engine/BotEngine.swift b/examples/cua-bots-macos/Sources/CuaBotsCore/Engine/BotEngine.swiftindex 616e247d0e..885313c055 100644--- a/examples/cua-bots-macos/Sources/CuaBotsCore/Engine/BotEngine.swift+++ b/examples/cua-bots-macos/Sources/CuaBotsCore/Engine/BotEngine.swift@@ -9,8 +9,10 @@ public enum EngineUpdate: Equatable, Sendable {case assistant(turn: UInt32, text: String)/// A tool the harness is running ("Run tests", "Open browser").case tool(turn: UInt32, title: String)+ case turnStartedcase turnEnded(turn: UInt32)case failed(String)+ case exited}/// Where a bot is in its life, as the engine reports it.diff --git a/examples/cua-bots-macos/Sources/CuaBotsCore/Store/BotStore.swift b/examples/cua-bots-macos/Sources/CuaBotsCore/Store/BotStore.swiftindex a54ce07695..c19a19dd30 100644--- a/examples/cua-bots-macos/Sources/CuaBotsCore/Store/BotStore.swift+++ b/examples/cua-bots-macos/Sources/CuaBotsCore/Store/BotStore.swift@@ -50,6 +50,8 @@ public final class BotStore: ObservableObject {private var pollers: [String: Task<Void, Never>] = [:]private var currentTask: [String: String] = [:]private var busy: Set<String> = []+ private var failedTurns: Set<String> = []+ private var pollFailures: [String: Int] = [:]public init(volume: VolumeStore, dataDirectory: URL, engine: BotEngine? = nil) {self.volume = volume@@ -186,6 +188,9 @@ public final class BotStore: ObservableObject {private func deliver(_ id: String, _ text: String) async {guard let engine, let bot = bot(id) else { return }+ if failedTurns.contains(id) { await pollOnce(id) }+ failedTurns.remove(id)+ pollFailures[id] = 0do {if bot.runID == nil {await bringUp(id, firstPrompt: text)@@ -368,15 +373,25 @@ public final class BotStore: ObservableObject {do {let (updates, cursor) = try await engine.poll(bot, cursor: cursors[id] ?? 0)cursors[id] = cursor+ pollFailures[id] = 0for u in updates { handle(id, u) }} catch {// A poll that fails once is not news; the next one retries.+ pollFailures[id, default: 0] += 1+ if pollFailures[id, default: 0] >= 3 {+ fail(id, "Couldn't read the agent's updates: \(error.localizedDescription). Send a message to retry.")+ save()+ }}return !busy.contains(id)}func handle(_ id: String, _ update: EngineUpdate) {switch update {+ case .turnStarted:+ failedTurns.remove(id)+ busy.insert(id)+ self.update(id) { $0.mood = .thinking; $0.status = "Thinking" }case .assistant(let turn, let text):turnText[id] = (turn, text)// Live status from the markers seen so far.@@ -388,15 +403,24 @@ public final class BotStore: ObservableObject {if !t.isEmpty { self.update(id) { $0.status = String(t.prefix(40)); $0.mood = .working } }case .turnEnded(let turn):busy.remove(id)- let text = turnText[id].flatMap { $0.turn == turn ? $0.text : nil } ?? turnText[id]?.text ?? ""- turnText[id] = nil- finishTurn(id, text)- if let b = bot(id), let engine {- Task { try? await engine.checkpoint(b, volume: self.volume) }+ if failedTurns.contains(id) {+ turnText[id] = nil+ } else {+ let text = turnText[id].flatMap { $0.turn == turn ? $0.text : nil } ?? turnText[id]?.text ?? ""+ turnText[id] = nil+ finishTurn(id, text)+ if let b = bot(id), let engine {+ Task { try? await engine.checkpoint(b, volume: self.volume) }+ }}case .failed(let reason):- busy.remove(id)fail(id, reason)+ case .exited:+ busy.remove(id)+ turnText[id] = nil+ pollers[id]?.cancel()+ pollers[id] = nil+ if !failedTurns.contains(id) { finishTurn(id, "") }}save()}@@ -494,6 +518,9 @@ public final class BotStore: ObservableObject {}private func fail(_ id: String, _ reason: String) {+ busy.remove(id)+ turnText[id] = nil+ guard failedTurns.insert(id).inserted else { return }update(id) { $0.mood = .error; $0.status = "Needs a look" }append(ChatMessage(botID: id, role: .system, text: reason, kind: .notice))if let bot = bot(id) { notify(bot, .problem, "\(bot.name) hit a problem", reason) }@@ -595,6 +622,7 @@ public final class BotStore: ObservableObject {var approvals: [ApprovalRequest]var notifications: [BotNotification]var bots: [Bot]+ var cursors: [String: UInt64]?}var stateURL: URL { dataDirectory.appendingPathComponent("state.json") }@@ -602,7 +630,7 @@ public final class BotStore: ObservableObject {public func save() {let e = JSONEncoder()e.dateEncodingStrategy = .iso8601- let saved = Saved(messages: messages, approvals: approvals, notifications: notifications, bots: bots)+ let saved = Saved(messages: messages, approvals: approvals, notifications: notifications, bots: bots, cursors: cursors)if let data = try? e.encode(saved) { try? data.write(to: stateURL, options: .atomic) }for bot in bots { try? volume.writeJSON(bot, VolumeLayout.identity(bot.id)) }}@@ -615,6 +643,7 @@ public final class BotStore: ObservableObject {messages = saved.messagesapprovals = saved.approvalsnotifications = saved.notifications+ cursors = saved.cursors ?? [:]for b in saved.bots { runtime[b.id] = b }}// The Volume is the source of truth for which bots exist.@@ -626,6 +655,7 @@ public final class BotStore: ObservableObject {return bot}.sorted { $0.createdAt < $1.createdAt }for bot in bots {+ if bot.mood == .error { failedTurns.insert(bot.id) }rules[bot.id] = (try? volume.readJSON([CustomRule].self, "agents/\(bot.id)/identity/rules.json"))?? CustomRule.defaultstasks[bot.id] = (try? volume.readJSON([BotTask].self, VolumeLayout.tasks(bot.id))) ?? []diff --git a/examples/cua-bots-macos/Sources/CuaBotsCua/CuaEngine.swift b/examples/cua-bots-macos/Sources/CuaBotsCua/CuaEngine.swiftindex 2c59d9db30..53a69135d0 100644--- a/examples/cua-bots-macos/Sources/CuaBotsCua/CuaEngine.swift+++ b/examples/cua-bots-macos/Sources/CuaBotsCua/CuaEngine.swift@@ -129,6 +129,13 @@ public final class CuaEngine: BotEngine {let json = try await space(bot).agentEvents(runId: run, cursor: cursor, max: 500)let page = try JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any] ?? [:]let events = page["events"] as? [[String: Any]] ?? []+ let updates = Self.decode(events, botID: bot.id, turnText: &turnText)+ let next = (page["cursor"] as? NSNumber)?.uint64Value ?? cursor+ return (updates, next)+ }++ static func decode(_ events: [[String: Any]], botID: String,+ turnText: inout [String: (turn: UInt32, text: String)]) -> [EngineUpdate] {var updates: [EngineUpdate] = []for e in events {let kind = e["kind"] as? String ?? ""@@ -136,26 +143,28 @@ public final class CuaEngine: BotEngine {switch kind {case "message":let chunk = e["text"] as? String ?? ""- var current = turnText[bot.id] ?? (turn, "")+ var current = turnText[botID] ?? (turn, "")if current.turn != turn { current = (turn, "") }current.text += chunk- turnText[bot.id] = current+ turnText[botID] = currentupdates.append(.assistant(turn: turn, text: current.text))case "tool_call":updates.append(.tool(turn: turn, title: e["tool_title"] as? String ?? "Working"))+ case "turn_started":+ updates.append(.turnStarted)case "turn_ended":updates.append(.turnEnded(turn: turn))- turnText[bot.id] = nil+ turnText[botID] = nilcase "error":updates.append(.failed(e["text"] as? String ?? "The agent reported an error"))case "exited":- updates.append(.failed("The agent stopped: \(e["text"] as? String ?? "exited")"))+ updates.append(.exited)+ turnText[botID] = nildefault:break}}- let next = (page["cursor"] as? NSNumber)?.uint64Value ?? cursor- return (updates, next)+ return updates}public func interrupt(_ bot: Bot) async throws {diff --git a/examples/cua-bots-macos/Tests/CuaBotsCoreTests/CoreTests.swift b/examples/cua-bots-macos/Tests/CuaBotsCoreTests/CoreTests.swiftindex 4d82d712f8..a4ccf64e25 100644--- a/examples/cua-bots-macos/Tests/CuaBotsCoreTests/CoreTests.swift+++ b/examples/cua-bots-macos/Tests/CuaBotsCoreTests/CoreTests.swift@@ -5,6 +5,25 @@ import Testingimport Foundationimport SwiftUI@testable import CuaBotsCore+@testable import CuaBotsCua++@MainActor+struct EngineEventTests {+ @Test func testExitIsTerminalWithoutInventingAnError() {+ var text: [String: (turn: UInt32, text: String)] = ["ada": (1, "partial")]+ let updates = CuaEngine.decode([+ ["kind": "error", "text": "Authentication required"],+ ["kind": "exited", "text": "task stopped"],+ ], botID: "ada", turnText: &text)+ #expect(updates == [.failed("Authentication required"), .exited])+ #expect(text.isEmpty)+ }++ @Test func testCleanExitHasNoFailureUpdate() {+ var text: [String: (turn: UInt32, text: String)] = [:]+ #expect(CuaEngine.decode([["kind": "exited"]], botID: "ada", turnText: &text) == [.exited])+ }+}struct DirectiveTests {@Test func testParsesAndStripsMarkers() {@@ -158,6 +177,10 @@ final class ScriptedEngine: BotEngine {var replies: [String] = []var paused = falsevar resetCount = 0+ var pollError: Error?+ var scriptedUpdates: [EngineUpdate]?+ var replay = false+ var polledCursors: [UInt64] = []private var queue: [EngineUpdate] = []private var turn: UInt32 = 0private var seq: UInt64 = 0@@ -177,12 +200,24 @@ final class ScriptedEngine: BotEngine {sent.append(text)turn += 1let reply = replies.isEmpty ? "Okay." : replies.removeFirst()+ queue.append(.turnStarted)queue.append(.tool(turn: turn, title: "Reading files"))queue.append(.assistant(turn: turn, text: reply))queue.append(.turnEnded(turn: turn))}func poll(_ bot: Bot, cursor: UInt64) async throws -> (updates: [EngineUpdate], cursor: UInt64) {+ polledCursors.append(cursor)+ if let pollError { throw pollError }+ if let scriptedUpdates {+ if replay {+ return cursor >= UInt64(scriptedUpdates.count) ? ([], cursor)+ : (scriptedUpdates, UInt64(scriptedUpdates.count))+ }+ self.scriptedUpdates = nil+ seq += UInt64(scriptedUpdates.count)+ return (scriptedUpdates, seq)+ }let out = queuequeue = []seq += UInt64(out.count)@@ -207,6 +242,110 @@ struct StoreTests {dataDirectory: root.appendingPathComponent("data"), engine: engine)}+ @Test func testFailureEndsTurnAndKeepsFirstCause() async {+ let engine = ScriptedEngine()+ let store = makeStore(engine)+ let bot = await store.createBot(name: "Ada", avatar: .default(for: "Ada"), harness: .hermes, placement: .local)+ engine.scriptedUpdates = [.failed("Authentication required"), .failed("task stopped"), .turnEnded(turn: 1), .exited]+ await store.pollOnce(bot.id)+ #expect(!store.isBusy(bot.id))+ #expect(store.bot(bot.id)?.status == "Needs a look")+ #expect(store.notifications.count == 1)+ #expect(store.messages(for: bot.id).filter { $0.text == "task stopped" }.isEmpty)+ engine.scriptedUpdates = [.exited]+ await store.send(bot.id, "retry")+ engine.scriptedUpdates = nil+ await store.pollOnce(bot.id)+ #expect(store.bot(bot.id)?.status == "Ready")+ engine.scriptedUpdates = [.failed("Authentication required")]+ await store.send(bot.id, "again")+ await store.pollOnce(bot.id)+ #expect(store.notifications.count == 2)+ }++ @Test func testRecoverableFailureKeepsPollingQueuedTurn() async throws {+ let engine = ScriptedEngine()+ let store = makeStore(engine)+ let bot = await store.createBot(name: "Ada", avatar: .default(for: "Ada"), harness: .hermes, placement: .local)+ engine.scriptedUpdates = [.failed("quota"), .turnEnded(turn: 1), .turnStarted]+ await store.pollOnce(bot.id)+ #expect(store.isBusy(bot.id))+ #expect(store.bot(bot.id)?.status == "Thinking")++ engine.scriptedUpdates = [.assistant(turn: 2, text: "ok"), .turnEnded(turn: 2)]+ let deadline = ContinuousClock.now.advanced(by: .seconds(5))+ while store.isBusy(bot.id) && ContinuousClock.now < deadline {+ try await Task.sleep(for: .milliseconds(50))+ }+ #expect(store.messages(for: bot.id).last?.text == "ok")+ #expect(store.bot(bot.id)?.status == "Ready")+ #expect(!store.isBusy(bot.id))+ #expect(store.notifications.count == 1)+ store.handle(bot.id, .exited)+ }++ @Test func testFirstErrorIsDeduplicatedPerTurn() async {+ let engine = ScriptedEngine()+ let store = makeStore(engine)+ let bot = await store.createBot(name: "Ada", avatar: .default(for: "Ada"), harness: .hermes, placement: .local)+ engine.scriptedUpdates = [.failed("cause"), .failed("consequence"), .turnEnded(turn: 1),+ .turnStarted, .failed("cause"), .turnEnded(turn: 2)]+ await store.pollOnce(bot.id)+ #expect(store.notifications.count == 2)+ #expect(store.notifications.allSatisfy { $0.body == "cause" })+ #expect(store.bot(bot.id)?.status == "Needs a look")+ #expect(!store.isBusy(bot.id))+ }++ @Test func testFailureIsNotReplayedAfterReload() async {+ let engine = ScriptedEngine()+ engine.scriptedUpdates = [.failed("agent missing")]+ engine.replay = true+ let store = makeStore(engine)+ let bot = await store.createBot(name: "Ada", avatar: .default(for: "Ada"), harness: .hermes, placement: .local)+ await store.pollOnce(bot.id)+ store.save()+ let again = makeStore(engine)+ await again.pollOnce(bot.id)+ #expect(again.notifications.count == 1)+ #expect(engine.polledCursors.last == 1)+ }++ @Test func testIdlePollDoesNotRewriteState() async throws {+ let engine = ScriptedEngine()+ let store = makeStore(engine)+ let bot = await store.createBot(name: "Ada", avatar: .default(for: "Ada"), harness: .hermes, placement: .local)+ await store.pollOnce(bot.id)+ let state = root.appendingPathComponent("data/state.json")+ let timestamp = Date(timeIntervalSince1970: 1_000)+ try FileManager.default.setAttributes([.modificationDate: timestamp], ofItemAtPath: state.path)+ await store.pollOnce(bot.id)+ let attributes = try FileManager.default.attributesOfItem(atPath: state.path)+ #expect(attributes[.modificationDate] as? Date == timestamp)+ }++ @Test func testRepeatedPollFailureStopsThinking() async {+ let engine = ScriptedEngine()+ let store = makeStore(engine)+ let bot = await store.createBot(name: "Ada", avatar: .default(for: "Ada"), harness: .hermes, placement: .local)+ engine.pollError = NSError(domain: "Space unavailable", code: 404)+ for _ in 0..<3 { await store.pollOnce(bot.id) }+ #expect(!store.isBusy(bot.id))+ #expect(store.bot(bot.id)?.status == "Needs a look")+ #expect(store.notifications.count == 1)+ }++ @Test func testCleanExitIsNotAnError() async {+ let engine = ScriptedEngine()+ let store = makeStore(engine)+ let bot = await store.createBot(name: "Ada", avatar: .default(for: "Ada"), harness: .hermes, placement: .local)+ engine.scriptedUpdates = [.exited]+ await store.pollOnce(bot.id)+ #expect(!store.isBusy(bot.id))+ #expect(store.bot(bot.id)?.status == "Ready")+ #expect(store.notifications.isEmpty)+ }+@Test func testCreateWritesTheHomeAndIntroduces() async throws {let engine = ScriptedEngine()engine.replies = ["[[status: Settling in]]\nHi Sam, I'm Ada."]diff --git a/libs/cua/crates/cua-agents/runner/acp-runner.mjs b/libs/cua/crates/cua-agents/runner/acp-runner.mjsindex 54e0191c96..59bb97a711 100644--- a/libs/cua/crates/cua-agents/runner/acp-runner.mjs+++ b/libs/cua/crates/cua-agents/runner/acp-runner.mjs@@ -166,6 +166,26 @@ async function checkKey(spec) {const keyCheck = checkKey(cfg.keyCheck).catch(() => null);const agentLog = fs.openSync(P("agent.log"), "a");+const logStart = fs.fstatSync(agentLog).size;++function diagnostic(error, phase) {+ const size = fs.fstatSync(agentLog).size;+ const tail = Buffer.alloc(Math.min(4096, size - logStart));+ const fd = fs.openSync(P("agent.log"), "r");+ try {+ fs.readSync(fd, tail, 0, tail.length, size - tail.length);+ } finally {+ fs.closeSync(fd);+ }+ return redact(`${error?.message ?? error}`+ + (error?.code != null ? ` (code ${error.code})` : "")+ + (error?.data != null ? ` ${JSON.stringify(error.data)}` : "")+ + ` (${phase}: ${cfg.agent.command})`+ + (error?.code === -32000 && cfg.authHint ? `\n${cfg.authHint}` : "")+ + (tail.length ? `\n${tail.toString("utf8").trim()}` : "")+ + (phase === "spawn" ? `\nPATH=${env.PATH ?? ""}` : "")+ + `\nAgent log: ${P("agent.log")}`);+}// Resolve ~/.cua/bin links: some agents (Antigravity's .par) find their// sibling files relative to argv[0].let command = cfg.agent.command;@@ -180,17 +200,18 @@ const child = spawn(command, cfg.agent.args ?? [], {save({ agentPid: child.pid ?? null });let exiting = false;child.on("error", (e) => {- emit("error", { message: `could not start the agent: ${e.message}` });- finish(127, `could not start the agent: ${e.message}`);+ finish(127, "could not start the agent", diagnostic(e, "spawn"));});child.on("exit", (code, signal) => {if (!exiting) {- flush();- emit("error", { message: `the agent exited unexpectedly (code ${code}, signal ${signal})` });- finish(code ?? 1, "agent exited");+ finish(code || 1, "agent exited", diagnostic(new Error(`the agent exited unexpectedly (code ${code}, signal ${signal})`), "transport"));}});+child.stdout.on("end", () => {+ finish(1, "ACP stdout closed", diagnostic(new Error("agent stdout closed"), "transport"));+});+// End this run's cua-driver session on the guest MCP (cua-spacesd keys it by// X-Cua-Agent-Session), so the run's presence cursor leaves at once instead// of after the server's idle timeout. Best effort, bounded.@@ -209,13 +230,22 @@ function endAgentSessions() {return Promise.allSettled(ends);}-function finish(code, why) {+function endTurn(stopReason, usage = null) {+ if (exiting || state.status !== "running") return;+ flush();+ save({ status: "idle", stopReason, queued: queue.length });+ emit("turn_ended", { stopReason, usage });+}++function finish(code, why, message = null) {if (exiting) return;- exiting = true;flush();+ if (message) emit("error", { message });+ endTurn(code !== 0 ? "error" : why);+ exiting = true;const failed = code !== 0;emit("run_exited", { code, reason: why, resumable: Boolean(state.sessionId && state.loadSession) });- save({ status: failed ? "failed" : "exited", error: failed ? why : null });+ save({ status: failed ? "failed" : "exited", error: failed ? redact(message ?? why) : null });try {child.kill("SIGTERM");} catch {}@@ -284,11 +314,31 @@ function blocks(text, files) {await client.connectWith(stream, async (ctx) => {- const init = await ctx.request(acp.methods.agent.initialize, {+ const requestStartup = async (method, params, phase) => {+ let timer;+ try {+ return await Promise.race([+ ctx.request(method, params),+ new Promise((_, reject) => {+ timer = setTimeout(() => {+ const error = new Error(`${phase} timed out`);+ finish(1, error.message, diagnostic(error, phase));+ reject(error);+ }, cfg.startupTimeoutMs ?? 180000);+ }),+ ]);+ } catch (error) {+ error.phase = phase;+ throw error;+ } finally {+ clearTimeout(timer);+ }+ };+ const init = await requestStartup(acp.methods.agent.initialize, {protocolVersion: acp.PROTOCOL_VERSION,clientCapabilities: {},clientInfo: { name: "cua", version: "1" },- });+ }, "initialize");const caps = init.agentCapabilities ?? {};const loadSession = Boolean(caps.loadSession || caps.sessionCapabilities?.resume);save({ loadSession });@@ -298,7 +348,7 @@ await client// need none.const method = (init.authMethods ?? []).find((m) => m.id === cfg.authMethod);if (method) {- await ctx.request(acp.methods.agent.authenticate, { methodId: method.id });+ await requestStartup(acp.methods.agent.authenticate, { methodId: method.id }, "authenticate");emit("authenticated", { methodId: method.id });}// HTTP MCP servers only for agents that declare mcpCapabilities.http@@ -335,14 +385,15 @@ await clientif (prev.sessionId && loadSession) {try {if (caps.sessionCapabilities?.resume) {- await ctx.request(acp.methods.agent.session.resume, { sessionId: prev.sessionId, ...request });+ await requestStartup(acp.methods.agent.session.resume, { sessionId: prev.sessionId, ...request }, "session resume");} else {replaying = true;- await ctx.request(acp.methods.agent.session.load, { sessionId: prev.sessionId, ...request });+ await requestStartup(acp.methods.agent.session.load, { sessionId: prev.sessionId, ...request }, "session load");}sessionId = prev.sessionId;resumed = true;} catch (e) {+ if (exiting || e?.code === -32000) throw e;emit("notice", { message: `could not resume session ${prev.sessionId}: ${e?.message ?? e}; starting a new one` });} finally {replaying = false;@@ -351,20 +402,21 @@ await clientif (!sessionId) {let res;try {- res = await ctx.request(acp.methods.agent.session.new, request);+ res = await requestStartup(acp.methods.agent.session.new, request, "session");} catch (e) {// Some agents reject session MCP servers they cannot start; keep// the run and say so rather than failing it.- if (!request.mcpServers.length) throw e;+ if (exiting || e?.code === -32000 || !request.mcpServers.length) throw e;emit("notice", {message: `the agent refused the run's MCP servers (${e?.message ?? e}${e?.data ? ": " + JSON.stringify(e.data) : ""}); continuing without them`,});request.mcpServers = [];- res = await ctx.request(acp.methods.agent.session.new, request);+ res = await requestStartup(acp.methods.agent.session.new, request, "session");}sessionId = res.sessionId;modes = res.modes ?? null;}+ if (exiting) return;save({ sessionId, status: "idle" });emit("session", { sessionId, resumed, modes });// The sandbox is the boundary: pick the agent's own "full access" mode@@ -386,27 +438,26 @@ await clientsave({ status: "running", queued: queue.length });emit("turn_started", { prompt: msg.text, files: msg.files ?? [] });const rejected = await keyCheck;+ if (exiting) return;if (rejected) {// The same record a failed prompt leaves, without the harness's// retries: one error, the turn ends, the supervisor notifies once.emit("error", { message: rejected.message, data: { errorKind: "authentication_failed", status: rejected.status, source: "key_check" } });- save({ status: "idle", stopReason: "error", queued: queue.length });- emit("turn_ended", { stopReason: "error" });+ endTurn("error");return;}let res;try {res = await ctx.request(acp.methods.agent.session.prompt, { sessionId, prompt: blocks(msg.text, msg.files) });} catch (e) {+ if (exiting) return;flush();- emit("error", { message: e?.message ?? String(e), data: e?.data ?? null });- save({ status: "idle", stopReason: "error" });- emit("turn_ended", { stopReason: "error" });+ const message = (e?.message ?? String(e)) + (e?.code === -32000 && cfg.authHint ? `\n${cfg.authHint}` : "");+ emit("error", { message, code: e?.code ?? null, data: e?.data ?? null });+ endTurn("error");return;}- flush();- save({ status: "idle", stopReason: res?.stopReason ?? null, queued: queue.length });- emit("turn_ended", { stopReason: res?.stopReason ?? null, usage: res?.usage ?? null });+ endTurn(res?.stopReason ?? null, res?.usage ?? null);};let idleSince = Date.now();@@ -450,6 +501,5 @@ await client}}).catch((e) => {- emit("error", { message: `ACP connection failed: ${e?.message ?? e}`, data: e?.data ?? null });- finish(1, `ACP connection failed: ${e?.message ?? e}`);+ finish(1, "ACP connection failed", diagnostic(e, e?.phase ?? "ACP connection"));});diff --git a/libs/cua/crates/cua-agents/runner/test/run-end.test.mjs b/libs/cua/crates/cua-agents/runner/test/run-end.test.mjsindex 1636ff2781..fe714e7b8d 100644--- a/libs/cua/crates/cua-agents/runner/test/run-end.test.mjs+++ b/libs/cua/crates/cua-agents/runner/test/run-end.test.mjs@@ -28,6 +28,135 @@ function stubSdk(root) {);}+async function failureRun(t, { request = "return new Promise(() => {});", config = {}, agent = "setInterval(() => {}, 1000)", previous = {}, log = "", sdk = null } = {}) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "cua-failure-"));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ stubSdk(root);+ const sdkDir = path.join(root, "node_modules/@agentclientprotocol/sdk");+ if (sdk) {+ fs.rmSync(sdkDir, { recursive: true });+ fs.symlinkSync(sdk, sdkDir);+ } else {+ fs.writeFileSync(path.join(sdkDir, "index.js"), `+ export const PROTOCOL_VERSION = 1;+ export const methods = {agent: {initialize: 'initialize', authenticate: 'authenticate', session: {new: 'new', load: 'load', resume: 'resume', prompt: 'prompt'}}, client: {session: {requestPermission: 'permission', update: 'update'}}};+ export const ndJsonStream = () => null;+ export function client() { return {onRequest() {return this}, onNotification() {return this}, connectWith: async (_, callback) => callback({request: async (method, params) => {${request}}})}; }+ `);+ }+ fs.copyFileSync(path.join(here, "..", "acp-runner.mjs"), path.join(root, "runner.mjs"));+ const run = path.join(root, "run");+ fs.mkdirSync(run);+ fs.writeFileSync(path.join(run, "run.json"), JSON.stringify({ cwd: run, agent: {command: process.execPath, args: ["-e", agent]}, startupTimeoutMs: 1000, ...config }));+ fs.writeFileSync(path.join(run, "state.json"), JSON.stringify(previous));+ fs.writeFileSync(path.join(run, "agent.log"), log);+ fs.writeFileSync(path.join(run, "secrets.json"), JSON.stringify({ TOKEN: "secret-12345678" }));+ const child = spawn(process.execPath, [path.join(root, "runner.mjs"), run], {stdio: ["ignore", "ignore", "pipe"], detached: true});+ const kill = () => { try { process.kill(-child.pid, "SIGKILL"); } catch {} };+ t.after(kill);+ let stderr = "";+ child.stderr.on("data", (data) => stderr += data);+ await new Promise((resolve, reject) => {+ const timer = setTimeout(() => { kill(); reject(new Error(`runner hung: ${stderr}`)); }, 4000);+ child.on("exit", () => {clearTimeout(timer); resolve();});+ });+ return {events: fs.readFileSync(path.join(run, "events.jsonl"), "utf8").trim().split("\n").map(JSON.parse), state: JSON.parse(fs.readFileSync(path.join(run, "state.json"), "utf8"))};+}++for (const [name, options, expected] of [+ ["missing executable", {config: {agent: {command: "/missing/cua-agent"}}}, /ENOENT.*spawn: \/missing\/cua-agent[\s\S]*PATH/],+ ["missing interpreter with restricted PATH", {config: {agent: {command: "/usr/bin/env", args: ["cua-missing-interpreter"]}, env: {PATH: "/empty"}}}, /cua-missing-interpreter/],+ ["adapter installation failure", {agent: "console.error('agent not installed'); process.exit(1)", log: "old launch\n"}, /agent not installed/],+ ["initialize timeout", {config: {startupTimeoutMs: 100}}, /timed out.*initialize/],+ ["session timeout", {request: "if (method === 'initialize') return {}; return new Promise(() => {});", config: {startupTimeoutMs: 100}}, /timed out.*session/],+ ["authentication timeout", {request: "if (method === 'initialize') return {authMethods: [{id: 'login'}]}; return new Promise(() => {});", config: {authMethod: "login", startupTimeoutMs: 100}}, /timed out.*authenticate/],+ ["ACP structured error", {request: "while (!(await import('node:fs')).readFileSync(process.argv[2] + '/agent.log', 'utf8').includes('current launch')) await new Promise(r => setTimeout(r, 10)); throw Object.assign(new Error('internal error secret-12345678'), {code: -32603, data: {cause: 'adapter unavailable'}});", agent: "console.error('discarded prefix' + 'x'.repeat(10000) + 'current launch'); setInterval(() => {}, 1000)", config: {startupTimeoutMs: 1000}, log: "old launch\n"}, /-32603[\s\S]*adapter unavailable[\s\S]*current launch/],+ ["authentication required", {request: "if (method === 'initialize') return {agentCapabilities: {mcpCapabilities: {http: true}}}; throw Object.assign(new Error('Authentication required'), {code: -32000});", config: {authHint: "Run ~/.cua/bin/claude inside this bot's Space", mcpServers: [{type: "http", name: "test", url: "http://localhost"}]}}, /Authentication required[\s\S]*~\/\.cua\/bin\/claude.*Space/],+]) {+ test(name + " is diagnostic and terminal", {timeout: 6000}, async (t) => {+ const {events, state} = await failureRun(t, options);+ const errors = events.filter(e => e.type === "error");+ assert.equal(errors.length, 1);+ assert.match(errors[0].message, expected);+ assert.equal(events.filter(e => e.type === "run_exited").length, 1);+ assert.equal(state.status, "failed");+ assert.equal(JSON.stringify({events, state}).includes("secret-12345678"), false);+ assert.equal(errors[0].message.includes("old launch"), false);+ assert.equal(errors[0].message.includes("discarded prefix"), false);+ assert.ok(errors[0].message.length < 6000);+ assert.equal(errors[0].message.includes("PATH="), name === "missing executable");+ if (name === "authentication required") assert.equal(events.some(e => e.type === "notice"), false);+ });+}++test("prompt errors retain the provider reason without launch diagnostics", {timeout: 6000}, async (t) => {+ const {events} = await failureRun(t, {+ config: {prompt: "hello", idleExitSecs: 0.01},+ request: `if (method === 'initialize') return {};+ if (method === 'new') return {sessionId: 's'};+ while (!(await import('node:fs')).readFileSync(process.argv[2] + '/agent.log', 'utf8').includes('earlier turn stderr')) await new Promise(r => setTimeout(r, 10));+ throw Object.assign(new Error('Provider quota exceeded'), {code: -32001, data: {retryAfter: 60}});`,+ agent: "console.error('earlier turn stderr'); setInterval(() => {}, 1000)",+ });+ const errors = events.filter(e => e.type === "error");+ assert.equal(errors.length, 1);+ assert.equal(errors[0].message, "Provider quota exceeded");+ assert.equal(errors[0].code, -32001);+ assert.deepEqual(errors[0].data, {retryAfter: 60});+ assert.equal(errors[0].message.includes("PATH="), false);+ assert.equal(errors[0].message.includes("earlier turn stderr"), false);+ assert.equal(events.filter(e => e.type === "turn_ended").length, 1);+});++test("prompt authentication errors include the guest sign-in command and remain recoverable", {timeout: 6000}, async (t) => {+ const authHint = "Run ~/.cua/bin/claude inside the Space to sign in";+ const {events, state} = await failureRun(t, {+ config: {prompt: "hello", idleExitSecs: 0.01, authHint},+ request: `if (method === 'initialize') return {};+ if (method === 'new') return {sessionId: 's'};+ throw Object.assign(new Error('Authentication required'), {code: -32000});`,+ });+ const errors = events.filter(e => e.type === "error");+ assert.equal(errors.length, 1);+ assert.equal(errors[0].message, `Authentication required\n${authHint}`);+ assert.equal(errors[0].code, -32000);+ assert.equal(events.filter(e => e.type === "turn_ended").length, 1);+ assert.equal(state.status, "exited");+});++test("transport exit ends a pending prompt exactly once", {timeout: 6000}, async (t) => {+ const {events, state} = await failureRun(t, {config: {prompt: "hello"}, request: "if (method === 'initialize') return {}; if (method === 'new') return {sessionId: 's'}; return new Promise(() => {});", agent: "setTimeout(() => process.exit(1), 300)"});+ assert.equal(events.filter(e => e.type === "turn_ended").length, 1);+ assert.equal(state.status, "failed");+});++for (const [name, agent, prompt] of [+ ["stdout closure", "setTimeout(() => process.stdout.end(), 300); setInterval(() => {}, 1000)", "return new Promise(() => {});"],+ ["late prompt rejection", "setTimeout(() => process.exit(1), 300)", "await new Promise(r => setTimeout(r, 400)); throw new Error('transport lost');"],+ ["late prompt success", "setTimeout(() => process.exit(1), 300)", "await new Promise(r => setTimeout(r, 400)); return {stopReason: 'end_turn'};"],+]) {+ test(name + " cannot duplicate or overwrite the terminal turn", {timeout: 6000}, async (t) => {+ const {events, state} = await failureRun(t, {agent, config: {prompt: "hello"}, request: `if (method === 'initialize') return {}; if (method === 'new') return {sessionId: 's'}; ${prompt}`});+ assert.equal(events.filter(e => e.type === "error").length, 1);+ assert.equal(events.filter(e => e.type === "turn_ended").length, 1);+ assert.equal(state.status, "failed");+ assert.equal(state.stopReason, "error");+ });+}++test("real SDK disconnect ends a pending prompt", {timeout: 6000}, async (t) => {+ if (!process.env.CUA_ACP_SDK_DIR) return t.skip("Set CUA_ACP_SDK_DIR to the installed @agentclientprotocol/sdk directory");+ const agent = `require('node:readline').createInterface({input: process.stdin}).on('line', line => {+ const m = JSON.parse(line);+ if (m.method === 'session/prompt') return setTimeout(() => process.exit(1), 30);+ const result = m.method === 'initialize' ? {protocolVersion: 1, agentCapabilities: {}} : {sessionId: 's'};+ process.stdout.write(JSON.stringify({jsonrpc: '2.0', id: m.id, result}) + '\\n');+ });`;+ const {events, state} = await failureRun(t, {sdk: process.env.CUA_ACP_SDK_DIR, agent, config: {prompt: "hello", startupTimeoutMs: 1000}});+ assert.equal(events.filter(e => e.type === "turn_ended").length, 1);+ assert.equal(state.status, "failed");+});+test("run end sends DELETE /mcp with the run's agent session", async () => {const seen = [];const server = http.createServer((req, res) => {diff --git a/libs/cua/crates/cua-agents/src/harness.rs b/libs/cua/crates/cua-agents/src/harness.rsindex b8b863c737..87f0179cd9 100644--- a/libs/cua/crates/cua-agents/src/harness.rs+++ b/libs/cua/crates/cua-agents/src/harness.rs@@ -351,7 +351,9 @@ impl Harness {);match (self.logins, self.cli) {(Some(l), Some(cli)) if !l.is_empty() => {- s.push_str(&format!(", or sign in by running `{cli}` inside the Space"));+ s.push_str(&format!(+ ", or sign in by running `~/.cua/bin/{cli}` inside the Space"+ ));}(None, _) => s.push_str(&format!(", or configure {} inside the Space", self.name)),_ => {}diff --git a/libs/cua/crates/cua-agents/src/runs.rs b/libs/cua/crates/cua-agents/src/runs.rsindex 9b14311d55..828ea0865e 100644--- a/libs/cua/crates/cua-agents/src/runs.rs+++ b/libs/cua/crates/cua-agents/src/runs.rs@@ -959,6 +959,7 @@ impl Agents {"exitWhenIdle": opts.exit_when_idle,"idleExitSecs": opts.idle_exit_secs.unwrap_or(1800),"authMethod": h.auth_method,+ "authHint": h.auth_hint(),"keyCheck": harness::key_check(h, &opts.env, endpoint.is_some()),"mcpBridge": format!("{}/.cua/bin/mcp-remote", self.home),"modeKinds": h.mode_kinds,@@ -1162,9 +1163,15 @@ impl Agents {if before.alive == Some(false) {// Restart: installs are cached, the runner resumes the session.if before.status == RunStatus::Failed {+ let mut state = self+ .json_file(&format!("{rdir}/state.json"))+ .await?+ .unwrap_or_else(|| json!({}));+ state["status"] = json!("starting");+ state["error"] = Value::Null;self.write(&format!("{rdir}/state.json"),- br#"{"status":"starting","error":null}"#.to_vec(),+ serde_json::to_vec(&state)?,0o600,).await?;@@ -1391,7 +1398,8 @@ mod tests {"{e}");assert!(- e.contains("Authentication required") && e.contains("`claude`"),+ e.contains("Authentication required")+ && e.contains("`~/.cua/bin/claude` inside the Space"),"{e}");assert!(diff --git a/libs/cua/crates/cua-agents/tests/e2e_live.rs b/libs/cua/crates/cua-agents/tests/e2e_live.rsindex 95d2a14d4b..7be4e595ba 100644--- a/libs/cua/crates/cua-agents/tests/e2e_live.rs+++ b/libs/cua/crates/cua-agents/tests/e2e_live.rs@@ -156,6 +156,26 @@ async fn e2e_harness_runs() {&& r.text.contains(&format!("{id}-proof"))&& arts.iter().any(|x| x.path.ends_with("/proof.txt"));// Follow-up in the same session.+ let session = a.status(&run).await.unwrap().session_id;+ let resumable = a+ .events(&run, 0, 100_000)+ .await+ .unwrap()+ .events+ .iter()+ .any(|e| {+ e.kind == "initialized"+ && (e.raw["agentCapabilities"]["loadSession"] == true+ || e.raw["agentCapabilities"]["sessionCapabilities"]["resume"].is_object())+ });+ a.stop(&run).await.unwrap();+ a.guest()+ .run(cua_spacesd_client::Command::shell(format!(+ "python3 -c 'import json; p=\"{}/state.json\"; s=json.load(open(p)); s.update(status=\"failed\", error=\"transport lost\"); json.dump(s,open(p,\"w\"))'",+ started.run_dir+ )))+ .await+ .unwrap();a.send(&run,"Now a follow-up. mock: tool list_windows; say followup-ok",@@ -168,7 +188,19 @@ async fn e2e_harness_runs() {}).await;let r2 = a.result(&run).await.unwrap();- let followup_ok = fu && r2.turn == 2 && r2.text.contains("followup-ok");+ let followup_ok = fu+ && r2.turn == 2+ && r2.text.contains("followup-ok")+ && (!resumable || a.status(&run).await.unwrap().session_id == session);+ let restarted = a.events(&run, 0, 100_000).await.unwrap().events;+ assert_eq!(+ restarted+ .iter()+ .filter(|e| e.kind == "turn_started")+ .count(),+ 2,+ "restart must not replay the introduction"+ );// The sandbox's own MCP (cua-driver through the spacesd) was called.let evs = a.events(&run, 0, 100_000).await.unwrap().events;let mcp_ok = evs.iter().any(|e| {