@roam-agent/roam-computer-use 0.0.0-stage → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +80 -2
  3. package/assets/reference/img.jpg +0 -0
  4. package/docs/README.md +45 -0
  5. package/docs/content/docs/explanation/action-pipeline.mdx +36 -0
  6. package/docs/content/docs/explanation/architecture.mdx +161 -0
  7. package/docs/content/docs/explanation/index.mdx +19 -0
  8. package/docs/content/docs/explanation/meta.json +5 -0
  9. package/docs/content/docs/explanation/observation-pipeline.mdx +37 -0
  10. package/docs/content/docs/explanation/platform-boundary.mdx +37 -0
  11. package/docs/content/docs/explanation/state-and-scheduling.mdx +35 -0
  12. package/docs/content/docs/how-to-guides/develop-and-validate.mdx +112 -0
  13. package/docs/content/docs/how-to-guides/index.mdx +12 -0
  14. package/docs/content/docs/how-to-guides/linux.mdx +68 -0
  15. package/docs/content/docs/how-to-guides/meta.json +1 -0
  16. package/docs/content/docs/how-to-guides/troubleshooting.mdx +126 -0
  17. package/docs/content/docs/index.mdx +67 -0
  18. package/docs/content/docs/meta.json +5 -0
  19. package/docs/content/docs/reference/agent/contract.mdx +162 -0
  20. package/docs/content/docs/reference/agent/index.mdx +8 -0
  21. package/docs/content/docs/reference/agent/meta.json +8 -0
  22. package/docs/content/docs/reference/agent/tools.mdx +221 -0
  23. package/docs/content/docs/reference/codebase.mdx +139 -0
  24. package/docs/content/docs/reference/configuration.mdx +113 -0
  25. package/docs/content/docs/reference/index.mdx +28 -0
  26. package/docs/content/docs/reference/meta.json +10 -0
  27. package/docs/content/docs/reference/platforms/index.mdx +18 -0
  28. package/docs/content/docs/reference/platforms/macos/accessibility.mdx +61 -0
  29. package/docs/content/docs/reference/platforms/macos/actions.mdx +63 -0
  30. package/docs/content/docs/reference/platforms/macos/capture.mdx +58 -0
  31. package/docs/content/docs/reference/platforms/macos/implementation.mdx +98 -0
  32. package/docs/content/docs/reference/platforms/macos/index.mdx +16 -0
  33. package/docs/content/docs/reference/platforms/macos/meta.json +10 -0
  34. package/docs/content/docs/reference/platforms/macos/root-targeting.mdx +47 -0
  35. package/docs/content/docs/reference/platforms/meta.json +8 -0
  36. package/docs/content/docs/reference/platforms/windows.mdx +75 -0
  37. package/docs/content/docs/tutorials/getting-started.mdx +46 -0
  38. package/docs/content/docs/tutorials/index.mdx +10 -0
  39. package/docs/content/docs/tutorials/meta.json +1 -0
  40. package/extensions/computer-use.ts +235 -0
  41. package/native/linux/bridge-rs/Cargo.lock +1204 -0
  42. package/native/linux/bridge-rs/Cargo.toml +21 -0
  43. package/native/linux/bridge-rs/src/atspi.rs +670 -0
  44. package/native/linux/bridge-rs/src/error.rs +65 -0
  45. package/native/linux/bridge-rs/src/lib.rs +11 -0
  46. package/native/linux/bridge-rs/src/main.rs +1110 -0
  47. package/native/linux/bridge-rs/src/protocol.rs +49 -0
  48. package/native/linux/bridge-rs/src/state.rs +293 -0
  49. package/native/linux/bridge-rs/src/wayland.rs +89 -0
  50. package/native/linux/bridge-rs/src/x11.rs +909 -0
  51. package/native/linux/bridge-rs/tests/protocol_tests.rs +73 -0
  52. package/native/macos/activity_glow.swift +169 -0
  53. package/native/macos/bridge.swift +3968 -0
  54. package/native/windows/bridge-rs/Cargo.lock +396 -0
  55. package/native/windows/bridge-rs/Cargo.toml +30 -0
  56. package/native/windows/bridge-rs/src/capture.rs +561 -0
  57. package/native/windows/bridge-rs/src/error.rs +81 -0
  58. package/native/windows/bridge-rs/src/input.rs +501 -0
  59. package/native/windows/bridge-rs/src/lib.rs +85 -0
  60. package/native/windows/bridge-rs/src/main.rs +1683 -0
  61. package/native/windows/bridge-rs/src/protocol.rs +53 -0
  62. package/native/windows/bridge-rs/src/refs.rs +237 -0
  63. package/native/windows/bridge-rs/src/state.rs +55 -0
  64. package/native/windows/bridge-rs/src/uia.rs +1252 -0
  65. package/native/windows/bridge-rs/src/window.rs +718 -0
  66. package/native/windows/bridge-rs/tests/protocol_tests.rs +252 -0
  67. package/native/windows/bridge-rs/tests/refs_tests.rs +86 -0
  68. package/native/windows/bridge-rs/tests/state_tests.rs +33 -0
  69. package/package.json +104 -5
  70. package/prebuilt/macos/arm64/bridge +0 -0
  71. package/prebuilt/macos/x64/bridge +0 -0
  72. package/roam/README.md +52 -0
  73. package/roam/bridge/macos/arm64/bridge +0 -0
  74. package/roam/bridge/macos/x64/bridge +0 -0
  75. package/roam/bridge/manifest.json +20 -0
  76. package/roam/helper-path.d.mts +9 -0
  77. package/roam/helper-path.mjs +36 -0
  78. package/roam/identity.d.mts +16 -0
  79. package/roam/identity.mjs +64 -0
  80. package/roam/index.ts +51 -0
  81. package/roam/redirect.ts +51 -0
  82. package/roam/repair.ts +120 -0
  83. package/scripts/build-native.mjs +286 -0
  84. package/scripts/setup-helper.mjs +635 -0
  85. package/src/actions.ts +130 -0
  86. package/src/bridge.ts +2594 -0
  87. package/src/cdp.ts +658 -0
  88. package/src/config.ts +226 -0
  89. package/src/contract.ts +107 -0
  90. package/src/extension/index.ts +9 -0
  91. package/src/find-params.ts +21 -0
  92. package/src/note.ts +195 -0
  93. package/src/outline.ts +702 -0
  94. package/src/output.ts +134 -0
  95. package/src/permissions.ts +111 -0
  96. package/src/platform/architecture.ts +23 -0
  97. package/src/platform/coerce.ts +16 -0
  98. package/src/platform/index.ts +61 -0
  99. package/src/platform/linux/backend.ts +186 -0
  100. package/src/platform/linux/helper.ts +238 -0
  101. package/src/platform/macos/backend.ts +147 -0
  102. package/src/platform/macos/browser.ts +110 -0
  103. package/src/platform/macos/helper.ts +369 -0
  104. package/src/platform/macos/permissions.ts +146 -0
  105. package/src/platform/types.ts +229 -0
  106. package/src/platform/windows/backend.ts +142 -0
  107. package/src/platform/windows/helper.ts +140 -0
  108. package/src/root-selection.ts +25 -0
  109. package/src/runtime.ts +129 -0
  110. package/src/state.ts +146 -0
  111. package/src/view.ts +147 -0
