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