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