Skip to main content

computer_use_linux/
diagnostics.rs

1use crate::windowing::registry::{
2    self, COSMIC_WAYLAND_BACKEND, GNOME_SHELL_EXTENSION_BACKEND, GNOME_SHELL_INTROSPECT_BACKEND,
3    HYPRLAND_BACKEND, I3_BACKEND, KWIN_BACKEND, LABWC_BACKEND, NIRI_BACKEND, UMBRIEL_BACKEND,
4    WLR_FOREIGN_TOPLEVEL_BACKEND, X11_BACKEND,
5};
6use crate::ydotool;
7use schemars::JsonSchema;
8use serde::Serialize;
9use std::{
10    collections::{BTreeMap, HashMap},
11    env, fs,
12    fs::OpenOptions,
13    os::unix::fs::MetadataExt,
14    path::{Path, PathBuf},
15    process::Command,
16    sync::Mutex,
17};
18
19const DESKTOP_ENV_KEYS: &[&str] = &[
20    "DBUS_SESSION_BUS_ADDRESS",
21    "DESKTOP_SESSION",
22    "DISPLAY",
23    "HYPRLAND_INSTANCE_SIGNATURE",
24    "NIRI_SOCKET",
25    "UMBRIEL_SOCKET",
26    "XAUTHORITY",
27    "YDOTOOL_SOCKET",
28    "XDG_SESSION_DESKTOP",
29    "WAYLAND_DISPLAY",
30    "XDG_CURRENT_DESKTOP",
31    "XDG_RUNTIME_DIR",
32    "XDG_SESSION_TYPE",
33];
34const FORCE_YDOTOOL_KEYBOARD_ENV_KEYS: &[&str] = &["COMPUTER_USE_LINUX_FORCE_YDOTOOL_KEYBOARD"];
35const FORCE_YDOTOOL_POINTER_ENV_KEYS: &[&str] = &["COMPUTER_USE_LINUX_FORCE_YDOTOOL_POINTER"];
36const FORCE_XDOTOOL_KEYBOARD_ENV_KEYS: &[&str] = &["COMPUTER_USE_LINUX_FORCE_XDOTOOL_KEYBOARD"];
37const FORCE_PORTAL_KEYBOARD_ENV_KEYS: &[&str] = &["COMPUTER_USE_LINUX_FORCE_PORTAL_KEYBOARD"];
38const FORCE_PORTAL_POINTER_ENV_KEYS: &[&str] = &["COMPUTER_USE_LINUX_FORCE_PORTAL_POINTER"];
39const PORTAL_DEVICE_KEYBOARD: u32 = 1;
40const PORTAL_DEVICE_POINTER: u32 = 2;
41const PORTAL_SOURCE_MONITOR: u32 = 1;
42/// ScreenCast version that added `AvailableCursorModes` and `cursor_mode`.
43const SCREENCAST_CURSOR_MODE_VERSION: u32 = 2;
44const REMOTE_DESKTOP_KEYBOARD_METHODS: &[&str] = &[
45    "CreateSession",
46    "SelectDevices",
47    "Start",
48    "NotifyKeyboardKeycode",
49    "NotifyKeyboardKeysym",
50];
51const REMOTE_DESKTOP_POINTER_METHODS: &[&str] = &[
52    "CreateSession",
53    "SelectDevices",
54    "Start",
55    "NotifyPointerMotionAbsolute",
56    "NotifyPointerButton",
57    "NotifyPointerAxisDiscrete",
58];
59const SCREENCAST_POINTER_METHODS: &[&str] = &["SelectSources"];
60// Methods each standalone portal entry must export before doctor reports it.
61// `busctl introspect` exits 0 and prints only its header for an interface the
62// portal does not export, so exit status alone proves nothing (issue #156).
63const SCREENSHOT_PORTAL_METHODS: &[&str] = &["Screenshot"];
64const SCREENCAST_PORTAL_METHODS: &[&str] = &["CreateSession", "SelectSources", "Start"];
65const INPUT_CAPTURE_PORTAL_METHODS: &[&str] = &["GetZones", "Enable", "ConnectToEIS"];
66
67#[derive(Debug, Clone, Serialize, JsonSchema)]
68pub struct DoctorReport {
69    pub platform: PlatformReport,
70    pub portals: PortalReport,
71    pub accessibility: AccessibilityReport,
72    pub windowing: WindowingReport,
73    pub input: InputReport,
74    pub readiness: ReadinessReport,
75    /// Which interchangeable backends this environment supports, per layer, plus
76    /// the one the tool prefers. Lets an agent (or selector) understand what's
77    /// available and choose accordingly instead of assuming one fixed path.
78    pub capabilities: CapabilityMap,
79}
80
81#[derive(Debug, Clone, Serialize, JsonSchema)]
82pub struct CapabilityMap {
83    /// Pointer/keyboard injection backends, best-first.
84    pub input: Vec<String>,
85    /// Screen capture backends, best-first.
86    pub screenshot: Vec<String>,
87    /// Window listing/focus backends available.
88    pub window_control: Vec<String>,
89    /// Accessibility (element-targeted, non-pointer) backends.
90    pub accessibility: Vec<String>,
91    /// Display/session isolation contexts the host can provide.
92    pub isolation: Vec<String>,
93    /// Routes for type_text and press_key with delivery "background", which
94    /// leave the user's keyboard focus alone: at_spi (named elements),
95    /// devtools (a browser tab, when COMPUTER_USE_LINUX_DEVTOOLS names a
96    /// port), for terminals kitty, wezterm, tmux, screen and tiocsti, and
97    /// hyprland when Hyprland background mode is on, and
98    /// seat (a whole window through the agent's own keyboard focus).
99    pub background_input: Vec<String>,
100    /// The agent seat on this desktop: its route (x11-master,
101    /// sway-transient-seat or hyprland-send-key-state) and pointer support,
102    /// or the reason it has none.
103    pub background_seat: serde_json::Value,
104    /// The backend the tool will use by default for each selectable layer.
105    pub preferred: PreferredBackends,
106}
107
108#[derive(Debug, Clone, Serialize, JsonSchema)]
109pub struct PreferredBackends {
110    pub input: Option<String>,
111    pub screenshot: Option<String>,
112    pub window_control: Option<String>,
113}
114
115#[derive(Debug, Clone, Serialize, JsonSchema)]
116pub struct PlatformReport {
117    pub os: String,
118    pub arch: String,
119    pub desktop_session: Option<String>,
120    pub xdg_session_type: Option<String>,
121    pub xdg_current_desktop: Option<String>,
122    pub wayland_display: Option<String>,
123    pub display: Option<String>,
124    pub xauthority: Option<String>,
125    pub dbus_session_bus_address: Option<String>,
126    pub xdg_runtime_dir: Option<String>,
127    pub gnome_shell_version: Check,
128    pub gnome_screenshot: Check,
129    /// The DMS shell's `dms screenshot all` route, tried first on Umbriel
130    /// sessions because their portal captures one output.
131    pub dms_screenshot: Check,
132    /// Native X11 display for the root-window screenshot route. Fails on
133    /// Wayland sessions, including XWayland, by design.
134    pub x11_display: Check,
135}
136
137#[derive(Debug, Clone, Serialize, JsonSchema)]
138pub struct PortalReport {
139    pub desktop_portal: Check,
140    pub remote_desktop: Check,
141    pub remote_desktop_keyboard: Check,
142    pub screencast: Check,
143    pub screenshot: Check,
144    pub input_capture: Check,
145    pub mutter_remote_desktop: Check,
146    pub mutter_screencast: Check,
147}
148
149#[derive(Debug, Clone, Serialize, JsonSchema)]
150pub struct AccessibilityReport {
151    pub at_spi_bus: Check,
152    pub toolkit_accessibility: Check,
153    pub at_spi_enabled: Check,
154    pub screen_reader_enabled: Check,
155    pub forced_toolkit_bridge: bool,
156}
157
158#[derive(Debug, Clone, Serialize, JsonSchema)]
159pub struct WindowingReport {
160    pub gnome_shell_introspect: Check,
161    pub computer_use_linux_gnome_shell_extension: Check,
162    pub cosmic_helper: Check,
163    pub kwin: Check,
164    pub hyprland: Check,
165    pub niri: Check,
166    pub backends: BTreeMap<String, Check>,
167    pub can_list_windows: bool,
168    pub can_focus_apps: bool,
169    pub can_focus_windows: bool,
170    pub note: String,
171}
172
173#[derive(Debug, Clone, Serialize, JsonSchema)]
174pub struct InputReport {
175    pub ydotool: Check,
176    pub ydotoold: Check,
177    pub ydotool_socket: Check,
178    pub uinput: Check,
179    /// X11 XTEST keyboard backend. Preferred over ydotool on X11 sessions,
180    /// where raw evdev scancodes are re-mapped by the active XKB layout.
181    pub xdotool: Check,
182    /// Wayland virtual-keyboard backend for layout-safe Unicode literal text.
183    pub wtype: Check,
184    /// Selkies pixelflux computer-use server. Detail is the port only.
185    pub pixelflux: Check,
186}
187
188#[derive(Debug, Clone, Serialize, JsonSchema)]
189pub struct ReadinessReport {
190    pub can_register_mcp_tools: bool,
191    pub can_build_accessibility_tree: bool,
192    pub can_query_windows: bool,
193    pub can_focus_apps: bool,
194    pub can_focus_windows: bool,
195    pub can_send_development_input: bool,
196    /// A raw screenshot was successfully captured while producing this report.
197    /// Doctor only detects routes, so this remains false until capture is tested.
198    pub can_capture_screenshots: bool,
199    pub screenshot_capture_status: ScreenshotCaptureStatus,
200    pub recommended_next_step: String,
201    pub blockers: Vec<String>,
202    /// Untested capabilities and optional remediation, without blocking setup.
203    pub warnings: Vec<String>,
204}
205
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
207#[serde(rename_all = "snake_case")]
208pub enum ScreenshotCaptureStatus {
209    /// No backend route was detected; no capture was attempted.
210    Unavailable,
211    /// At least one route was detected; no capture was attempted.
212    Unverified,
213    /// A raw screenshot was captured successfully for this report.
214    Verified,
215    /// The raw capture attempted for this report failed.
216    Failed,
217}
218
219const SCREENSHOT_UNAVAILABLE: &str = "No screenshot route was detected: GNOME Shell is absent, the XDG portal does not export org.freedesktop.portal.Screenshot, this is not a native X11 session, and gnome-screenshot is not installed. get_app_state and screenshot return no image; element-aware actions from the accessibility tree still work.";
220const SCREENSHOT_UNVERIFIED: &str = "Screenshot routes were detected, but capture is unverified. Doctor does not take a screenshot or check screenshot consent. GNOME Shell can reject callers, and a portal may require consent for the caller's app ID. Call screenshot or get_app_state to verify capture.";
221const SCREENSHOT_MISSING_GNOME_FALLBACK: &str = "gnome-screenshot is not installed. On GNOME it provides a fallback when Shell or portal calls are denied; install it or inspect the desktop portal logs and screenshot permissions for the actual caller.";
222const SCREENSHOT_FAILED: &str = "Screenshot capture failed for this request. Inspect screenshot_error for the full backend errors; accessibility-tree actions still work.";
223const SCREENSHOT_FAILED_NEXT_STEP: &str = "Inspect screenshot_error and the desktop portal logs for the failed capture. On GNOME, gnome-screenshot can provide a fallback when Shell or portal calls are denied.";
224const READY_NEXT_STEP: &str = "Computer Use is ready: AT-SPI tree support, window targeting, and a Linux input backend are available.";
225
226impl ReadinessReport {
227    /// Record only the raw backend capture, before crop or encoding can fail.
228    pub(crate) fn record_screenshot_result(&mut self, succeeded: bool) {
229        self.can_capture_screenshots = succeeded;
230        self.screenshot_capture_status = if succeeded {
231            ScreenshotCaptureStatus::Verified
232        } else {
233            ScreenshotCaptureStatus::Failed
234        };
235        self.warnings.retain(|warning| {
236            warning != SCREENSHOT_UNVERIFIED && warning != SCREENSHOT_MISSING_GNOME_FALLBACK
237        });
238        self.blockers
239            .retain(|blocker| blocker != SCREENSHOT_UNAVAILABLE && blocker != SCREENSHOT_FAILED);
240        if !succeeded {
241            self.blockers.push(SCREENSHOT_FAILED.to_string());
242        }
243        if self.can_build_accessibility_tree
244            && self.can_query_windows
245            && self.can_focus_windows
246            && self.can_send_development_input
247        {
248            self.recommended_next_step = if succeeded {
249                READY_NEXT_STEP
250            } else {
251                SCREENSHOT_FAILED_NEXT_STEP
252            }
253            .to_string();
254        }
255    }
256}
257
258#[derive(Debug, Clone, Serialize, JsonSchema)]
259pub struct SetupReport {
260    pub before: DoctorReport,
261    pub accessibility_command: Check,
262    pub after: DoctorReport,
263    pub changed_accessibility: bool,
264    pub requires_target_app_restart: bool,
265    pub message: String,
266}
267
268#[derive(Debug, Clone, Serialize, JsonSchema)]
269pub struct Check {
270    pub ok: bool,
271    pub detail: String,
272}
273
274impl Check {
275    fn ok(detail: impl Into<String>) -> Self {
276        Self {
277            ok: true,
278            detail: detail.into(),
279        }
280    }
281
282    fn fail(detail: impl Into<String>) -> Self {
283        Self {
284            ok: false,
285            detail: detail.into(),
286        }
287    }
288}
289
290pub fn doctor_report() -> DoctorReport {
291    hydrate_session_bus_env();
292
293    let platform = platform_report();
294    let portals = portal_report();
295    let accessibility = accessibility_report();
296    let windowing = windowing_report(&platform);
297    let input = input_report();
298    let readiness = readiness_report_with_portal_keyboard(
299        &platform,
300        &portals.remote_desktop_keyboard,
301        &accessibility,
302        &windowing,
303        &input,
304        !screenshot_backends(&platform, &portals, &input).is_empty(),
305    );
306
307    let capabilities = capability_map_with_portal_keyboard(
308        &platform,
309        &portals,
310        &portals.remote_desktop_keyboard,
311        &accessibility,
312        &windowing,
313        &input,
314    );
315
316    DoctorReport {
317        platform,
318        portals,
319        accessibility,
320        windowing,
321        input,
322        readiness,
323        capabilities,
324    }
325}
326
327/// Derive the per-layer backend capability map from the individual checks. Lists
328/// are ordered best-first and mirror the order the tool actually tries them.
329#[cfg(test)]
330fn capability_map(
331    platform: &PlatformReport,
332    portals: &PortalReport,
333    accessibility: &AccessibilityReport,
334    windowing: &WindowingReport,
335    input: &InputReport,
336) -> CapabilityMap {
337    capability_map_with_portal_keyboard(
338        platform,
339        portals,
340        &portals.remote_desktop,
341        accessibility,
342        windowing,
343        input,
344    )
345}
346
347fn capability_map_with_portal_keyboard(
348    platform: &PlatformReport,
349    portals: &PortalReport,
350    remote_desktop_keyboard: &Check,
351    accessibility: &AccessibilityReport,
352    windowing: &WindowingReport,
353    input: &InputReport,
354) -> CapabilityMap {
355    let mut input_backends = Vec::new();
356    if input.pixelflux.ok {
357        input_backends.push("pixelflux".to_string());
358    }
359    // Absolute uinput pointer: accurate, non-blocking of coordinates; preferred.
360    if input.uinput.ok && platform_is_wayland(platform) && !is_cosmic_wayland_platform(platform) {
361        input_backends.push("abs_pointer".to_string());
362    }
363    let force_ydotool = env_flag_enabled_any(FORCE_YDOTOOL_KEYBOARD_ENV_KEYS);
364    let force_xdotool = env_flag_enabled_any(FORCE_XDOTOOL_KEYBOARD_ENV_KEYS);
365    let force_portal_keyboard = env_flag_enabled_any(FORCE_PORTAL_KEYBOARD_ENV_KEYS);
366    let portal_pointer_available = portal_pointer_input_available(platform, portals);
367    let portal_keyboard_available =
368        portal_keyboard_input_available(platform, remote_desktop_keyboard);
369    let portal_available = portal_pointer_available || portal_keyboard_available;
370    let portal_forced_for_all_input = portal_pointer_available
371        && portal_keyboard_available
372        && force_portal_for_all_input(
373            env_flag_enabled_any(FORCE_PORTAL_POINTER_ENV_KEYS),
374            env_flag_enabled_any(FORCE_PORTAL_KEYBOARD_ENV_KEYS),
375            env_flag_enabled_any(FORCE_YDOTOOL_POINTER_ENV_KEYS),
376            force_ydotool,
377        );
378    if should_advertise_xdotool(platform, input, force_ydotool, force_xdotool) {
379        input_backends.push("xdotool".to_string());
380    }
381    if should_advertise_wtype(
382        platform,
383        input,
384        force_ydotool,
385        force_xdotool,
386        force_portal_keyboard,
387    ) {
388        input_backends.push("wtype".to_string());
389    }
390    let portal_first = portal_forced_for_all_input
391        || (is_cosmic_wayland_platform(platform)
392            && portal_pointer_available
393            && !env_flag_enabled_any(FORCE_YDOTOOL_POINTER_ENV_KEYS));
394    if portal_available && portal_first {
395        input_backends.push("portal".to_string());
396    }
397    if input.ydotool.ok && input.ydotool_socket.ok {
398        input_backends.push("ydotool".to_string());
399    }
400    if portal_available && !portal_first {
401        input_backends.push("portal".to_string());
402    }
403
404    let screenshot_backends = screenshot_backends(platform, portals, input);
405
406    let mut window_backends = Vec::new();
407    let x11_available = windowing
408        .backends
409        .get(X11_BACKEND)
410        .is_some_and(|check| check.ok);
411    let prefer_x11_over_introspect = windowing.gnome_shell_introspect.ok
412        && x11_available
413        && registry::backend_can_exact_focus(X11_BACKEND);
414    if windowing.computer_use_linux_gnome_shell_extension.ok {
415        window_backends.push("gnome_shell_extension".to_string());
416    }
417    if prefer_x11_over_introspect {
418        window_backends.push(X11_BACKEND.to_string());
419    }
420    if windowing.gnome_shell_introspect.ok {
421        window_backends.push("gnome_introspect".to_string());
422    }
423    if windowing.cosmic_helper.ok {
424        window_backends.push("cosmic".to_string());
425    }
426    if windowing.kwin.ok {
427        window_backends.push("kwin".to_string());
428    }
429    if windowing.hyprland.ok {
430        window_backends.push("hyprland".to_string());
431    }
432    if windowing.niri.ok {
433        window_backends.push(NIRI_BACKEND.to_string());
434    }
435    // i3, labwc, wlr-foreign-toplevel and the generic X11/EWMH backend have
436    // no dedicated WindowingReport field; read them from the probe map so the
437    // capability list matches the registry order.
438    for backend in [
439        UMBRIEL_BACKEND,
440        I3_BACKEND,
441        LABWC_BACKEND,
442        WLR_FOREIGN_TOPLEVEL_BACKEND,
443    ] {
444        if windowing
445            .backends
446            .get(backend)
447            .is_some_and(|check| check.ok)
448        {
449            window_backends.push(backend.to_string());
450        }
451    }
452    if x11_available && !prefer_x11_over_introspect {
453        window_backends.push(X11_BACKEND.to_string());
454    }
455
456    let mut accessibility_backends = Vec::new();
457    if can_build_accessibility_tree(accessibility) {
458        accessibility_backends.push("at_spi".to_string());
459    }
460
461    // Isolation contexts: the live shared session is always available; a headless
462    // GNOME session is possible when gnome-shell is installed (it supports
463    // --headless --virtual-monitor), giving the agent its own seat.
464    let mut isolation = vec!["shared".to_string()];
465    if platform.gnome_shell_version.ok {
466        isolation.push("headless_gnome".to_string());
467    }
468
469    let preferred = PreferredBackends {
470        input: input_backends.first().cloned(),
471        screenshot: screenshot_backends.first().cloned(),
472        window_control: window_backends.first().cloned(),
473    };
474
475    let background_input =
476        crate::background_input::available_routes(!accessibility_backends.is_empty());
477
478    CapabilityMap {
479        input: input_backends,
480        screenshot: screenshot_backends,
481        window_control: window_backends,
482        accessibility: accessibility_backends,
483        isolation,
484        background_input,
485        background_seat: crate::agent_seat::doctor_summary(),
486        preferred,
487    }
488}
489
490pub fn hydrate_session_bus_env() {
491    static HYDRATED_ENV: Mutex<Option<HashMap<String, String>>> = Mutex::new(None);
492    let mut hydrated = HYDRATED_ENV
493        .lock()
494        .unwrap_or_else(|error| error.into_inner());
495    let current = desktop_environment();
496    if hydrated.as_ref() == Some(&current) {
497        return;
498    }
499    hydrate_common_command_path();
500    hydrate_desktop_env_from_process_tree();
501    let systemd_discovery_succeeded = hydrate_desktop_env_from_systemd_user();
502
503    if env_var("XDG_RUNTIME_DIR").is_none() {
504        if let Some(runtime) = xdg_runtime_dir() {
505            if runtime.exists() {
506                env::set_var("XDG_RUNTIME_DIR", runtime);
507            }
508        }
509    }
510
511    if env_var("DBUS_SESSION_BUS_ADDRESS").is_none() {
512        if let Some(runtime) = xdg_runtime_dir() {
513            let bus = runtime.join("bus");
514            if bus.exists() {
515                env::set_var(
516                    "DBUS_SESSION_BUS_ADDRESS",
517                    format!("unix:path={}", bus.display()),
518                );
519            }
520        }
521    }
522    let current = desktop_environment();
523    if systemd_discovery_succeeded
524        && current.contains_key("DBUS_SESSION_BUS_ADDRESS")
525        && current.contains_key("XDG_RUNTIME_DIR")
526        && current.contains_key("XDG_CURRENT_DESKTOP")
527        && current.contains_key("XDG_SESSION_TYPE")
528        && process_env_has_graphical_display(&current)
529    {
530        *hydrated = Some(current);
531    }
532}
533
534fn desktop_environment() -> HashMap<String, String> {
535    DESKTOP_ENV_KEYS
536        .iter()
537        .copied()
538        .chain(["PATH"])
539        .filter_map(|key| env_var(key).map(|value| (key.to_string(), value)))
540        .collect()
541}
542
543fn hydrate_common_command_path() {
544    let mut entries = env::var_os("PATH")
545        .map(|path| env::split_paths(&path).collect::<Vec<_>>())
546        .unwrap_or_default();
547    for path in [
548        "/run/current-system/sw/bin",
549        "/usr/local/bin",
550        "/usr/bin",
551        "/bin",
552    ] {
553        let path = PathBuf::from(path);
554        if path.exists() && !entries.iter().any(|entry| entry == &path) {
555            entries.push(path);
556        }
557    }
558    if let Ok(path) = env::join_paths(entries) {
559        env::set_var("PATH", path);
560    }
561}
562
563fn hydrate_desktop_env_from_process_tree() {
564    for process_env in desktop_process_environments() {
565        hydrate_desktop_env_from_map(&process_env);
566
567        if DESKTOP_ENV_KEYS.iter().all(|key| env_var(key).is_some()) {
568            break;
569        }
570    }
571}
572
573fn hydrate_desktop_env_from_systemd_user() -> bool {
574    let mut command = Command::new("systemctl");
575    command.args(["--user", "show-environment"]);
576    let Ok(output) =
577        crate::command_runner::output_blocking(&mut command, "read systemd user environment")
578    else {
579        return false;
580    };
581    if !output.status.success() {
582        return false;
583    }
584    let env_map = parse_line_environment(&output.stdout);
585    hydrate_desktop_env_from_map(&env_map);
586    true
587}
588
589fn hydrate_desktop_env_from_map(process_env: &HashMap<String, String>) {
590    let current_env = DESKTOP_ENV_KEYS
591        .iter()
592        .filter_map(|key| env_var(key).map(|value| ((*key).to_string(), value)))
593        .collect();
594    for (key, value) in desktop_env_hydration_updates(&current_env, process_env) {
595        env::set_var(key, value);
596    }
597}
598
599fn desktop_env_hydration_updates(
600    current_env: &HashMap<String, String>,
601    source_env: &HashMap<String, String>,
602) -> Vec<(&'static str, String)> {
603    // A nested X11 desktop can share a user manager with a Wayland host.
604    // Preserve its complete process-local session instead of grafting the
605    // host's WAYLAND_DISPLAY onto it.
606    let preserve_native_x11 = current_env
607        .get("XDG_SESSION_TYPE")
608        .is_some_and(|value| value.trim().eq_ignore_ascii_case("x11"))
609        && current_env
610            .get("DISPLAY")
611            .is_some_and(|value| !value.trim().is_empty())
612        && current_env
613            .get("WAYLAND_DISPLAY")
614            .is_none_or(|value| value.trim().is_empty());
615
616    DESKTOP_ENV_KEYS
617        .iter()
618        .filter_map(|key| {
619            if current_env
620                .get(*key)
621                .is_some_and(|value| !value.trim().is_empty())
622                || preserve_native_x11 && *key == "WAYLAND_DISPLAY"
623            {
624                return None;
625            }
626            source_env
627                .get(*key)
628                .filter(|value| !value.trim().is_empty())
629                .map(|value| (*key, value.clone()))
630        })
631        .collect()
632}
633
634fn desktop_process_environments() -> Vec<HashMap<String, String>> {
635    let mut environments = Vec::new();
636    let mut visited_pids = Vec::new();
637    let mut pid = parent_pid("self");
638
639    for _ in 0..8 {
640        let Some(current_pid) = pid else {
641            break;
642        };
643        if current_pid <= 1 {
644            break;
645        }
646
647        visited_pids.push(current_pid);
648        if let Some(process_env) = read_process_environ(current_pid) {
649            environments.push(process_env);
650        }
651        pid = parent_pid(&current_pid.to_string());
652    }
653
654    if !visited_pids.contains(&1) && process_owner_matches_current_user(1) {
655        if let Some(process_env) = read_process_environ(1).filter(process_env_has_graphical_display)
656        {
657            environments.push(process_env);
658        }
659    }
660
661    environments
662}
663
664fn parent_pid(pid: &str) -> Option<u32> {
665    let status = fs::read_to_string(format!("/proc/{pid}/status")).ok()?;
666    parse_parent_pid(&status)
667}
668
669fn parse_parent_pid(status: &str) -> Option<u32> {
670    status.lines().find_map(|line| {
671        let value = line.strip_prefix("PPid:")?.trim();
672        value.parse::<u32>().ok()
673    })
674}
675
676fn read_process_environ(pid: u32) -> Option<HashMap<String, String>> {
677    let bytes = fs::read(format!("/proc/{pid}/environ")).ok()?;
678    Some(parse_environ(&bytes))
679}
680
681fn process_owner_matches_current_user(pid: u32) -> bool {
682    let Some(current_uid) = user_id().and_then(|uid| uid.parse::<u32>().ok()) else {
683        return false;
684    };
685    fs::metadata(format!("/proc/{pid}"))
686        .ok()
687        .is_some_and(|metadata| metadata.uid() == current_uid)
688}
689
690fn process_env_has_graphical_display(process_env: &HashMap<String, String>) -> bool {
691    process_env
692        .get("DISPLAY")
693        .or_else(|| process_env.get("WAYLAND_DISPLAY"))
694        .is_some_and(|value| !value.trim().is_empty())
695}
696
697fn parse_environ(bytes: &[u8]) -> HashMap<String, String> {
698    bytes
699        .split(|byte| *byte == 0)
700        .filter_map(|entry| {
701            if entry.is_empty() {
702                return None;
703            }
704            let split = entry.iter().position(|byte| *byte == b'=')?;
705            let (key, value) = entry.split_at(split);
706            let value = &value[1..];
707            let key = std::str::from_utf8(key).ok()?.to_string();
708            let value = std::str::from_utf8(value).ok()?.to_string();
709            Some((key, value))
710        })
711        .collect()
712}
713
714fn parse_line_environment(bytes: &[u8]) -> HashMap<String, String> {
715    bytes
716        .split(|byte| *byte == b'\n')
717        .filter_map(|entry| {
718            if entry.is_empty() {
719                return None;
720            }
721            let split = entry.iter().position(|byte| *byte == b'=')?;
722            let (key, value) = entry.split_at(split);
723            let value = &value[1..];
724            let key = std::str::from_utf8(key).ok()?.to_string();
725            let value = std::str::from_utf8(value).ok()?.to_string();
726            Some((key, value))
727        })
728        .collect()
729}
730
731pub fn setup_accessibility_report() -> SetupReport {
732    hydrate_session_bus_env();
733
734    let before = doctor_report();
735    let accessibility_command =
736        enable_accessibility(&before.accessibility, command_check_with_session_bus);
737    let after = doctor_report();
738    let before_ready = before.readiness.can_build_accessibility_tree;
739    let after_ready = after.readiness.can_build_accessibility_tree;
740    let saved_before = check_detail_contains_true(&before.accessibility.toolkit_accessibility);
741    let saved_after = check_detail_contains_true(&after.accessibility.toolkit_accessibility);
742    let changed_accessibility = after_ready && saved_after && (!before_ready || !saved_before);
743    let requires_target_app_restart = changed_accessibility;
744    let message = if after_ready && !saved_after {
745        "AT-SPI is available at runtime, but toolkit-accessibility could not be verified as enabled in GSettings. Newly launched apps may have no accessibility tree. Check accessibility_command and the saved setting; other accessibility tools can change it."
746    } else if after_ready {
747        if changed_accessibility {
748            "AT-SPI accessibility is enabled. Restart already-running target apps if their AT-SPI tree is still empty."
749        } else {
750            "AT-SPI accessibility is ready."
751        }
752    } else {
753        "Could not enable AT-SPI accessibility automatically. Check the accessibility_command detail and enable org.a11y.Status IsEnabled or org.gnome.desktop.interface toolkit-accessibility manually."
754    }
755    .to_string();
756
757    SetupReport {
758        before,
759        accessibility_command,
760        after,
761        changed_accessibility,
762        requires_target_app_restart,
763        message,
764    }
765}
766
767// Runtime IsEnabled does not establish the setting read by newly launched
768// GTK apps. Always check the saved key, even when an existing tree is usable.
769fn enable_accessibility(
770    before: &AccessibilityReport,
771    mut run: impl FnMut(&str, &[&str]) -> Check,
772) -> Check {
773    let setting = if check_detail_contains_true(&before.toolkit_accessibility) {
774        before.toolkit_accessibility.clone()
775    } else {
776        let write = run(
777            "gsettings",
778            &[
779                "set",
780                "org.gnome.desktop.interface",
781                "toolkit-accessibility",
782                "true",
783            ],
784        );
785        let read = run(
786            "gsettings",
787            &[
788                "get",
789                "org.gnome.desktop.interface",
790                "toolkit-accessibility",
791            ],
792        );
793        if !check_detail_contains_true(&read) {
794            let runtime = run(
795                "busctl",
796                &[
797                    "--user",
798                    "set-property",
799                    "org.a11y.Bus",
800                    "/org/a11y/bus",
801                    "org.a11y.Status",
802                    "IsEnabled",
803                    "b",
804                    "true",
805                ],
806            );
807            return Check::fail(format!(
808                "Saved toolkit-accessibility was not verified: {}; write: {}; runtime fallback: {}",
809                read.detail, write.detail, runtime.detail
810            ));
811        }
812        read
813    };
814    if !can_build_accessibility_tree(before) {
815        let runtime = run(
816            "busctl",
817            &[
818                "--user",
819                "set-property",
820                "org.a11y.Bus",
821                "/org/a11y/bus",
822                "org.a11y.Status",
823                "IsEnabled",
824                "b",
825                "true",
826            ],
827        );
828        return Check::ok(format!(
829            "Saved toolkit-accessibility verified: {}; runtime request: {}",
830            setting.detail, runtime.detail
831        ));
832    }
833    Check::ok("Saved toolkit-accessibility is enabled; runtime AT-SPI is available")
834}
835
836fn platform_report() -> PlatformReport {
837    PlatformReport {
838        os: std::env::consts::OS.to_string(),
839        arch: std::env::consts::ARCH.to_string(),
840        desktop_session: env_var("DESKTOP_SESSION"),
841        xdg_session_type: env_var("XDG_SESSION_TYPE"),
842        xdg_current_desktop: env_var("XDG_CURRENT_DESKTOP"),
843        wayland_display: env_var("WAYLAND_DISPLAY"),
844        display: env_var("DISPLAY"),
845        xauthority: env_var("XAUTHORITY"),
846        dbus_session_bus_address: dbus_session_address(),
847        xdg_runtime_dir: xdg_runtime_dir().map(|path| path.display().to_string()),
848        gnome_shell_version: command_check("gnome-shell", &["--version"]),
849        gnome_screenshot: command_check("gnome-screenshot", &["--version"]),
850        dms_screenshot: dms_screenshot_check(),
851        x11_display: x11_display_check(),
852    }
853}
854
855fn x11_display_check() -> Check {
856    if !crate::x11_display::is_native_x11_session() {
857        return Check::fail("not a native X11 session");
858    }
859    // The transport enforces the deadline, so no detached worker remains
860    // blocked after a diagnostic timeout.
861    match crate::x11_display::X11Display::connect().map(|display| display.describe()) {
862        Ok(detail) => Check::ok(detail),
863        Err(error) => Check::fail(format!("{error:#}")),
864    }
865}
866
867fn portal_report() -> PortalReport {
868    let (remote_desktop, remote_desktop_keyboard, screencast) = remote_desktop_portal_checks();
869    PortalReport {
870        remote_desktop_keyboard,
871        desktop_portal: bus_name_check("org.freedesktop.portal.Desktop"),
872        remote_desktop,
873        screencast,
874        screenshot: portal_interface_methods_check(
875            "org.freedesktop.portal.Screenshot",
876            SCREENSHOT_PORTAL_METHODS,
877        ),
878        input_capture: portal_interface_methods_check(
879            "org.freedesktop.portal.InputCapture",
880            INPUT_CAPTURE_PORTAL_METHODS,
881        ),
882        mutter_remote_desktop: bus_name_check("org.gnome.Mutter.RemoteDesktop"),
883        mutter_screencast: bus_name_check("org.gnome.Mutter.ScreenCast"),
884    }
885}
886
887fn accessibility_report() -> AccessibilityReport {
888    AccessibilityReport {
889        at_spi_bus: atspi_bus_address_check(),
890        toolkit_accessibility: command_check_with_session_bus(
891            "gsettings",
892            &[
893                "get",
894                "org.gnome.desktop.interface",
895                "toolkit-accessibility",
896            ],
897        ),
898        at_spi_enabled: at_spi_enabled_check(),
899        screen_reader_enabled: screen_reader_enabled_check(),
900        forced_toolkit_bridge: toolkit_bridge_forced(),
901    }
902}
903
904fn windowing_report(platform: &PlatformReport) -> WindowingReport {
905    let probes = registry::probe_backends();
906    let backend_check = |id: &str| {
907        probes
908            .iter()
909            .find(|probe| probe.id == id)
910            .map(check_from_backend_probe)
911            .unwrap_or_else(|| Check::fail("backend probe did not run"))
912    };
913    let gnome_shell_introspect = backend_check(GNOME_SHELL_INTROSPECT_BACKEND);
914    let computer_use_linux_gnome_shell_extension = backend_check(GNOME_SHELL_EXTENSION_BACKEND);
915    let cosmic_helper = backend_check(COSMIC_WAYLAND_BACKEND);
916    let kwin = backend_check(KWIN_BACKEND);
917    let hyprland = backend_check(HYPRLAND_BACKEND);
918    let niri = backend_check(NIRI_BACKEND);
919    let backends = probes
920        .iter()
921        .map(|probe| (probe.id.to_string(), check_from_backend_probe(probe)))
922        .collect::<BTreeMap<_, _>>();
923    let can_list_windows = probes.iter().any(|probe| probe.can_list_windows);
924    let can_focus_apps = probes.iter().any(|probe| probe.can_focus_apps);
925    let can_focus_windows = probes.iter().any(|probe| probe.can_focus_windows);
926    let note = if can_list_windows {
927        if !can_focus_windows {
928            "A window listing backend is available for list_windows, but focused-window and targeted-input verification are unavailable (for example wmctrl is present but xprop is missing on X11)."
929        } else if cosmic_helper.ok && is_cosmic_wayland_platform(platform) {
930            "A COSMIC Wayland window backend is available for list_windows, focused_window, and targeted input verification."
931        } else if kwin.ok {
932            "A KWin/Plasma window backend is available for list_windows, focused_window, and targeted input verification."
933        } else if hyprland.ok {
934            "A Hyprland window backend is available for list_windows, focused_window, and targeted input verification."
935        } else if niri.ok {
936            "A niri window backend is available for list_windows, focused_window, and targeted input verification."
937        } else {
938            "A window listing backend is available for list_windows, focused_window, and targeted input verification."
939        }
940    } else {
941        "Window listing is unavailable or denied. Computer Use can still use screenshots, AT-SPI, and global ydotool input, but targeted window input cannot be verified. On GNOME, run setup_window_targeting to install the optional GNOME Shell extension backend. On COSMIC, ensure the bundled COSMIC helper is present and can connect to the session. On KDE/Plasma, ensure KWin exposes org.kde.KWin scripting on the session bus. On Hyprland, ensure hyprctl is available in the session. On niri, ensure the session exposes NIRI_SOCKET so the niri IPC socket is reachable. On labwc, the session socket labwc.sock lists windows. On other wlroots compositors, zwlr_foreign_toplevel_manager_v1 lists windows."
942    }
943    .to_string();
944
945    WindowingReport {
946        gnome_shell_introspect,
947        computer_use_linux_gnome_shell_extension,
948        cosmic_helper,
949        kwin,
950        hyprland,
951        niri,
952        backends,
953        can_list_windows,
954        can_focus_apps,
955        can_focus_windows,
956        note,
957    }
958}
959
960fn check_from_backend_probe(probe: &registry::BackendProbe) -> Check {
961    if probe.ok {
962        Check::ok(probe.detail.clone())
963    } else {
964        Check::fail(probe.detail.clone())
965    }
966}
967
968fn pixelflux_check() -> Check {
969    let Some(config) = crate::pixelflux::PixelfluxConfig::from_env() else {
970        return Check::fail("PIXELFLUX_CU is not set");
971    };
972    let port = config.port;
973    let probed = std::thread::spawn(move || {
974        let runtime = tokio::runtime::Builder::new_current_thread()
975            .enable_all()
976            .build()
977            .ok()?;
978        runtime.block_on(crate::pixelflux::probe(&config)).ok()
979    })
980    .join();
981    match probed {
982        Ok(Some(())) => Check::ok(port.to_string()),
983        _ => Check::fail(format!("{port} unreachable")),
984    }
985}
986
987fn input_report() -> InputReport {
988    InputReport {
989        ydotool: match ydotool::ensure_supported() {
990            Ok(support) => Check::ok(support.detail),
991            Err(detail) => Check::fail(detail),
992        },
993        ydotoold: process_check("ydotoold"),
994        ydotool_socket: ydotool_socket_check(),
995        uinput: read_write_path_check(Path::new("/dev/uinput")),
996        xdotool: command_path_check("xdotool"),
997        wtype: command_path_check("wtype"),
998        pixelflux: pixelflux_check(),
999    }
1000}
1001
1002#[cfg(test)]
1003fn readiness_report(
1004    platform: &PlatformReport,
1005    portals: &PortalReport,
1006    accessibility: &AccessibilityReport,
1007    windowing: &WindowingReport,
1008    input: &InputReport,
1009) -> ReadinessReport {
1010    readiness_report_with_portal_keyboard(
1011        platform,
1012        &portals.remote_desktop,
1013        accessibility,
1014        windowing,
1015        input,
1016        !screenshot_backends(platform, portals, input).is_empty(),
1017    )
1018}
1019
1020/// Screenshot routes in the order `capture_screenshot_raw` tries them. Both the
1021/// capability map and readiness read this list so they cannot disagree.
1022fn screenshot_backends(
1023    platform: &PlatformReport,
1024    portals: &PortalReport,
1025    input: &InputReport,
1026) -> Vec<String> {
1027    let mut backends = Vec::new();
1028    if input.pixelflux.ok {
1029        backends.push("pixelflux".to_string());
1030    }
1031    if platform.dms_screenshot.ok {
1032        backends.push("dms".to_string());
1033    }
1034    if platform.gnome_shell_version.ok {
1035        backends.push("gnome_shell".to_string());
1036    }
1037    if portals.screenshot.ok {
1038        backends.push("portal".to_string());
1039    }
1040    if platform.x11_display.ok {
1041        backends.push("x11".to_string());
1042    }
1043    // Subprocess fallback for background/systemd contexts the DBus paths reject.
1044    if platform.gnome_screenshot.ok {
1045        backends.push("gnome_screenshot".to_string());
1046    }
1047    backends
1048}
1049
1050fn readiness_report_with_portal_keyboard(
1051    platform: &PlatformReport,
1052    remote_desktop_keyboard: &Check,
1053    accessibility: &AccessibilityReport,
1054    windowing: &WindowingReport,
1055    input: &InputReport,
1056    screenshot_routes_detected: bool,
1057) -> ReadinessReport {
1058    let mut blockers = Vec::new();
1059    let mut warnings = Vec::new();
1060    let can_build_accessibility_tree = can_build_accessibility_tree(accessibility);
1061    let can_query_windows = windowing.can_list_windows;
1062    let can_focus_apps = windowing.can_focus_apps;
1063    let can_focus_windows = windowing.can_focus_windows;
1064    let can_send_development_input =
1065        can_send_development_input(platform, remote_desktop_keyboard, input);
1066
1067    if let Some(blocker) =
1068        atspi_disabled_blocker(accessibility, accessibility.forced_toolkit_bridge)
1069    {
1070        blockers.push(blocker);
1071    }
1072
1073    if !can_query_windows {
1074        blockers.push(if is_cosmic_wayland_platform(platform) {
1075            "COSMIC Wayland window introspection is unavailable; targeted window focus and verification will be disabled.".to_string()
1076        } else {
1077            "Window introspection is unavailable; targeted window focus and verification will be disabled."
1078                .to_string()
1079        });
1080    }
1081
1082    if can_query_windows && !can_focus_windows {
1083        blockers.push(
1084            "Exact window activation is unavailable; app-level focus may work, but window_id/title/terminal-targeted input cannot be verified."
1085                .to_string(),
1086        );
1087    }
1088
1089    if !can_send_development_input {
1090        blockers.push(
1091            "Development keyboard input is unavailable; enable XDG RemoteDesktop portal input or install wtype on compatible Wayland compositors, install xdotool with DISPLAY on X11, or use ydotool with a connectable ydotoold socket. Read/write /dev/uinput alone provides only absolute pointer input."
1092                .to_string(),
1093        );
1094    }
1095
1096    if screenshot_routes_detected {
1097        warnings.push(SCREENSHOT_UNVERIFIED.to_string());
1098        if platform.gnome_shell_version.ok && !platform.gnome_screenshot.ok {
1099            warnings.push(SCREENSHOT_MISSING_GNOME_FALLBACK.to_string());
1100        }
1101    } else {
1102        blockers.push(SCREENSHOT_UNAVAILABLE.to_string());
1103    }
1104
1105    let recommended_next_step = if !can_build_accessibility_tree {
1106        "Run setup_accessibility to enable AT-SPI accessibility before element-aware actions."
1107            .to_string()
1108    } else if !can_query_windows {
1109        format!(
1110            "Enable a supported window backend before using targeted keyboard input: {}",
1111            registry::descriptors()
1112                .iter()
1113                .map(|descriptor| descriptor.missing_hint)
1114                .collect::<Vec<_>>()
1115                .join(" ")
1116        )
1117    } else if !can_focus_windows {
1118        "Enable an exact-focus window backend before using window_id, title, or terminal-targeted input.".to_string()
1119    } else if !can_send_development_input {
1120        "Enable a keyboard-capable input backend: enable the XDG RemoteDesktop portal or install wtype on compatible Wayland compositors, install xdotool for X11, or start ydotoold with a socket accessible to this desktop user."
1121            .to_string()
1122    } else if !screenshot_routes_detected {
1123        "Enable a screenshot route: install an XDG desktop portal backend that implements Screenshot for this desktop, or install gnome-screenshot. Accessibility-tree actions work meanwhile."
1124            .to_string()
1125    } else {
1126        "AT-SPI tree support, window targeting, and a Linux input backend are available. Call screenshot or get_app_state to verify screenshot capture."
1127            .to_string()
1128    };
1129
1130    ReadinessReport {
1131        can_register_mcp_tools: true,
1132        can_build_accessibility_tree,
1133        can_query_windows,
1134        can_focus_apps,
1135        can_focus_windows,
1136        can_send_development_input,
1137        can_capture_screenshots: false,
1138        screenshot_capture_status: if screenshot_routes_detected {
1139            ScreenshotCaptureStatus::Unverified
1140        } else {
1141            ScreenshotCaptureStatus::Unavailable
1142        },
1143        recommended_next_step,
1144        blockers,
1145        warnings,
1146    }
1147}
1148
1149fn can_send_development_input(
1150    platform: &PlatformReport,
1151    remote_desktop_keyboard: &Check,
1152    input: &InputReport,
1153) -> bool {
1154    let force_ydotool = env_flag_enabled_any(FORCE_YDOTOOL_KEYBOARD_ENV_KEYS);
1155    let force_xdotool = env_flag_enabled_any(FORCE_XDOTOOL_KEYBOARD_ENV_KEYS);
1156    input.pixelflux.ok
1157        || portal_keyboard_input_available(platform, remote_desktop_keyboard)
1158        || platform_is_wayland(platform)
1159            && wtype_compatible_wayland_desktop(platform.xdg_current_desktop.as_deref())
1160            && input.wtype.ok
1161            && !force_ydotool
1162        || should_advertise_xdotool(platform, input, force_ydotool, force_xdotool)
1163        || input.ydotool.ok && input.ydotool_socket.ok
1164}
1165
1166fn portal_pointer_input_available(platform: &PlatformReport, portals: &PortalReport) -> bool {
1167    platform_is_wayland(platform) && portals.remote_desktop.ok
1168}
1169
1170fn portal_keyboard_input_available(
1171    platform: &PlatformReport,
1172    remote_desktop_keyboard: &Check,
1173) -> bool {
1174    platform_is_wayland(platform) && remote_desktop_keyboard.ok
1175}
1176
1177fn is_cosmic_wayland_platform(platform: &PlatformReport) -> bool {
1178    platform
1179        .xdg_current_desktop
1180        .as_deref()
1181        .is_some_and(|desktop| desktop.to_ascii_lowercase().contains("cosmic"))
1182        && platform.xdg_session_type.as_deref() == Some("wayland")
1183}
1184
1185pub(crate) fn can_build_accessibility_tree_now() -> bool {
1186    hydrate_session_bus_env();
1187    let accessibility = accessibility_report();
1188    can_build_accessibility_tree(&accessibility)
1189}
1190
1191fn can_build_accessibility_tree(accessibility: &AccessibilityReport) -> bool {
1192    accessibility_tree_ready(accessibility, accessibility.forced_toolkit_bridge)
1193}
1194
1195fn accessibility_tree_ready(accessibility: &AccessibilityReport, forced_bridge: bool) -> bool {
1196    accessibility.at_spi_bus.ok
1197        && (forced_bridge
1198            || check_detail_contains_true(&accessibility.at_spi_enabled)
1199            || check_detail_contains_true(&accessibility.toolkit_accessibility))
1200}
1201
1202fn atspi_disabled_blocker(
1203    accessibility: &AccessibilityReport,
1204    forced_bridge: bool,
1205) -> Option<String> {
1206    if accessibility_tree_ready(accessibility, forced_bridge) {
1207        None
1208    } else {
1209        Some(
1210            "AT-SPI accessibility is disabled; enable org.a11y.Status IsEnabled or org.gnome.desktop.interface toolkit-accessibility for tree extraction."
1211                .to_string(),
1212        )
1213    }
1214}
1215
1216fn toolkit_bridge_forced() -> bool {
1217    if toolkit_bridge_forced_by_env(env_var) {
1218        return true;
1219    }
1220    let compositor = compositor_environ();
1221    toolkit_bridge_forced_by_env(|key| {
1222        env_var(key).or_else(|| compositor.as_ref().and_then(|vars| vars.get(key).cloned()))
1223    })
1224}
1225
1226fn toolkit_bridge_forced_by_env(vars: impl Fn(&str) -> Option<String>) -> bool {
1227    vars("QT_LINUX_ACCESSIBILITY_ALWAYS_ON").is_some_and(|value| value == "1")
1228        || vars("GTK_MODULES").is_some_and(|value| value.contains("atk-bridge"))
1229}
1230
1231fn compositor_environ() -> Option<HashMap<String, String>> {
1232    // Read only the process proven to own the selected Wayland connection.
1233    // Another desktop or nested compositor must not enable this session's tree.
1234    let pid = crate::windowing::wayland_session::compositor_pid()?;
1235    read_process_environ(pid)
1236}
1237
1238fn check_detail_contains_true(check: &Check) -> bool {
1239    check.ok && check.detail.to_ascii_lowercase().contains("true")
1240}
1241
1242fn env_var(key: &str) -> Option<String> {
1243    env::var(key).ok().filter(|value| !value.trim().is_empty())
1244}
1245
1246fn xdg_runtime_dir() -> Option<PathBuf> {
1247    if let Some(value) = env_var("XDG_RUNTIME_DIR") {
1248        return Some(PathBuf::from(value));
1249    }
1250    user_id().map(|uid| PathBuf::from(format!("/run/user/{uid}")))
1251}
1252
1253fn dbus_session_address() -> Option<String> {
1254    if let Some(value) = env_var("DBUS_SESSION_BUS_ADDRESS") {
1255        return Some(value);
1256    }
1257    xdg_runtime_dir()
1258        .map(|runtime| format!("unix:path={}", runtime.join("bus").display()))
1259        .filter(|address| {
1260            address
1261                .strip_prefix("unix:path=")
1262                .is_some_and(|p| Path::new(p).exists())
1263        })
1264}
1265
1266fn ydotool_socket_check() -> Check {
1267    match ydotool::connectable_socket_path() {
1268        Ok(path) => Check::ok(format!("connectable: {}", path.display())),
1269        Err(detail) => Check::fail(format!("no trusted connectable ydotool socket ({detail})")),
1270    }
1271}
1272
1273fn user_id() -> Option<String> {
1274    let mut command = Command::new("id");
1275    command.arg("-u");
1276    let output = crate::command_runner::output_blocking(&mut command, "query user id").ok()?;
1277    output
1278        .status
1279        .success()
1280        .then(|| String::from_utf8_lossy(&output.stdout).trim().to_string())
1281        .filter(|value| !value.is_empty())
1282}
1283
1284fn command_path_check(command: &str) -> Check {
1285    command_check("sh", &["-c", &format!("command -v {command}")])
1286}
1287
1288fn platform_is_wayland(platform: &PlatformReport) -> bool {
1289    match platform.xdg_session_type.as_deref() {
1290        Some(value) => value.eq_ignore_ascii_case("wayland"),
1291        None => platform
1292            .wayland_display
1293            .as_deref()
1294            .is_some_and(|display| !display.trim().is_empty()),
1295    }
1296}
1297
1298pub(crate) fn wtype_compatible_wayland_desktop(desktop: Option<&str>) -> bool {
1299    desktop.is_none_or(|desktop| {
1300        let desktop = desktop.to_ascii_lowercase();
1301        !["gnome", "kde", "plasma", "cosmic"]
1302            .iter()
1303            .any(|known_incompatible| desktop.contains(known_incompatible))
1304    })
1305}
1306
1307fn should_advertise_wtype(
1308    platform: &PlatformReport,
1309    input: &InputReport,
1310    force_ydotool: bool,
1311    force_xdotool: bool,
1312    force_portal_keyboard: bool,
1313) -> bool {
1314    // The server routes keyboard input to xdotool before wtype only when
1315    // xdotool can run, and to the portal whenever it is forced.
1316    platform_is_wayland(platform)
1317        && wtype_compatible_wayland_desktop(platform.xdg_current_desktop.as_deref())
1318        && input.wtype.ok
1319        && !force_ydotool
1320        && !should_advertise_xdotool(platform, input, force_ydotool, force_xdotool)
1321        && !force_portal_keyboard
1322}
1323
1324fn should_advertise_xdotool(
1325    platform: &PlatformReport,
1326    input: &InputReport,
1327    force_ydotool: bool,
1328    force_xdotool: bool,
1329) -> bool {
1330    !force_ydotool
1331        && input.xdotool.ok
1332        && platform
1333            .display
1334            .as_deref()
1335            .is_some_and(|display| !display.trim().is_empty())
1336        && (force_xdotool || !platform_is_wayland(platform))
1337}
1338
1339fn env_flag_enabled_any(keys: &[&str]) -> bool {
1340    keys.iter()
1341        .any(|key| env::var(key).ok().as_deref() == Some("1"))
1342}
1343
1344fn force_portal_for_all_input(
1345    force_portal_pointer: bool,
1346    force_portal_keyboard: bool,
1347    force_ydotool_pointer: bool,
1348    force_ydotool_keyboard: bool,
1349) -> bool {
1350    force_portal_pointer
1351        && force_portal_keyboard
1352        && !force_ydotool_pointer
1353        && !force_ydotool_keyboard
1354}
1355
1356fn process_check(process_name: &str) -> Check {
1357    command_check("pgrep", &["-a", process_name])
1358}
1359
1360#[cfg(test)]
1361fn socket_connect_check(path: &Path) -> Check {
1362    match socket_connect_result(path) {
1363        Ok(()) => Check::ok(format!("connectable: {}", path.display())),
1364        Err(detail) => Check::fail(detail),
1365    }
1366}
1367
1368#[cfg(test)]
1369fn socket_connect_result(path: &Path) -> std::result::Result<(), String> {
1370    if !path.exists() {
1371        return Err(format!("missing: {}", path.display()));
1372    }
1373
1374    std::os::unix::net::UnixDatagram::unbound()
1375        .and_then(|socket| socket.connect(path))
1376        .map_err(|error| format!("{}: datagram: {error}", path.display()))
1377}
1378
1379fn read_write_path_check(path: &Path) -> Check {
1380    if !path.exists() {
1381        return Check::fail(format!("missing: {}", path.display()));
1382    }
1383
1384    match OpenOptions::new().read(true).write(true).open(path) {
1385        Ok(_) => Check::ok(format!("read/write: {}", path.display())),
1386        Err(error) => Check::fail(format!("{}: {error}", path.display())),
1387    }
1388}
1389
1390fn bus_name_check(name: &str) -> Check {
1391    command_check_with_session_bus("busctl", &["--user", "status", name])
1392}
1393
1394fn portal_interface_check(interface: &str) -> Check {
1395    command_check_with_session_bus(
1396        "busctl",
1397        &[
1398            "--user",
1399            "introspect",
1400            "org.freedesktop.portal.Desktop",
1401            "/org/freedesktop/portal/desktop",
1402            interface,
1403        ],
1404    )
1405}
1406
1407/// Introspect a portal interface and require it to export `methods`.
1408fn portal_interface_methods_check(interface: &str, methods: &[&str]) -> Check {
1409    require_busctl_methods(portal_interface_check(interface), interface, methods)
1410}
1411
1412fn require_busctl_methods(introspection: Check, interface: &str, methods: &[&str]) -> Check {
1413    if !introspection.ok {
1414        return introspection;
1415    }
1416    let missing = missing_busctl_methods(&introspection, methods);
1417    if missing.is_empty() {
1418        return introspection;
1419    }
1420    if !busctl_introspection_has_members(&introspection.detail) {
1421        return Check::fail(format!(
1422            "{interface} is not exported by the portal (introspection listed no members)"
1423        ));
1424    }
1425    Check::fail(format!(
1426        "{interface} is missing required methods: {}",
1427        missing.join(", ")
1428    ))
1429}
1430
1431fn busctl_introspection_has_members(detail: &str) -> bool {
1432    detail
1433        .lines()
1434        .any(|line| line.trim_start().starts_with('.'))
1435}
1436
1437fn remote_desktop_portal_checks() -> (Check, Check, Check) {
1438    let introspection = portal_interface_check("org.freedesktop.portal.RemoteDesktop");
1439    let screencast = portal_interface_methods_check(
1440        "org.freedesktop.portal.ScreenCast",
1441        SCREENCAST_PORTAL_METHODS,
1442    );
1443    if !introspection.ok {
1444        return (introspection.clone(), introspection, screencast);
1445    }
1446
1447    let available_device_types = command_check_with_session_bus(
1448        "busctl",
1449        &[
1450            "--user",
1451            "get-property",
1452            "org.freedesktop.portal.Desktop",
1453            "/org/freedesktop/portal/desktop",
1454            "org.freedesktop.portal.RemoteDesktop",
1455            "AvailableDeviceTypes",
1456        ],
1457    );
1458    let available_source_types = command_check_with_session_bus(
1459        "busctl",
1460        &[
1461            "--user",
1462            "get-property",
1463            "org.freedesktop.portal.Desktop",
1464            "/org/freedesktop/portal/desktop",
1465            "org.freedesktop.portal.ScreenCast",
1466            "AvailableSourceTypes",
1467        ],
1468    );
1469    let screencast_version = command_check_with_session_bus(
1470        "busctl",
1471        &[
1472            "--user",
1473            "get-property",
1474            "org.freedesktop.portal.Desktop",
1475            "/org/freedesktop/portal/desktop",
1476            "org.freedesktop.portal.ScreenCast",
1477            "version",
1478        ],
1479    );
1480    let available_cursor_modes = command_check_with_session_bus(
1481        "busctl",
1482        &[
1483            "--user",
1484            "get-property",
1485            "org.freedesktop.portal.Desktop",
1486            "/org/freedesktop/portal/desktop",
1487            "org.freedesktop.portal.ScreenCast",
1488            "AvailableCursorModes",
1489        ],
1490    );
1491    let pointer = remote_desktop_pointer_check_from(
1492        &introspection,
1493        &screencast,
1494        &available_device_types,
1495        &available_source_types,
1496        &screencast_version,
1497        &available_cursor_modes,
1498    );
1499    let keyboard = remote_desktop_keyboard_check_from(&introspection, &available_device_types);
1500    (pointer, keyboard, screencast)
1501}
1502
1503fn remote_desktop_pointer_check_from(
1504    introspection: &Check,
1505    screencast: &Check,
1506    available_device_types: &Check,
1507    available_source_types: &Check,
1508    screencast_version: &Check,
1509    available_cursor_modes: &Check,
1510) -> Check {
1511    if !introspection.ok {
1512        return Check::fail(introspection.detail.clone());
1513    }
1514    let missing_methods = missing_busctl_methods(introspection, REMOTE_DESKTOP_POINTER_METHODS);
1515    if !missing_methods.is_empty() {
1516        return Check::fail(format!(
1517            "RemoteDesktop interface is missing required pointer methods: {}",
1518            missing_methods.join(", ")
1519        ));
1520    }
1521
1522    if !screencast.ok {
1523        return Check::fail(format!(
1524            "ScreenCast interface is unavailable for portal pointer input: {}",
1525            screencast.detail
1526        ));
1527    }
1528    let missing_screencast_methods = missing_busctl_methods(screencast, SCREENCAST_POINTER_METHODS);
1529    if !missing_screencast_methods.is_empty() {
1530        return Check::fail(format!(
1531            "ScreenCast interface is missing required pointer methods: {}",
1532            missing_screencast_methods.join(", ")
1533        ));
1534    }
1535
1536    let device_types = match remote_desktop_device_types(available_device_types) {
1537        Ok(device_types) => device_types,
1538        Err(detail) => return Check::fail(detail),
1539    };
1540    if device_types & PORTAL_DEVICE_POINTER == 0 {
1541        return Check::fail(format!(
1542            "RemoteDesktop AvailableDeviceTypes={device_types} does not include pointer input"
1543        ));
1544    }
1545
1546    let source_types = match screencast_source_types(available_source_types) {
1547        Ok(source_types) => source_types,
1548        Err(detail) => return Check::fail(detail),
1549    };
1550    if source_types & PORTAL_SOURCE_MONITOR == 0 {
1551        return Check::fail(format!(
1552            "ScreenCast AvailableSourceTypes={source_types} does not include monitor sources"
1553        ));
1554    }
1555
1556    let version = match screencast_version_number(screencast_version) {
1557        Ok(version) => version,
1558        Err(detail) => return Check::fail(detail),
1559    };
1560    if version >= SCREENCAST_CURSOR_MODE_VERSION {
1561        let cursor_modes = match screencast_cursor_modes(available_cursor_modes) {
1562            Ok(cursor_modes) => cursor_modes,
1563            Err(detail) => return Check::fail(detail),
1564        };
1565        if cursor_modes & crate::remote_desktop::CURSOR_MODE_HIDDEN == 0 {
1566            return Check::fail(format!(
1567                "ScreenCast AvailableCursorModes={cursor_modes} does not include hidden cursor mode"
1568            ));
1569        }
1570
1571        return Check::ok(format!(
1572            "pointer-capable RemoteDesktop portal (AvailableDeviceTypes={device_types}, AvailableSourceTypes={source_types}, ScreenCast version={version}, AvailableCursorModes={cursor_modes})"
1573        ));
1574    }
1575
1576    Check::ok(format!(
1577        "pointer-capable RemoteDesktop portal (AvailableDeviceTypes={device_types}, AvailableSourceTypes={source_types}, ScreenCast version={version}, hidden cursor mode is the interface default)"
1578    ))
1579}
1580
1581fn screencast_version_number(screencast_version: &Check) -> Result<u32, String> {
1582    if !screencast_version.ok {
1583        return Err(format!(
1584            "ScreenCast version is unavailable: {}",
1585            screencast_version.detail
1586        ));
1587    }
1588    parse_busctl_u32_property(&screencast_version.detail).ok_or_else(|| {
1589        format!(
1590            "ScreenCast version has an unexpected value: {}",
1591            screencast_version.detail
1592        )
1593    })
1594}
1595
1596fn screencast_cursor_modes(available_cursor_modes: &Check) -> Result<u32, String> {
1597    if !available_cursor_modes.ok {
1598        return Err(format!(
1599            "ScreenCast AvailableCursorModes is unavailable: {}",
1600            available_cursor_modes.detail
1601        ));
1602    }
1603    parse_busctl_u32_property(&available_cursor_modes.detail).ok_or_else(|| {
1604        format!(
1605            "ScreenCast AvailableCursorModes has an unexpected value: {}",
1606            available_cursor_modes.detail
1607        )
1608    })
1609}
1610
1611fn remote_desktop_keyboard_check_from(
1612    introspection: &Check,
1613    available_device_types: &Check,
1614) -> Check {
1615    if !introspection.ok {
1616        return Check::fail(introspection.detail.clone());
1617    }
1618
1619    let missing_methods = missing_busctl_methods(introspection, REMOTE_DESKTOP_KEYBOARD_METHODS);
1620    if !missing_methods.is_empty() {
1621        return Check::fail(format!(
1622            "RemoteDesktop interface is missing required keyboard methods: {}",
1623            missing_methods.join(", ")
1624        ));
1625    }
1626
1627    let device_types = match remote_desktop_device_types(available_device_types) {
1628        Ok(device_types) => device_types,
1629        Err(detail) => return Check::fail(detail),
1630    };
1631    if device_types & PORTAL_DEVICE_KEYBOARD == 0 {
1632        return Check::fail(format!(
1633            "RemoteDesktop AvailableDeviceTypes={device_types} does not include keyboard input"
1634        ));
1635    }
1636
1637    Check::ok(format!(
1638        "keyboard-capable RemoteDesktop portal (AvailableDeviceTypes={device_types})"
1639    ))
1640}
1641
1642fn missing_busctl_methods<'a>(introspection: &Check, methods: &'a [&'a str]) -> Vec<&'a str> {
1643    methods
1644        .iter()
1645        .copied()
1646        .filter(|method| !busctl_introspection_has_method(&introspection.detail, method))
1647        .collect()
1648}
1649
1650fn remote_desktop_device_types(available_device_types: &Check) -> Result<u32, String> {
1651    if !available_device_types.ok {
1652        return Err(format!(
1653            "RemoteDesktop AvailableDeviceTypes is unavailable: {}",
1654            available_device_types.detail
1655        ));
1656    }
1657    parse_busctl_u32_property(&available_device_types.detail).ok_or_else(|| {
1658        format!(
1659            "RemoteDesktop AvailableDeviceTypes has an unexpected value: {}",
1660            available_device_types.detail
1661        )
1662    })
1663}
1664
1665fn screencast_source_types(available_source_types: &Check) -> Result<u32, String> {
1666    if !available_source_types.ok {
1667        return Err(format!(
1668            "ScreenCast AvailableSourceTypes is unavailable: {}",
1669            available_source_types.detail
1670        ));
1671    }
1672    parse_busctl_u32_property(&available_source_types.detail).ok_or_else(|| {
1673        format!(
1674            "ScreenCast AvailableSourceTypes has an unexpected value: {}",
1675            available_source_types.detail
1676        )
1677    })
1678}
1679
1680fn busctl_introspection_has_method(detail: &str, method: &str) -> bool {
1681    detail.lines().any(|line| {
1682        let mut fields = line.split_whitespace();
1683        fields
1684            .next()
1685            .is_some_and(|name| name.trim_start_matches('.') == method)
1686            && fields.next() == Some("method")
1687    })
1688}
1689
1690fn parse_busctl_u32_property(detail: &str) -> Option<u32> {
1691    let mut fields = detail.split_whitespace();
1692    if fields.next()? != "u" {
1693        return None;
1694    }
1695    let value = fields.next()?;
1696    value
1697        .strip_prefix("0x")
1698        .map(|hex| u32::from_str_radix(hex, 16).ok())
1699        .unwrap_or_else(|| value.parse().ok())
1700}
1701
1702fn atspi_bus_address_check() -> Check {
1703    let busctl = command_check_with_session_bus(
1704        "busctl",
1705        &[
1706            "--user",
1707            "call",
1708            "org.a11y.Bus",
1709            "/org/a11y/bus",
1710            "org.a11y.Bus",
1711            "GetAddress",
1712        ],
1713    );
1714    if busctl.ok {
1715        return busctl;
1716    }
1717
1718    gdbus_call_check(
1719        "org.a11y.Bus",
1720        "/org/a11y/bus",
1721        "org.a11y.Bus.GetAddress",
1722        &[],
1723    )
1724}
1725
1726fn atspi_status_property_check(property: &str) -> Check {
1727    let busctl = command_check_with_session_bus(
1728        "busctl",
1729        &[
1730            "--user",
1731            "get-property",
1732            "org.a11y.Bus",
1733            "/org/a11y/bus",
1734            "org.a11y.Status",
1735            property,
1736        ],
1737    );
1738    if busctl.ok {
1739        return busctl;
1740    }
1741
1742    gdbus_call_check(
1743        "org.a11y.Bus",
1744        "/org/a11y/bus",
1745        "org.freedesktop.DBus.Properties.Get",
1746        &["org.a11y.Status", property],
1747    )
1748}
1749
1750// check_detail_contains_true reads this detail, so keep "true" in it.
1751fn at_spi_enabled_check() -> Check {
1752    describe_bool(
1753        atspi_status_property_check("IsEnabled"),
1754        "AT-SPI IsEnabled is true",
1755        "AT-SPI IsEnabled is false",
1756    )
1757}
1758
1759// at-spi2-core 2.62 removed ScreenReaderEnabled; it mirrored this key.
1760fn screen_reader_enabled_check() -> Check {
1761    let mut check = atspi_status_property_check("ScreenReaderEnabled");
1762    if !check.ok {
1763        check = command_check_with_session_bus(
1764            "gsettings",
1765            &[
1766                "get",
1767                "org.gnome.desktop.a11y.applications",
1768                "screen-reader-enabled",
1769            ],
1770        );
1771    }
1772    describe_bool(check, "Screen reader is on", "Screen reader is off")
1773}
1774
1775// Replaces raw busctl, gdbus or gsettings boolean output with text.
1776fn describe_bool(check: Check, on: &str, off: &str) -> Check {
1777    let detail = check.detail.to_ascii_lowercase();
1778    match (check.ok, detail.contains("true"), detail.contains("false")) {
1779        (true, true, false) => Check::ok(on),
1780        (true, false, true) => Check::ok(off),
1781        _ => check,
1782    }
1783}
1784
1785fn gdbus_call_check(destination: &str, object_path: &str, method: &str, args: &[&str]) -> Check {
1786    let mut command_args = vec![
1787        "call",
1788        "--session",
1789        "--dest",
1790        destination,
1791        "--object-path",
1792        object_path,
1793        "--method",
1794        method,
1795    ];
1796    command_args.extend_from_slice(args);
1797    command_check_with_session_bus("gdbus", &command_args)
1798}
1799
1800/// The `dms` route `capture_screenshot_raw` tries on an Umbriel session.
1801fn dms_screenshot_check() -> Check {
1802    if !crate::windowing::backends::umbriel::is_umbriel_session() {
1803        Check::fail("not an Umbriel session")
1804    } else if crate::screenshot_impl::dms_on_path() {
1805        Check::ok("dms is on PATH")
1806    } else {
1807        Check::fail("dms is not on PATH")
1808    }
1809}
1810
1811fn command_check(command: &str, args: &[&str]) -> Check {
1812    run_command(command, args, false)
1813}
1814
1815fn command_check_with_session_bus(command: &str, args: &[&str]) -> Check {
1816    run_command(command, args, true)
1817}
1818
1819fn run_command(command: &str, args: &[&str], with_session_bus: bool) -> Check {
1820    let mut cmd = Command::new(command);
1821    cmd.args(args);
1822
1823    if with_session_bus {
1824        if let Some(address) = dbus_session_address() {
1825            cmd.env("DBUS_SESSION_BUS_ADDRESS", address);
1826        }
1827        if let Some(runtime) = xdg_runtime_dir() {
1828            cmd.env("XDG_RUNTIME_DIR", runtime);
1829        }
1830    }
1831
1832    // Introspection can block while a portal retrieves backend properties.
1833    // Bound every probe and reap its process group instead of stalling doctor
1834    // and every get_app_state request waiting for that diagnostic.
1835    match crate::command_runner::output_blocking(&mut cmd, &format!("run diagnostic {command}")) {
1836        Ok(output) if output.status.success() => {
1837            let detail = String::from_utf8_lossy(&output.stdout).trim().to_string();
1838            Check::ok(if detail.is_empty() {
1839                "ok".into()
1840            } else {
1841                detail
1842            })
1843        }
1844        Ok(output) => {
1845            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
1846            let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
1847            let detail = if !stderr.is_empty() { stderr } else { stdout };
1848            Check::fail(if detail.is_empty() {
1849                format!("exit status {}", output.status)
1850            } else {
1851                detail
1852            })
1853        }
1854        Err(error) => Check::fail(format!("{error:#}")),
1855    }
1856}
1857
1858#[cfg(test)]
1859pub(crate) mod tests {
1860    use super::*;
1861
1862    /// A complete report for tests outside this module. With accessibility
1863    /// disabled, get_app_state skips the tree and touches no desktop service.
1864    pub(crate) fn doctor_report_fixture(
1865        accessibility_enabled: bool,
1866        windows_available: bool,
1867    ) -> DoctorReport {
1868        let platform = platform_report();
1869        let portals = portal_report(Check::fail("missing"));
1870        let accessibility = accessibility_report(
1871            Check::ok("bus"),
1872            Check::ok(accessibility_enabled.to_string()),
1873        );
1874        let windowing = windowing_report(windows_available, windows_available);
1875        let input = input_report(true);
1876        DoctorReport {
1877            readiness: readiness_report(&platform, &portals, &accessibility, &windowing, &input),
1878            capabilities: capability_map(&platform, &portals, &accessibility, &windowing, &input),
1879            platform,
1880            portals,
1881            accessibility,
1882            windowing,
1883            input,
1884        }
1885    }
1886
1887    #[test]
1888    fn describe_bool_reads_busctl_gdbus_and_gsettings_output() {
1889        for (raw, expected) in [("b true", "on"), ("(<false>,)", "off"), ("false", "off")] {
1890            assert_eq!(describe_bool(Check::ok(raw), "on", "off").detail, expected);
1891        }
1892        let failed = describe_bool(Check::fail("no such property"), "on", "off");
1893        assert!(!failed.ok);
1894        assert_eq!(failed.detail, "no such property");
1895    }
1896
1897    #[test]
1898    fn diagnostic_command_timeout_reaps_the_hung_process() {
1899        use std::time::{Duration, Instant};
1900
1901        let pid_path = std::env::temp_dir().join(format!(
1902            "cul-diagnostic-timeout-{}-{}.pid",
1903            std::process::id(),
1904            getrandom::u64().unwrap()
1905        ));
1906        let started = Instant::now();
1907        let result = run_command(
1908            "/bin/sh",
1909            &[
1910                "-c",
1911                "printf '%s' \"$$\" > \"$1\"; exec /bin/sleep 60",
1912                "diagnostic-timeout-test",
1913                pid_path.to_str().unwrap(),
1914            ],
1915            false,
1916        );
1917        let elapsed = started.elapsed();
1918        let pid = fs::read_to_string(&pid_path);
1919        let _ = fs::remove_file(&pid_path);
1920        let pid: u32 = pid.expect("fixture must record its pid").parse().unwrap();
1921
1922        assert!(!result.ok, "hung diagnostic must fail");
1923        assert!(result.detail.contains("timed out after 2000 ms"));
1924        assert!(elapsed < Duration::from_secs(4), "took {elapsed:?}");
1925        assert!(
1926            !Path::new(&format!("/proc/{pid}")).exists(),
1927            "diagnostic child must be killed and reaped before returning"
1928        );
1929    }
1930
1931    #[test]
1932    fn diagnostic_spawn_failure_keeps_the_os_cause() {
1933        let path = std::env::temp_dir().join(format!(
1934            "cul-missing-diagnostic-{}-{}",
1935            std::process::id(),
1936            getrandom::u64().unwrap()
1937        ));
1938        let result = run_command(path.to_str().unwrap(), &[], false);
1939        assert!(!result.ok);
1940        assert!(result.detail.contains("failed to run diagnostic"));
1941        assert!(result.detail.contains("os error 2"));
1942    }
1943
1944    #[test]
1945    fn setup_repairs_saved_key_even_when_runtime_is_ready() {
1946        let mut before = accessibility_report(Check::ok("bus"), Check::ok("false"));
1947        before.at_spi_enabled = Check::ok("b true");
1948        let mut calls = Vec::new();
1949        let result = enable_accessibility(&before, |program, args| {
1950            calls.push((program.to_string(), args.join(" ")));
1951            Check::ok(if args[0] == "get" { "true" } else { "" })
1952        });
1953        assert!(result.ok);
1954        assert_eq!(
1955            calls,
1956            vec![
1957                (
1958                    "gsettings".into(),
1959                    "set org.gnome.desktop.interface toolkit-accessibility true".into()
1960                ),
1961                (
1962                    "gsettings".into(),
1963                    "get org.gnome.desktop.interface toolkit-accessibility".into()
1964                ),
1965            ]
1966        );
1967    }
1968
1969    #[test]
1970    fn setup_does_not_claim_saved_success_from_command_exit_status() {
1971        let before = accessibility_report(Check::ok("bus"), Check::ok("false"));
1972        let mut calls = Vec::new();
1973        let result = enable_accessibility(&before, |program, args| {
1974            calls.push(program.to_string());
1975            Check::ok(if args[0] == "get" {
1976                "false"
1977            } else {
1978                "exit status 0"
1979            })
1980        });
1981        assert!(!result.ok);
1982        assert!(result.detail.contains("not verified"));
1983        assert_eq!(calls, ["gsettings", "gsettings", "busctl"]);
1984    }
1985
1986    #[test]
1987    fn setup_preserves_enabled_settings_without_writing() {
1988        let before = accessibility_report(Check::ok("bus"), Check::ok("true"));
1989        let result = enable_accessibility(&before, |_, _| panic!("already enabled"));
1990        assert!(result.ok);
1991    }
1992
1993    fn platform_report() -> PlatformReport {
1994        PlatformReport {
1995            os: "linux".to_string(),
1996            arch: "x86_64".to_string(),
1997            desktop_session: None,
1998            xdg_session_type: Some("wayland".to_string()),
1999            xdg_current_desktop: Some("GNOME".to_string()),
2000            wayland_display: Some("wayland-0".to_string()),
2001            display: Some(":0".to_string()),
2002            xauthority: Some("/run/user/1000/Xauthority".to_string()),
2003            dbus_session_bus_address: Some("unix:path=/run/user/1000/bus".to_string()),
2004            xdg_runtime_dir: Some("/run/user/1000".to_string()),
2005            gnome_shell_version: Check::ok("GNOME Shell 46.0"),
2006            gnome_screenshot: Check::ok("gnome-screenshot 41.0"),
2007            dms_screenshot: Check::fail("not an Umbriel session"),
2008            x11_display: Check::fail("not a native X11 session"),
2009        }
2010    }
2011
2012    fn portal_report(remote_desktop: Check) -> PortalReport {
2013        PortalReport {
2014            remote_desktop_keyboard: remote_desktop.clone(),
2015            desktop_portal: Check::ok("ok"),
2016            remote_desktop,
2017            screencast: Check::fail("missing"),
2018            screenshot: Check::fail("missing"),
2019            input_capture: Check::fail("missing"),
2020            mutter_remote_desktop: Check::fail("missing"),
2021            mutter_screencast: Check::fail("missing"),
2022        }
2023    }
2024
2025    fn accessibility_report(
2026        at_spi_bus: Check,
2027        toolkit_accessibility: Check,
2028    ) -> AccessibilityReport {
2029        AccessibilityReport {
2030            at_spi_bus,
2031            toolkit_accessibility,
2032            at_spi_enabled: Check::fail("(<false>,)"),
2033            screen_reader_enabled: Check::fail("(<false>,)"),
2034            forced_toolkit_bridge: false,
2035        }
2036    }
2037    #[test]
2038    fn bus_reachable_and_forced_bridge_is_enabled() {
2039        let enabled = accessibility_report(Check::ok("bus"), Check::fail("false"));
2040        assert!(accessibility_tree_ready(&enabled, true));
2041        assert!(atspi_disabled_blocker(&enabled, true).is_none());
2042        let down = accessibility_report(Check::fail("no bus"), Check::fail("false"));
2043        assert!(!accessibility_tree_ready(&down, true));
2044        assert!(
2045            atspi_disabled_blocker(&down, true).is_some_and(|blocker| blocker.contains("disabled"))
2046        );
2047        assert!(toolkit_bridge_forced_by_env(|key| {
2048            (key == "QT_LINUX_ACCESSIBILITY_ALWAYS_ON").then(|| "1".to_string())
2049        }));
2050        assert!(toolkit_bridge_forced_by_env(|key| {
2051            (key == "GTK_MODULES").then(|| "gail:atk-bridge".to_string())
2052        }));
2053        assert!(!toolkit_bridge_forced_by_env(|_| None));
2054    }
2055
2056    fn windowing_report(can_list_windows: bool, can_focus_windows: bool) -> WindowingReport {
2057        WindowingReport {
2058            gnome_shell_introspect: if can_list_windows {
2059                Check::ok("ok")
2060            } else {
2061                Check::fail("denied")
2062            },
2063            computer_use_linux_gnome_shell_extension: if can_focus_windows {
2064                Check::ok("ok")
2065            } else {
2066                Check::fail("missing")
2067            },
2068            cosmic_helper: Check::fail("missing"),
2069            kwin: Check::fail("not a KWin session"),
2070            hyprland: Check::fail("not a Hyprland session"),
2071            niri: Check::fail("not a niri session"),
2072            backends: BTreeMap::new(),
2073            can_list_windows,
2074            can_focus_apps: true,
2075            can_focus_windows,
2076            note: String::new(),
2077        }
2078    }
2079
2080    fn input_report(can_send_input: bool) -> InputReport {
2081        let check = if can_send_input {
2082            Check::ok("ok")
2083        } else {
2084            Check::fail("missing")
2085        };
2086        input_report_parts(check.clone(), check.clone(), check.clone(), check)
2087    }
2088
2089    fn input_report_parts(
2090        ydotool: Check,
2091        ydotoold: Check,
2092        ydotool_socket: Check,
2093        uinput: Check,
2094    ) -> InputReport {
2095        InputReport {
2096            ydotool,
2097            ydotoold,
2098            ydotool_socket,
2099            uinput,
2100            xdotool: Check::fail("missing xdotool"),
2101            wtype: Check::fail("missing wtype"),
2102            pixelflux: Check::fail("PIXELFLUX_CU is not set"),
2103        }
2104    }
2105
2106    #[test]
2107    fn accessibility_tree_requires_reachable_at_spi_bus() {
2108        let report = accessibility_report(Check::fail("permission denied"), Check::ok("true"));
2109
2110        assert!(!can_build_accessibility_tree(&report));
2111    }
2112
2113    #[test]
2114    fn accessibility_tree_is_ready_when_bus_and_toolkit_are_ready() {
2115        let report = accessibility_report(
2116            Check::ok("('unix:path=/run/user/1000/at-spi/bus',)"),
2117            Check::ok("true"),
2118        );
2119
2120        assert!(can_build_accessibility_tree(&report));
2121    }
2122
2123    #[test]
2124    fn capability_map_advertises_only_a_buildable_accessibility_tree() {
2125        let platform = platform_report();
2126        let portals = portal_report(Check::fail("missing"));
2127        let windowing = windowing_report(false, false);
2128        let input = input_report(false);
2129
2130        for accessibility in [
2131            accessibility_report(Check::fail("permission denied"), Check::ok("true")),
2132            accessibility_report(
2133                Check::ok("('unix:path=/run/user/1000/at-spi/bus',)"),
2134                Check::ok("false"),
2135            ),
2136        ] {
2137            let capabilities =
2138                capability_map(&platform, &portals, &accessibility, &windowing, &input);
2139            assert!(capabilities.accessibility.is_empty());
2140        }
2141    }
2142
2143    #[test]
2144    fn parses_parent_pid_from_proc_status() {
2145        let status = "Name:\ttest\nPid:\t42\nPPid:\t7\n";
2146
2147        assert_eq!(parse_parent_pid(status), Some(7));
2148    }
2149
2150    #[test]
2151    fn parses_nul_separated_process_environment() {
2152        let environment = parse_environ(
2153            b"DISPLAY=:0\0WAYLAND_DISPLAY=wayland-0\0EMPTY=\0NO_EQUALS\0XDG_SESSION_TYPE=wayland\0",
2154        );
2155
2156        assert_eq!(environment.get("DISPLAY").map(String::as_str), Some(":0"));
2157        assert_eq!(
2158            environment.get("WAYLAND_DISPLAY").map(String::as_str),
2159            Some("wayland-0")
2160        );
2161        assert_eq!(environment.get("EMPTY").map(String::as_str), Some(""));
2162        assert!(!environment.contains_key("NO_EQUALS"));
2163    }
2164
2165    #[test]
2166    fn desktop_env_hydration_includes_xauthority() {
2167        assert!(DESKTOP_ENV_KEYS.contains(&"XAUTHORITY"));
2168    }
2169
2170    #[test]
2171    fn desktop_env_hydration_preserves_explicit_native_x11() {
2172        let current_env = HashMap::from([
2173            ("DISPLAY".to_string(), ":90".to_string()),
2174            ("XDG_SESSION_TYPE".to_string(), "x11".to_string()),
2175        ]);
2176        let host_env = HashMap::from([
2177            ("WAYLAND_DISPLAY".to_string(), "wayland-0".to_string()),
2178            (
2179                "XDG_CURRENT_DESKTOP".to_string(),
2180                "ubuntu:GNOME".to_string(),
2181            ),
2182        ]);
2183
2184        let updates = desktop_env_hydration_updates(&current_env, &host_env);
2185
2186        assert!(!updates.iter().any(|(key, _)| *key == "WAYLAND_DISPLAY"));
2187        assert!(updates
2188            .iter()
2189            .any(|(key, value)| { *key == "XDG_CURRENT_DESKTOP" && value == "ubuntu:GNOME" }));
2190    }
2191
2192    #[test]
2193    fn desktop_env_hydration_still_imports_wayland_for_incomplete_sessions() {
2194        let current_env = HashMap::new();
2195        let host_env = HashMap::from([("WAYLAND_DISPLAY".to_string(), "wayland-0".to_string())]);
2196
2197        let updates = desktop_env_hydration_updates(&current_env, &host_env);
2198
2199        assert!(updates
2200            .iter()
2201            .any(|(key, value)| *key == "WAYLAND_DISPLAY" && value == "wayland-0"));
2202    }
2203
2204    #[test]
2205    fn graphical_process_env_requires_display() {
2206        let with_display = HashMap::from([("DISPLAY".to_string(), ":0".to_string())]);
2207        let with_wayland =
2208            HashMap::from([("WAYLAND_DISPLAY".to_string(), "wayland-0".to_string())]);
2209        let without_display = HashMap::from([("XAUTHORITY".to_string(), "/tmp/xauth".to_string())]);
2210
2211        assert!(process_env_has_graphical_display(&with_display));
2212        assert!(process_env_has_graphical_display(&with_wayland));
2213        assert!(!process_env_has_graphical_display(&without_display));
2214    }
2215
2216    #[test]
2217    fn capabilities_prefer_xdotool_before_ydotool_on_x11() {
2218        let mut platform = platform_report();
2219        platform.xdg_session_type = Some("x11".to_string());
2220        platform.wayland_display = None;
2221        platform.display = Some(":0".to_string());
2222        let input = InputReport {
2223            ydotool: Check::ok("ydotool"),
2224            ydotoold: Check::ok("ydotoold"),
2225            ydotool_socket: Check::ok("connectable"),
2226            uinput: Check::fail("missing"),
2227            xdotool: Check::ok("xdotool"),
2228            wtype: Check::fail("missing wtype"),
2229            pixelflux: Check::fail("PIXELFLUX_CU is not set"),
2230        };
2231
2232        let capabilities = capability_map(
2233            &platform,
2234            &portal_report(Check::fail("missing")),
2235            &accessibility_report(Check::fail("missing"), Check::fail("missing")),
2236            &windowing_report(false, false),
2237            &input,
2238        );
2239
2240        assert_eq!(capabilities.input, ["xdotool", "ydotool"]);
2241        assert_eq!(capabilities.preferred.input.as_deref(), Some("xdotool"));
2242    }
2243
2244    #[test]
2245    fn pixelflux_only_desktop_is_input_ready() {
2246        let platform = platform_report();
2247        let mut input = input_report(false);
2248        input.pixelflux = Check::ok("loopback port 8080");
2249        assert!(can_send_development_input(
2250            &platform,
2251            &Check::fail("missing portal"),
2252            &input,
2253        ));
2254    }
2255
2256    #[test]
2257    fn x11_diagnostics_ignore_portal_and_accept_xdotool() {
2258        let mut platform = platform_report();
2259        platform.xdg_session_type = Some("x11".to_string());
2260        platform.wayland_display = None;
2261        platform.display = Some(":0".to_string());
2262        let portals = portal_report(Check::ok("org.freedesktop.portal.RemoteDesktop"));
2263        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2264        let windowing = windowing_report(true, true);
2265        let mut input = input_report(false);
2266        input.xdotool = Check::ok("xdotool");
2267
2268        let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
2269        let readiness = readiness_report(&platform, &portals, &accessibility, &windowing, &input);
2270
2271        assert_eq!(capabilities.input, ["xdotool"]);
2272        assert_eq!(capabilities.preferred.input.as_deref(), Some("xdotool"));
2273        assert!(readiness.can_send_development_input);
2274    }
2275
2276    #[test]
2277    fn wayland_diagnostics_advertise_wtype_without_portal_or_ydotool() {
2278        let mut platform = platform_report();
2279        platform.xdg_session_type = Some("wayland".to_string());
2280        platform.xdg_current_desktop = Some("Hyprland".to_string());
2281        platform.wayland_display = Some("wayland-0".to_string());
2282        let portals = portal_report(Check::fail("missing"));
2283        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2284        let windowing = windowing_report(true, true);
2285        let mut input = input_report(false);
2286        input.wtype = Check::ok("wtype");
2287
2288        let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
2289        let readiness = readiness_report(&platform, &portals, &accessibility, &windowing, &input);
2290
2291        assert_eq!(capabilities.input, ["wtype"]);
2292        assert_eq!(capabilities.preferred.input.as_deref(), Some("wtype"));
2293        assert!(readiness.can_send_development_input);
2294    }
2295
2296    #[test]
2297    fn wtype_excludes_known_incompatible_wayland_desktops() {
2298        assert!(wtype_compatible_wayland_desktop(Some("Hyprland")));
2299        assert!(wtype_compatible_wayland_desktop(Some("sway")));
2300        assert!(wtype_compatible_wayland_desktop(None));
2301        assert!(!wtype_compatible_wayland_desktop(Some("GNOME")));
2302        assert!(!wtype_compatible_wayland_desktop(Some("KDE;Plasma")));
2303        assert!(!wtype_compatible_wayland_desktop(Some("COSMIC")));
2304    }
2305
2306    #[test]
2307    fn wayland_diagnostics_prefer_ydotool_before_portal() {
2308        let platform = platform_report();
2309        let portals = portal_report(Check::ok("org.freedesktop.portal.RemoteDesktop"));
2310        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2311        let windowing = windowing_report(true, true);
2312        let input = input_report_parts(
2313            Check::ok("ydotool"),
2314            Check::ok("ydotoold"),
2315            Check::ok("connectable"),
2316            Check::fail("missing uinput"),
2317        );
2318
2319        let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
2320
2321        assert_eq!(capabilities.input, ["ydotool", "portal"]);
2322        assert_eq!(capabilities.preferred.input.as_deref(), Some("ydotool"));
2323    }
2324
2325    #[test]
2326    fn writable_uinput_advertises_abs_pointer_first() {
2327        let platform = platform_report();
2328        let portals = portal_report(Check::fail("missing"));
2329        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2330        let windowing = windowing_report(true, true);
2331        let input = input_report_parts(
2332            Check::ok("ydotool"),
2333            Check::ok("ydotoold"),
2334            Check::ok("connectable"),
2335            Check::ok("read/write: /dev/uinput"),
2336        );
2337
2338        let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
2339
2340        assert_eq!(capabilities.input, ["abs_pointer", "ydotool"]);
2341    }
2342
2343    #[test]
2344    fn portal_force_order_requires_both_input_modalities() {
2345        assert!(force_portal_for_all_input(true, true, false, false));
2346        assert!(!force_portal_for_all_input(true, false, false, false));
2347        assert!(!force_portal_for_all_input(true, true, true, false));
2348        assert!(!force_portal_for_all_input(true, true, false, true));
2349    }
2350
2351    fn remote_desktop_runtime_introspection() -> Check {
2352        Check::ok(
2353            "NAME TYPE SIGNATURE RESULT/VALUE FLAGS\n\
2354             .CreateSession method a{sv} o -\n\
2355             .SelectDevices method oa{sv} o -\n\
2356             .Start method osa{sv} o -\n\
2357             .NotifyPointerMotionAbsolute method oa{sv}udd - -\n\
2358             .NotifyPointerButton method oa{sv}iu - -\n\
2359             .NotifyPointerAxisDiscrete method oa{sv}ui - -\n\
2360             .NotifyKeyboardKeycode method ouu - -\n\
2361             .NotifyKeyboardKeysym method ouu - -\n\
2362             .AvailableDeviceTypes property u 3 emits-change",
2363        )
2364    }
2365
2366    fn screencast_runtime_introspection() -> Check {
2367        Check::ok(
2368            "NAME TYPE SIGNATURE RESULT/VALUE FLAGS\n\
2369             .SelectSources method oa{sv} o -",
2370        )
2371    }
2372
2373    #[test]
2374    fn cosmic_prefers_per_monitor_portal_over_uinput_and_ydotool() {
2375        let mut platform = platform_report();
2376        platform.xdg_session_type = Some("wayland".to_string());
2377        platform.xdg_current_desktop = Some("COSMIC".to_string());
2378        let input = input_report_parts(
2379            Check::ok("ydotool"),
2380            Check::ok("socket"),
2381            Check::ok("socket"),
2382            Check::ok("uinput"),
2383        );
2384        let capabilities = capability_map(
2385            &platform,
2386            &portal_report(Check::ok("portal")),
2387            &accessibility_report(Check::ok("bus"), Check::ok("true")),
2388            &windowing_report(true, true),
2389            &input,
2390        );
2391        assert_eq!(capabilities.preferred.input.as_deref(), Some("portal"));
2392        assert!(!capabilities
2393            .input
2394            .iter()
2395            .any(|backend| backend == "abs_pointer"));
2396    }
2397
2398    #[test]
2399    fn remote_desktop_portal_rejects_header_only_introspection() {
2400        let introspection = Check::ok("NAME TYPE SIGNATURE RESULT/VALUE FLAGS");
2401        let available_device_types = Check::ok("u 3");
2402        let pointer = remote_desktop_pointer_check_from(
2403            &introspection,
2404            &screencast_runtime_introspection(),
2405            &available_device_types,
2406            &Check::ok("u 1"),
2407            &Check::ok("u 2"),
2408            &Check::ok("u 2"),
2409        );
2410        let keyboard = remote_desktop_keyboard_check_from(&introspection, &available_device_types);
2411
2412        assert!(!pointer.ok);
2413        assert!(pointer.detail.contains("CreateSession"));
2414        assert!(pointer.detail.contains("NotifyPointerButton"));
2415        assert!(!keyboard.ok);
2416        assert!(keyboard.detail.contains("NotifyKeyboardKeysym"));
2417
2418        let input = input_report_parts(
2419            Check::ok("ydotool"),
2420            Check::ok("ydotoold"),
2421            Check::fail("no connectable ydotool socket"),
2422            Check::ok("read/write: /dev/uinput"),
2423        );
2424        let platform = platform_report();
2425        let portals = portal_report(pointer);
2426        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2427        let windowing = windowing_report(true, true);
2428        let capabilities = capability_map_with_portal_keyboard(
2429            &platform,
2430            &portals,
2431            &keyboard,
2432            &accessibility,
2433            &windowing,
2434            &input,
2435        );
2436        let readiness = readiness_report_with_portal_keyboard(
2437            &platform,
2438            &keyboard,
2439            &accessibility,
2440            &windowing,
2441            &input,
2442            true,
2443        );
2444
2445        assert!(!capabilities.input.iter().any(|backend| backend == "portal"));
2446        assert!(!readiness.can_send_development_input);
2447    }
2448
2449    #[test]
2450    fn keyboard_only_portal_remains_advertised_without_pointer_capability() {
2451        let platform = platform_report();
2452        let keyboard = remote_desktop_keyboard_check_from(
2453            &remote_desktop_runtime_introspection(),
2454            &Check::ok("u 1"),
2455        );
2456        let portals = portal_report(Check::fail(
2457            "ScreenCast AvailableSourceTypes=2 does not include monitor sources",
2458        ));
2459        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2460        let windowing = windowing_report(true, true);
2461        let input = input_report_parts(
2462            Check::fail("missing ydotool"),
2463            Check::fail("ydotoold not running"),
2464            Check::fail("no connectable ydotool socket"),
2465            Check::fail("/dev/uinput: Permission denied"),
2466        );
2467
2468        let capabilities = capability_map_with_portal_keyboard(
2469            &platform,
2470            &portals,
2471            &keyboard,
2472            &accessibility,
2473            &windowing,
2474            &input,
2475        );
2476        let readiness = readiness_report_with_portal_keyboard(
2477            &platform,
2478            &keyboard,
2479            &accessibility,
2480            &windowing,
2481            &input,
2482            true,
2483        );
2484
2485        assert!(!portals.remote_desktop.ok);
2486        assert_eq!(capabilities.input, ["portal"]);
2487        assert_eq!(capabilities.preferred.input.as_deref(), Some("portal"));
2488        assert!(readiness.can_send_development_input);
2489    }
2490
2491    #[test]
2492    fn remote_desktop_pointer_rejects_missing_screencast_contract() {
2493        let check = remote_desktop_pointer_check_from(
2494            &remote_desktop_runtime_introspection(),
2495            &Check::ok("NAME TYPE SIGNATURE RESULT/VALUE FLAGS"),
2496            &Check::ok("u 2"),
2497            &Check::ok("u 1"),
2498            &Check::ok("u 2"),
2499            &Check::ok("u 2"),
2500        );
2501
2502        assert!(!check.ok);
2503        assert!(check.detail.contains("SelectSources"));
2504    }
2505
2506    #[test]
2507    fn remote_desktop_pointer_rejects_missing_monitor_source_type() {
2508        let check = remote_desktop_pointer_check_from(
2509            &remote_desktop_runtime_introspection(),
2510            &screencast_runtime_introspection(),
2511            &Check::ok("u 2"),
2512            &Check::ok("u 2"),
2513            &Check::ok("u 2"),
2514            &Check::ok("u 2"),
2515        );
2516
2517        assert!(!check.ok);
2518        assert!(check.detail.contains("does not include monitor sources"));
2519    }
2520
2521    #[test]
2522    fn remote_desktop_portal_rejects_missing_keyboard_device_type() {
2523        let check = remote_desktop_keyboard_check_from(
2524            &remote_desktop_runtime_introspection(),
2525            &Check::ok("u 2"),
2526        );
2527
2528        assert!(!check.ok);
2529        assert!(check.detail.contains("does not include keyboard input"));
2530    }
2531
2532    #[test]
2533    fn remote_desktop_portal_accepts_runtime_keyboard_contract() {
2534        let check = remote_desktop_keyboard_check_from(
2535            &remote_desktop_runtime_introspection(),
2536            &Check::ok("u 3"),
2537        );
2538
2539        assert!(check.ok);
2540        assert!(check.detail.contains("AvailableDeviceTypes=3"));
2541    }
2542
2543    #[test]
2544    fn pointer_only_portal_remains_advertised_without_keyboard_readiness() {
2545        let platform = platform_report();
2546        let available_device_types = Check::ok("u 2");
2547        let pointer = remote_desktop_pointer_check_from(
2548            &remote_desktop_runtime_introspection(),
2549            &screencast_runtime_introspection(),
2550            &available_device_types,
2551            &Check::ok("u 1"),
2552            &Check::ok("u 2"),
2553            &Check::ok("u 1"),
2554        );
2555        let keyboard = remote_desktop_keyboard_check_from(
2556            &remote_desktop_runtime_introspection(),
2557            &available_device_types,
2558        );
2559        let portals = portal_report(pointer);
2560        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2561        let windowing = windowing_report(true, true);
2562        let input = input_report_parts(
2563            Check::fail("missing ydotool"),
2564            Check::fail("ydotoold not running"),
2565            Check::fail("no connectable ydotool socket"),
2566            Check::fail("/dev/uinput: Permission denied"),
2567        );
2568
2569        let capabilities = capability_map_with_portal_keyboard(
2570            &platform,
2571            &portals,
2572            &keyboard,
2573            &accessibility,
2574            &windowing,
2575            &input,
2576        );
2577        let readiness = readiness_report_with_portal_keyboard(
2578            &platform,
2579            &keyboard,
2580            &accessibility_report(Check::ok("bus"), Check::ok("true")),
2581            &windowing_report(true, true),
2582            &input,
2583            true,
2584        );
2585
2586        assert!(portals.remote_desktop.ok);
2587        assert!(capabilities.input.iter().any(|backend| backend == "portal"));
2588        assert!(!readiness.can_send_development_input);
2589    }
2590
2591    #[test]
2592    fn capabilities_require_display_to_advertise_xdotool() {
2593        let mut platform = platform_report();
2594        platform.xdg_session_type = Some("x11".to_string());
2595        platform.wayland_display = None;
2596        platform.display = None;
2597        let input = InputReport {
2598            ydotool: Check::ok("ydotool"),
2599            ydotoold: Check::ok("ydotoold"),
2600            ydotool_socket: Check::ok("connectable"),
2601            uinput: Check::fail("missing"),
2602            xdotool: Check::ok("xdotool"),
2603            wtype: Check::fail("missing wtype"),
2604            pixelflux: Check::fail("PIXELFLUX_CU is not set"),
2605        };
2606
2607        let capabilities = capability_map(
2608            &platform,
2609            &portal_report(Check::fail("missing")),
2610            &accessibility_report(Check::fail("missing"), Check::fail("missing")),
2611            &windowing_report(false, false),
2612            &input,
2613        );
2614
2615        assert_eq!(capabilities.input, ["ydotool"]);
2616        assert_eq!(capabilities.preferred.input.as_deref(), Some("ydotool"));
2617    }
2618
2619    #[test]
2620    fn xdotool_diagnostics_force_precedence_matches_runtime() {
2621        let mut platform = platform_report();
2622        platform.xdg_session_type = Some("wayland".to_string());
2623        platform.display = Some(":0".to_string());
2624        let mut input = input_report(false);
2625        input.xdotool = Check::ok("xdotool");
2626
2627        assert!(should_advertise_xdotool(&platform, &input, false, true));
2628        assert!(!should_advertise_xdotool(&platform, &input, true, true));
2629    }
2630
2631    #[test]
2632    fn parses_systemd_show_environment_output() {
2633        let environment = parse_line_environment(
2634            b"DISPLAY=:0\nHYPRLAND_INSTANCE_SIGNATURE=abc\nNO_EQUALS\nYDOTOOL_SOCKET=/run/ydotoold/socket\n",
2635        );
2636
2637        assert_eq!(environment.get("DISPLAY").map(String::as_str), Some(":0"));
2638        assert_eq!(
2639            environment
2640                .get("HYPRLAND_INSTANCE_SIGNATURE")
2641                .map(String::as_str),
2642            Some("abc")
2643        );
2644        assert_eq!(
2645            environment.get("YDOTOOL_SOCKET").map(String::as_str),
2646            Some("/run/ydotoold/socket")
2647        );
2648        assert!(!environment.contains_key("NO_EQUALS"));
2649    }
2650
2651    #[test]
2652    fn readiness_requires_exact_window_focus_for_targeted_input() {
2653        let platform = platform_report();
2654        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2655        let windowing = windowing_report(true, false);
2656        let input = input_report(true);
2657
2658        let mut readiness = readiness_report(
2659            &platform,
2660            &portal_report(Check::fail("missing")),
2661            &accessibility,
2662            &windowing,
2663            &input,
2664        );
2665
2666        readiness.record_screenshot_result(true);
2667        assert!(readiness.can_capture_screenshots);
2668
2669        assert!(readiness.can_query_windows);
2670        assert!(!readiness.can_focus_windows);
2671        assert!(readiness
2672            .recommended_next_step
2673            .contains("exact-focus window backend"));
2674        assert!(readiness
2675            .blockers
2676            .iter()
2677            .any(|blocker| blocker.contains("Exact window activation")));
2678    }
2679
2680    #[test]
2681    fn header_only_introspection_is_not_an_exported_interface() {
2682        // busctl introspect of an interface the portal lacks: header line, exit 0.
2683        let header_only = Check::ok("NAME TYPE SIGNATURE RESULT/VALUE FLAGS");
2684
2685        let check = require_busctl_methods(
2686            header_only,
2687            "org.freedesktop.portal.Screenshot",
2688            SCREENSHOT_PORTAL_METHODS,
2689        );
2690
2691        assert!(!check.ok);
2692        assert!(check.detail.contains("is not exported by the portal"));
2693    }
2694
2695    #[test]
2696    fn portal_interface_must_export_every_required_method() {
2697        let partial = Check::ok(
2698            "NAME        TYPE     SIGNATURE RESULT/VALUE FLAGS\n.PickColor  method   sa{sv}    o            -\n.version    property u         2            emits-change",
2699        );
2700        let check = require_busctl_methods(
2701            partial,
2702            "org.freedesktop.portal.Screenshot",
2703            SCREENSHOT_PORTAL_METHODS,
2704        );
2705        assert!(!check.ok);
2706        assert!(check
2707            .detail
2708            .contains("missing required methods: Screenshot"));
2709
2710        let full = Check::ok(
2711            "NAME        TYPE     SIGNATURE RESULT/VALUE FLAGS\n.PickColor  method   sa{sv}    o            -\n.Screenshot method   sa{sv}    o            -",
2712        );
2713        assert!(
2714            require_busctl_methods(
2715                full,
2716                "org.freedesktop.portal.Screenshot",
2717                SCREENSHOT_PORTAL_METHODS
2718            )
2719            .ok
2720        );
2721
2722        let failed = Check::fail("busctl: No such interface");
2723        let passthrough = require_busctl_methods(
2724            failed,
2725            "org.freedesktop.portal.Screenshot",
2726            SCREENSHOT_PORTAL_METHODS,
2727        );
2728        assert!(!passthrough.ok);
2729        assert_eq!(passthrough.detail, "busctl: No such interface");
2730    }
2731
2732    #[test]
2733    fn readiness_blocks_when_no_screenshot_route_is_detected() {
2734        let mut platform = platform_report();
2735        platform.gnome_shell_version = Check::fail("No such file or directory (os error 2)");
2736        platform.gnome_screenshot = Check::fail("No such file or directory (os error 2)");
2737        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2738        let windowing = windowing_report(true, true);
2739        let input = input_report(true);
2740        let portals = portal_report(Check::fail("missing"));
2741
2742        let readiness = readiness_report(&platform, &portals, &accessibility, &windowing, &input);
2743
2744        assert!(!readiness.can_capture_screenshots);
2745        assert_eq!(
2746            readiness.screenshot_capture_status,
2747            ScreenshotCaptureStatus::Unavailable
2748        );
2749        assert!(readiness.warnings.is_empty());
2750        assert!(readiness
2751            .blockers
2752            .iter()
2753            .any(|blocker| blocker.contains("No screenshot route was detected")));
2754        assert!(readiness
2755            .recommended_next_step
2756            .contains("Enable a screenshot route"));
2757        let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
2758        assert!(capabilities.screenshot.is_empty());
2759        assert_eq!(capabilities.preferred.screenshot, None);
2760    }
2761
2762    #[test]
2763    fn native_x11_display_is_a_screenshot_route_ahead_of_gnome_screenshot() {
2764        let mut platform = platform_report();
2765        platform.gnome_shell_version = Check::fail("missing");
2766        platform.x11_display = Check::ok("native X11 root window 2880x1920, depth 24");
2767        let portals = portal_report(Check::fail("missing"));
2768        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2769        let windowing = windowing_report(true, true);
2770        let input = input_report(true);
2771
2772        let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
2773        let readiness = readiness_report(&platform, &portals, &accessibility, &windowing, &input);
2774
2775        assert_eq!(capabilities.screenshot, ["x11", "gnome_screenshot"]);
2776        assert_eq!(capabilities.preferred.screenshot.as_deref(), Some("x11"));
2777        assert!(!readiness.can_capture_screenshots);
2778        assert_eq!(
2779            readiness.screenshot_capture_status,
2780            ScreenshotCaptureStatus::Unverified
2781        );
2782        assert!(readiness.blockers.is_empty());
2783    }
2784
2785    #[test]
2786    fn screenshot_route_detection_is_not_capture_verification() {
2787        let mut platform = platform_report();
2788        platform.gnome_shell_version = Check::fail("missing");
2789        platform.gnome_screenshot = Check::fail("missing");
2790        let mut portals = portal_report(Check::fail("missing"));
2791        portals.screenshot = Check::ok(".Screenshot method sa{sv} o -");
2792        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2793        let windowing = windowing_report(true, true);
2794        let input = input_report(true);
2795
2796        let mut readiness =
2797            readiness_report(&platform, &portals, &accessibility, &windowing, &input);
2798        let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
2799
2800        assert!(!readiness.can_capture_screenshots);
2801        assert_eq!(
2802            readiness.screenshot_capture_status,
2803            ScreenshotCaptureStatus::Unverified
2804        );
2805        assert_eq!(readiness.warnings, [SCREENSHOT_UNVERIFIED]);
2806        assert!(readiness.blockers.is_empty());
2807        assert_eq!(capabilities.screenshot, ["portal"]);
2808
2809        readiness.record_screenshot_result(false);
2810        assert!(!readiness.can_capture_screenshots);
2811        assert_eq!(
2812            readiness.screenshot_capture_status,
2813            ScreenshotCaptureStatus::Failed
2814        );
2815        assert_eq!(readiness.blockers, [SCREENSHOT_FAILED]);
2816        assert!(readiness.warnings.is_empty());
2817        assert_eq!(readiness.recommended_next_step, SCREENSHOT_FAILED_NEXT_STEP);
2818
2819        readiness.record_screenshot_result(true);
2820        assert!(readiness.can_capture_screenshots);
2821        assert_eq!(
2822            readiness.screenshot_capture_status,
2823            ScreenshotCaptureStatus::Verified
2824        );
2825        assert!(readiness.blockers.is_empty());
2826        assert_eq!(readiness.recommended_next_step, READY_NEXT_STEP);
2827    }
2828
2829    #[test]
2830    fn readiness_treats_kwin_as_full_window_backend() {
2831        let platform = platform_report();
2832        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2833        let mut windowing = windowing_report(false, false);
2834        windowing.kwin = Check::ok("KWin scripting is available");
2835        windowing.can_list_windows = true;
2836        windowing.can_focus_apps = true;
2837        windowing.can_focus_windows = true;
2838        let input = input_report(true);
2839
2840        let readiness = readiness_report(
2841            &platform,
2842            &portal_report(Check::fail("missing")),
2843            &accessibility,
2844            &windowing,
2845            &input,
2846        );
2847
2848        assert!(readiness.can_query_windows);
2849        assert!(readiness.can_focus_apps);
2850        assert!(readiness.can_focus_windows);
2851        assert!(readiness.blockers.is_empty());
2852    }
2853
2854    #[test]
2855    fn readiness_message_mentions_generic_window_targeting() {
2856        let platform = platform_report();
2857        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2858        let windowing = windowing_report(true, true);
2859        let input = input_report(true);
2860
2861        let readiness = readiness_report(
2862            &platform,
2863            &portal_report(Check::fail("missing")),
2864            &accessibility,
2865            &windowing,
2866            &input,
2867        );
2868
2869        assert!(readiness.blockers.is_empty());
2870        assert!(readiness
2871            .recommended_next_step
2872            .contains("AT-SPI tree support"));
2873        assert!(readiness.recommended_next_step.contains("window targeting"));
2874        assert!(!readiness
2875            .recommended_next_step
2876            .contains("GNOME window targeting"));
2877    }
2878
2879    #[test]
2880    fn readiness_accepts_connectable_ydotool_socket_without_direct_uinput_access() {
2881        let platform = platform_report();
2882        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2883        let windowing = windowing_report(true, true);
2884        let input = input_report_parts(
2885            Check::ok("ydotool"),
2886            Check::ok("ydotoold"),
2887            Check::ok("connectable: /tmp/.ydotool_socket"),
2888            Check::fail("/dev/uinput: Permission denied"),
2889        );
2890
2891        let readiness = readiness_report(
2892            &platform,
2893            &portal_report(Check::fail("missing")),
2894            &accessibility,
2895            &windowing,
2896            &input,
2897        );
2898
2899        assert!(readiness.can_send_development_input);
2900        assert!(readiness.blockers.is_empty());
2901    }
2902
2903    #[test]
2904    fn readiness_uses_connectable_ydotool_socket_when_process_probe_fails() {
2905        let platform = platform_report();
2906        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2907        let windowing = windowing_report(true, true);
2908        let input = input_report_parts(
2909            Check::ok("ydotool"),
2910            Check::fail("ydotoold process name not found"),
2911            Check::ok("connectable: /run/user/1000/.ydotool_socket"),
2912            Check::fail("/dev/uinput: Permission denied"),
2913        );
2914        let portals = portal_report(Check::fail("missing"));
2915
2916        let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
2917        let readiness = readiness_report(&platform, &portals, &accessibility, &windowing, &input);
2918
2919        assert!(capabilities
2920            .input
2921            .iter()
2922            .any(|backend| backend == "ydotool"));
2923        assert!(readiness.can_send_development_input);
2924    }
2925
2926    #[test]
2927    fn wayland_readiness_rejects_pointer_only_uinput_without_keyboard_backend() {
2928        let platform = platform_report();
2929        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2930        let windowing = windowing_report(true, true);
2931        let input = input_report_parts(
2932            Check::ok("ydotool"),
2933            Check::fail("ydotoold not running"),
2934            Check::fail("no connectable ydotool socket"),
2935            Check::ok("read/write: /dev/uinput"),
2936        );
2937
2938        let readiness = readiness_report(
2939            &platform,
2940            &portal_report(Check::fail("missing")),
2941            &accessibility,
2942            &windowing,
2943            &input,
2944        );
2945
2946        assert!(!readiness.can_send_development_input);
2947        assert!(readiness
2948            .blockers
2949            .iter()
2950            .any(|blocker| blocker.contains("absolute pointer input")));
2951        assert!(readiness
2952            .recommended_next_step
2953            .contains("keyboard-capable input backend"));
2954    }
2955
2956    #[test]
2957    fn x11_readiness_rejects_pointer_only_uinput_without_keyboard_backend() {
2958        let mut platform = platform_report();
2959        platform.xdg_session_type = Some("x11".to_string());
2960        platform.wayland_display = None;
2961        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2962        let windowing = windowing_report(true, true);
2963        let input = input_report_parts(
2964            Check::fail("missing ydotool"),
2965            Check::fail("ydotoold not running"),
2966            Check::fail("no connectable ydotool socket"),
2967            Check::ok("read/write: /dev/uinput"),
2968        );
2969
2970        let readiness = readiness_report(
2971            &platform,
2972            &portal_report(Check::fail("missing")),
2973            &accessibility,
2974            &windowing,
2975            &input,
2976        );
2977
2978        assert!(!readiness.can_send_development_input);
2979    }
2980
2981    #[test]
2982    fn readiness_accepts_remote_desktop_portal_without_local_input_backend() {
2983        let platform = platform_report();
2984        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2985        let windowing = windowing_report(true, true);
2986        let input = input_report_parts(
2987            Check::fail("missing ydotool"),
2988            Check::fail("ydotoold not running"),
2989            Check::fail("no connectable ydotool socket"),
2990            Check::fail("/dev/uinput: Permission denied"),
2991        );
2992
2993        let readiness = readiness_report(
2994            &platform,
2995            &portal_report(Check::ok("org.freedesktop.portal.RemoteDesktop")),
2996            &accessibility,
2997            &windowing,
2998            &input,
2999        );
3000
3001        assert!(readiness.can_send_development_input);
3002        assert!(readiness.blockers.is_empty());
3003    }
3004
3005    #[test]
3006    fn readiness_rejects_inaccessible_ydotool_paths() {
3007        let platform = platform_report();
3008        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
3009        let windowing = windowing_report(true, true);
3010        let input = input_report_parts(
3011            Check::ok("ydotool"),
3012            Check::ok("ydotoold"),
3013            Check::fail("/tmp/.ydotool_socket: Permission denied"),
3014            Check::fail("/dev/uinput: Permission denied"),
3015        );
3016
3017        let readiness = readiness_report(
3018            &platform,
3019            &portal_report(Check::fail("missing")),
3020            &accessibility,
3021            &windowing,
3022            &input,
3023        );
3024
3025        assert!(!readiness.can_send_development_input);
3026        assert!(readiness
3027            .recommended_next_step
3028            .contains("Enable a keyboard-capable input backend"));
3029        assert!(readiness
3030            .blockers
3031            .iter()
3032            .any(|blocker| blocker.contains("Development keyboard input is unavailable")));
3033    }
3034
3035    #[test]
3036    fn capability_map_rejects_incompatible_ydotool_with_live_daemon() {
3037        let platform = platform_report();
3038        let portals = portal_report(Check::fail("missing"));
3039        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
3040        let windowing = windowing_report(true, true);
3041        let input = input_report_parts(
3042            Check::fail("unsupported legacy ydotool CLI"),
3043            Check::ok("ydotoold"),
3044            Check::ok("connectable socket"),
3045            Check::fail("/dev/uinput: Permission denied"),
3046        );
3047
3048        let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
3049        let readiness = readiness_report(&platform, &portals, &accessibility, &windowing, &input);
3050
3051        assert!(!capabilities
3052            .input
3053            .iter()
3054            .any(|backend| backend == "ydotool"));
3055        assert!(!readiness.can_send_development_input);
3056    }
3057
3058    #[test]
3059    fn ydotool_socket_check_rejects_legacy_stream_socket() {
3060        let dir = crate::test_sockets::socket_fixture(
3061            &format!("cul-diag-stream-{}", std::process::id()),
3062            "ydotool.sock",
3063        );
3064        let _ = std::fs::remove_dir_all(&dir);
3065        std::fs::create_dir_all(&dir).expect("create temp diagnostics dir");
3066        let socket = dir.join("ydotool.sock");
3067        let listener =
3068            std::os::unix::net::UnixListener::bind(&socket).expect("bind temp diagnostics socket");
3069
3070        let check = socket_connect_check(&socket);
3071
3072        assert!(!check.ok, "{check:?}");
3073        drop(listener);
3074        let _ = std::fs::remove_dir_all(&dir);
3075    }
3076
3077    #[test]
3078    fn ydotool_socket_check_accepts_datagram_socket() {
3079        let dir = crate::test_sockets::socket_fixture(
3080            &format!("cul-diag-dgram-{}", std::process::id()),
3081            "ydotool.sock",
3082        );
3083        let _ = std::fs::remove_dir_all(&dir);
3084        std::fs::create_dir_all(&dir).expect("create temp diagnostics dir");
3085        let socket = dir.join("ydotool.sock");
3086        let datagram =
3087            std::os::unix::net::UnixDatagram::bind(&socket).expect("bind temp datagram socket");
3088
3089        let check = socket_connect_check(&socket);
3090
3091        assert!(check.ok, "{check:?}");
3092        drop(datagram);
3093        let _ = std::fs::remove_dir_all(&dir);
3094    }
3095
3096    #[test]
3097    fn readiness_reports_cosmic_window_blocker_on_cosmic() {
3098        let mut platform = platform_report();
3099        platform.xdg_current_desktop = Some("COSMIC".to_string());
3100        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
3101        let windowing = windowing_report(false, false);
3102        let input = input_report(true);
3103
3104        let readiness = readiness_report(
3105            &platform,
3106            &portal_report(Check::fail("missing")),
3107            &accessibility,
3108            &windowing,
3109            &input,
3110        );
3111
3112        assert!(readiness
3113            .blockers
3114            .iter()
3115            .any(|blocker| blocker.contains("COSMIC Wayland window introspection")));
3116    }
3117
3118    #[test]
3119    fn desktop_env_hydration_imports_the_niri_socket() {
3120        let current_env = HashMap::new();
3121        let session_env = HashMap::from([(
3122            "NIRI_SOCKET".to_string(),
3123            "/run/user/1000/niri.wayland-1.42.sock".to_string(),
3124        )]);
3125
3126        let updates = desktop_env_hydration_updates(&current_env, &session_env);
3127
3128        assert!(updates.iter().any(|(key, value)| {
3129            *key == "NIRI_SOCKET" && value == "/run/user/1000/niri.wayland-1.42.sock"
3130        }));
3131    }
3132
3133    #[test]
3134    fn wtype_capability_honors_keyboard_backend_overrides() {
3135        let mut platform = platform_report();
3136        platform.xdg_session_type = Some("wayland".to_string());
3137        platform.xdg_current_desktop = Some("Hyprland".to_string());
3138        platform.wayland_display = Some("wayland-0".to_string());
3139        let mut input = input_report(false);
3140        input.wtype = Check::ok("wtype");
3141
3142        assert!(should_advertise_wtype(
3143            &platform, &input, false, false, false
3144        ));
3145        assert!(!should_advertise_wtype(
3146            &platform, &input, true, false, false
3147        ));
3148        assert!(!should_advertise_wtype(
3149            &platform, &input, false, false, true
3150        ));
3151
3152        // Forcing xdotool hides wtype only when xdotool can run: installed,
3153        // with DISPLAY set, as the server's keyboard routing requires.
3154        assert!(should_advertise_wtype(
3155            &platform, &input, false, true, false
3156        ));
3157        input.xdotool = Check::ok("xdotool");
3158        assert!(!should_advertise_wtype(
3159            &platform, &input, false, true, false
3160        ));
3161        platform.display = None;
3162        assert!(should_advertise_wtype(
3163            &platform, &input, false, true, false
3164        ));
3165    }
3166
3167    #[test]
3168    fn remote_desktop_pointer_rejects_missing_hidden_cursor_mode() {
3169        let check = remote_desktop_pointer_check_from(
3170            &remote_desktop_runtime_introspection(),
3171            &screencast_runtime_introspection(),
3172            &Check::ok("u 2"),
3173            &Check::ok("u 1"),
3174            &Check::ok("u 2"),
3175            &Check::ok("u 2"),
3176        );
3177
3178        assert!(!check.ok);
3179        assert!(check.detail.contains("does not include hidden cursor mode"));
3180    }
3181
3182    #[test]
3183    fn remote_desktop_pointer_accepts_screencast_v1_default_hidden_cursor() {
3184        let check = remote_desktop_pointer_check_from(
3185            &remote_desktop_runtime_introspection(),
3186            &screencast_runtime_introspection(),
3187            &Check::ok("u 2"),
3188            &Check::ok("u 1"),
3189            &Check::ok("u 1"),
3190            &Check::fail("AvailableCursorModes is not available on ScreenCast v1"),
3191        );
3192
3193        assert!(check.ok);
3194        assert!(check
3195            .detail
3196            .contains("hidden cursor mode is the interface default"));
3197    }
3198
3199    #[test]
3200    fn capability_map_reports_niri_window_control() {
3201        let platform = platform_report();
3202        let portals = portal_report(Check::fail("missing"));
3203        let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
3204        let mut windowing = windowing_report(false, false);
3205        windowing.niri = Check::ok("niri msg returned windows");
3206        let input = input_report(false);
3207
3208        let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
3209
3210        assert_eq!(capabilities.window_control, vec![NIRI_BACKEND]);
3211        assert_eq!(
3212            capabilities.preferred.window_control.as_deref(),
3213            Some(NIRI_BACKEND)
3214        );
3215    }
3216}