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(cua-driver, spacesd): say why a Windows desktop can't be captured (locked, RDP disconnected) (CUA-1727) (#5266)
Francesco Bonaccia0c06f202394
diff --git a/docs/content/docs/spaces/guides/unattended-access.mdx b/docs/content/docs/spaces/guides/unattended-access.mdxindex 77a686fce5..1d8f518eb1 100644--- a/docs/content/docs/spaces/guides/unattended-access.mdx+++ b/docs/content/docs/spaces/guides/unattended-access.mdx@@ -42,6 +42,21 @@ allowlist; the env token never leaves the machine.| Linux | systemd unit `cua-spacesd-host.service` (user unit; system unit as root). || Windows | Scheduled task `Cua\SpacesdHost` at logon, in your interactive session. |+On Windows the host runs in your signed-in session, so your devices reach the+desktop only while it is signed in, unlocked and on screen:++- **After a restart**, sign in once (or turn on automatic sign-in). The host+ starts at sign-in.+- **Locked:** Windows doesn't let apps see or use its lock screen. For+ unattended access, turn off automatic locking in **Settings > Accounts >+ Sign-in options** and the screen saver's "On resume, display logon screen".+- **Remote Desktop:** closing a Remote Desktop window leaves the session+ disconnected, and Windows stops drawing it. To leave a remote PC (a cloud VM)+ reachable, end Remote Desktop from an administrator prompt with+ `tscon %sessionname% /dest:console` instead.++A viewer or agent that connects in one of these states sees which one it is.+## Check, pause, remove```bash test="cli-shape" id="cua-host-status"diff --git a/libs/cua-driver/rust/crates/platform-windows/src/capture.rs b/libs/cua-driver/rust/crates/platform-windows/src/capture.rsindex ed8a92c98b..453b0b715f 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/capture.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/capture.rs@@ -772,6 +772,10 @@ pub fn screenshot_display_bytes() -> Result<Vec<u8>> {let _ = DeleteDC(mem_dc);ReleaseDC(HWND::default(), screen_dc);if let Err(error) = blt_result {+ // A locked PC or a disconnected Remote Desktop session: say which.+ if let Some(why) = crate::diagnostics::desktop_unavailable() {+ bail!("{} (BitBlt: {error})", why.message());+ }bail!("desktop capture: BitBlt failed: {error}");}if ok == 0 {diff --git a/libs/cua-driver/rust/crates/platform-windows/src/diagnostics.rs b/libs/cua-driver/rust/crates/platform-windows/src/diagnostics.rsindex 726fb538e3..dd80c66ac8 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/diagnostics.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/diagnostics.rs@@ -177,6 +177,94 @@ pub fn desktop_state() -> DesktopState {}}+/// Why this session's desktop can't be seen or driven right now, in words+/// a person can act on. `None` when it can (or when the cause is unknown).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DesktopUnavailable {+ /// The Remote Desktop session is disconnected: Windows draws nothing.+ Disconnected,+ /// The PC is locked (or on another secure desktop such as UAC).+ Locked,+}++impl DesktopUnavailable {+ /// The sentence a remote viewer or agent sees.+ pub fn message(self) -> &'static str {+ match self {+ Self::Disconnected => {+ "This PC's desktop isn't on screen: its Remote Desktop session is disconnected, \+ so Windows stopped drawing it. Reconnect, or sign in at the PC itself. To leave \+ a remote PC reachable, end Remote Desktop with \+ `tscon %sessionname% /dest:console` (as administrator) instead of closing the window."+ }+ Self::Locked => {+ "This PC is locked, and Windows doesn't let apps see or use its lock screen. \+ Unlock it at the PC. For unattended access, turn off automatic locking \+ (Settings > Accounts > Sign-in options, and the screen saver's \"On resume, \+ display logon screen\")."+ }+ }+ }+}++/// Decides from the session's connect state and its input desktop.+pub fn classify_desktop_unavailable(+ disconnected: bool,+ input_desktop_name: Option<&str>,+) -> Option<DesktopUnavailable> {+ if disconnected {+ return Some(DesktopUnavailable::Disconnected);+ }+ match input_desktop_name {+ Some(name) if name.eq_ignore_ascii_case("Default") => None,+ // Winlogon (locked, Ctrl+Alt+Del) or no access to the input desktop+ // at all, which is what a locked session gives a user process.+ _ => Some(DesktopUnavailable::Locked),+ }+}++/// Whether this process's session is a disconnected Remote Desktop session.+#[cfg(target_os = "windows")]+pub fn session_disconnected() -> bool {+ use windows::core::PWSTR;+ use windows::Win32::System::RemoteDesktop::{+ WTSConnectState, WTSDisconnected, WTSFreeMemory, WTSQuerySessionInformationW,+ WTS_CONNECTSTATE_CLASS, WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION,+ };+ unsafe {+ let mut buffer = PWSTR::null();+ let mut bytes = 0u32;+ if WTSQuerySessionInformationW(+ WTS_CURRENT_SERVER_HANDLE,+ WTS_CURRENT_SESSION,+ WTSConnectState,+ &mut buffer,+ &mut bytes,+ )+ .is_err()+ || buffer.is_null()+ {+ return false;+ }+ let state = if bytes as usize >= std::mem::size_of::<WTS_CONNECTSTATE_CLASS>() {+ *(buffer.0 as *const WTS_CONNECTSTATE_CLASS)+ } else {+ WTS_CONNECTSTATE_CLASS(-1)+ };+ WTSFreeMemory(buffer.0 as *mut std::ffi::c_void);+ state == WTSDisconnected+ }+}++/// Why the desktop can't be captured or driven now (`None`: it can, or the+/// cause is unknown). Called after a capture fails, to say why.+#[cfg(target_os = "windows")]+pub fn desktop_unavailable() -> Option<DesktopUnavailable> {+ let disconnected = session_disconnected();+ let state = desktop_state();+ classify_desktop_unavailable(disconnected, state.input_desktop_name.as_deref())+}+/// Whether the calling process has an attached interactive desktop.////// Two-step check:@@ -392,3 +480,36 @@ mod error_classification_tests {assert!(!is_degraded_ui_automation_error("provider is busy"));}}++#[cfg(test)]+mod desktop_unavailable_tests {+ use super::{classify_desktop_unavailable, DesktopUnavailable};++ #[test]+ fn a_disconnected_session_says_so_first() {+ assert_eq!(+ classify_desktop_unavailable(true, Some("Default")),+ Some(DesktopUnavailable::Disconnected)+ );+ assert!(DesktopUnavailable::Disconnected.message().contains("tscon"));+ }++ #[test]+ fn a_locked_session_is_the_winlogon_desktop_or_none() {+ assert_eq!(+ classify_desktop_unavailable(false, Some("Winlogon")),+ Some(DesktopUnavailable::Locked)+ );+ assert_eq!(+ classify_desktop_unavailable(false, None),+ Some(DesktopUnavailable::Locked)+ );+ assert!(DesktopUnavailable::Locked.message().contains("locked"));+ }++ #[test]+ fn the_default_desktop_is_available() {+ assert_eq!(classify_desktop_unavailable(false, Some("Default")), None);+ assert_eq!(classify_desktop_unavailable(false, Some("default")), None);+ }+}diff --git a/libs/cua-spacesd/crates/cua-spacesd-desktop/src/windows_display.rs b/libs/cua-spacesd/crates/cua-spacesd-desktop/src/windows_display.rsindex 20fb308618..00e5f46173 100644--- a/libs/cua-spacesd/crates/cua-spacesd-desktop/src/windows_display.rs+++ b/libs/cua-spacesd/crates/cua-spacesd-desktop/src/windows_display.rs@@ -172,7 +172,14 @@ fn grab(x: i32, y: i32, width: u32, height: u32) -> Result<Vec<u8>, ProviderErrolet _ = DeleteObject(bitmap);let _ = DeleteDC(memory);ReleaseDC(HWND(std::ptr::null_mut()), screen);- copied.map_err(|error| capture_error(format!("BitBlt failed: {error}")))?;+ copied.map_err(+ |error| match platform_windows::diagnostics::desktop_unavailable() {+ // A locked PC or a disconnected Remote Desktop session: the+ // viewer says which, not a raw GDI error.+ Some(why) => capture_error(format!("{} (BitBlt: {error})", why.message())),+ None => capture_error(format!("BitBlt failed: {error}")),+ },+ )?;if rows == 0 {return Err(capture_error("GetDIBits copied no rows"));}