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