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