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): report directory refresh failures (#4716)
injaneity1f96a4bf0e3f
diff --git a/.github/workflows/ci-cua-sdk.yml b/.github/workflows/ci-cua-sdk.ymlindex 4041c3f9a6..57e920317b 100644--- a/.github/workflows/ci-cua-sdk.yml+++ b/.github/workflows/ci-cua-sdk.yml@@ -98,6 +98,8 @@ jobs:- name: Build (wasm32)if: runner.os == 'Linux'run: cargo build --locked -p cua-sdk --target wasm32-unknown-unknown --no-default-features+ - name: Test Spaces discovery and post-create directory failures+ run: cargo test --locked -p cua-spaces --test relay --test cloud_discovery -- --test-threads=4- name: Test (embedded, daemon over UDS and loopback, CLI, Cua Spaces extensions)run: >cargo test --locked --no-fail-fast -p cua-sdk -p cua-daemon -p cua-clidiff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swiftindex 3c4e79e2a6..ad3d42553a 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift@@ -44,6 +44,7 @@ public final class AppModel {public private(set) var roster: AppRosterStatepublic var query = ""public var selection: MainSelection?+ public var rosterError: String?public var banner: String?public var bannerIsError = falsepublic var showingNewSpace = false@@ -385,13 +386,17 @@ public final class AppModel {creates = appCreatesSettle(state: creates, spaces: registrySpaces)recompose()loaded = true+ rosterError = nilif selection == nil, let first = sidebar.selectedId { selection = .space(first) }// A preview for every running Space from the daemon's cache// (it survives restarts), before one is opened.let running = streamableSpaceIdsTask { await thumbnails.warm(running) }} catch {- show(error: "Could not list Spaces: \(LiveSpacesBackend.words(error))")+ // Errors may contain server bodies or credential-bearing URLs.+ rosterError = loaded+ ? "Could not refresh Spaces. Previously loaded rows may be out of date."+ : "Could not load Spaces. Try refreshing again."}}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swiftindex e36181ace5..6fa01f53ee 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift@@ -22,7 +22,14 @@ public struct MainWindow: View {.navigationSplitViewColumnWidth(min: 200, ideal: 230, max: 300)} detail: {detail- .safeAreaInset(edge: .top, spacing: 0) { DevicesBanner(devices: model.devices) }+ .safeAreaInset(edge: .top, spacing: 0) {+ VStack(spacing: 0) {+ DevicesBanner(devices: model.devices)+ if let error = model.rosterError {+ SpacesDiscoveryNotice(error: error)+ }+ }+ }}.background(WindowReader { model.dropTargets.window = $0 }).searchable(text: $model.query, placement: .sidebar, prompt: chrome.searchPlaceholder)@@ -135,7 +142,7 @@ struct Sidebar: View {}}}- if let empty = sidebar.emptyText, sidebar.thisMachine == nil {+ if let empty = sidebar.emptyText, sidebar.thisMachine == nil, model.rosterError == nil {Text(empty).foregroundStyle(.secondary)}Section {@@ -382,10 +389,23 @@ struct EmptySpaces: View {var body: some View {let chrome = model.chromeContentUnavailableView {- Text(chrome.emptyTitle)+ Text(model.rosterError == nil ? chrome.emptyTitle : "Spaces could not be loaded")} actions: {Button(chrome.emptyAction) { Task { await model.openNewSpace() } }.buttonStyle(.glassProminent)}}}++/// Persistent discovery failure notice above the selected Space.+struct SpacesDiscoveryNotice: View {+ let error: String++ var body: some View {+ Text(error)+ .foregroundStyle(.red)+ .padding()+ .frame(maxWidth: .infinity, alignment: .leading)+ .accessibilityIdentifier("spaces-discovery-error")+ }+}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DiscoveryTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DiscoveryTests.swiftnew file mode 100644index 0000000000..5ef4ec59d7--- /dev/null+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DiscoveryTests.swift@@ -0,0 +1,116 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import CuaSDK+import CuaSpacesFFI+import CuaSpacesStreaming+@testable import CuaSpacesMacKit+import Foundation+import Testing+import SwiftUI+import Vision++/// Only the roster is scripted. No service, account, or desktop is contacted.+private final class DiscoveryBackend: SpacesBackend, @unchecked Sendable {+ var result: Result<[AppSpaceRow], Error> = .success([])+ func rows() async throws -> [AppSpaceRow] { try result.get() }+ func create(_ args: AppCreateSpaceArgs, createId: String, progress: @escaping @Sendable (SpaceCreateProgress) -> Void) async throws -> String { fatalError("unexpected create") }+ func cancelCreate(createId: String) async throws {}+ func add(url: String, token: String?, name: String?) async throws {}+ func remove(id: String, removeOnly: Bool) async throws {}+ func setPower(id: String, on: Bool) async throws {}+ func streamProvider(id: String) async throws -> SpaceStreamSourceProviding {+ try await FixtureSpacesBackend().streamProvider(id: id)+ }+ func localBackends() async -> [String]? { nil }+ func localStorage() async -> LocalStorage? { nil }+ func cloudAvailable() async -> Bool { false }+ func teleportContext(id: String) async throws -> (CuaSpacesFFI.Teleport, CuaSDK.Space)? { nil }+ func teleportHandle() -> CuaSpacesFFI.Teleport? { nil }+ func sendFiles(id: String, paths: [String]) async throws -> [AppSentFileInfo] { [] }+ func agentRuns(id: String) async throws -> [AppSpaceAgentRun] { [] }+}++@MainActor+@Suite("Discovery errors", .serialized)+struct DiscoveryTests {+ @Test func coldFailureIsSafeAndRecoveryClearsOnlyRosterError() async {+ let backend = DiscoveryBackend()+ backend.result = .failure(CuaError.Internal(message: "https://user:[email protected]/?token=private"))+ let model = ViewModelTests().makeModel(backend)+ model.show(error: "Unrelated action failed")+ await model.refresh()+ #expect(model.rosterError == "Could not load Spaces. Try refreshing again.")+ #expect(!model.loaded)+ backend.result = .success([])+ await model.refresh()+ #expect(model.rosterError == nil)+ #expect(model.loaded)+ #expect(model.banner == "Unrelated action failed")+ }++ @Test func warmFailureRetainsRowsAndEmptySuccessRemovesThem() async {+ let backend = DiscoveryBackend()+ backend.result = .success(FixtureSpacesBackend.sample)+ let model = ViewModelTests().makeModel(backend)+ await model.refresh()+ let before = model.spaces.map(\.id)+ #expect(!before.isEmpty)+ backend.result = .failure(CuaError.Internal(message: "transport failed"))+ await model.refresh()+ #expect(model.spaces.map(\.id) == before)+ #expect(model.rosterError == "Could not refresh Spaces. Previously loaded rows may be out of date.")+ backend.result = .success([])+ await model.refresh()+ #expect(!model.spaces.contains { $0.id == "local:aurora" || $0.id == "cloud:builder" })+ #expect(model.rosterError == nil)+ }++ @Test func warmFailureSidebarRetainsRows() async throws {+ let snapshots = SnapshotTests()+ let backend = DiscoveryBackend()+ backend.result = .success(FixtureSpacesBackend.sample)+ let model = ViewModelTests().makeModel(backend)+ await model.refresh()+ backend.result = .failure(CuaError.Internal(message: "fixture failure"))+ await model.refresh()+ try snapshots.assertSnapshot(Sidebar(model: model).frame(width: 260),+ "discovery-warm-sidebar", size: CGSize(width: 260, height: 520))+ }+ @Test func coldFailureTitleAndWindowNotice() async throws {+ let snapshots = SnapshotTests()+ let backend = DiscoveryBackend()+ backend.result = .failure(CuaError.Internal(message: "fixture"))+ let model = ViewModelTests().makeModel(backend)+ await model.refresh()+ let error = try #require(model.rosterError)+ let content = VStack(spacing: 0) {+ SpacesDiscoveryNotice(error: error)+ EmptySpaces(model: model)+ }.frame(width: 560, height: 300).background(Color.white)+ let size = CGSize(width: 560, height: 300)+ // Native ContentUnavailableView lays out lazily on this offscreen+ // surface; settle it before measuring and exporting the same bitmap.+ _ = snapshots.render(content, size: size)+ _ = snapshots.render(content, size: size)+ // Read the actual rendered pixels. A whole-window pixel tolerance+ // alone can miss a removed label that occupies only a small area.+ let bitmap = snapshots.render(content, size: size)+ let request = VNRecognizeTextRequest()+ request.recognitionLanguages = ["en-US"]+ request.recognitionLevel = .accurate+ request.usesLanguageCorrection = false+ let image = try #require(bitmap.cgImage)+ try VNImageRequestHandler(cgImage: image, options: [:]).perform([request])+ let text = (request.results ?? []).compactMap { $0.topCandidates(1).first?.string }.joined(separator: " ")+ #expect(text.contains("Could not load Spaces. Try refreshing again."))+ #expect(text.contains("Spaces could not be loaded"))+ // Export the exact bitmap OCR checked, not a separate render.+ if let directory = ProcessInfo.processInfo.environment["SNAPSHOT_EXPORT_DIR"] {+ let url = URL(fileURLWithPath: directory).appendingPathComponent("discovery-cold-content.png")+ let png = try #require(bitmap.representation(using: .png, properties: [:]))+ try png.write(to: url)+ }+ }++}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/discovery-warm-sidebar.png b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/discovery-warm-sidebar.pngnew file mode 100644index 0000000000..b2e3346456Binary files /dev/null and b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/Snapshots/discovery-warm-sidebar.png differdiff --git a/apps/cua-spaces/src-tauri/tests/commands.rs b/apps/cua-spaces/src-tauri/tests/commands.rsindex 7f490cec8e..afe62850cd 100644--- a/apps/cua-spaces/src-tauri/tests/commands.rs+++ b/apps/cua-spaces/src-tauri/tests/commands.rs@@ -823,3 +823,28 @@ async fn the_wizard_gets_the_first_gpu_option_of_each_runtime_that_has_one() {}]));}++/// This is the compiled command-layer route called by Tauri list_spaces,+/// not the frontend's injected listSpaces stub.+#[tokio::test]+async fn directory_failure_is_an_error_and_empty_recovery_succeeds() {+ struct Tokens(Mutex<String>);+ #[async_trait]+ impl cua_host::AccountTokens for Tokens {+ async fn access_token(&self) -> cua_host::Result<String> {+ Ok(self.0.lock().unwrap().clone())+ }+ }+ let relay = cua_host::testing::FakeRelay::start().await;+ relay.add_account("valid", "owner", None);+ let tokens = Arc::new(Tokens(Mutex::new("bad".into())));+ let home = tempfile::tempdir().unwrap();+ let mut config = CoreConfig::hermetic(home.path());+ config.relay = Some(cua_spaces::RelayAccount::new(&relay.url, tokens.clone()));+ let app = AppCore::new(config);+ let error = app.list_spaces().await.unwrap_err();+ assert!(error.contains("Relay authentication failed"), "{error}");+ assert!(!error.contains(&relay.url));+ *tokens.0.lock().unwrap() = "valid".into();+ assert!(app.list_spaces().await.unwrap().is_empty());+}diff --git a/apps/cua-spaces/src/components/desktop/MainWindow.test.tsx b/apps/cua-spaces/src/components/desktop/MainWindow.test.tsxindex 8ea42ff6ab..793df868fe 100644--- a/apps/cua-spaces/src/components/desktop/MainWindow.test.tsx+++ b/apps/cua-spaces/src/components/desktop/MainWindow.test.tsx@@ -552,3 +552,38 @@ describe("MainWindow launch at login", () => {expect(loginItem.calls).toEqual([]);});});++describe("discovery failures", () => {+ it("shows a safe cold error and recovers to a valid empty roster", async () => {+ let changed: (() => void) | undefined;+ let fails = true;+ setup({+ listSpaces: async () => { if (fails) throw new Error("https://user:[email protected]/?token=private"); return []; },+ onSpacesChanged: async (handler) => { changed = handler; return () => {}; },+ });+ expect(await screen.findByRole("alert")).toHaveTextContent("Could not load Spaces. Try refreshing again.");+ expect(document.body).not.toHaveTextContent("token=private");+ fails = false;+ await act(async () => { changed!(); });+ await waitFor(() => expect(screen.queryByText("Could not load Spaces. Try refreshing again.")).toBeNull());+ expect(screen.queryByRole("option", { name: /Aurora/ })).toBeNull();+ });++ it("retains warm rows during failure, then removes them after empty success", async () => {+ let changed: (() => void) | undefined;+ let result: SpaceRow[] | Error = ROWS;+ setup({+ listSpaces: async () => { if (result instanceof Error) throw result; return result; },+ onSpacesChanged: async (handler) => { changed = handler; return () => {}; },+ });+ await screen.findByRole("option", { name: /Aurora/ });+ result = new Error("transport failed: secret");+ await act(async () => { changed!(); });+ expect(await screen.findByRole("alert")).toHaveTextContent("Could not refresh Spaces. Previously loaded rows may be out of date.");+ expect(screen.getByRole("option", { name: /Aurora/ })).toBeInTheDocument();+ result = [];+ await act(async () => { changed!(); });+ await waitFor(() => expect(screen.queryByRole("option", { name: /Aurora/ })).toBeNull());+ expect(screen.queryByText("Could not refresh Spaces. Previously loaded rows may be out of date.")).toBeNull();+ });+});diff --git a/apps/cua-spaces/src/components/desktop/MainWindow.tsx b/apps/cua-spaces/src/components/desktop/MainWindow.tsxindex 4ca5e88ef0..0b1ed16588 100644--- a/apps/cua-spaces/src/components/desktop/MainWindow.tsx+++ b/apps/cua-spaces/src/components/desktop/MainWindow.tsx@@ -647,7 +647,7 @@ export function MainWindow({</ul></div>))}- {sidebar.emptyText && !sidebar.thisMachine && (+ {sidebar.emptyText && !sidebar.thisMachine && !sync.rosterError && (<p className="dw-hint dw-nav-section">{sidebar.emptyText}</p>)}<ul className="dw-nav-list" aria-label="Agents">@@ -797,6 +797,12 @@ export function MainWindow({/>)}+ {sync.rosterError && (+ <div className="dw-banner" data-tone="error" role="alert">+ {sync.rosterError}+ </div>+ )}+{banner && (<divclassName="dw-banner"@@ -874,7 +880,7 @@ export function MainWindow({<span className="dw-empty-art"><Sym name="square.grid.2x2" /></span>- <h2>{chrome.emptyTitle}</h2>+ <h2>{sync.rosterError ? "Spaces could not be loaded" : chrome.emptyTitle}</h2><buttontype="button"className="dw-btn dw-btn-primary dw-btn-lg"diff --git a/apps/cua-spaces/src/state/cloud.tsx b/apps/cua-spaces/src/state/cloud.tsxindex 5a42400598..1e7ac8c92b 100644--- a/apps/cua-spaces/src/state/cloud.tsx+++ b/apps/cua-spaces/src/state/cloud.tsx@@ -73,6 +73,8 @@ export function viewerRequestFor(space: Space): ViewerWindowRequest | null {export interface FleetSync {live: boolean;+ /** Refresh failure; previously loaded rows remain available. */+ rosterError: string | null;/** Whether Cua Cloud credentials are configured in the shell. */fleetConfigured: boolean;/** OAuth client id reported by the shell, when signed in; shown in Settings. */@@ -127,6 +129,8 @@ export function useFleetSync(now: () => number,): FleetSync {const live = fleet.isNative;+ const [rosterError, setRosterError] = useState<string | null>(null);+ const rosterLoaded = useRef(false);const [fleetConfigured, setFleetConfigured] = useState(false);const [clientId, setClientId] = useState<string | undefined>(undefined);const [identity, setIdentity] = useState<string | undefined>(undefined);@@ -180,12 +184,21 @@ export function useFleetSync(const refresh = useCallback(async () => {try {rowsRef.current = await fleet.listSpaces();+ rosterLoaded.current = true;+ setRosterError(null);// Finished creates the registry lists, finished deletes it dropped// (by id: the timestamp does not matter).createsRef.current = settleCreates(createsRef.current,rowsRef.current.map((row) => rowToSpace(row, 0)),);+ } catch {+ // Do not display server bodies or credential-bearing URLs.+ const message = rosterLoaded.current+ ? "Could not refresh Spaces. Previously loaded rows may be out of date."+ : "Could not load Spaces. Try refreshing again.";+ setRosterError(message);+ throw new Error(message);} finally {publish();}@@ -478,6 +491,7 @@ export function useFleetSync(return {live,+ rosterError,fleetConfigured,clientId,identity,diff --git a/libs/cua-spacesd/tests/spaces-e2e/tests/daemon_spaces.rs b/libs/cua-spacesd/tests/spaces-e2e/tests/daemon_spaces.rsindex cdc4dd4f4c..2651fdd1b0 100644--- a/libs/cua-spacesd/tests/spaces-e2e/tests/daemon_spaces.rs+++ b/libs/cua-spacesd/tests/spaces-e2e/tests/daemon_spaces.rs@@ -511,11 +511,24 @@ async fn space_service_lists_the_accounts_relay_machines() {.space.unwrap();assert_eq!(resolved.id, row.id);- // Signed out: the listing still works, without relay rows.+ // A configured account that loses authentication must not look like+ // successful empty discovery.rt.spaces().set_relay(Some(cua_spaces::RelayAccount::new(relay.url.clone(),Arc::new(cua_spaces::relay::NoAccount),)));+ let error = c+ .spaces()+ .list_spaces(pb::ListSpacesRequest {})+ .await+ .unwrap_err();+ assert_eq!(error.code(), tonic::Code::Unauthenticated);+ assert_eq!(+ error.message(),+ "Relay authentication failed. Sign in again to refresh your machines."+ );+ // Explicitly disabling relay discovery still permits a local-only list.+ rt.spaces().set_relay(None);let listed = c.spaces().list_spaces(pb::ListSpacesRequest {})diff --git a/libs/cua/crates/cua-cli/src/browse.rs b/libs/cua/crates/cua-cli/src/browse.rsindex d53161e924..49dac7d573 100644--- a/libs/cua/crates/cua-cli/src/browse.rs+++ b/libs/cua/crates/cua-cli/src/browse.rs@@ -197,10 +197,12 @@ pub async fn start(/// the other Spaces tools accept it) unless it already is one.pub async fn register_space(cua: &Arc<Cua>, sb: &str) -> Result<(), CuaError> {let spaces = cua.spaces();- let listed = spaces.call_tool_json("list_spaces".into(), None).await?;- let known = listed.content_json.contains(&format!("\"{sb}\""));- if known {- return Ok(());+ // SDK resolve verifies a cached/registered record without refreshing the+ // unrelated relay directory. Runtime resolve alone only parses some IDs.+ match spaces.resolve(sb.into()).await {+ Ok(_) => return Ok(()),+ Err(CuaError::NotFound(_)) => {}+ Err(error) => return Err(error),}let r = spaces.call_tool_json("add_space".into(), Some(json!({"url": sb}).to_string()))@@ -218,6 +220,78 @@ pub async fn register_space(cua: &Arc<Cua>, sb: &str) -> Result<(), CuaError> {mod tests {use super::*;+ #[tokio::test]+ async fn registration_uses_records_during_relay_failure() {+ for daemon in [false, true] {+ let home = tempfile::tempdir().unwrap();+ let relay = cua_host::testing::FakeRelay::start().await;+ let target = cua_spacesd_client::testing::MockServer::start(Default::default()).await;+ let runtime = cua_daemon::Runtime::new(cua_daemon::RuntimeConfig {+ spaces_home: Some(home.path().join("spaces")),+ state_dir: Some(home.path().join("sandboxes")),+ ..Default::default()+ })+ .unwrap();+ runtime+ .spaces()+ .set_relay(Some(cua_spaces::RelayAccount::new(+ &relay.url,+ Arc::new(cua_host::StaticToken("invalid-token".into())),+ )));+ let server = if daemon {+ Some(+ cua_daemon::server::start(+ runtime.clone(),+ cua_daemon::server::ServerConfig {+ socket_path: None,+ loopback: Some("127.0.0.1:0".parse().unwrap()),+ token: "fixture".into(),+ discovery_path: Some(home.path().join("daemon.json")),+ bridge_ticket_ttl: Duration::from_secs(30),+ },+ )+ .await+ .unwrap(),+ )+ } else {+ None+ };+ let cua = match &server {+ Some(server) => {+ Cua::connect(server.loopback_url.clone(), Some(server.token.clone())).unwrap()+ }+ None => Cua::from_runtime(runtime.clone()),+ };+ assert!(cua.spaces().list().await.is_err());+ // Canonical syntax is not evidence of registration.+ let id = format!("direct:{}", target.addr);+ assert!(matches!(+ cua.spaces().resolve(id.clone()).await,+ Err(CuaError::NotFound(_))+ ));+ register_space(&cua, &id).await.unwrap();+ assert_eq!(runtime.spaces().registry().list().unwrap().len(), 1);+ assert_eq!(cua.spaces().resolve(id.clone()).await.unwrap().id, id);+ // Existing records must not be re-added (and lose their metadata).+ let path = home.path().join("spaces/spaces.json");+ let before = std::fs::read(&path).unwrap();+ target+ .state+ .refuse_capabilities+ .store(true, std::sync::atomic::Ordering::SeqCst);+ register_space(&cua, &id).await.unwrap();+ assert_eq!(std::fs::read(&path).unwrap(), before);+ // A corrupt registry is an error, not proof of absence.+ std::fs::write(&path, b"not json").unwrap();+ let error = register_space(&cua, &id).await.unwrap_err();+ assert!(!matches!(error, CuaError::NotFound(_)));+ assert_eq!(std::fs::read(&path).unwrap(), b"not json");+ if let Some(server) = server {+ server.shutdown();+ }+ }+ }+#[test]fn picks_the_launched_window_and_the_active_tab() {let list = json!({"windows": [diff --git a/libs/cua/crates/cua-cli/src/sandbox.rs b/libs/cua/crates/cua-cli/src/sandbox.rsindex ba16f53b5e..966ef6de34 100644--- a/libs/cua/crates/cua-cli/src/sandbox.rs+++ b/libs/cua/crates/cua-cli/src/sandbox.rs@@ -3025,6 +3025,157 @@ pub(crate) fn confirm_delete(mod tests {use super::*;+ use cua_sandbox_core::{+ InstanceStatus, LocalEndpoints, LocalInstance, LocalRuntime, LocalStartSpec, LocalSummary,+ RuntimeError,+ };+ use std::{collections::BTreeMap, sync::Mutex};++ struct FakeRuntime {+ port: u16,+ started: Mutex<Vec<LocalStartSpec>>,+ deleted: Mutex<Vec<String>>,+ running: Mutex<BTreeMap<String, bool>>,+ }++ #[async_trait::async_trait]+ impl LocalRuntime for FakeRuntime {+ fn backend(&self) -> String {+ "fake".into()+ }+ async fn start(&self, spec: &LocalStartSpec) -> Result<LocalInstance, RuntimeError> {+ self.started.lock().unwrap().push(spec.clone());+ self.running.lock().unwrap().insert(spec.name.clone(), true);+ Ok(LocalInstance {+ name: spec.name.clone(),+ backend: "fake".into(),+ status: InstanceStatus::Running,+ endpoints: self.endpoints(&spec.name).await?,+ })+ }+ async fn stop(&self, name: &str) -> Result<(), RuntimeError> {+ self.running.lock().unwrap().insert(name.into(), false);+ Ok(())+ }+ async fn resume(&self, name: &str) -> Result<LocalInstance, RuntimeError> {+ Ok(LocalInstance {+ name: name.into(),+ backend: "fake".into(),+ status: InstanceStatus::Running,+ endpoints: self.endpoints(name).await?,+ })+ }+ async fn list(&self) -> Result<Vec<LocalSummary>, RuntimeError> {+ Ok(vec![])+ }+ async fn status(&self, name: &str) -> Result<InstanceStatus, RuntimeError> {+ match self.running.lock().unwrap().get(name) {+ Some(true) => Ok(InstanceStatus::Running),+ Some(false) => Ok(InstanceStatus::Stopped),+ None => Err(RuntimeError::NotFound(name.into())),+ }+ }+ async fn delete(&self, name: &str) -> Result<(), RuntimeError> {+ self.deleted.lock().unwrap().push(name.into());+ self.running.lock().unwrap().remove(name);+ Ok(())+ }+ async fn endpoints(&self, _name: &str) -> Result<LocalEndpoints, RuntimeError> {+ Ok(LocalEndpoints {+ host: "127.0.0.1".into(),+ ports: [(3211u16, self.port)].into(),+ ..Default::default()+ })+ }+ }++ #[tokio::test]+ async fn post_create_registration_outage_does_not_enter_cleanup() {+ let mut images = cua_image::testing::FakeRegistry::default();+ images.index(+ "ghcr.io/example/discovery:1",+ &["amd64", "arm64"],+ false,+ None,+ );+ cua_image::resolve::set_source(Some(Arc::new(images)));+ for daemon in [false, true] {+ let home = tempfile::tempdir().unwrap();+ let relay = cua_host::testing::FakeRelay::start().await;+ let srv = cua_spacesd_client::testing::MockServer::start(Default::default()).await;+ let local = Arc::new(FakeRuntime {+ port: srv.addr.port(),+ started: Mutex::new(vec![]),+ deleted: Mutex::new(vec![]),+ running: Mutex::new(BTreeMap::new()),+ });+ let runtime = cua_daemon::Runtime::new(cua_daemon::RuntimeConfig {+ local: Some(local.clone()),+ state_dir: Some(home.path().join("sandboxes")),+ spaces_home: Some(home.path().join("spaces")),+ ..Default::default()+ })+ .unwrap();+ runtime+ .spaces()+ .set_relay(Some(cua_spaces::RelayAccount::new(+ &relay.url,+ Arc::new(cua_host::StaticToken("bad".into())),+ )));+ let server = if daemon {+ Some(+ cua_daemon::server::start(+ runtime.clone(),+ cua_daemon::server::ServerConfig {+ socket_path: None,+ loopback: Some("127.0.0.1:0".parse().unwrap()),+ token: "fixture".into(),+ discovery_path: Some(home.path().join("daemon.json")),+ bridge_ticket_ttl: std::time::Duration::from_secs(30),+ },+ )+ .await+ .unwrap(),+ )+ } else {+ None+ };+ let cua = match &server {+ Some(server) => {+ Cua::connect(server.loopback_url.clone(), Some(server.token.clone())).unwrap()+ }+ None => Cua::from_runtime(runtime.clone()),+ };+ let mut options = SandboxCreateOptions::auto("ghcr.io/example/discovery:1");+ options.on = Some("local".into());+ options.kind = Some("container".into());+ options.name = Some("created-once".into());+ let sandbox = cua.sandboxes().create(options).await.unwrap();+ assert!(cua.spaces().list().await.is_err());+ // Exercise the actual registration and failure-cleanup seam used+ // after create by --browser, without launching a real browser.+ let registered = crate::browse::register_space(&cua, &sandbox.id()).await;+ let succeeded = registered.is_ok();+ if let Err(error) = registered {+ failed_after_create(&sandbox, false, error).await;+ }+ assert_eq!(local.started.lock().unwrap().len(), 1);+ assert!(+ local.deleted.lock().unwrap().is_empty(),+ "directory failure deleted the created sandbox"+ );+ assert!(succeeded);+ assert!(home.path().join("sandboxes/created-once.json").exists());+ assert_eq!(+ cua.spaces().resolve(sandbox.id()).await.unwrap().id,+ sandbox.id()+ );+ if let Some(server) = server {+ server.shutdown();+ }+ }+ }+#[test]fn sidecar_and_registry_secret_flags_parse() {let c = parse_sidecar("redis:7-alpine,port=6379,env=A=b=c,name=db").unwrap();diff --git a/libs/cua/crates/cua-sdk/tests/topologies.rs b/libs/cua/crates/cua-sdk/tests/topologies.rsindex af299adb71..479bca2f58 100644--- a/libs/cua/crates/cua-sdk/tests/topologies.rs+++ b/libs/cua/crates/cua-sdk/tests/topologies.rs@@ -42,6 +42,13 @@ enum Topology {}async fn world(t: Topology) -> (World, Arc<Cua>) {+ world_with_relay(t, None).await+}++async fn world_with_relay(+ t: Topology,+ relay: Option<cua_spaces::RelayAccount>,+) -> (World, Arc<Cua>) {let env = fixtures::start_env(Some(TOKEN), None).await;// Port forwards on a direct sandbox go over the driver's /tunnel.env.mock@@ -59,6 +66,7 @@ async fn world(t: Topology) -> (World, Arc<Cua>) {..Default::default()}).unwrap();+ runtime.spaces().set_relay(relay);let (cua, daemon) = match t {Topology::Embedded => {// Host local public URLs in-process: never reach a daemon the@@ -844,3 +852,37 @@ async fn daemon_rejects_wrong_token_and_reports_missing_daemon() {.await.expect("daemon stopped");}++async fn discovery_refusal(t: Topology) {+ let relay = cua_host::testing::FakeRelay::start().await;+ let (_world, cua) = world_with_relay(+ t,+ Some(cua_spaces::RelayAccount::new(+ &relay.url,+ Arc::new(cua_host::StaticToken("invalid-token".into())),+ )),+ )+ .await;+ let error = cua.spaces().list().await.unwrap_err();+ match error {+ CuaError::Unauthenticated(message) => assert_eq!(+ message,+ "Relay authentication failed. Sign in again to refresh your machines."+ ),+ other => panic!("unexpected discovery refusal: {other:?}"),+ }+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn discovery_refusal_embedded() {+ discovery_refusal(Topology::Embedded).await;+}+#[cfg(unix)]+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn discovery_refusal_daemon_socket() {+ discovery_refusal(Topology::DaemonSocket).await;+}+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn discovery_refusal_daemon_loopback() {+ discovery_refusal(Topology::DaemonLoopback).await;+}diff --git a/libs/cua/crates/cua-spaces/src/cloud.rs b/libs/cua/crates/cua-spaces/src/cloud.rsindex 9d08721f95..96f55a7fef 100644--- a/libs/cua/crates/cua-spaces/src/cloud.rs+++ b/libs/cua/crates/cua-spaces/src/cloud.rs@@ -146,12 +146,27 @@ impl Spaces {if let Err(e) = self.space(&id).await {tracing::warn!(space = %id, "the new cloud Space did not answer its handshake yet: {e}");}- let info = self- .list_all()- .await?+ // Provisioning has already succeeded. A directory outage must not+ // conceal a recorded target or imply that creation should be retried.+ let listed = match self.list_all().await {+ Ok(rows) => Ok(rows),+ Err(Error::Relay(_)) => self.list(),+ Err(e) => Err(e),+ };+ let unavailable = || {+ Error::Relay(cua_host::Error::Relay(+ concat!(+ "The cloud sandbox was created, but its Space details could not be read. ",+ "Inspect the existing sandbox before retrying creation."+ )+ .into(),+ ))+ };+ let info = listed+ .map_err(|_| unavailable())?.into_iter().find(|i| i.id == id)- .ok_or_else(|| Error::NotFound(format!("{id} on the relay")))?;+ .ok_or_else(unavailable)?;Ok(info)}diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rsindex 134d221367..2b21ab5910 100644--- a/libs/cua/crates/cua-spaces/src/spaces.rs+++ b/libs/cua/crates/cua-spaces/src/spaces.rs@@ -746,18 +746,26 @@ impl Spaces {Ok(out)}- /// Refreshes the relay directory (when a relay account is configured;- /// a failure is logged, not fatal) and lists every Space.+ /// Refreshes the relay directory when an account is configured, then+ /// lists every Space. A failed refresh is an error, not an empty or+ /// current directory. [`Self::list`] remains the cached, local read.pub async fn list_all(&self) -> Result<Vec<SpaceInfo>> {- if self.relay_account().is_some()- && let Err(e) = self.relay_machines().await- {- // Not signed in is the normal state of many hosts.- if e.tag() == "unauthenticated" {- tracing::debug!(error = %e, "relay directory skipped");- } else {- tracing::warn!(error = %e, "relay directory unavailable");- }+ if self.relay_account().is_some() {+ self.relay_machines().await.map_err(|e| {+ // Relay errors can contain server bodies and credential-bearing+ // URLs. Discovery's public error needs only the stable kind.+ Error::Relay(match e.tag() {+ "unauthenticated" => cua_host::Error::Unauthenticated(+ "Relay authentication failed. Sign in again to refresh your machines."+ .into(),+ ),+ "permission_denied" => cua_host::Error::PermissionDenied(+ "This device could not list relay machines. Check its account access."+ .into(),+ ),+ _ => cua_host::Error::Relay("Could not refresh relay machines.".into()),+ })+ })?;}self.list()}diff --git a/libs/cua/crates/cua-spaces/tests/cloud_discovery.rs b/libs/cua/crates/cua-spaces/tests/cloud_discovery.rsnew file mode 100644index 0000000000..e0abe8d5d1--- /dev/null+++ b/libs/cua/crates/cua-spaces/tests/cloud_discovery.rs@@ -0,0 +1,167 @@+//! Post-provisioning discovery with a fake cloud provider, fake registry and+//! loopback relay. No cloud account, VM, container, or real resource is used.+use async_trait::async_trait;+use cua_host::testing::FakeRelay;+use cua_image::testing::FakeRegistry;+use cua_sandbox_core::{+ ImageMode, PortExposure, Provider, ProviderCapabilities, ProviderCreate, ProviderInstance,+ Result, RunKind, Sandboxes, ServiceEndpoint, Status,+};+use cua_spaces::{RelayAccount, SpaceCreate, Spaces};+use std::sync::{+ Arc, Mutex,+ atomic::{AtomicUsize, Ordering},+};++const MACHINE: &str = "0123abcd4567ef89";+struct Tokens(Mutex<String>);+#[async_trait]+impl cua_host::AccountTokens for Tokens {+ async fn access_token(&self) -> cua_host::Result<String> {+ Ok(self.0.lock().unwrap().clone())+ }+}+struct Cloud {+ tokens: Arc<Tokens>,+ fail_discovery: bool,+ creates: AtomicUsize,+ deletes: AtomicUsize,+ instance: Mutex<Option<ProviderInstance>>,+}+#[async_trait]+impl Provider for Cloud {+ fn name(&self) -> &'static str {+ "aws"+ }+ fn joins_relay(&self) -> bool {+ true+ }+ fn capabilities(&self) -> ProviderCapabilities {+ ProviderCapabilities {+ kinds: vec![RunKind::Container],+ runtime: "fake",+ arches: vec!["amd64"],+ image_mode: ImageMode::Direct,+ ports: PortExposure::None,+ command: true,+ env_to_entrypoint: false,+ private_registry: false,+ suspend: false,+ max_cpus: None,+ max_memory_mb: None,+ credential_env: &[],+ gpus: vec![],+ }+ }+ fn check_configured(&self) -> Result<()> {+ Ok(())+ }+ async fn create(&self, spec: &ProviderCreate) -> Result<ProviderInstance> {+ self.creates.fetch_add(1, Ordering::SeqCst);+ let mut instance = ProviderInstance::new("fake-instance", &spec.name, Status::Running);+ instance.details.insert(+ cua_sandbox_core::byoc::DETAIL_RELAY_MACHINE.into(),+ MACHINE.into(),+ );+ *self.instance.lock().unwrap() = Some(instance.clone());+ if self.fail_discovery {+ *self.tokens.0.lock().unwrap() = "bad".into();+ }+ Ok(instance)+ }+ async fn get(&self, _: &str) -> Result<ProviderInstance> {+ Ok(self.instance.lock().unwrap().clone().unwrap())+ }+ async fn list(&self) -> Result<Vec<ProviderInstance>> {+ Ok(self.instance.lock().unwrap().clone().into_iter().collect())+ }+ async fn delete(&self, _: &str) -> Result<()> {+ self.deletes.fetch_add(1, Ordering::SeqCst);+ Ok(())+ }+ fn endpoint(&self, _: &ProviderInstance, _: u16) -> Result<ServiceEndpoint> {+ panic!("no guest endpoint needed")+ }+}++#[tokio::test]+async fn created_cloud_resources_survive_discovery_failure_and_missing_details() {+ let mut registry = FakeRegistry::default();+ registry.index("ghcr.io/example/discovery:1", &["amd64"], false, None);+ cua_image::resolve::set_source(Some(Arc::new(registry)));+ // Warm failure, cold failure, and a successful-but-empty directory.+ for (warm, fail_discovery) in [(true, true), (false, true), (false, false)] {+ let relay = FakeRelay::start().await;+ relay.add_account("owner", "owner-id", None);+ if warm {+ cua_host::RelayClient::new(&relay.url)+ .unwrap()+ .register(+ "owner",+ &cua_host::relay::RegisterRequest {+ id: MACHINE.into(),+ name: "existing".into(),+ allow: vec![],+ host: None,+ meta: Default::default(),+ },+ )+ .await+ .unwrap();+ }+ let tokens = Arc::new(Tokens(Mutex::new("owner".into())));+ let cloud = Arc::new(Cloud {+ tokens: tokens.clone(),+ fail_discovery,+ creates: AtomicUsize::new(0),+ deletes: AtomicUsize::new(0),+ instance: Mutex::new(None),+ });+ let home = tempfile::tempdir().unwrap();+ let sandboxes = Sandboxes::builder()+ .provider(cloud.clone())+ .state_dir(home.path().join("sandboxes"))+ .build();+ let spaces = Spaces::builder()+ .home(home.path())+ .sandboxes(sandboxes)+ .relay(RelayAccount::new(&relay.url, tokens))+ .build();+ if warm {+ assert_eq!(spaces.list_all().await.unwrap().len(), 1);+ }+ let result = spaces+ .create(SpaceCreate {+ on: Some(cua_sandbox_core::placement::On::Provider("aws".into())),+ name: Some("created-once".into()),+ image: Some("ghcr.io/example/discovery:1".into()),+ ..Default::default()+ })+ .await;+ if warm {+ assert_eq!(+ result.unwrap().ready().unwrap().id,+ format!("relay:{MACHINE}")+ );+ } else {+ let error = match result {+ Err(e) => e,+ Ok(_) => panic!("missing details must be explicit"),+ };+ assert_eq!(+ error.to_string(),+ "relay: The cloud sandbox was created, but its Space details could not be read. Inspect the existing sandbox before retrying creation."+ );+ }+ assert_eq!(cloud.creates.load(Ordering::SeqCst), 1);+ assert_eq!(cloud.deletes.load(Ordering::SeqCst), 0);+ assert!(home.path().join("sandboxes/created-once.json").exists());+ assert!(+ spaces+ .sandboxes()+ .by_relay_machine(MACHINE)+ .unwrap()+ .is_some()+ );+ }+}diff --git a/libs/cua/crates/cua-spaces/tests/relay.rs b/libs/cua/crates/cua-spaces/tests/relay.rsindex 5d53067135..a4185c4c16 100644--- a/libs/cua/crates/cua-spaces/tests/relay.rs+++ b/libs/cua/crates/cua-spaces/tests/relay.rs@@ -153,14 +153,26 @@ async fn lists_owned_and_shared_relay_machines_as_spaces() {.build();let err = bad.relay_machines().await.unwrap_err();assert_eq!(err.tag(), "unauthenticated", "{err}");- // list_all tolerates an unreachable directory.- assert!(bad.list_all().await.unwrap().is_empty());+ // Refresh failure must not be reported as a successful empty directory.+ let err = bad.list_all().await.unwrap_err();+ assert_eq!(err.tag(), "unauthenticated");+ assert_eq!(+ err.to_string(),+ "Relay authentication failed. Sign in again to refresh your machines."+ );}#[tokio::test]async fn relay_spaces_need_an_account() {let home = tempfile::tempdir().unwrap();let spaces = Spaces::builder().home(home.path()).build();+ assert!(spaces.list_all().await.unwrap().is_empty());+ let direct = MockServer::start(MockAuth::default()).await;+ let registered = spaces+ .add(&direct.url(), None, Some("local-only".into()))+ .await+ .unwrap();+ assert_eq!(spaces.list_all().await.unwrap()[0].id, registered.id);let err = spaces.relay_machines().await.unwrap_err();assert_eq!(err.tag(), "host_capability_missing", "{err}");let err = spaces.space(&format!("relay:{MACHINE}")).await.unwrap_err();@@ -249,6 +261,10 @@ async fn relay_spaces_carry_the_enrolled_device_session() {.build();let err = bare.relay_machines().await.unwrap_err();assert_eq!(err.tag(), "permission_denied", "{err}");+ assert_eq!(+ bare.list_all().await.unwrap_err().tag(),+ "permission_denied"+ );relay.fresh_sign_in("user-1");let device = Arc::new(@@ -284,3 +300,97 @@ async fn relay_spaces_carry_the_enrolled_device_session() {"{proxied:?}");}++/// A failed refresh leaves the explicit cached route available, while a+/// successful empty response replaces old directory rows.+#[tokio::test]+async fn discovery_failure_is_not_stale_success_and_empty_recovery_clears_cache() {+ struct Tokens {+ current: std::sync::Mutex<String>,+ calls: AtomicU32,+ }+ #[async_trait::async_trait]+ impl AccountTokens for Tokens {+ async fn access_token(&self) -> cua_host::Result<String> {+ self.calls.fetch_add(1, Ordering::SeqCst);+ Ok(self.current.lock().unwrap().clone())+ }+ }+ let relay = FakeRelay::start().await;+ relay.add_account("owner", "owner", None);+ relay.add_account("empty", "stranger", None);+ cua_host::RelayClient::new(&relay.url)+ .unwrap()+ .register(+ "owner",+ &cua_host::relay::RegisterRequest {+ id: MACHINE.into(),+ name: "studio".into(),+ allow: vec![],+ host: None,+ meta: Default::default(),+ },+ )+ .await+ .unwrap();+ let home = tempfile::tempdir().unwrap();+ let tokens = Arc::new(Tokens {+ current: std::sync::Mutex::new("owner".into()),+ calls: AtomicU32::new(0),+ });+ let spaces = Spaces::builder()+ .home(home.path())+ .relay(RelayAccount::new(&relay.url, tokens.clone()))+ .build();+ let direct = MockServer::start(MockAuth::default()).await;+ let local = spaces+ .add(&direct.url(), None, Some("registered".into()))+ .await+ .unwrap();+ assert_eq!(spaces.list_all().await.unwrap().len(), 2);+ *tokens.current.lock().unwrap() = "bad".into();+ assert_eq!(+ spaces.list_all().await.unwrap_err().tag(),+ "unauthenticated"+ );+ let calls = tokens.calls.load(Ordering::SeqCst);+ assert_eq!(spaces.list().unwrap().len(), 2);+ assert_eq!(+ tokens.calls.load(Ordering::SeqCst),+ calls,+ "cached reads never refresh"+ );+ *tokens.current.lock().unwrap() = "empty".into();+ let recovered = spaces.list_all().await.unwrap();+ assert_eq!(recovered.len(), 1);+ assert_eq!(recovered[0].id, local.id);+ assert_eq!(spaces.list().unwrap().len(), 1);+}++#[tokio::test]+async fn discovery_errors_do_not_expose_provider_payloads() {+ struct UnsafeError;+ #[async_trait::async_trait]+ impl AccountTokens for UnsafeError {+ async fn access_token(&self) -> cua_host::Result<String> {+ Err(cua_host::Error::Relay(format!(+ "https://user:[email protected]/?token=secret {}",+ "untrusted".repeat(1000)+ )))+ }+ }+ let home = tempfile::tempdir().unwrap();+ let spaces = Spaces::builder()+ .home(home.path())+ .relay(RelayAccount::new(+ "http://127.0.0.1:1",+ Arc::new(UnsafeError),+ ))+ .build();+ let error = spaces.list_all().await.unwrap_err();+ assert_eq!(error.tag(), "relay");+ assert_eq!(+ error.to_string(),+ "relay: Could not refresh relay machines."+ );+}diff --git a/libs/cua/python/tests/test_spaces.py b/libs/cua/python/tests/test_spaces.pyindex 6ae6726022..c26a1a58e2 100644--- a/libs/cua/python/tests/test_spaces.py+++ b/libs/cua/python/tests/test_spaces.py@@ -134,6 +134,7 @@ def daemon_exercise(fixtures, cua_binary, tmp_path, teleport: bool):os.environ,CUA_HOME=str(home),HOME=str(home),+ CUA_DAEMON_NO_RELAY="1",CUA_SPACES_TELEPORT_HOME=fixtures["teleport_host_home"],CUA_SPACES_AGENT_CREDENTIALS_HOME="none",)diff --git a/libs/cua/swift/Tests/CuaTests/SpacesTests.swift b/libs/cua/swift/Tests/CuaTests/SpacesTests.swiftindex 6fa8aa407a..34177b7ede 100644--- a/libs/cua/swift/Tests/CuaTests/SpacesTests.swift+++ b/libs/cua/swift/Tests/CuaTests/SpacesTests.swift@@ -228,6 +228,7 @@ func exerciseSpaces(_ cua: Cua, _ fx: Fixtures, tmp: URL, teleport: Bool = falsevar env = ProcessInfo.processInfo.environmentenv["HOME"] = homeenv["CUA_HOME"] = home+ env["CUA_DAEMON_NO_RELAY"] = "1"env["CUA_SPACES_TELEPORT_HOME"] = fx.fields["teleport_host_home"]env["CUA_SPACES_AGENT_CREDENTIALS_HOME"] = "none"daemon.environment = envdiff --git a/libs/cua/typescript/test/spaces.test.mjs b/libs/cua/typescript/test/spaces.test.mjsindex 2475ca44f6..6f5a4130af 100644--- a/libs/cua/typescript/test/spaces.test.mjs+++ b/libs/cua/typescript/test/spaces.test.mjs@@ -158,6 +158,7 @@ async function daemonExercise(cli, teleport) {...process.env,CUA_HOME: home,HOME: home,+ CUA_DAEMON_NO_RELAY: "1",CUA_SPACES_TELEPORT_HOME: fx.teleport_host_home,CUA_SPACES_AGENT_CREDENTIALS_HOME: "none",},