Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(doctor): proper Windows diagnostics + interactive-session detection (#1543)

Francesco Bonaccied8d5bd90375
diff --git a/docs/content/docs/cua-driver/guide/getting-started/installation.mdx b/docs/content/docs/cua-driver/guide/getting-started/installation.mdx
index 86e70ac4e1..8be616380c 100644
--- a/docs/content/docs/cua-driver/guide/getting-started/installation.mdx
+++ b/docs/content/docs/cua-driver/guide/getting-started/installation.mdx
@@ -225,6 +225,55 @@ cua-driver --help
# OVERVIEW: macOS Accessibility-driven computer-use agent — MCP stdio server.
```
+For a structured environment + install report on any platform, run:
+
+```bash
+cua-driver doctor
+# [ok ] binary: cua-driver 0.2.1 (aarch64-macos)
+# [ok ] install dir: /Users/you/.local/bin/cua-driver
+# [ok ] home dir: /Users/you/.cua-driver-rs (3 release dirs cached)
+# [ok ] telemetry: enabled (install-id present)
+# ...
+```
+
+`doctor` runs version + install-layout + telemetry checks on every platform, plus platform-specific probes (legacy LaunchAgent / updater cleanup on macOS, UI Automation + interactive desktop session on Windows, X11/Wayland + AT-SPI on Linux). For the detailed macOS TCC + cdhash report, run `cua-driver diagnose` — `doctor` only surfaces a pointer to it. Pass `--json` for a scripting-friendly shape. Exit code is `0` when every probe is `[ok]` / `[warn]`, non-zero only on `[err]` (e.g. the binary cannot resolve its own install dir).
+
+### Windows: interactive-session requirements
+
+Window-driving tools — `list_windows`, `click`, `type_text`, `screenshot`, `get_window_state` — all bottom out in Win32 APIs (`EnumWindows`, `GetForegroundWindow`, `PrintWindow`) that are scoped to the **calling process's WindowStation + Desktop**. A process without an attached interactive desktop sees zero windows even when the user's logged-in desktop has plenty.
+
+**Windows session model in one paragraph.** Every Windows process runs inside a numbered session. Session `0` is reserved for services and has no interactive desktop attached. Sessions `1`, `2`, ... are interactive logons — one per console / RDP user. SSH-launched processes (OpenSSH server) **default to Session 0** unless the SSH server is explicitly configured to spawn the shell inside the interactive session. The same applies to most Windows service hosts, scheduled tasks running under SYSTEM, and background invocations from CI agents.
+
+If `cua-driver` lands in Session 0, the window tools will silently return empty arrays and "no windows found" — that's the APIs working as designed against a session with no desktop, not a cua-driver bug.
+
+**Diagnose with `cua-driver doctor`.** The Windows session probe surfaces this directly:
+
+```text
+[warn] interactive session: running in Session 0 (services); window-driving
+ tools (list_windows, click, type_text, screenshot, get_window_state)
+ will return empty results — these APIs need an attached interactive
+ desktop.
+ re-run cua-driver from an interactive logon (RDP, console, or a
+ scheduled task in the user's session) for the GUI tools to function.
+```
+
+A healthy interactive logon reports the inverse:
+
+```text
+[ok ] interactive session: session 2 has an attached interactive desktop
+ (WinSta0 + foreground window)
+```
+
+**Common fixes for "all my tools return empty arrays on Windows".**
+
+- **Run from RDP or the local console** — the simplest fix; both put your shell in your own interactive session, not Session 0.
+- **Run from a Windows Terminal / PowerShell launched by your logged-in user** — same effect.
+- **Scheduled Task in the user's session** — register a scheduled task with `Run only when user is logged on` checked and the principal set to your logged-in user. Cua Driver launched from that task inherits the user's interactive desktop.
+- **Use a session-launcher utility** — if you must invoke from a service / SSH context, run the binary through a launcher that spawns it inside an explicit interactive session id rather than inheriting Session 0.
+- **Configure your SSH server to spawn inside the interactive session** — possible with most modern Windows SSH server distributions but requires extra setup; the scheduled-task approach is usually simpler.
+
+Run `cua-driver doctor` after switching contexts to confirm the warning has cleared.
+
## Grant TCC permissions
Cua Driver needs two permissions:
diff --git a/docs/content/docs/cua-driver/reference/cli-reference.mdx b/docs/content/docs/cua-driver/reference/cli-reference.mdx
index a49ebb23f8..cee47eef1b 100644
--- a/docs/content/docs/cua-driver/reference/cli-reference.mdx
+++ b/docs/content/docs/cua-driver/reference/cli-reference.mdx
@@ -7,16 +7,16 @@ description: Command Line Interface reference for Cua Driver
AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
Generated by: npx tsx scripts/docs-generators/cua-driver.ts
Source: recursive Swift sources under libs/cua-driver/Sources
- Version: 0.1.9
+ Version: 0.2.0
*/}
import { Callout } from 'fumadocs-ui/components/callout';
import { VersionHeader } from '@/components/version-selector';
<VersionHeader
- versions={[{"version":"0.1","href":"/cua-driver/reference/cli-reference","isCurrent":true}]}
- currentVersion="0.1"
- fullVersion="0.1.9"
+ versions={[{"version":"0.2","href":"/cua-driver/reference/cli-reference","isCurrent":true}]}
+ currentVersion="0.2"
+ fullVersion="0.2.0"
packageName="cua-driver"
installCommand="curl -fsSL https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/install.sh | bash"
/>
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools.mdx b/docs/content/docs/cua-driver/reference/mcp-tools.mdx
index 9e35e14119..244226ba14 100644
--- a/docs/content/docs/cua-driver/reference/mcp-tools.mdx
+++ b/docs/content/docs/cua-driver/reference/mcp-tools.mdx
@@ -7,7 +7,7 @@ description: Reference for every MCP tool cua-driver exposes
AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
Generated by: npx tsx scripts/docs-generators/cua-driver.ts
Source: recursive Swift sources under libs/cua-driver/Sources
- Version: 0.1.9
+ Version: 0.2.0
*/}
import { Callout } from 'fumadocs-ui/components/callout';
diff --git a/libs/cua-driver-rs/Cargo.lock b/libs/cua-driver-rs/Cargo.lock
index 886f8eb704..6e08265679 100644
--- a/libs/cua-driver-rs/Cargo.lock
+++ b/libs/cua-driver-rs/Cargo.lock
@@ -242,7 +242,7 @@ dependencies = [
[[package]]
name = "cua-driver"
-version = "0.1.3"
+version = "0.2.1"
dependencies = [
"anyhow",
"async-trait",
@@ -267,7 +267,7 @@ dependencies = [
[[package]]
name = "cursor-overlay"
-version = "0.1.3"
+version = "0.2.1"
dependencies = [
"anyhow",
"image",
@@ -394,7 +394,7 @@ checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
[[package]]
name = "focus-monitor-win"
-version = "0.1.3"
+version = "0.2.1"
dependencies = [
"windows",
]
@@ -831,7 +831,7 @@ dependencies = [
[[package]]
name = "mcp-server"
-version = "0.1.3"
+version = "0.2.1"
dependencies = [
"anyhow",
"async-trait",
@@ -1117,7 +1117,7 @@ checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
[[package]]
name = "platform-linux"
-version = "0.1.3"
+version = "0.2.1"
dependencies = [
"anyhow",
"async-trait",
@@ -1136,7 +1136,7 @@ dependencies = [
[[package]]
name = "platform-macos"
-version = "0.1.3"
+version = "0.2.1"
dependencies = [
"anyhow",
"async-trait",
@@ -1166,7 +1166,7 @@ dependencies = [
[[package]]
name = "platform-windows"
-version = "0.1.3"
+version = "0.2.1"
dependencies = [
"anyhow",
"async-trait",
diff --git a/libs/cua-driver-rs/PARITY.md b/libs/cua-driver-rs/PARITY.md
index cc8ad8118d..4ef3cddca9 100644
--- a/libs/cua-driver-rs/PARITY.md
+++ b/libs/cua-driver-rs/PARITY.md
@@ -1460,6 +1460,80 @@ Now uses prefix `cua-driver-rs-v` (Rust port's actual tag prefix).
---
+## CLI subcommand: `doctor`
+- Swift: `libs/cua-driver/Sources/CuaDriverCLI/DoctorCommand.swift` (legacy-cleanup only — single
+ `Nothing to clean — install is up to date.` codepath, no diagnostics)
+- Rust: `libs/cua-driver-rs/crates/cua-driver/src/doctor.rs` +
+ `libs/cua-driver-rs/crates/cua-driver/src/cli.rs::run_doctor_cmd`
+- Status: INTENTIONAL_DIVERGENCE (Rust adds full diagnostic surface)
+- Test: `crates/cua-driver/src/doctor.rs` `#[cfg(test)] mod tests`
+ (5 unit tests: text rendering, JSON rendering, status-tag mapping,
+ cross-platform probe smoke path)
+
+### Behavior
+
+Probe-runner that emits a structured report. Each probe is one line
+tagged `[ok]`, `[warn]`, or `[err]` so the output is grep-friendly.
+`--json` switches to a machine-readable shape for scripting (also
+suppresses the update-available banner so JSON output stays parseable).
+
+**Cross-platform probes:**
+- `binary` — version + `<arch>-<os>` target triple
+- `install dir` — `current_exe()` resolved through symlinks
+- `home dir` — `~/.cua-driver-rs` existence + cached release-dir count
+- `telemetry` — env-var opt-out state + install-id file presence
+ (presence only — UUID value never read)
+
+**Windows probes:**
+- `interactive session` — `ProcessIdToSessionId(GetCurrentProcessId())`.
+ Session 0 → `[warn]` with explicit guidance ("re-run from an
+ interactive logon — RDP, console, or a scheduled task in the user's
+ session"). Sessions ≥1 → `OpenWindowStationW(WinSta0)` +
+ `GetForegroundWindow()` confirmation probe → `[ok]` when both succeed.
+- `UI Automation` — `CoCreateInstance(CUIAutomation)` succeeds → `[ok]`,
+ else `[err]`.
+- `EnumWindows visible` — top-level visible-window count. When zero
+ *and* Session 0 was warned above, the probe appends a "consistent
+ with Session 0" detail so the two findings read as one.
+
+**Linux probes:**
+- `display server` — `DISPLAY` / `WAYLAND_DISPLAY` matrix (X11 only,
+ Wayland only with XWayland hint, both set, neither set).
+- `X11 connection` — quick handshake via `platform_linux::x11::list_windows(None)`.
+- `AT-SPI` — `AT_SPI_BUS` env var, fallback to `gdbus introspect
+ --session --dest org.a11y.Bus`.
+
+**macOS probes:**
+- `legacy LaunchAgent` — opportunistic removal of
+ `~/Library/LaunchAgents/com.trycua.cua_driver_updater.plist` (preserves
+ the old DoctorCommand cleanup behavior, now as a structured probe).
+- `legacy update script` — opportunistic removal of
+ `/usr/local/bin/cua-driver-update` (root-owned path gets a `[warn]`
+ with the `sudo rm` command).
+- `TCC + cdhash report` — pointer to `cua-driver diagnose` for the
+ full bundle / signature / TCC dump.
+
+### Exit code
+
+`0` when every probe is `[ok]` or `[warn]`. Non-zero only when at
+least one `[err]` probe failed (e.g. `current_exe()` returned an error,
+or `CoCreateInstance(CUIAutomation)` failed on Windows). Warnings
+deliberately do not fail the run because misconfigured environments
+are sometimes the expected state — CI invocations of `doctor` to
+render the report still expect exit 0.
+
+### Why the divergence from Swift
+
+The Swift port's `DoctorCommand` only handles legacy install-bit
+cleanup on macOS. The Rust port runs on Windows + Linux as well, where
+the analogous misconfigurations (Session 0 on Windows, missing
+`DISPLAY` on Linux, no AT-SPI on Linux) are *the* source of "the tools
+are broken" reports. Folding diagnostics into `doctor` mirrors what
+users instinctively try first when something silently returns empty
+arrays.
+
+---
+
## CLI subcommand: `dump-docs`
- Swift: `libs/cua-driver/Sources/CuaDriverCLI/DumpDocsCommand.swift`
- Rust: `libs/cua-driver-rs/crates/cua-driver/src/cli.rs::run_dump_docs_with_type`
diff --git a/libs/cua-driver-rs/crates/cua-driver/Cargo.toml b/libs/cua-driver-rs/crates/cua-driver/Cargo.toml
index 0f93d0b784..dbfe772e1c 100644
--- a/libs/cua-driver-rs/crates/cua-driver/Cargo.toml
+++ b/libs/cua-driver-rs/crates/cua-driver/Cargo.toml
@@ -29,6 +29,11 @@ ureq = { version = "3", features = ["json"] }
# pre-release tags (`-dev`, `-rc.1`) sort below their corresponding release
# and we never recommend a pre-release as an "update".
semver = "1"
+# Bounded `Child::wait_timeout` for the Linux AT-SPI / gdbus probe in
+# `doctor`. We can't rely on `gdbus introspect` returning quickly when the
+# session D-Bus is hung — without a timeout, `doctor` would block forever
+# on a broken accessibility stack. Tiny dep, exactly this use case.
+wait-timeout = "0.2"
# Used by crate::bundle::parent_is_not_launchd() for the TCC
# auto-relaunch detection path on Unix (only the macOS heuristic
diff --git a/libs/cua-driver-rs/crates/cua-driver/src/cli.rs b/libs/cua-driver-rs/crates/cua-driver/src/cli.rs
index da1aa9441b..dbd8bfa03a 100644
--- a/libs/cua-driver-rs/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver-rs/crates/cua-driver/src/cli.rs
@@ -47,7 +47,7 @@ pub enum Command {
Recording { subcommand: String, args: Vec<String>, socket: Option<String> },
DumpDocs { pretty: bool, doc_type: String },
Update { apply: bool },
- Doctor,
+ Doctor { json: bool },
Diagnose,
Config {
/// `show` | `get` | `set` | `reset` (None → show)
@@ -96,6 +96,9 @@ pub fn parse_command() -> Command {
println!(" --no-daemon-relaunch Stay in-process; skip auto-launching the CuaDriverRs daemon.");
println!(" Also: CUA_DRIVER_RS_MCP_NO_RELAUNCH=1");
println!(" --socket <path> Override the daemon UDS path used by the proxy fallback.");
+ println!();
+ println!("doctor options:");
+ println!(" --json Emit the probe report as JSON for scripting.");
std::process::exit(0);
}
@@ -150,7 +153,12 @@ pub fn parse_command() -> Command {
let apply = args.iter().any(|a| a == "--apply");
Command::Update { apply }
}
- Some("doctor") => Command::Doctor,
+ Some("doctor") => {
+ // `--json` switches to machine-readable output for scripting.
+ // Bare flag — no value, position-independent.
+ let json = args.iter().any(|a| a == "--json");
+ Command::Doctor { json }
+ }
Some("diagnose") => Command::Diagnose,
Some("config") => {
let subcommand = pos.next().map(str::to_owned);
@@ -1362,52 +1370,27 @@ pub fn run_config_cmd(
}
}
-/// `cua-driver doctor` — clean up stale install bits left from older cua-driver versions.
+/// `cua-driver doctor` — run platform-aware diagnostic probes and emit a
+/// structured report.
///
-/// Mirrors Swift `DoctorCommand`:
-/// - Removes the legacy LaunchAgent plist (~/Library/LaunchAgents/com.trycua.cua_driver_updater.plist)
-/// via `launchctl unload` then `fs::remove_file`.
-/// - Removes the legacy update script (/usr/local/bin/cua-driver-update) if writable;
-/// otherwise prints the `sudo rm` command the user must run manually.
-pub fn run_doctor_cmd() {
- let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
- let legacy_plist = format!("{home}/Library/LaunchAgents/com.trycua.cua_driver_updater.plist");
- let legacy_script = "/usr/local/bin/cua-driver-update";
-
- let mut cleaned_anything = false;
-
- // — Legacy LaunchAgent plist —
- if std::path::Path::new(&legacy_plist).exists() {
- cleaned_anything = true;
- println!("Removing legacy LaunchAgent: {legacy_plist}");
-
- // Try to unload it first (ignore errors — may not be loaded).
- let _ = std::process::Command::new("launchctl")
- .args(["unload", &legacy_plist])
- .status();
-
- match std::fs::remove_file(&legacy_plist) {
- Ok(()) => println!(" ✓ Removed."),
- Err(e) => eprintln!(" ✗ Failed to remove {legacy_plist}: {e}"),
- }
- }
-
- // — Legacy update script —
- if std::path::Path::new(legacy_script).exists() {
- cleaned_anything = true;
- println!("Removing legacy update script: {legacy_script}");
- match std::fs::remove_file(legacy_script) {
- Ok(()) => println!(" ✓ Removed."),
- Err(_) => {
- // Root-owned — user must sudo.
- println!(" Could not remove (root-owned). Run manually:");
- println!(" sudo rm -f {legacy_script}");
- }
- }
+/// See [`crate::doctor`] for the probe catalog. Output is plain text by
+/// default; `--json` switches to a machine-readable shape for scripting.
+/// Exit code is `0` when every probe is `[ok]` or `[warn]`, non-zero when
+/// at least one `[err]` probe failed (e.g. the binary cannot resolve its
+/// own install dir).
+pub fn run_doctor_cmd(json: bool) {
+ let report = crate::doctor::run();
+
+ if json {
+ let val = report.to_json();
+ let out = serde_json::to_string_pretty(&val).unwrap_or_else(|_| val.to_string());
+ println!("{out}");
+ } else {
+ print!("{}", report.to_text());
}
- if !cleaned_anything {
- println!("Nothing to clean — install is up to date.");
+ if report.has_errors() {
+ process::exit(1);
}
}
@@ -1463,7 +1446,7 @@ pub fn telemetry_entry_event(cmd: &Command) -> Option<String> {
Command::Config { .. } => event::CONFIG.to_owned(),
Command::DumpDocs { .. } => "cua_driver_dump_docs".to_owned(),
Command::Update { .. } => "cua_driver_update".to_owned(),
- Command::Doctor => "cua_driver_doctor".to_owned(),
+ Command::Doctor { .. } => "cua_driver_doctor".to_owned(),
Command::Diagnose => "cua_driver_diagnose".to_owned(),
Command::TelemetryInstallEvent => return None,
};
diff --git a/libs/cua-driver-rs/crates/cua-driver/src/doctor.rs b/libs/cua-driver-rs/crates/cua-driver/src/doctor.rs
new file mode 100644
index 0000000000..5bdd19fa3a
--- /dev/null
+++ b/libs/cua-driver-rs/crates/cua-driver/src/doctor.rs
@@ -0,0 +1,586 @@
+//! `cua-driver doctor` — environment + install diagnostic probes.
+//!
+//! The doctor subcommand runs a battery of platform-aware probes and emits
+//! a structured report (plain text by default, JSON via `--json`). Each probe
+//! produces one line tagged `[ok]`, `[warn]`, or `[err]` so the output is
+//! grep-friendly without losing detail.
+//!
+//! Exit code: `0` when every probe is `[ok]` or `[warn]`. Non-zero only when
+//! at least one `[err]` probe failed — e.g. the binary cannot read its own
+//! install dir. Warnings (e.g. running outside an interactive desktop on
+//! Windows) do not fail because they are sometimes the expected state (CI
+//! invocations of `doctor` to render the report).
+//!
+//! ## Probe categories
+//!
+//! - **Cross-platform**: version + arch, install layout, home dir,
+//! telemetry state.
+//! - **Windows**: interactive desktop session detection (Session 0 warning),
+//! UI Automation COM availability, top-level window enumeration count.
+//! - **Linux**: `DISPLAY` / `WAYLAND_DISPLAY` presence, X11 connection
+//! reachability, AT-SPI bus availability hint.
+//! - **macOS**: existing legacy-cleanup steps (LaunchAgent plist + update
+//! script), plus a hint to run `cua-driver diagnose` for a full
+//! TCC / cdhash / install layout dump.
+
+use std::path::PathBuf;
+
+/// Probe outcome.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Status {
+ Ok,
+ Warn,
+ Err,
+}
+
+impl Status {
+ fn tag(self) -> &'static str {
+ match self {
+ Status::Ok => "ok",
+ Status::Warn => "warn",
+ Status::Err => "err",
+ }
+ }
+}
+
+/// One probe result.
+#[derive(Debug, Clone)]
+pub struct Probe {
+ /// Short stable label (e.g. `"binary"`, `"home dir"`).
+ pub label: String,
+ pub status: Status,
+ /// One-line summary printed next to the tag.
+ pub message: String,
+ /// Optional multi-line detail (continuation lines indented under the
+ /// summary in text mode, separate JSON field in `--json` mode).
+ pub detail: Option<String>,
+}
+
+impl Probe {
+ pub fn ok(label: impl Into<String>, message: impl Into<String>) -> Self {
+ Self { label: label.into(), status: Status::Ok, message: message.into(), detail: None }
+ }
+ pub fn warn(label: impl Into<String>, message: impl Into<String>) -> Self {
+ Self { label: label.into(), status: Status::Warn, message: message.into(), detail: None }
+ }
+ pub fn err(label: impl Into<String>, message: impl Into<String>) -> Self {
+ Self { label: label.into(), status: Status::Err, message: message.into(), detail: None }
+ }
+ pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
+ self.detail = Some(detail.into());
+ self
+ }
+}
+
+/// Aggregated probe results for one `doctor` run.
+#[derive(Debug, Clone, Default)]
+pub struct Report {
+ pub probes: Vec<Probe>,
+}
+
+impl Report {
+ pub fn push(&mut self, probe: Probe) {
+ self.probes.push(probe);
+ }
+
+ /// True iff at least one probe is `Status::Err`. Drives the process
+ /// exit code — warnings never fail the run.
+ pub fn has_errors(&self) -> bool {
+ self.probes.iter().any(|p| p.status == Status::Err)
+ }
+
+ /// Plain-text rendering. Each probe is one summary line; multi-line
+ /// `detail` blocks are indented underneath.
+ pub fn to_text(&self) -> String {
+ let mut out = String::new();
+ for probe in &self.probes {
+ out.push_str(&format!(
+ "[{tag:<4}] {label}: {msg}\n",
+ tag = probe.status.tag(),
+ label = probe.label,
+ msg = probe.message,
+ ));
+ if let Some(detail) = &probe.detail {
+ for line in detail.lines() {
+ out.push_str(" ");
+ out.push_str(line);
+ out.push('\n');
+ }
+ }
+ }
+ out
+ }
+
+ /// JSON rendering: `{ "probes": [...], "ok": bool }`. Each probe is
+ /// `{ "label", "status", "message", "detail" }`.
+ pub fn to_json(&self) -> serde_json::Value {
+ let probes: Vec<serde_json::Value> = self
+ .probes
+ .iter()
+ .map(|p| {
+ let mut obj = serde_json::Map::new();
+ obj.insert("label".into(), serde_json::Value::String(p.label.clone()));
+ obj.insert("status".into(), serde_json::Value::String(p.status.tag().into()));
+ obj.insert("message".into(), serde_json::Value::String(p.message.clone()));
+ if let Some(d) = &p.detail {
+ obj.insert("detail".into(), serde_json::Value::String(d.clone()));
+ }
+ serde_json::Value::Object(obj)
+ })
+ .collect();
+ serde_json::json!({
+ "ok": !self.has_errors(),
+ "probes": probes,
+ })
+ }
+}
+
+// ── Cross-platform probes ─────────────────────────────────────────────────
+
+/// Probe: version + target triple — the same string `cua-driver --version`
+/// returns, plus the build-time target so the user can sanity-check arch.
+fn probe_version() -> Probe {
+ let version = env!("CARGO_PKG_VERSION");
+ let target = build_target_triple();
+ Probe::ok("binary", format!("cua-driver {version} ({target})"))
+}
+
+/// Build-time target triple. We don't have a `built` crate dependency, so
+/// we synthesise `<arch>-<os>` which is enough to disambiguate the host
+/// without adding a new transitive dep.
+fn build_target_triple() -> String {
+ format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS)
+}
+
+/// Probe: where the binary lives on disk. Resolves symlinks (e.g. the
+/// `~/.local/bin/cua-driver -> packages/current/cua-driver` chain) so the
+/// user sees the actual versioned release dir.
+fn probe_install_layout() -> Probe {
+ let exe = std::env::current_exe();
+ match exe {
+ Err(e) => Probe::err("install dir", format!("could not resolve current_exe: {e}")),
+ Ok(path) => {
+ let canonical = std::fs::canonicalize(&path)
+ .unwrap_or_else(|_| path.clone());
+ let mut detail = String::new();
+ if path != canonical {
+ detail.push_str(&format!("argv exe: {}\n", path.display()));
+ detail.push_str(&format!("resolved: {}", canonical.display()));
+ } else {
+ detail.push_str(&format!("path: {}", canonical.display()));
+ }
+ Probe::ok("install dir", canonical.display().to_string()).with_detail(detail)
+ }
+ }
+}
+
+/// Probe: package-home directory (`~/.cua-driver-rs`) — counts cached
+/// release dirs so the user can sanity-check
+/// `CUA_DRIVER_RS_KEEP_VERSIONS` is doing the right thing.
+fn probe_home_dir() -> Probe {
+ let home = match home_dir() {
+ Some(h) => h,
+ None => return Probe::warn("home dir", "neither HOME nor USERPROFILE set"),
+ };
+ let cua_home = home.join(".cua-driver-rs");
+ if !cua_home.exists() {
+ return Probe::warn(
+ "home dir",
+ format!("{} does not exist yet (created on first run)", cua_home.display()),
+ );
+ }
+ let releases = cua_home.join("packages").join("releases");
+ // Only count subdirectories — bare files inside `releases/` (stray
+ // download artifacts, lock files, .DS_Store) are not actual cached
+ // versions and shouldn't inflate the "release dir(s) cached" metric.
+ let release_count = std::fs::read_dir(&releases)
+ .map(|entries| {
+ entries
+ .filter_map(Result::ok)
+ .filter(|entry| entry.metadata().map(|m| m.is_dir()).unwrap_or(false))
+ .count()
+ })
+ .unwrap_or(0);
+ Probe::ok(
+ "home dir",
+ format!(
+ "{} ({release_count} release dir{} cached)",
+ cua_home.display(),
+ if release_count == 1 { "" } else { "s" },
+ ),
+ )
+}
+
+/// Probe: telemetry state — env-var opt-out + install-id file presence.
+/// Reports without reading the UUID itself (privacy-preserving — only
+/// presence, not value).
+fn probe_telemetry() -> Probe {
+ let env_disabled = std::env::var("CUA_DRIVER_RS_TELEMETRY_ENABLED")
+ .ok()
+ .map(|v| matches!(v.to_ascii_lowercase().as_str(), "0" | "false" | "no" | "off"))
+ .unwrap_or(false);
+ let install_id_present = home_dir()
+ .map(|h| h.join(".cua-driver-rs").join(".telemetry_id").exists())
+ .unwrap_or(false);
+ if env_disabled {
+ Probe::ok(
+ "telemetry",
+ "disabled via CUA_DRIVER_RS_TELEMETRY_ENABLED",
+ )
+ } else {
+ let id_state = if install_id_present { "install-id present" } else { "install-id not yet generated" };
+ Probe::ok("telemetry", format!("enabled ({id_state})"))
+ }
+}
+
+/// `$HOME` on Unix, `%USERPROFILE%` on Windows.
+fn home_dir() -> Option<PathBuf> {
+ std::env::var_os("HOME")
+ .or_else(|| std::env::var_os("USERPROFILE"))
+ .map(PathBuf::from)
+}
+
+// ── Platform-specific probe entry-points ──────────────────────────────────
+
+/// Append every platform-specific probe to the report.
+#[cfg(target_os = "windows")]
+fn append_platform_probes(report: &mut Report) {
+ use platform_windows::diagnostics as diag;
+
+ // Interactive desktop session probe — the critical Windows check. SSH
+ // (and most service contexts) land processes in Session 0 with no
+ // attached WindowStation+Desktop, which silently breaks every
+ // window-driving tool. Surface the misconfiguration directly so users
+ // don't waste hours debugging tools that are working as designed.
+ let in_session_0 = match diag::current_session_id() {
+ Some(0) => {
+ report.push(
+ Probe::warn(
+ "interactive session",
+ "running in Session 0 (services); window-driving tools (list_windows, click, type_text, screenshot, get_window_state) will return empty results — these APIs need an attached interactive desktop.",
+ )
+ .with_detail(
+ "re-run cua-driver from an interactive logon (RDP, console, or a scheduled task in the user's session) for the GUI tools to function.",
+ ),
+ );
+ true
+ }
+ Some(sid) => {
+ match diag::interactive_desktop_check() {
+ Ok(true) => report.push(Probe::ok(
+ "interactive session",
+ format!(
+ "session {sid} has an attached interactive desktop (WinSta0 + foreground window)"
+ ),
+ )),
+ Ok(false) => report.push(
+ Probe::warn(
+ "interactive session",
+ format!(
+ "session {sid}: WinSta0 reachable but no foreground window — desktop may be locked or no app is in the foreground"
+ ),
+ ),
+ ),
+ Err(e) => report.push(Probe::warn(
+ "interactive session",
+ format!("session {sid} desktop probe failed: {e}"),
+ )),
+ }
+ false
+ }
+ None => {
+ report.push(Probe::warn(
+ "interactive session",
+ "ProcessIdToSessionId failed — cannot determine session id",
+ ));
+ false
+ }
+ };
+
+ // COM / UI Automation availability.
+ match diag::ui_automation_available() {
+ Ok(()) => report.push(Probe::ok(
+ "UI Automation",
+ "CoCreateInstance(CUIAutomation) succeeded",
+ )),
+ Err(e) => report.push(Probe::err(
+ "UI Automation",
+ format!("CoCreateInstance(CUIAutomation) failed: {e}"),
+ )),
+ }
+
+ // EnumWindows count — cross-check the session probe. When Session 0
+ // is in play, this almost always reports zero visible windows, which
+ // reinforces the warning above instead of looking like a separate bug.
+ let visible = platform_windows::win32::list_windows(None).len();
+ let probe = Probe::ok(
+ "EnumWindows visible",
+ format!("{visible} window{}", if visible == 1 { "" } else { "s" }),
+ );
+ let probe = if visible == 0 && in_session_0 {
+ probe.with_detail(
+ "consistent with the Session 0 warning above — EnumWindows is scoped to the calling session's desktop.",
+ )
+ } else {
+ probe
+ };
+ report.push(probe);
+}
+
+/// Run `gdbus introspect` against the AT-SPI accessibility bus and report
+/// whether it returned success within `timeout`. Any of: spawn failure,
+/// timeout elapsed, non-zero exit — all collapse to `false` (the caller
+/// only cares about reachability, not the failure mode).
+///
+/// Kept separate from `append_platform_probes` so it's straightforward to
+/// unit-test the timeout path without invoking the full doctor run.
+#[cfg(target_os = "linux")]
+fn probe_at_spi_bus_via_gdbus(timeout: std::time::Duration) -> bool {
+ use std::process::{Command, Stdio};
+ use wait_timeout::ChildExt;
+
+ let mut child = match Command::new("gdbus")
+ .args([
+ "introspect",
+ "--session",
+ "--dest",
+ "org.a11y.Bus",
+ "--object-path",
+ "/org/a11y/bus",
+ ])
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ {
+ Ok(c) => c,
+ Err(_) => return false,
+ };
+ match child.wait_timeout(timeout) {
+ Ok(Some(status)) => status.success(),
+ Ok(None) => {
+ // Timed out — kill the stuck child so we don't leave a
+ // gdbus process hanging around after `doctor` exits.
+ let _ = child.kill();
+ let _ = child.wait();
+ false
+ }
+ Err(_) => {
+ let _ = child.kill();
+ let _ = child.wait();
+ false
+ }
+ }
+}
+
+#[cfg(target_os = "linux")]
+fn append_platform_probes(report: &mut Report) {
+ // Display server probe. Order matters: Wayland wins when both are set
+ // (XWayland leaves DISPLAY pointing at the X server XWayland exposes,
+ // but the actual session is still Wayland).
+ let display = std::env::var("DISPLAY").ok().filter(|v| !v.is_empty());
+ let wayland = std::env::var("WAYLAND_DISPLAY").ok().filter(|v| !v.is_empty());
+ match (display.as_deref(), wayland.as_deref()) {
+ (None, None) => report.push(
+ Probe::warn(
+ "display server",
+ "neither DISPLAY nor WAYLAND_DISPLAY set — window-driving tools will fail",
+ )
+ .with_detail(
+ "run from an interactive desktop session (X11 / Wayland with XWayland) or set DISPLAY explicitly.",
+ ),
+ ),
+ (Some(d), None) => report.push(Probe::ok(
+ "display server",
+ format!("X11 (DISPLAY={d})"),
+ )),
+ (None, Some(w)) => report.push(
+ Probe::warn(
+ "display server",
+ format!("Wayland only (WAYLAND_DISPLAY={w}, DISPLAY unset)"),
+ )
+ .with_detail(
+ "X11 tools (list_windows, screenshot) need XWayland — start your session with XWayland enabled.",
+ ),
+ ),
+ (Some(d), Some(w)) => report.push(Probe::ok(
+ "display server",
+ format!("Wayland+XWayland (WAYLAND_DISPLAY={w}, DISPLAY={d})"),
+ )),
+ }
+
+ // X11 window enumeration probe. An empty result could mean either an
+ // unreachable display or a healthy display with no top-level windows
+ // open — `list_windows` doesn't distinguish the two — so the warning
+ // hedges instead of asserting a connection failure.
+ match platform_linux::x11::list_windows(None) {
+ v if v.is_empty() => report.push(
+ Probe::warn(
+ "X11 connection",
+ "no top-level windows returned (possible disconnected or inaccessible X11 display)",
+ ),
+ ),
+ v => report.push(Probe::ok(
+ "X11 connection",
+ format!("connected, {} visible top-level window{}", v.len(), if v.len() == 1 { "" } else { "s" }),
+ )),
+ }
+
+ // AT-SPI bus probe. We don't link D-Bus directly — instead, check for
+ // the AT_SPI_BUS env var which the at-spi daemon advertises when
+ // running, and fall back to checking gdbus's view of the
+ // org.a11y.Bus name.
+ let at_spi_env = std::env::var("AT_SPI_BUS").ok().filter(|v| !v.is_empty());
+ match at_spi_env {
+ Some(addr) => report.push(Probe::ok("AT-SPI", format!("bus address present (AT_SPI_BUS={addr})"))),
+ None => {
+ // Bounded wait — a hung session bus daemon would otherwise
+ // block `doctor` indefinitely. 3s is enough for a healthy
+ // gdbus introspect to complete (single round-trip on the
+ // session bus) and short enough that a stuck bus surfaces
+ // as a warning instead of looking like the binary froze.
+ let bus_ok = probe_at_spi_bus_via_gdbus(std::time::Duration::from_secs(3));
+ if bus_ok {
+ report.push(Probe::ok("AT-SPI", "org.a11y.Bus reachable via session bus"));
+ } else {
+ report.push(
+ Probe::warn("AT-SPI", "accessibility bus not reachable")
+ .with_detail(
+ "install at-spi2-core and ensure the user session has D-Bus running for get_window_state to work.",
+ ),
+ );
+ }
+ }
+ }
+}
+
+#[cfg(target_os = "macos")]
+fn append_platform_probes(report: &mut Report) {
+ // The legacy cleanup behavior — preserved as opportunistic probes so
+ // existing users on stale installs still get the cleanup, but the
+ // output is now structured.
+ let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
+ let legacy_plist = format!("{home}/Library/LaunchAgents/com.trycua.cua_driver_updater.plist");
+ let legacy_script = "/usr/local/bin/cua-driver-update";
+
+ if std::path::Path::new(&legacy_plist).exists() {
+ let _ = std::process::Command::new("launchctl")
+ .args(["unload", &legacy_plist])
+ .status();
+ match std::fs::remove_file(&legacy_plist) {
+ Ok(()) => report.push(Probe::ok(
+ "legacy LaunchAgent",
+ format!("removed stale {legacy_plist}"),
+ )),
+ Err(e) => report.push(Probe::warn(
+ "legacy LaunchAgent",
+ format!("could not remove {legacy_plist}: {e}"),
+ )),
+ }
+ } else {
+ report.push(Probe::ok("legacy LaunchAgent", "not present"));
+ }
+
+ if std::path::Path::new(legacy_script).exists() {
+ match std::fs::remove_file(legacy_script) {
+ Ok(()) => report.push(Probe::ok(
+ "legacy update script",
+ format!("removed stale {legacy_script}"),
+ )),
+ Err(_) => report.push(
+ Probe::warn(
+ "legacy update script",
+ format!("{legacy_script} present and root-owned — remove with `sudo rm -f {legacy_script}`"),
+ ),
+ ),
+ }
+ } else {
+ report.push(Probe::ok("legacy update script", "not present"));
+ }
+
+ report.push(Probe::ok(
+ "TCC + cdhash report",
+ "for a full bundle / signature / TCC dump, run `cua-driver diagnose`",
+ ));
+}
+
+#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
+fn append_platform_probes(report: &mut Report) {
+ report.push(Probe::warn(
+ "platform",
+ format!("no platform-specific probes implemented for {}", std::env::consts::OS),
+ ));
+}
+
+// ── Public entry point ────────────────────────────────────────────────────
+
+/// Run every probe and return the aggregated report.
+pub fn run() -> Report {
+ let mut report = Report::default();
+ report.push(probe_version());
+ report.push(probe_install_layout());
+ report.push(probe_home_dir());
+ report.push(probe_telemetry());
+ append_platform_probes(&mut report);
+ report
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn report_to_text_renders_status_tag_and_message() {
+ let mut r = Report::default();
+ r.push(Probe::ok("a", "alpha"));
+ r.push(Probe::warn("b", "bravo").with_detail("two\nlines"));
+ r.push(Probe::err("c", "charlie"));
+ let text = r.to_text();
+ assert!(text.contains("[ok ] a: alpha"));
+ assert!(text.contains("[warn] b: bravo"));
+ assert!(text.contains(" two"));
+ assert!(text.contains(" lines"));
+ assert!(text.contains("[err ] c: charlie"));
+ }
+
+ #[test]
+ fn report_to_json_marks_ok_false_when_any_error() {
+ let mut r = Report::default();
+ r.push(Probe::ok("a", "alpha"));
+ r.push(Probe::err("b", "bravo"));
+ let json = r.to_json();
+ assert_eq!(json["ok"], serde_json::Value::Bool(false));
+ assert_eq!(json["probes"].as_array().unwrap().len(), 2);
+ assert_eq!(json["probes"][1]["status"], "err");
+ }
+
+ #[test]
+ fn report_to_json_marks_ok_true_when_only_warnings() {
+ let mut r = Report::default();
+ r.push(Probe::ok("a", "alpha"));
+ r.push(Probe::warn("b", "bravo"));
+ let json = r.to_json();
+ // Warnings do not fail the run — exit-code-driving flag stays true.
+ assert_eq!(json["ok"], serde_json::Value::Bool(true));
+ }
+
+ #[test]
+ fn cross_platform_probes_always_emit_something() {
+ // Smoke test: run the cross-platform probes and confirm they all
+ // produced a probe (no silent dropouts).
+ let v = probe_version();
+ assert_eq!(v.label, "binary");
+ let i = probe_install_layout();
+ assert_eq!(i.label, "install dir");
+ let h = probe_home_dir();
+ assert_eq!(h.label, "home dir");
+ let t = probe_telemetry();
+ assert_eq!(t.label, "telemetry");
+ }
+
+ #[test]
+ fn run_emits_at_least_cross_platform_probes() {
+ let report = run();
+ // 4 cross-platform + at least 1 platform-specific.
+ assert!(report.probes.len() >= 5, "got {}", report.probes.len());
+ }
+}
diff --git a/libs/cua-driver-rs/crates/cua-driver/src/main.rs b/libs/cua-driver-rs/crates/cua-driver/src/main.rs
index 51fc67d394..1a763d3a0c 100644
--- a/libs/cua-driver-rs/crates/cua-driver/src/main.rs
+++ b/libs/cua-driver-rs/crates/cua-driver/src/main.rs
@@ -26,6 +26,7 @@
mod bundle;
mod cli;
+mod doctor;
mod proxy;
mod serve;
mod telemetry;
@@ -181,12 +182,15 @@ fn main() {
cli::run_update_cmd(apply);
return;
}
- cli::Command::Doctor => {
+ cli::Command::Doctor { json } => {
// Long-running interactive entry point — kick off the
// background "new version available?" check so the banner
// can land on stderr if the user is on an outdated install.
- version_check::maybe_announce_update();
- cli::run_doctor_cmd();
+ // Skip the banner in --json mode so output stays parseable.
+ if !json {
+ version_check::maybe_announce_update();
+ }
+ cli::run_doctor_cmd(json);
return;
}
cli::Command::Diagnose => {
@@ -384,11 +388,14 @@ fn main() -> anyhow::Result<()> {
cli::run_update_cmd(apply);
return Ok(());
}
- cli::Command::Doctor => {
+ cli::Command::Doctor { json } => {
// Long-running interactive entry point — kick off the
// background update check so the banner can land on stderr.
- version_check::maybe_announce_update();
- cli::run_doctor_cmd();
+ // Skip the banner in --json mode so output stays parseable.
+ if !json {
+ version_check::maybe_announce_update();
+ }
+ cli::run_doctor_cmd(json);
return Ok(());
}
cli::Command::Diagnose => {
diff --git a/libs/cua-driver-rs/crates/platform-windows/Cargo.toml b/libs/cua-driver-rs/crates/platform-windows/Cargo.toml
index 0d892b396d..7dd6da7fb6 100644
--- a/libs/cua-driver-rs/crates/platform-windows/Cargo.toml
+++ b/libs/cua-driver-rs/crates/platform-windows/Cargo.toml
@@ -36,5 +36,10 @@ windows = { version = "0.58", features = [
"Win32_UI_Shell",
"Win32_Media",
"Win32_System_Registry",
+ # `cua-driver doctor` interactive-session probe:
+ # - Win32_System_RemoteDesktop → ProcessIdToSessionId
+ # - Win32_System_StationsAndDesktops → OpenWindowStationW
+ "Win32_System_RemoteDesktop",
+ "Win32_System_StationsAndDesktops",
] }
base64 = { workspace = true }
diff --git a/libs/cua-driver-rs/crates/platform-windows/src/diagnostics.rs b/libs/cua-driver-rs/crates/platform-windows/src/diagnostics.rs
new file mode 100644
index 0000000000..89158f2e04
--- /dev/null
+++ b/libs/cua-driver-rs/crates/platform-windows/src/diagnostics.rs
@@ -0,0 +1,188 @@
+//! Windows-specific environment probes used by `cua-driver doctor`.
+//!
+//! These are read-only checks against the process environment + Win32 APIs.
+//! They never block, never touch the network, and never mutate state — they
+//! exist purely so `doctor` can report a structured snapshot of "is this
+//! process actually able to drive GUIs on this host".
+//!
+//! ## Why the session-id probe matters
+//!
+//! Window-driving tools (`list_windows`, `click`, `type_text`, `screenshot`,
+//! `get_window_state`) all bottom out in Win32 APIs that are scoped to the
+//! calling process's WindowStation + Desktop. A process that lives in
+//! Session 0 (services) — which is where Windows lands all SSH-launched
+//! processes by default — has no attached interactive desktop, so
+//! `EnumWindows` / `GetForegroundWindow` / `PrintWindow` silently return
+//! empty results. That looks like the tools are broken; they aren't. The
+//! session probe surfaces this misconfiguration directly so users know to
+//! re-run from an interactive logon (RDP, console, or a scheduled task in
+//! the user's session) instead of debugging a non-bug.
+
+#[cfg(target_os = "windows")]
+use windows::core::PCWSTR;
+#[cfg(target_os = "windows")]
+use windows::Win32::System::Com::{
+ CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_INPROC_SERVER,
+ COINIT_APARTMENTTHREADED,
+};
+#[cfg(target_os = "windows")]
+use windows::Win32::System::RemoteDesktop::ProcessIdToSessionId;
+#[cfg(target_os = "windows")]
+use windows::Win32::System::StationsAndDesktops::{
+ CloseWindowStation, OpenWindowStationW,
+};
+#[cfg(target_os = "windows")]
+use windows::Win32::System::Threading::GetCurrentProcessId;
+#[cfg(target_os = "windows")]
+use windows::Win32::UI::Accessibility::{CUIAutomation, IUIAutomation};
+#[cfg(target_os = "windows")]
+use windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow;
+
+/// Session ID of the calling process via `ProcessIdToSessionId`.
+///
+/// Returns `None` only when the API call itself fails — a healthy process
+/// always has a session id, even if it's `0` (services session).
+#[cfg(target_os = "windows")]
+pub fn current_session_id() -> Option<u32> {
+ unsafe {
+ let pid = GetCurrentProcessId();
+ let mut sid: u32 = 0;
+ if ProcessIdToSessionId(pid, &mut sid).is_ok() {
+ Some(sid)
+ } else {
+ None
+ }
+ }
+}
+
+/// Whether the calling process has an attached interactive desktop.
+///
+/// Two-step check:
+/// 1. `OpenWindowStationW(L"WinSta0", ...)` — succeeds when the
+/// interactive window station exists and we can open a handle.
+/// 2. `GetForegroundWindow()` — returns a non-null HWND when a desktop
+/// with a foreground window is actually attached (i.e. an
+/// interactive logon session is active, not just a locked screen
+/// with no foreground app).
+///
+/// `Ok(true)` only when both succeed. `Ok(false)` when `OpenWindowStationW`
+/// succeeded but `GetForegroundWindow` returned null (locked desktop or
+/// transient state). `Err` when `OpenWindowStationW` failed outright.
+#[cfg(target_os = "windows")]
+pub fn interactive_desktop_check() -> Result<bool, String> {
+ unsafe {
+ let name: Vec<u16> = "WinSta0\0".encode_utf16().collect();
+ // 0 access mask = read-only probe; we never actually need to read
+ // or modify the station, just confirm a handle is openable.
+ let h = OpenWindowStationW(PCWSTR(name.as_ptr()), false, 0)
+ .map_err(|e| format!("OpenWindowStationW(WinSta0): {e}"))?;
+ let fg = GetForegroundWindow();
+ let _ = CloseWindowStation(h);
+ Ok(fg.0 != std::ptr::null_mut())
+ }
+}
+
+/// Probe whether `CoCreateInstance(CUIAutomation)` succeeds — the same
+/// COM call used by `get_window_state` / `list_windows` element-walks.
+///
+/// Initialises COM (apartment-threaded) for the duration of the probe
+/// and uninitialises before returning so the rest of the doctor run is
+/// unaffected.
+#[cfg(target_os = "windows")]
+pub fn ui_automation_available() -> Result<(), String> {
+ unsafe {
+ // Failure here means COM is already initialised in this thread
+ // (likely apartment-threaded too); we only call CoUninitialize
+ // when our CoInitializeEx actually paired with a fresh init.
+ let init_result = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
+ let need_uninit = init_result.is_ok();
+
+ let probe = CoCreateInstance::<_, IUIAutomation>(
+ &CUIAutomation,
+ None,
+ CLSCTX_INPROC_SERVER,
+ );
+
+ if need_uninit {
+ CoUninitialize();
+ }
+
+ probe.map(|_| ()).map_err(|e| format!("{e}"))
+ }
+}
+
+// ── Non-Windows stubs so the cua-driver crate can call into us
+// unconditionally during compilation on other targets. These never run —
+// they exist purely to keep the type-checker happy on macOS / Linux.
+
+#[cfg(not(target_os = "windows"))]
+pub fn current_session_id() -> Option<u32> {
+ None
+}
+
+#[cfg(not(target_os = "windows"))]
+pub fn interactive_desktop_check() -> Result<bool, String> {
+ Err("not a Windows host".to_owned())
+}
+
+#[cfg(not(target_os = "windows"))]
+pub fn ui_automation_available() -> Result<(), String> {
+ Err("not a Windows host".to_owned())
+}
+
+/// True when `err` is the specific failure shape produced by
+/// `CoCreateInstance(CUIAutomation)` running in a non-interactive
+/// (Session 0 / service) context where the UI Automation COM server
+/// can't be activated. Used by the test below to keep CI matrices that
+/// run under SYSTEM from failing on what is an expected outcome.
+///
+/// We pattern-match on the formatted error string rather than the raw
+/// HRESULT because `ui_automation_available` already flattens the COM
+/// error to a `String`. The substrings cover the two HRESULTs that
+/// surface here in practice — `CO_E_NOTINITIALIZED` (`0x800401F0`) and
+/// `REGDB_E_CLASSNOTREG` (`0x80040154`) — plus a generic "not
+/// registered" wording the windows crate sometimes emits.
+#[cfg(target_os = "windows")]
+pub fn is_non_interactive_error(err: &str) -> bool {
+ let lower = err.to_ascii_lowercase();
+ lower.contains("0x800401f0")
+ || lower.contains("0x80040154")
+ || lower.contains("co_e_notinitialized")
+ || lower.contains("regdb_e_classnotreg")
+ || lower.contains("class not registered")
+ || lower.contains("not been initialized")
+}
+
+#[cfg(all(test, target_os = "windows"))]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn current_session_id_returns_some_on_windows() {
+ // ProcessIdToSessionId on the current process must always succeed.
+ // The value depends on the runner: an interactive dev box gives
+ // `>0`, CI running as SYSTEM gives `0`.
+ assert!(current_session_id().is_some());
+ }
+
+ #[test]
+ fn ui_automation_available_succeeds_in_test_runner() {
+ // On an interactive logon session, CoCreateInstance(CUIAutomation)
+ // must succeed. On non-interactive sessions (Session 0, SYSTEM-
+ // run CI agents, scheduled tasks without a desktop) it fails in
+ // a predictable way — we accept that as a valid outcome rather
+ // than failing the test, so the same suite runs green on both
+ // dev boxes and headless CI runners.
+ match ui_automation_available() {
+ Ok(()) => {}
+ Err(e) => {
+ let non_interactive = current_session_id() == Some(0)
+ || is_non_interactive_error(&e);
+ assert!(
+ non_interactive,
+ "ui_automation_available failed in what looks like an interactive session: {e}",
+ );
+ }
+ }
+ }
+}
diff --git a/libs/cua-driver-rs/crates/platform-windows/src/lib.rs b/libs/cua-driver-rs/crates/platform-windows/src/lib.rs
index d119217bdc..413e36e6b4 100644
--- a/libs/cua-driver-rs/crates/platform-windows/src/lib.rs
+++ b/libs/cua-driver-rs/crates/platform-windows/src/lib.rs
@@ -13,6 +13,7 @@ use mcp_server::tool::ToolRegistry;
pub mod tools;
pub mod overlay;
+pub mod diagnostics;
#[cfg(target_os = "windows")]
pub mod win32;