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-macos): list relay machines after an update that misses the daemon handoff (#4625)
ddupontb05ce7166fb9
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swiftindex 24e1f895e4..025f70078f 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift@@ -210,7 +210,7 @@ public enum AppEnvironment {/// between, the SDK refuses it with `DaemonNotRunning`, and one more/// start replaces it. Without a daemon the SDK runs Spaces in the app.static func makeLiveBackend(supervisor: DaemonSupervisor?, daemonError: inout String?) throws -> LiveSpacesBackend {- daemonError = supervisor?.start()+ daemonError = startDaemon(supervisor)do {return try LiveSpacesBackend.make()} catch CuaError.DaemonNotRunning(let message) where supervisor != nil {@@ -219,6 +219,17 @@ public enum AppEnvironment {}}+ /// `cua daemon start`, once more when it failed: a daemon of the build+ /// before an update that was slow to stop is gone by then, and the+ /// second start brings up this build's instead of leaving the app to+ /// run Spaces in-process.+ static func startDaemon(_ supervisor: DaemonSupervisor?) -> String? {+ guard let supervisor else { return nil }+ guard let first = supervisor.start() else { return nil }+ NSLog("Cua Spaces: starting the cua daemon failed, trying again: %@", first)+ return supervisor.start()+ }+/// The `cua` this app bundles, when it has one.static var bundledCua: String? {let executable = Bundle.main.executablePath ?? CommandLine.arguments[0]diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DaemonSupervisor.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DaemonSupervisor.swiftindex b94b4ec366..f978166f70 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DaemonSupervisor.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DaemonSupervisor.swift@@ -37,8 +37,10 @@ public final class DaemonSupervisor: @unchecked Sendable {}/// Runs `cua daemon start`, bounded by `timeout`: `nil` when this app's- /// daemon runs afterwards, else why not.- public func start(timeout: TimeInterval = 30) -> String? {+ /// daemon runs afterwards, else why not. Replacing a daemon of another+ /// build waits up to 30 s for it to stop (one with Spaces running takes+ /// that long), then up to 10 s for this build's to start.+ public func start(timeout: TimeInterval = 60) -> String? {let process = Process()process.executableURL = URL(fileURLWithPath: cua)process.arguments = ["daemon", "start"]diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MachineAccessTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MachineAccessTests.swiftindex e1305d19a9..7be0c08ea0 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MachineAccessTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/MachineAccessTests.swift@@ -93,14 +93,15 @@ enum MachinesFixture {return s}- static func model(rows: [AppSpaceRow], enrollment: Enrollment, hostSetUp: Bool = false) async -> AppModel {+ static func model(rows: [AppSpaceRow], enrollment: Enrollment, hostSetUp: Bool = false,+ hostStatus: HostStatus? = nil) async -> AppModel {let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cua-machines-\(UUID().uuidString)")let fixture = FixtureDevices(snapshot: devices(enrollment))let m = AppModel(backend: FixtureSpacesBackend(rows: rows),keyvault: KeyvaultModel(client: nil, clock: { fixtureNow }),onboarding: OnboardingModel(statePath: dir.appendingPathComponent("o.json").path),settingsPath: dir.appendingPathComponent("settings.json").path,- host: hostSetUp ? FixtureHost(status: relayHost) : FixtureHost(),+ host: hostSetUp ? FixtureHost(status: hostStatus ?? relayHost) : FixtureHost(),account: FixtureAccount(), telemetry: FixtureTelemetry(),devices: fixture, presence: FixturePresence())m.onboarding.finish()@@ -229,6 +230,41 @@ struct MachineAccessTests {size: CGSize(width: 260, height: 600))}+ /// The user's Macs after updating to 0.7.0: this Mac (relay+ /// `b695…`, not sharing) and cua.local ("Mac.localdomain", relay+ /// `9e9d…`: sharing, desktop not shared, Spaces on with none running,+ /// the cua-spacesd 0.2.2 of an older app). cua.local is listed under+ /// My machines however its probe went; this Mac only as This machine.+ @Test func anOlderHostThatKeepsItsDesktopPrivateIsListed() async throws {+ let other = "relay:9e9d969d41649428f693b403f6f8f225"+ let thisId = "b6953d14ff94b10fcbb38bdd13c47824"+ let probes: [([String], Bool, String?)] = [+ (["host_spaces", "files"], true, nil),+ (["desktop_stream", "window_stream", "host_spaces", "files"], true, nil),+ ([], false, "permission denied: this machine does not share its desktop"),+ ]+ for (features, reachable, error) in probes {+ var mac = MachinesFixture.row(other, "Mac.localdomain", os: .macos, features: features,+ reachable: reachable, error: error)+ mac.spacesdVersion = "0.2.2"+ var me = MachinesFixture.row("relay:\(thisId)", "Dillons-MacBook-Pro-2.local", os: .macos,+ features: [], reachable: false)+ me.spacesdVersion = "0.2.0"+ var status = MachinesFixture.relayHost+ status.machineId = thisId+ status.name = "Dillons-MacBook-Pro-2.local"+ status.sharing = false+ status.shareDesktop = true+ status.provideSpaces = false+ let m = await MachinesFixture.model(rows: [FixtureSpacesBackend.sample[0], mac, me],+ enrollment: .enrolled, hostSetUp: true, hostStatus: status)+ #expect(m.sidebar.thisMachine != nil)+ let mine = try #require(m.sidebar.sections.first { $0.title == "My machines" },+ "no My machines for \(features) \(String(describing: error))")+ #expect(mine.rows.map(\.id) == [other])+ }+ }+// MARK: - Snapshotsfunc card(_ cover: AppDesktopCover) -> some View {diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdxindex 32d4a6b545..4ad38fdd81 100644--- a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx+++ b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx@@ -2263,6 +2263,10 @@ pub fn input_refusal_text(message: &str) -> Option<&'static str>/// Registers the streaming client for this ...pub fn register_stream_client(client: Arc<dyn StreamClient>)+// mod thumbnails+/// The `desktop_stream` feature of a host ...+pub fn desktop_not_shared(caps: &GetCapabilitiesResponse) -> Option<&Feature>+// mod walk/// A single file as a walk entry named ...pub fn single(path: &Path, name: &str) -> Result<WalkEntry>diff --git a/libs/cua/crates/cua-cli/src/extension.rs b/libs/cua/crates/cua-cli/src/extension.rsindex 342e1967ca..82784030ec 100644--- a/libs/cua/crates/cua-cli/src/extension.rs+++ b/libs/cua/crates/cua-cli/src/extension.rs@@ -252,12 +252,20 @@ pub(crate) async fn missing_daemon_extensions() -> Vec<String> {.collect()}-/// Asks the running daemon to stop and waits (bounded) for it to go.+/// How long [`stop_daemon`] waits for the daemon to go: one with Spaces+/// running unmounts their volumes and lets go of their VMs first, which+/// took 12 s on a Mac with one running macOS Space (10 s was too short:+/// the app updated to 0.7.0 was left without its daemon).+pub(crate) const STOP_WAIT: std::time::Duration = std::time::Duration::from_secs(30);++/// Asks the running daemon to stop and waits (bounded by [`STOP_WAIT`])+/// for it to go.pub(crate) async fn stop_daemon(discovery: &Path, pid: u32) -> Result<(), CuaError> {if let Ok(client) = cua_daemon::client::existing_daemon().await {let _ = client.shutdown().await;}- for _ in 0..100 {+ let tick = std::time::Duration::from_millis(100);+ for _ in 0..(STOP_WAIT.as_millis() / tick.as_millis()) {let gone = match cua_daemon::Discovery::read(discovery) {Some(d) => d.pid != pid,None => true,@@ -265,9 +273,10 @@ pub(crate) async fn stop_daemon(discovery: &Path, pid: u32) -> Result<(), CuaErrif gone && cua_daemon::client::live_address().is_none() {return Ok(());}- tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ tokio::time::sleep(tick).await;}Err(CuaError::Timeout(format!(- "the running cua daemon (pid {pid}) did not stop within 10 s"+ "the running cua daemon (pid {pid}) did not stop within {} s",+ STOP_WAIT.as_secs())))}diff --git a/libs/cua/crates/cua-sdk/src/native/cua.rs b/libs/cua/crates/cua-sdk/src/native/cua.rsindex 32ec454d6b..b63d071469 100644--- a/libs/cua/crates/cua-sdk/src/native/cua.rs+++ b/libs/cua/crates/cua-sdk/src/native/cua.rs@@ -190,6 +190,32 @@ impl Cua {}}+/// The relay account `cua daemon` lists the account's machines with: the+/// signed-in session (read per call, so a later sign-in works without a+/// new runtime) on the relay this machine uses, as this enrolled device.+/// An embedded runtime on the session gets the same, so a Spaces app that+/// runs Spaces in-process (its daemon could not be started) still lists+/// "My machines".+#[cfg(all(feature = "spaces", feature = "host"))]+fn session_relay_account(home: &std::path::Path) -> cua_spaces::RelayAccount {+ let url = cua_host::relay_url_for(None, home);+ let session = Arc::new(cua_auth::Session::from_env());+ let tokens: Arc<dyn cua_host::AccountTokens> =+ Arc::new(super::host::SessionTokens(session.clone()));+ let account = cua_spaces::RelayAccount::new(url.clone(), tokens.clone());+ match cua_host::DeviceAuth::new(+ &url,+ tokens,+ Arc::new(session.store().clone()),+ cua_host::device_name(),+ ) {+ Ok(device) => account.with_device(Arc::new(+ device.with_pending_file(cua_host::device_pending_file(home)),+ )),+ Err(_) => account,+ }+}+#[uniffi::export]impl Cua {/// Runs the SDK runtime in this process. Performs no I/O beyond@@ -229,6 +255,15 @@ impl Cua {let _guard = runtime().enter();Runtime::new(rc)?};+ #[cfg(all(feature = "spaces", feature = "host"))]+ if config.fleet_from_session && std::env::var_os("CUA_DAEMON_NO_RELAY").is_none() {+ let home = config+ .spaces_home+ .clone()+ .map(PathBuf::from)+ .unwrap_or_else(cua_daemon::cua_home);+ rt.spaces().set_relay(Some(session_relay_account(&home)));+ }Ok(Arc::new(Self {backend: Backend::Embedded(rt),config,diff --git a/libs/cua/crates/cua-sdk/src/native/spaces.rs b/libs/cua/crates/cua-sdk/src/native/spaces.rsindex 82b7714ab0..79da0cbc45 100644--- a/libs/cua/crates/cua-sdk/src/native/spaces.rs+++ b/libs/cua/crates/cua-sdk/src/native/spaces.rs@@ -2251,7 +2251,9 @@ impl Spaces {let host = self.host.clone();run(async move {match &host {- Host::Embedded(s) => Ok(s.list()?.into_iter().map(Into::into).collect()),+ // With the account's relay machines, the directory read+ // again, as `cua daemon`'s `ListSpaces` does.+ Host::Embedded(s) => Ok(s.list_all().await?.into_iter().map(Into::into).collect()),Host::Daemon(d) => Ok(d.spaces().list_spaces(dpb::ListSpacesRequest {})diff --git a/libs/cua/crates/cua-sdk/tests/embedded_relay.rs b/libs/cua/crates/cua-sdk/tests/embedded_relay.rsnew file mode 100644index 0000000000..626dcf2ad4--- /dev/null+++ b/libs/cua/crates/cua-sdk/tests/embedded_relay.rs@@ -0,0 +1,104 @@+//! An embedded runtime on the signed-in session lists the account's relay+//! machines, as `cua daemon` does. The Spaces app falls back to an embedded+//! runtime when its daemon cannot be started (an update whose old daemon+//! took longer than `cua daemon start` waited to stop it); that runtime had+//! no relay account and never refreshed the directory, so "My machines"+//! went empty while `cua spaces ls` still listed them.+//!+//! One test (it sets process environment): a temp `CUA_HOME`, the file+//! credential store and a loopback fake relay; nothing real is touched.++use cua_host::testing::FakeRelay;+use cua_sdk::{Cua, CuaConfig};++/// cua.local as the user's Mac saw it: online, sharing, desktop not shared+/// (spacesd 0.2.2 from an older app), and the user's Mac itself, not sharing.+const OTHER_MAC: &str = "9e9d969d41649428f693b403f6f8f225";+const THIS_MAC: &str = "b6953d14ff94b10fcbb38bdd13c47824";++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn embedded_runtime_on_the_session_lists_your_relay_machines() {+ let relay = FakeRelay::start().await;+ relay.add_account("owner-token", "user-1", Some("[email protected]"));+ let client = cua_host::RelayClient::new(&relay.url).unwrap();+ for (id, name) in [+ (OTHER_MAC, "Mac.localdomain"),+ (THIS_MAC, "Dillons-MacBook-Pro-2.local"),+ ] {+ client+ .register(+ "owner-token",+ &cua_host::relay::RegisterRequest {+ id: id.into(),+ name: name.into(),+ allow: vec![],+ host: None,+ meta: Default::default(),+ },+ )+ .await+ .unwrap();+ }+ relay.set_online(OTHER_MAC, true, "0.2.2");+ relay.set_online(THIS_MAC, true, "0.2.0");++ let home = tempfile::tempdir().unwrap();+ unsafe {+ std::env::set_var("CUA_HOME", home.path());+ std::env::set_var("CUA_CREDENTIAL_STORE", "file");+ std::env::set_var("CUA_RELAY_URL", &relay.url);+ std::env::remove_var("CUA_DAEMON_NO_RELAY");+ std::env::remove_var("CUA_FLEET_SESSION");+ }+ cua_auth::Store::from_env()+ .save(&cua_auth::Credentials {+ access_token: "owner-token".into(),+ refresh_token: None,+ expires_at: "2999-01-01T00:00:00Z".into(),+ token_type: "Bearer".into(),+ scope: None,+ id_token: None,+ })+ .unwrap();++ // The app's configuration (`CuaConfig(fleetFromSession: true)`).+ let cua = Cua::embedded(CuaConfig {+ state_dir: Some(home.path().join("sandboxes").display().to_string()),+ spaces_home: Some(home.path().display().to_string()),+ fleet_pool_home: Some(home.path().join("pools").display().to_string()),+ fleet_from_env: false,+ fleet_from_session: true,+ ..Default::default()+ })+ .unwrap();+ let ids: Vec<String> = cua+ .spaces()+ .list()+ .await+ .unwrap()+ .into_iter()+ .map(|s| s.id)+ .collect();+ assert!(ids.contains(&format!("relay:{OTHER_MAC}")), "{ids:?}");+ assert!(ids.contains(&format!("relay:{THIS_MAC}")), "{ids:?}");++ // Without the session (`fleet_from_session` off) nothing reaches the+ // relay: an SDK user who did not ask for the session gets none of it.+ let bare = Cua::embedded(CuaConfig {+ state_dir: Some(home.path().join("sandboxes2").display().to_string()),+ spaces_home: Some(home.path().join("bare").display().to_string()),+ fleet_pool_home: Some(home.path().join("pools2").display().to_string()),+ fleet_from_env: false,+ fleet_from_session: false,+ ..Default::default()+ })+ .unwrap();+ assert!(+ bare.spaces()+ .list()+ .await+ .unwrap()+ .iter()+ .all(|s| !s.id.starts_with("relay:"))+ );+}diff --git a/libs/cua/crates/cua-sdk/tests/thumbnails.rs b/libs/cua/crates/cua-sdk/tests/thumbnails.rsindex 4b2d808e4f..c6ba137ae9 100644--- a/libs/cua/crates/cua-sdk/tests/thumbnails.rs+++ b/libs/cua/crates/cua-sdk/tests/thumbnails.rs@@ -59,3 +59,41 @@ async fn thumbnails_come_from_the_cache_within_max_age() {assert_eq!(shared.image, fresh.image);assert_eq!(shots(), 2);}++/// A host that does not share its desktop says so in its capabilities+/// (cua-spacesd with `share_desktop` off): no capture is asked of it at+/// all, so its owner's access log shows no refused ComputerService calls.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn a_host_that_does_not_share_its_desktop_is_never_asked_for_one() {+ let dir = tempfile::tempdir().unwrap();+ let server = MockServer::start(Default::default()).await;+ server.state.withhold(+ "desktop_stream",+ "this machine does not share its desktop (it only provides Spaces)",+ );+ let shots = || server.state.observed.screenshots.lock().unwrap().len();+ let c = cua(&dir);+ let info = c+ .spaces()+ .add(server.url(), None, Some("spare".into()))+ .await+ .unwrap();+ let space = c.spaces().space(info.id.clone()).await.unwrap();+ assert!(space.thumbnail(None).await.is_err());+ assert!(space.thumbnail(Some(0)).await.is_err());+ assert_eq!(shots(), 0, "no screenshot was asked for");++ // A stream unsupported for another reason still takes screenshots.+ let other = MockServer::start(Default::default()).await;+ other+ .state+ .withhold("desktop_stream", "no encoder in this image");+ let info = c+ .spaces()+ .add(other.url(), None, Some("headless".into()))+ .await+ .unwrap();+ let space = c.spaces().space(info.id).await.unwrap();+ assert!(space.thumbnail(None).await.is_ok());+ assert_eq!(other.state.observed.screenshots.lock().unwrap().len(), 1);+}diff --git a/libs/cua/crates/cua-spaces-app-core/src/spaces/sidebar.rs b/libs/cua/crates/cua-spaces-app-core/src/spaces/sidebar.rsindex def848b1c1..3cbf641673 100644--- a/libs/cua/crates/cua-spaces-app-core/src/spaces/sidebar.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/spaces/sidebar.rs@@ -1307,6 +1307,147 @@ mod tests {assert_eq!(shares_desktop(&direct), None);}+ /// The user's Macs after updating to 0.7.0: cua.local+ /// (`relay:9e9d…`, "Mac.localdomain") shares, keeps its desktop+ /// private, provides Spaces with none running and runs the cua-spacesd+ /// of an older app (0.2.2); this Mac (`relay:b695…`) is not sharing.+ const OTHER_MAC: &str = "9e9d969d41649428f693b403f6f8f225";+ const THIS_MAC: &str = "b6953d14ff94b10fcbb38bdd13c47824";++ fn roster_row(+ id: &str,+ name: &str,+ version: &str,+ features: &[&str],+ reachable: bool,+ error: Option<&str>,+ ) -> Space {+ let row: SpaceRow = serde_json::from_value(serde_json::json!({+ "id": id,+ "name": name,+ "provider": id.split(':').next().unwrap(),+ "spacesdVersion": version,+ "features": features,+ "os": "macos",+ "reachable": reachable,+ "error": error,+ }))+ .unwrap();+ super::super::row_to_space(&row, 0)+ }++ /// One of your machines that is online and provides Spaces is listed+ /// under "My machines" whatever it shares and whichever cua-spacesd it+ /// runs: desktop off with Spaces on and none running (a current host+ /// says so in its features), an older host that reports every feature+ /// or whose probe was refused or has not answered yet.+ #[test]+ fn your_other_machine_is_listed_whatever_it_shares_or_runs() {+ let other = format!("relay:{OTHER_MAC}");+ let this = format!("relay:{THIS_MAC}");+ let probes: [(&[&str], bool, Option<&str>); 4] = [+ // Current cua-spacesd, desktop not shared: desktop features+ // unsupported, host_spaces on.+ (&["pty", "files", "host_spaces"], true, None),+ // 0.2.2 reports the desktop's features to anyone.+ (+ &["pty", "desktop_stream", "window_stream", "host_spaces"],+ true,+ None,+ ),+ // Refused or unanswered: no features at all.+ (&[], false, Some("permission denied: desktop not shared")),+ (&[], false, None),+ ];+ for (features, reachable, error) in probes {+ let spaces = vec![+ roster_row(+ "local:space-753034eaaf",+ "Apple-Virtual-Machine-1.local",+ "0.1.1",+ &["pty"],+ true,+ None,+ ),+ roster_row(+ &other,+ "Mac.localdomain",+ "0.2.2",+ features,+ reachable,+ error,+ ),+ roster_row(+ &this,+ "Dillons-MacBook-Pro-2.local",+ "0.2.0",+ &[],+ false,+ None,+ ),+ ];+ let listed = without_this_relay_machine(&spaces, Some(THIS_MAC));+ let view = sidebar(&listed, "", "");+ let mine = view+ .sections+ .iter()+ .find(|s| s.title == "My machines")+ .unwrap_or_else(|| panic!("no My machines for {features:?} {error:?}: {view:?}"));+ assert_eq!(+ mine.rows.iter().map(|r| r.id.as_str()).collect::<Vec<_>>(),+ [other.as_str()],+ "{features:?} {error:?}"+ );+ assert!(view.sections.iter().any(|s| s.title == "This Mac"+ && s.rows.iter().any(|r| r.id == "local:space-753034eaaf")));+ }+ // Desktop not shared but providing Spaces: its detail says so, with+ // Spaces still offered (not hidden as "shares nothing").+ let m = roster_row(+ &other,+ "Mac.localdomain",+ "0.2.2",+ &["pty", "host_spaces"],+ true,+ None,+ );+ assert_eq!(shares_desktop(&m), Some(false));+ assert_eq!(+ desktop_note(&m).as_deref(),+ Some(+ "Mac.localdomain isn\u{2019}t sharing its desktop. You can still create Spaces on it."+ )+ );+ }++ /// This Mac is left out by its exact relay machine id only: never by+ /// a prefix, another case, or the other Mac's id.+ #[test]+ fn this_mac_is_excluded_only_by_its_exact_id() {+ let spaces: Vec<Space> = [+ format!("relay:{OTHER_MAC}"),+ format!("relay:{THIS_MAC}"),+ format!("relay:{THIS_MAC}0"),+ "relay:b6953d14".to_string(),+ format!("relay:{}", THIS_MAC.to_uppercase()),+ ]+ .iter()+ .map(|id| roster_row(id, "Mac", "0.2.2", &[], true, None))+ .collect();+ let ids = |v: Vec<Space>| v.into_iter().map(|s| s.id).collect::<Vec<_>>();+ let all = ids(spaces.clone());+ let without = |own: &str| ids(without_this_relay_machine(&spaces, Some(own)));+ let mut want = all.clone();+ want.retain(|id| *id != format!("relay:{THIS_MAC}"));+ assert_eq!(without(THIS_MAC), want);+ // A prefix or a near miss of this Mac's id drops nothing else.+ assert_eq!(without("b6953d14ff94"), all);+ assert_eq!(without(&format!("relay:{THIS_MAC}")), all);+ assert_eq!(without(&format!(" {THIS_MAC}")), all);+ // Not set up as a host: nothing is dropped.+ assert_eq!(ids(without_this_relay_machine(&spaces, None)), all);+ }+/// This machine's own relay entry is dropped by id; another machine/// of the same name and the Spaces this machine provides stay.#[test]diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rsindex 16dd82d132..a9227a9e70 100644--- a/libs/cua/crates/cua-spaces/src/spaces.rs+++ b/libs/cua/crates/cua-spaces/src/spaces.rs@@ -2530,6 +2530,16 @@ impl Spaces {async fn capture_thumbnail_once(&self, id: &str) -> Result<crate::thumbnails::Thumbnail> {use crate::thumbnails::{MAX_DIMENSION, QUALITY, Thumbnail};let space = self.space(id).await?;+ // A machine that does not share its desktop says so in its+ // capabilities: never ask its ComputerService (each refusal is a+ // line in its owner's access log). The refusal still backs off.+ if let Some(f) = crate::thumbnails::desktop_not_shared(space.capabilities()) {+ return Err(Error::CapabilityMissing {+ space: id.to_string(),+ feature: f.name.clone(),+ limitation: f.limitation.clone(),+ });+ }let shot = space.spacesd()?.screenshot(cua_spacesd_client::ScreenshotOptions {diff --git a/libs/cua/crates/cua-spaces/src/thumbnails.rs b/libs/cua/crates/cua-spaces/src/thumbnails.rsindex 34bffb53a7..aa2023a751 100644--- a/libs/cua/crates/cua-spaces/src/thumbnails.rs+++ b/libs/cua/crates/cua-spaces/src/thumbnails.rs@@ -140,6 +140,22 @@ impl std::fmt::Debug for ThumbnailCache {}}+/// The `desktop_stream` feature of a host that does not share its desktop+/// (cua-spacesd with `share_desktop` off reports every desktop feature+/// unsupported to a relayed caller, saying why): there is no desktop to+/// capture, so a thumbnail is not asked for. `None` for any other Space,+/// including one whose stream is unsupported for another reason (it may+/// still take screenshots).+pub fn desktop_not_shared(+ caps: &cua_proto::env::v1::GetCapabilitiesResponse,+) -> Option<&cua_proto::env::v1::Feature> {+ caps.features.iter().find(|f| {+ f.name == "desktop_stream"+ && !f.supported+ && f.limitation.contains("does not share its desktop")+ })+}+/// The file stem of a Space id (hex of its SHA-256, 32 chars).fn stem(space: &str) -> String {hex::encode(&Sha256::digest(space.as_bytes())[..16])diff --git a/libs/cua/crates/cua-spacesd-client/src/testing.rs b/libs/cua/crates/cua-spacesd-client/src/testing.rsindex 174ad62657..efac02e53f 100644--- a/libs/cua/crates/cua-spacesd-client/src/testing.rs+++ b/libs/cua/crates/cua-spacesd-client/src/testing.rs@@ -149,6 +149,9 @@ pub struct MockState {/// Extra supported features reported by `GetCapabilities` (for clients/// that gate on stream / window features).extra_features: Mutex<Vec<String>>,+ /// Features reported unsupported, with their limitation (a host that+ /// does not share its desktop).+ withheld_features: Mutex<Vec<(String, String)>>,/// `GetCapabilities.version` (default `0.0.0-mock`).version: Mutex<Option<String>>,/// `GetCapabilitiesResponse::machine_seal_public_key` (S1); empty (an@@ -295,6 +298,15 @@ impl MockState {.retain(|f| !names.contains(&f.as_str()));}+ /// Also report `name` as unsupported, saying `limitation` (cua-spacesd+ /// with `share_desktop` off reports its desktop features so).+ pub fn withhold(&self, name: &str, limitation: &str) {+ self.withheld_features+ .lock()+ .unwrap()+ .push((name.to_string(), limitation.to_string()));+ }+/// Report `version` as this mock's cua-spacesd version.pub fn set_version(&self, version: &str) {*self.version.lock().unwrap() = Some(version.to_string());@@ -634,6 +646,19 @@ impl SystemService for Svc {..Default::default()}),)+ .chain(+ self.0+ .withheld_features+ .lock()+ .unwrap()+ .iter()+ .map(|(n, why)| pb::Feature {+ name: n.clone(),+ supported: false,+ limitation: why.clone(),+ ..Default::default()+ }),+ ).collect(),hostname: "mock".into(),limits: Some(pb::Limits {