@@ -0,0 +1,21 @@
1
+ [package]
2
+ name = "linux-bridge"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+ description = "AT-SPI native helper for pi-computer-use on Linux"
6
+
7
+ [dependencies]
8
+ base64 = "0.22"
9
+ png = "0.17"
10
+ serde = { version = "1", features = ["derive"] }
11
+ serde_json = "1"
12
+ tokio = { version = "1", features = ["io-std", "io-util", "macros", "rt-multi-thread", "sync", "time"] }
13
+ x11rb = { version = "0.13", features = ["composite", "xtest"] }
14
+ zbus = { version = "4", default-features = false, features = ["tokio"] }
15
+
16
+ [dev-dependencies]
17
+ zbus = { version = "4", default-features = false, features = ["tokio", "p2p"] }
18
+
19
+ [lib]
20
+ name = "linux_bridge"
21
+ path = "src/lib.rs"
@@ -0,0 +1,670 @@
1
+ //! Minimal, dependency-light AT-SPI2 client built on zbus.
2
+ //!
3
+ //! Linux desktop accessibility is intentionally used in preference to global
4
+ //! pointer/keyboard injection: Action and EditableText calls are delivered to
5
+ //! applications in the background and do not steal focus.
6
+
7
+ use std::collections::{HashMap, HashSet, VecDeque};
8
+
9
+ use serde_json::{json, Value};
10
+ use zbus::zvariant::OwnedObjectPath;
11
+ use zbus::{Connection, Proxy};
12
+
13
+ use crate::{ErrorCode, ProtocolError};
14
+
15
+ const DBUS_DESTINATION: &str = "org.freedesktop.DBus";
16
+ const DBUS_ROOT: &str = "/org/freedesktop/DBus";
17
+ const DBUS_INTERFACE: &str = "org.freedesktop.DBus";
18
+ const REGISTRY_DESTINATION: &str = "org.a11y.atspi.Registry";
19
+ const REGISTRY_ROOT: &str = "/org/a11y/atspi/accessible/root";
20
+ const ACCESSIBLE: &str = "org.a11y.atspi.Accessible";
21
+ const COMPONENT: &str = "org.a11y.atspi.Component";
22
+ const ACTION: &str = "org.a11y.atspi.Action";
23
+ const MAX_ATSPI_ACTIONS: usize = 64;
24
+ const EDITABLE_TEXT: &str = "org.a11y.atspi.EditableText";
25
+ pub const TEXT: &str = "org.a11y.atspi.Text";
26
+
27
+ #[derive(Debug, Clone, PartialEq, Eq, Hash)]
28
+ pub struct AccessibleRef {
29
+ pub destination: String,
30
+ pub path: String,
31
+ }
32
+
33
+ #[derive(Debug, Clone, PartialEq)]
34
+ pub struct Rect {
35
+ pub x: i32,
36
+ pub y: i32,
37
+ pub width: i32,
38
+ pub height: i32,
39
+ }
40
+
41
+ #[derive(Debug, Clone)]
42
+ pub struct RootSnapshot {
43
+ pub accessible: AccessibleRef,
44
+ pub pid: u64,
45
+ pub name: String,
46
+ pub app_name: String,
47
+ pub role: String,
48
+ pub frame: Option<Rect>,
49
+ pub x11_window: Option<u32>,
50
+ pub is_focused: bool,
51
+ pub is_minimized: bool,
52
+ pub z_order: Option<usize>,
53
+ }
54
+
55
+ #[derive(Debug, Clone)]
56
+ pub struct NodeSnapshot {
57
+ pub reference: String,
58
+ pub accessible: AccessibleRef,
59
+ pub parent: Option<AccessibleRef>,
60
+ pub name: String,
61
+ pub role: String,
62
+ pub description: String,
63
+ pub value: String,
64
+ pub interfaces: HashSet<String>,
65
+ pub bounds: Option<Rect>,
66
+ pub is_secure: bool,
67
+ pub depth: usize,
68
+ }
69
+
70
+ impl NodeSnapshot {
71
+ #[cfg(test)]
72
+ pub(crate) fn minimal(accessible: AccessibleRef) -> Self {
73
+ Self {
74
+ reference: String::new(),
75
+ accessible,
76
+ parent: None,
77
+ name: String::new(),
78
+ role: String::new(),
79
+ description: String::new(),
80
+ value: String::new(),
81
+ interfaces: HashSet::new(),
82
+ bounds: None,
83
+ is_secure: false,
84
+ depth: 0,
85
+ }
86
+ }
87
+
88
+ pub fn searchable_text(&self) -> String {
89
+ format!("{} {} {}", self.name, self.description, self.value).to_lowercase()
90
+ }
91
+ }
92
+
93
+ #[derive(Clone)]
94
+ pub struct AtspiClient {
95
+ connection: Connection,
96
+ }
97
+
98
+ impl AtspiClient {
99
+ pub async fn connect() -> Result<Self, ProtocolError> {
100
+ let session = Connection::session().await.map_err(unavailable)?;
101
+ let bus = Proxy::new(&session, "org.a11y.Bus", "/org/a11y/bus", "org.a11y.Bus")
102
+ .await
103
+ .map_err(unavailable)?;
104
+ let address: String = bus.call("GetAddress", &()).await.map_err(unavailable)?;
105
+ let connection = zbus::connection::Builder::address(address.as_str())
106
+ .map_err(unavailable)?
107
+ .build()
108
+ .await
109
+ .map_err(unavailable)?;
110
+ Ok(Self { connection })
111
+ }
112
+
113
+ pub async fn available() -> bool {
114
+ Self::connect().await.is_ok()
115
+ }
116
+
117
+ async fn proxy<'a>(
118
+ &'a self,
119
+ accessible: &'a AccessibleRef,
120
+ interface: &'a str,
121
+ ) -> Result<Proxy<'a>, ProtocolError> {
122
+ Proxy::new(
123
+ &self.connection,
124
+ accessible.destination.as_str(),
125
+ accessible.path.as_str(),
126
+ interface,
127
+ )
128
+ .await
129
+ .map_err(atspi_error)
130
+ }
131
+
132
+ async fn children(
133
+ &self,
134
+ accessible: &AccessibleRef,
135
+ ) -> Result<Vec<AccessibleRef>, ProtocolError> {
136
+ let proxy = self.proxy(accessible, ACCESSIBLE).await?;
137
+ let children: Vec<(String, OwnedObjectPath)> =
138
+ proxy.call("GetChildren", &()).await.map_err(atspi_error)?;
139
+ Ok(children
140
+ .into_iter()
141
+ .filter(|(destination, path)| !destination.is_empty() && path.as_str() != "/")
142
+ .map(|(destination, path)| AccessibleRef {
143
+ destination,
144
+ path: path.to_string(),
145
+ })
146
+ .collect())
147
+ }
148
+
149
+ async fn string_property(&self, accessible: &AccessibleRef, property: &str) -> String {
150
+ match self.proxy(accessible, ACCESSIBLE).await {
151
+ Ok(proxy) => proxy.get_property(property).await.unwrap_or_default(),
152
+ Err(_) => String::new(),
153
+ }
154
+ }
155
+
156
+ async fn role(&self, accessible: &AccessibleRef) -> String {
157
+ match self.proxy(accessible, ACCESSIBLE).await {
158
+ Ok(proxy) => proxy.call("GetRoleName", &()).await.unwrap_or_default(),
159
+ Err(_) => String::new(),
160
+ }
161
+ }
162
+
163
+ async fn interfaces(&self, accessible: &AccessibleRef) -> HashSet<String> {
164
+ match self.proxy(accessible, ACCESSIBLE).await {
165
+ Ok(proxy) => proxy
166
+ .call::<_, _, Vec<String>>("GetInterfaces", &())
167
+ .await
168
+ .unwrap_or_default()
169
+ .into_iter()
170
+ .collect(),
171
+ Err(_) => HashSet::new(),
172
+ }
173
+ }
174
+
175
+ async fn bounds(&self, accessible: &AccessibleRef) -> Option<Rect> {
176
+ let proxy = self.proxy(accessible, COMPONENT).await.ok()?;
177
+ let (x, y, width, height): (i32, i32, i32, i32) =
178
+ proxy.call("GetExtents", &(0u32)).await.ok()?;
179
+ (width > 0 && height > 0).then_some(Rect {
180
+ x,
181
+ y,
182
+ width,
183
+ height,
184
+ })
185
+ }
186
+
187
+ async fn application_pid(&self, accessible: &AccessibleRef) -> u64 {
188
+ let Ok(bus) = Proxy::new(
189
+ &self.connection,
190
+ DBUS_DESTINATION,
191
+ DBUS_ROOT,
192
+ DBUS_INTERFACE,
193
+ )
194
+ .await
195
+ else {
196
+ return 0;
197
+ };
198
+ let connection_pid: Option<u32> = bus
199
+ .call(
200
+ "GetConnectionUnixProcessID",
201
+ &(accessible.destination.as_str()),
202
+ )
203
+ .await
204
+ .ok();
205
+ connection_pid.map(u64::from).unwrap_or(0)
206
+ }
207
+
208
+ pub async fn list_roots(
209
+ &self,
210
+ filter_pid: Option<u64>,
211
+ ) -> Result<Vec<RootSnapshot>, ProtocolError> {
212
+ let registry = AccessibleRef {
213
+ destination: REGISTRY_DESTINATION.to_owned(),
214
+ path: REGISTRY_ROOT.to_owned(),
215
+ };
216
+ let applications = self.children(&registry).await?;
217
+ let mut roots = Vec::new();
218
+ for app in applications {
219
+ let pid = self.application_pid(&app).await;
220
+ if filter_pid.is_some_and(|wanted| wanted != pid) {
221
+ continue;
222
+ }
223
+ let app_name = self.string_property(&app, "Name").await;
224
+ let windows = self.children(&app).await.unwrap_or_default();
225
+ for window in windows {
226
+ let role = self.role(&window).await;
227
+ let name = self.string_property(&window, "Name").await;
228
+ roots.push(RootSnapshot {
229
+ frame: self.bounds(&window).await,
230
+ accessible: window,
231
+ pid,
232
+ name: if name.is_empty() {
233
+ app_name.clone()
234
+ } else {
235
+ name
236
+ },
237
+ app_name: app_name.clone(),
238
+ role,
239
+ x11_window: None,
240
+ is_focused: false,
241
+ is_minimized: false,
242
+ z_order: None,
243
+ });
244
+ }
245
+ }
246
+ Ok(roots)
247
+ }
248
+
249
+ pub async fn snapshot(
250
+ &self,
251
+ root: &RootSnapshot,
252
+ max_nodes: usize,
253
+ max_depth: usize,
254
+ ) -> Result<Vec<NodeSnapshot>, ProtocolError> {
255
+ self.snapshot_from(&root.accessible, max_nodes, max_depth)
256
+ .await
257
+ }
258
+
259
+ pub async fn snapshot_from(
260
+ &self,
261
+ start: &AccessibleRef,
262
+ max_nodes: usize,
263
+ max_depth: usize,
264
+ ) -> Result<Vec<NodeSnapshot>, ProtocolError> {
265
+ let mut result = Vec::new();
266
+ let mut seen = HashSet::new();
267
+ let mut queue = VecDeque::from([(start.clone(), None, 0usize)]);
268
+ while let Some((accessible, parent, depth)) = queue.pop_front() {
269
+ if result.len() >= max_nodes || depth > max_depth || !seen.insert(accessible.clone()) {
270
+ continue;
271
+ }
272
+ let interfaces = self.interfaces(&accessible).await;
273
+ let role = self.role(&accessible).await;
274
+ let name = self.string_property(&accessible, "Name").await;
275
+ let description = self.string_property(&accessible, "Description").await;
276
+ let is_secure =
277
+ role.eq_ignore_ascii_case("password text") || role.eq_ignore_ascii_case("password");
278
+ let value = if !is_secure && interfaces.contains(TEXT) {
279
+ self.read_text(&accessible).await.unwrap_or_default()
280
+ } else {
281
+ String::new()
282
+ };
283
+ let children = self.children(&accessible).await.unwrap_or_default();
284
+ for child in children {
285
+ queue.push_back((child, Some(accessible.clone()), depth + 1));
286
+ }
287
+ result.push(NodeSnapshot {
288
+ reference: String::new(),
289
+ bounds: self.bounds(&accessible).await,
290
+ accessible,
291
+ parent,
292
+ name,
293
+ role,
294
+ description,
295
+ value,
296
+ interfaces,
297
+ is_secure,
298
+ depth,
299
+ });
300
+ }
301
+ Ok(result)
302
+ }
303
+
304
+ pub async fn read_text(&self, accessible: &AccessibleRef) -> Result<String, ProtocolError> {
305
+ let proxy = self.proxy(accessible, TEXT).await?;
306
+ proxy
307
+ .call("GetText", &(0i32, -1i32))
308
+ .await
309
+ .map_err(atspi_error)
310
+ }
311
+
312
+ pub async fn press(&self, node: &NodeSnapshot) -> Result<bool, ProtocolError> {
313
+ if !node.interfaces.contains(ACTION) {
314
+ return Err(ProtocolError::new(
315
+ "Target does not expose the AT-SPI Action interface",
316
+ ErrorCode::CapabilityDeferred,
317
+ ));
318
+ }
319
+ let proxy = self.proxy(&node.accessible, ACTION).await?;
320
+ let action_count = bounded_action_count(proxy.get_property::<i32>("NActions").await.ok())?;
321
+ let mut names = Vec::new();
322
+ if action_count > 1 {
323
+ names.reserve(action_count);
324
+ for index in 0..action_count {
325
+ let name: String = proxy
326
+ .call("GetName", &(index as i32))
327
+ .await
328
+ .unwrap_or_default();
329
+ names.push(name);
330
+ }
331
+ }
332
+ let Some(action_index) = selected_action_index(action_count, &names) else {
333
+ return Ok(false);
334
+ };
335
+ proxy
336
+ .call("DoAction", &(action_index))
337
+ .await
338
+ .map_err(atspi_error)
339
+ }
340
+
341
+ pub async fn set_text(&self, node: &NodeSnapshot, text: &str) -> Result<bool, ProtocolError> {
342
+ if !node.interfaces.contains(EDITABLE_TEXT) {
343
+ return Err(ProtocolError::new(
344
+ "Target does not expose the AT-SPI EditableText interface",
345
+ ErrorCode::CapabilityDeferred,
346
+ ));
347
+ }
348
+ let proxy = self.proxy(&node.accessible, EDITABLE_TEXT).await?;
349
+ proxy
350
+ .call("SetTextContents", &(text))
351
+ .await
352
+ .map_err(atspi_error)
353
+ }
354
+ }
355
+
356
+ pub fn root_json(reference: &str, root: &RootSnapshot, z_order: usize) -> Value {
357
+ let kind = if root.role.to_lowercase().contains("dialog") {
358
+ "dialog"
359
+ } else {
360
+ "window"
361
+ };
362
+ let frame = root
363
+ .frame
364
+ .as_ref()
365
+ .map(|r| json!({"x":r.x,"y":r.y,"width":r.width,"height":r.height}))
366
+ .unwrap_or_else(|| json!({"x":0,"y":0,"width":0,"height":0}));
367
+ json!({
368
+ "kind": kind,
369
+ "rootRef": reference,
370
+ "windowRef": reference,
371
+ "ref": reference,
372
+ "windowId": root.x11_window,
373
+ "title": root.name,
374
+ "pid": root.pid,
375
+ "appName": root.app_name,
376
+ "processName": root.app_name,
377
+ "role": root.role,
378
+ "subrole": "",
379
+ "zOrder": root.z_order.unwrap_or(z_order),
380
+ "framePoints": frame,
381
+ "bounds": frame,
382
+ "scaleFactor": 1.0,
383
+ "isFocused": root.is_focused,
384
+ "isMain": root.is_focused || z_order == 0,
385
+ "isMinimized": root.is_minimized,
386
+ "isOnscreen": true,
387
+ "isModal": kind == "dialog",
388
+ "metadata": {"backend":"at-spi2","busName":root.accessible.destination,"objectPath":root.accessible.path},
389
+ "isBrowser": false,
390
+ "browserFamily": Value::Null
391
+ })
392
+ }
393
+
394
+ pub fn outline_json(root: &RootSnapshot, nodes: &[NodeSnapshot], max_nodes: usize) -> Value {
395
+ let mut descendants: HashMap<AccessibleRef, Vec<Value>> = HashMap::new();
396
+ let mut roots = Vec::new();
397
+ for node in nodes.iter().rev() {
398
+ let rect = node
399
+ .bounds
400
+ .as_ref()
401
+ .map(|r| {
402
+ let origin_x = root.frame.as_ref().map(|f| f.x).unwrap_or(0);
403
+ let origin_y = root.frame.as_ref().map(|f| f.y).unwrap_or(0);
404
+ json!({"x":relative_coordinate(r.x, origin_x),"y":relative_coordinate(r.y, origin_y),"w":r.width,"h":r.height})
405
+ })
406
+ .unwrap_or_else(|| json!({"x":0,"y":0,"w":0,"h":0}));
407
+ let can_press = node.interfaces.contains(ACTION);
408
+ let can_set_value = node.interfaces.contains(EDITABLE_TEXT);
409
+ let mut actions = Vec::new();
410
+ if can_press {
411
+ actions.push("press");
412
+ }
413
+ if can_set_value {
414
+ actions.push("setValue");
415
+ }
416
+ let mut children = descendants.remove(&node.accessible).unwrap_or_default();
417
+ children.reverse();
418
+ let value = json!({
419
+ "ref": node.reference,
420
+ "role": node.role,
421
+ "subrole": "",
422
+ "identifier": node.accessible.path,
423
+ "title": node.name,
424
+ "description": node.description,
425
+ "value": if node.is_secure { "" } else { &node.value },
426
+ "actions": actions,
427
+ "canPress": can_press,
428
+ "canFocus": false,
429
+ "canSetValue": can_set_value,
430
+ "canScroll": false,
431
+ "canIncrement": false,
432
+ "canDecrement": false,
433
+ "isTextInput": can_set_value,
434
+ "rect": rect,
435
+ "focused": false,
436
+ "offscreen": node.bounds.is_none(),
437
+ "pictureOnly": false,
438
+ "truncated": nodes.len() >= max_nodes && node.depth == 0,
439
+ "text": if node.value.is_empty() || node.is_secure { json!([]) } else {
440
+ json!([{"string":node.value,"confidence":1.0,"rect":rect}])
441
+ },
442
+ "children": children
443
+ });
444
+ if let Some(parent) = &node.parent {
445
+ descendants.entry(parent.clone()).or_default().push(value);
446
+ } else {
447
+ roots.push(value);
448
+ }
449
+ }
450
+ roots.reverse();
451
+ if roots.is_empty() {
452
+ json!({"role":"window","title":"","children":[],"truncated":false})
453
+ } else {
454
+ let mut root = roots.remove(0);
455
+ if !roots.is_empty() {
456
+ root["children"]
457
+ .as_array_mut()
458
+ .expect("children array")
459
+ .extend(roots);
460
+ }
461
+ root
462
+ }
463
+ }
464
+
465
+ fn normalized_action_name(name: &str) -> String {
466
+ name.trim()
467
+ .to_ascii_lowercase()
468
+ .replace(['-', '_'], " ")
469
+ .split_whitespace()
470
+ .collect::<Vec<_>>()
471
+ .join(" ")
472
+ }
473
+
474
+ fn activation_action_index(names: &[String]) -> usize {
475
+ const PRIORITY: [&str; 5] = ["activate", "click", "press", "invoke", "open"];
476
+ PRIORITY
477
+ .iter()
478
+ .find_map(|wanted| {
479
+ names
480
+ .iter()
481
+ .position(|name| normalized_action_name(name) == *wanted)
482
+ })
483
+ .unwrap_or(0)
484
+ }
485
+
486
+ fn selected_action_index(action_count: usize, names: &[String]) -> Option<i32> {
487
+ match action_count {
488
+ 0 => None,
489
+ 1 => Some(0),
490
+ _ => Some(activation_action_index(names) as i32),
491
+ }
492
+ }
493
+
494
+ fn bounded_action_count(raw_count: Option<i32>) -> Result<usize, ProtocolError> {
495
+ let count = raw_count.unwrap_or(0);
496
+ if count <= 1 {
497
+ return Ok(count.max(0) as usize);
498
+ }
499
+ let count = usize::try_from(count).map_err(|_| {
500
+ ProtocolError::new(
501
+ "AT-SPI action count is invalid",
502
+ ErrorCode::CapabilityDeferred,
503
+ )
504
+ })?;
505
+ if count > MAX_ATSPI_ACTIONS {
506
+ return Err(ProtocolError::new(
507
+ format!(
508
+ "AT-SPI target exposes {count} actions; maximum supported is {MAX_ATSPI_ACTIONS}"
509
+ ),
510
+ ErrorCode::CapabilityDeferred,
511
+ ));
512
+ }
513
+ Ok(count)
514
+ }
515
+
516
+ fn relative_coordinate(value: i32, origin: i32) -> i32 {
517
+ value.saturating_sub(origin)
518
+ }
519
+
520
+ fn unavailable(error: impl std::fmt::Display) -> ProtocolError {
521
+ ProtocolError::new(
522
+ format!("AT-SPI2 is unavailable: {error}"),
523
+ ErrorCode::CapabilityDeferred,
524
+ )
525
+ }
526
+
527
+ fn atspi_error(error: impl std::fmt::Display) -> ProtocolError {
528
+ ProtocolError::new(
529
+ format!("AT-SPI2 request failed: {error}"),
530
+ ErrorCode::InternalError,
531
+ )
532
+ }
533
+
534
+ #[cfg(test)]
535
+ mod tests {
536
+ use super::*;
537
+
538
+ #[test]
539
+ fn activation_action_selection_prefers_semantics_over_index_zero() {
540
+ let row = ["expand or contract", "edit", "activate"].map(str::to_owned);
541
+ assert_eq!(activation_action_index(&row), 2);
542
+ let mixed = ["open", "press", "click"].map(str::to_owned);
543
+ assert_eq!(activation_action_index(&mixed), 2);
544
+ let unsupported = ["expand or contract", "edit"].map(str::to_owned);
545
+ assert_eq!(activation_action_index(&unsupported), 0);
546
+ assert_eq!(activation_action_index(&[" InVoKe ".into()]), 0);
547
+ }
548
+
549
+ #[test]
550
+ fn action_count_and_dispatch_boundaries_are_explicit() {
551
+ assert_eq!(bounded_action_count(Some(0)).unwrap(), 0);
552
+ assert_eq!(selected_action_index(0, &[]), None);
553
+ assert_eq!(bounded_action_count(Some(1)).unwrap(), 1);
554
+ assert_eq!(selected_action_index(1, &[]), Some(0));
555
+
556
+ let mut names = vec!["edit".to_owned(); 64];
557
+ names[63] = "activate".to_owned();
558
+ assert_eq!(bounded_action_count(Some(64)).unwrap(), 64);
559
+ assert_eq!(selected_action_index(64, &names), Some(63));
560
+ assert!(bounded_action_count(Some(65)).is_err());
561
+ assert!(bounded_action_count(Some(i32::MAX)).is_err());
562
+ }
563
+
564
+ #[test]
565
+ fn relative_coordinates_saturate_instead_of_overflowing() {
566
+ assert_eq!(relative_coordinate(i32::MIN, i32::MAX), i32::MIN);
567
+ assert_eq!(relative_coordinate(i32::MAX, i32::MIN), i32::MAX);
568
+ assert_eq!(relative_coordinate(355, 100), 255);
569
+ }
570
+
571
+ struct MockBus;
572
+
573
+ #[zbus::interface(name = "org.freedesktop.DBus")]
574
+ impl MockBus {
575
+ #[zbus(name = "GetConnectionUnixProcessID")]
576
+ fn get_connection_unix_process_id(&self, name: &str) -> u32 {
577
+ assert_eq!(name, ":1.42");
578
+ 25361
579
+ }
580
+ }
581
+
582
+ struct MockApplication;
583
+
584
+ #[zbus::interface(name = "org.a11y.atspi.Application")]
585
+ impl MockApplication {
586
+ #[zbus(property)]
587
+ fn id(&self) -> i32 {
588
+ 8
589
+ }
590
+ }
591
+
592
+ #[tokio::test]
593
+ async fn application_pid_uses_only_accessibility_bus_process_id() {
594
+ tokio::time::timeout(std::time::Duration::from_secs(5), async {
595
+ let (server_socket, client_socket) = tokio::net::UnixStream::pair().unwrap();
596
+ let guid = zbus::Guid::generate();
597
+ let server = zbus::connection::Builder::unix_stream(server_socket)
598
+ .server(guid)
599
+ .unwrap()
600
+ .p2p()
601
+ .serve_at(DBUS_ROOT, MockBus)
602
+ .unwrap()
603
+ .serve_at(REGISTRY_ROOT, MockApplication)
604
+ .unwrap()
605
+ .build();
606
+ let client = zbus::connection::Builder::unix_stream(client_socket)
607
+ .p2p()
608
+ .build();
609
+ let (server, connection) = tokio::try_join!(server, client).unwrap();
610
+ let client = AtspiClient { connection };
611
+ let app = AccessibleRef {
612
+ destination: ":1.42".into(),
613
+ path: REGISTRY_ROOT.into(),
614
+ };
615
+ let application = client
616
+ .proxy(&app, "org.a11y.atspi.Application")
617
+ .await
618
+ .unwrap();
619
+ assert_eq!(application.get_property::<i32>("Id").await.unwrap(), 8);
620
+ assert_eq!(client.application_pid(&app).await, 25361);
621
+ drop(server);
622
+ })
623
+ .await
624
+ .expect("mock accessibility bus should respond promptly");
625
+ }
626
+
627
+ #[tokio::test]
628
+ #[ignore = "requires a live session AT-SPI bus"]
629
+ async fn connects_through_get_address_method() {
630
+ AtspiClient::connect()
631
+ .await
632
+ .expect("org.a11y.Bus.GetAddress should return a usable bus address");
633
+ }
634
+
635
+ #[test]
636
+ fn root_shape_has_cross_platform_aliases() {
637
+ let root = RootSnapshot {
638
+ accessible: AccessibleRef {
639
+ destination: ":1.2".into(),
640
+ path: "/window".into(),
641
+ },
642
+ pid: 42,
643
+ name: "Editor".into(),
644
+ app_name: "Text Editor".into(),
645
+ role: "frame".into(),
646
+ frame: Some(Rect {
647
+ x: 1,
648
+ y: 2,
649
+ width: 3,
650
+ height: 4,
651
+ }),
652
+ x11_window: Some(99),
653
+ is_focused: true,
654
+ is_minimized: false,
655
+ z_order: Some(0),
656
+ };
657
+ let value = root_json("@w1", &root, 0);
658
+ assert_eq!(value["rootRef"], "@w1");
659
+ assert_eq!(value["windowRef"], "@w1");
660
+ assert_eq!(value["windowId"], 99);
661
+ assert_eq!(value["metadata"]["backend"], "at-spi2");
662
+ assert_eq!(value["title"], "Editor");
663
+ assert_eq!(value["appName"], "Text Editor");
664
+ assert_eq!(value["processName"], "Text Editor");
665
+
666
+ let mut wayland_root = root;
667
+ wayland_root.x11_window = None;
668
+ assert!(root_json("@w2", &wayland_root, 0)["windowId"].is_null());
669
+ }
670
+ }