Skip to content

Computer use CLI for AI agents

style: apply cargo fmt to all files

Lahfir3a796023f060
diff --git a/crates/core/src/action.rs b/crates/core/src/action.rs
index cea43f804..499377aa3 100644
--- a/crates/core/src/action.rs
+++ b/crates/core/src/action.rs
@@ -113,7 +113,11 @@ pub struct ElementState {
impl ActionResult {
pub fn new(action: impl Into<String>) -> Self {
- Self { action: action.into(), ref_id: None, post_state: None }
+ Self {
+ action: action.into(),
+ ref_id: None,
+ post_state: None,
+ }
}
pub fn with_ref(mut self, ref_id: impl Into<String>) -> Self {
diff --git a/crates/core/src/adapter.rs b/crates/core/src/adapter.rs
index 83458e1de..6d22d8bf7 100644
--- a/crates/core/src/adapter.rs
+++ b/crates/core/src/adapter.rs
@@ -61,11 +61,17 @@ pub struct NativeHandle {
impl NativeHandle {
pub fn from_ptr(ptr: *const std::ffi::c_void) -> Self {
- Self { ptr, _not_send_sync: PhantomData }
+ Self {
+ ptr,
+ _not_send_sync: PhantomData,
+ }
}
pub fn null() -> Self {
- Self { ptr: std::ptr::null(), _not_send_sync: PhantomData }
+ Self {
+ ptr: std::ptr::null(),
+ _not_send_sync: PhantomData,
+ }
}
}
diff --git a/crates/core/src/commands/check.rs b/crates/core/src/commands/check.rs
index 5db209a6f..6a6fd6fbf 100644
--- a/crates/core/src/commands/check.rs
+++ b/crates/core/src/commands/check.rs
@@ -1,8 +1,5 @@
use crate::{
- action::Action,
- adapter::PlatformAdapter,
- commands::helpers::resolve_ref,
- error::AppError,
+ action::Action, adapter::PlatformAdapter, commands::helpers::resolve_ref, error::AppError,
};
use serde_json::Value;
diff --git a/crates/core/src/commands/clear.rs b/crates/core/src/commands/clear.rs
index 746c33a4d..e6a858344 100644
--- a/crates/core/src/commands/clear.rs
+++ b/crates/core/src/commands/clear.rs
@@ -1,8 +1,5 @@
use crate::{
- action::Action,
- adapter::PlatformAdapter,
- commands::helpers::resolve_ref,
- error::AppError,
+ action::Action, adapter::PlatformAdapter, commands::helpers::resolve_ref, error::AppError,
};
use serde_json::Value;
diff --git a/crates/core/src/commands/click.rs b/crates/core/src/commands/click.rs
index 69ef927d8..1e079c2f1 100644
--- a/crates/core/src/commands/click.rs
+++ b/crates/core/src/commands/click.rs
@@ -1,8 +1,5 @@
use crate::{
- action::Action,
- adapter::PlatformAdapter,
- commands::helpers::resolve_ref,
- error::AppError,
+ action::Action, adapter::PlatformAdapter, commands::helpers::resolve_ref, error::AppError,
};
use serde_json::Value;
diff --git a/crates/core/src/commands/close_app.rs b/crates/core/src/commands/close_app.rs
index c8e1a8d6d..33c970017 100644
--- a/crates/core/src/commands/close_app.rs
+++ b/crates/core/src/commands/close_app.rs
@@ -1,8 +1,7 @@
use crate::{adapter::PlatformAdapter, error::AppError};
use serde_json::{json, Value};
-const PROTECTED_PROCESSES: &[&str] =
- &["loginwindow", "windowserver", "dock", "launchd", "finder"];
+const PROTECTED_PROCESSES: &[&str] = &["loginwindow", "windowserver", "dock", "launchd", "finder"];
pub struct CloseAppArgs {
pub app: String,
diff --git a/crates/core/src/commands/double_click.rs b/crates/core/src/commands/double_click.rs
index 13a68e812..50c80a569 100644
--- a/crates/core/src/commands/double_click.rs
+++ b/crates/core/src/commands/double_click.rs
@@ -1,8 +1,5 @@
use crate::{
- action::Action,
- adapter::PlatformAdapter,
- commands::helpers::resolve_ref,
- error::AppError,
+ action::Action, adapter::PlatformAdapter, commands::helpers::resolve_ref, error::AppError,
};
use serde_json::Value;
diff --git a/crates/core/src/commands/drag.rs b/crates/core/src/commands/drag.rs
index 9f967c319..edd8446ab 100644
--- a/crates/core/src/commands/drag.rs
+++ b/crates/core/src/commands/drag.rs
@@ -17,7 +17,11 @@ pub struct DragArgs {
pub fn execute(args: DragArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
let from = resolve_point(&args.from_ref, args.from_xy, "from", adapter)?;
let to = resolve_point(&args.to_ref, args.to_xy, "to", adapter)?;
- let params = DragParams { from: from.clone(), to: to.clone(), duration_ms: args.duration_ms };
+ let params = DragParams {
+ from: from.clone(),
+ to: to.clone(),
+ duration_ms: args.duration_ms,
+ };
adapter.drag(params)?;
Ok(json!({
"dragged": true,
@@ -37,10 +41,15 @@ fn resolve_point(
let bounds = adapter
.get_element_bounds(&handle)?
.ok_or_else(|| AppError::invalid_input(format!("Element {ref_id} has no bounds")))?;
- Ok(Point { x: bounds.x + bounds.width / 2.0, y: bounds.y + bounds.height / 2.0 })
+ Ok(Point {
+ x: bounds.x + bounds.width / 2.0,
+ y: bounds.y + bounds.height / 2.0,
+ })
} else if let Some((x, y)) = xy {
Ok(Point { x, y })
} else {
- Err(AppError::invalid_input(format!("Provide --{label} <ref> or --{label}-xy x,y")))
+ Err(AppError::invalid_input(format!(
+ "Provide --{label} <ref> or --{label}-xy x,y"
+ )))
}
}
diff --git a/crates/core/src/commands/find.rs b/crates/core/src/commands/find.rs
index 8423ca365..93fd27580 100644
--- a/crates/core/src/commands/find.rs
+++ b/crates/core/src/commands/find.rs
@@ -47,26 +47,37 @@ fn search_tree(
) {
let role_match = args.role.as_deref().is_none_or(|r| node.role == r);
let name_match = args.name.as_deref().is_none_or(|n| {
- node.name.as_deref().is_some_and(|name| {
- name.to_lowercase().contains(&n.to_lowercase())
- })
+ node.name
+ .as_deref()
+ .is_some_and(|name| name.to_lowercase().contains(&n.to_lowercase()))
});
let value_match = args.value.as_deref().is_none_or(|v| {
- node.value.as_deref().is_some_and(|val| {
- val.to_lowercase().contains(&v.to_lowercase())
- })
+ node.value
+ .as_deref()
+ .is_some_and(|val| val.to_lowercase().contains(&v.to_lowercase()))
});
let text_match = args.text.as_deref().is_none_or(|t| {
let t_lower = t.to_lowercase();
- let in_name = node.name.as_deref().is_some_and(|n| n.to_lowercase().contains(&t_lower));
- let in_value = node.value.as_deref().is_some_and(|v| v.to_lowercase().contains(&t_lower));
- let in_desc = node.description.as_deref().is_some_and(|d| d.to_lowercase().contains(&t_lower));
+ let in_name = node
+ .name
+ .as_deref()
+ .is_some_and(|n| n.to_lowercase().contains(&t_lower));
+ let in_value = node
+ .value
+ .as_deref()
+ .is_some_and(|v| v.to_lowercase().contains(&t_lower));
+ let in_desc = node
+ .description
+ .as_deref()
+ .is_some_and(|d| d.to_lowercase().contains(&t_lower));
in_name || in_value || in_desc
});
if role_match && name_match && value_match && text_match {
let interactive = node.ref_id.is_some();
- let display_name = node.name.as_deref()
+ let display_name = node
+ .name
+ .as_deref()
.or(node.description.as_deref())
.map(String::from)
.unwrap_or_else(|| format!("(unnamed {})", node.role));
diff --git a/crates/core/src/commands/focus_window.rs b/crates/core/src/commands/focus_window.rs
index cbe2f0bfc..cad7e52a0 100644
--- a/crates/core/src/commands/focus_window.rs
+++ b/crates/core/src/commands/focus_window.rs
@@ -11,15 +11,22 @@ pub struct FocusWindowArgs {
}
pub fn execute(args: FocusWindowArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
- let filter = WindowFilter { focused_only: false, app: args.app.clone() };
+ let filter = WindowFilter {
+ focused_only: false,
+ app: args.app.clone(),
+ };
let windows = adapter.list_windows(&filter)?;
let window = if let Some(id) = &args.window_id {
windows.into_iter().find(|w| &w.id == id)
} else if let Some(title) = &args.title {
- windows.into_iter().find(|w| w.title.contains(title.as_str()))
+ windows
+ .into_iter()
+ .find(|w| w.title.contains(title.as_str()))
} else if let Some(app) = &args.app {
- windows.into_iter().find(|w| w.app.eq_ignore_ascii_case(app))
+ windows
+ .into_iter()
+ .find(|w| w.app.eq_ignore_ascii_case(app))
} else {
return Err(AppError::invalid_input(
"Provide --window-id, --app, or --title to identify the window",
diff --git a/crates/core/src/commands/helpers.rs b/crates/core/src/commands/helpers.rs
index 1affded8c..7cdd14d7f 100644
--- a/crates/core/src/commands/helpers.rs
+++ b/crates/core/src/commands/helpers.rs
@@ -14,7 +14,10 @@ pub fn resolve_ref(
) -> Result<(RefEntry, NativeHandle), AppError> {
validate_ref_id(ref_id)?;
let refmap = RefMap::load().map_err(|_| AppError::stale_ref(ref_id))?;
- let entry = refmap.get(ref_id).ok_or_else(|| AppError::stale_ref(ref_id))?.clone();
+ let entry = refmap
+ .get(ref_id)
+ .ok_or_else(|| AppError::stale_ref(ref_id))?
+ .clone();
let handle = adapter.resolve_element(&entry)?;
Ok((entry, handle))
}
@@ -25,9 +28,9 @@ pub fn validate_ref_id(ref_id: &str) -> Result<(), AppError> {
&& ref_id.len() <= 12
&& ref_id[2..].chars().all(|c| c.is_ascii_digit());
if !valid {
- return Err(AppError::invalid_input(
- format!("Invalid ref_id '{ref_id}': must match @e{{N}} where N is a positive integer"),
- ));
+ return Err(AppError::invalid_input(format!(
+ "Invalid ref_id '{ref_id}': must match @e{{N}} where N is a positive integer"
+ )));
}
Ok(())
}
@@ -40,9 +43,13 @@ pub fn resolve_app_pid(app: Option<&str>, adapter: &dyn PlatformAdapter) -> Resu
.map(|a| a.pid)
.ok_or_else(|| AppError::invalid_input(format!("App '{name}' not found")))
} else {
- let filter = WindowFilter { focused_only: true, app: None };
+ let filter = WindowFilter {
+ focused_only: true,
+ app: None,
+ };
let windows = adapter.list_windows(&filter)?;
- windows.first()
+ windows
+ .first()
.map(|w| w.pid)
.ok_or_else(|| AppError::invalid_input("No focused window. Use --app to specify."))
}
diff --git a/crates/core/src/commands/hover.rs b/crates/core/src/commands/hover.rs
index 28ae0509f..d4b0a9067 100644
--- a/crates/core/src/commands/hover.rs
+++ b/crates/core/src/commands/hover.rs
@@ -25,16 +25,16 @@ pub fn execute(args: HoverArgs, adapter: &dyn PlatformAdapter) -> Result<Value,
Ok(json!({ "hovered": true, "x": point.x, "y": point.y }))
}
-fn resolve_hover_point(
- args: &HoverArgs,
- adapter: &dyn PlatformAdapter,
-) -> Result<Point, AppError> {
+fn resolve_hover_point(args: &HoverArgs, adapter: &dyn PlatformAdapter) -> Result<Point, AppError> {
if let Some(ref_id) = &args.ref_id {
let (_entry, handle) = resolve_ref(ref_id, adapter)?;
let bounds = adapter
.get_element_bounds(&handle)?
.ok_or_else(|| AppError::invalid_input(format!("Element {ref_id} has no bounds")))?;
- Ok(Point { x: bounds.x + bounds.width / 2.0, y: bounds.y + bounds.height / 2.0 })
+ Ok(Point {
+ x: bounds.x + bounds.width / 2.0,
+ y: bounds.y + bounds.height / 2.0,
+ })
} else if let Some((x, y)) = args.xy {
Ok(Point { x, y })
} else {
diff --git a/crates/core/src/commands/is_check.rs b/crates/core/src/commands/is_check.rs
index c779a2fea..ae46db3a8 100644
--- a/crates/core/src/commands/is_check.rs
+++ b/crates/core/src/commands/is_check.rs
@@ -38,7 +38,9 @@ pub fn execute(args: IsArgs, adapter: &dyn PlatformAdapter) -> Result<Value, App
IsProperty::Expanded => entry.states.contains(&"expanded".to_string()),
};
- Ok(json!({ "property": prop_name, "ref": args.ref_id, "result": result, "applicable": applicable }))
+ Ok(
+ json!({ "property": prop_name, "ref": args.ref_id, "result": result, "applicable": applicable }),
+ )
}
fn is_applicable(property: &IsProperty, role: &str) -> bool {
@@ -46,8 +48,12 @@ fn is_applicable(property: &IsProperty, role: &str) -> bool {
IsProperty::Visible | IsProperty::Enabled | IsProperty::Focused => true,
IsProperty::Checked => matches!(
role,
- "checkbox" | "switch" | "radiobutton" | "togglebutton"
- | "menuitemcheckbox" | "menuitemradio"
+ "checkbox"
+ | "switch"
+ | "radiobutton"
+ | "togglebutton"
+ | "menuitemcheckbox"
+ | "menuitemradio"
),
IsProperty::Expanded => matches!(
role,
diff --git a/crates/core/src/commands/key_down.rs b/crates/core/src/commands/key_down.rs
index 1abb7f4f9..743884c10 100644
--- a/crates/core/src/commands/key_down.rs
+++ b/crates/core/src/commands/key_down.rs
@@ -1,8 +1,5 @@
use crate::{
- action::Action,
- adapter::PlatformAdapter,
- commands::press::parse_combo,
- error::AppError,
+ action::Action, adapter::PlatformAdapter, commands::press::parse_combo, error::AppError,
};
use serde_json::{json, Value};
diff --git a/crates/core/src/commands/key_up.rs b/crates/core/src/commands/key_up.rs
index 1e548e0f1..df8b88d1f 100644
--- a/crates/core/src/commands/key_up.rs
+++ b/crates/core/src/commands/key_up.rs
@@ -1,8 +1,5 @@
use crate::{
- action::Action,
- adapter::PlatformAdapter,
- commands::press::parse_combo,
- error::AppError,
+ action::Action, adapter::PlatformAdapter, commands::press::parse_combo, error::AppError,
};
use serde_json::{json, Value};
diff --git a/crates/core/src/commands/list_windows.rs b/crates/core/src/commands/list_windows.rs
index 0e93391b8..5b0a3d34c 100644
--- a/crates/core/src/commands/list_windows.rs
+++ b/crates/core/src/commands/list_windows.rs
@@ -9,7 +9,10 @@ pub struct ListWindowsArgs {
}
pub fn execute(args: ListWindowsArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
- let filter = WindowFilter { focused_only: false, app: args.app };
+ let filter = WindowFilter {
+ focused_only: false,
+ app: args.app,
+ };
let windows = adapter.list_windows(&filter)?;
Ok(serde_json::to_value(windows)?)
}
diff --git a/crates/core/src/commands/maximize.rs b/crates/core/src/commands/maximize.rs
index f4b858c8f..09d9b7401 100644
--- a/crates/core/src/commands/maximize.rs
+++ b/crates/core/src/commands/maximize.rs
@@ -1,8 +1,5 @@
use crate::{
- action::WindowOp,
- adapter::PlatformAdapter,
- commands::helpers::resolve_app_pid,
- error::AppError,
+ action::WindowOp, adapter::PlatformAdapter, commands::helpers::resolve_app_pid, error::AppError,
};
use serde_json::{json, Value};
@@ -21,7 +18,10 @@ fn find_window(
pid: i32,
adapter: &dyn PlatformAdapter,
) -> Result<crate::node::WindowInfo, AppError> {
- let filter = crate::adapter::WindowFilter { focused_only: false, app: None };
+ let filter = crate::adapter::WindowFilter {
+ focused_only: false,
+ app: None,
+ };
let windows = adapter.list_windows(&filter)?;
windows
.into_iter()
diff --git a/crates/core/src/commands/minimize.rs b/crates/core/src/commands/minimize.rs
index 6c5269821..d081c1ae3 100644
--- a/crates/core/src/commands/minimize.rs
+++ b/crates/core/src/commands/minimize.rs
@@ -1,8 +1,5 @@
use crate::{
- action::WindowOp,
- adapter::PlatformAdapter,
- commands::helpers::resolve_app_pid,
- error::AppError,
+ action::WindowOp, adapter::PlatformAdapter, commands::helpers::resolve_app_pid, error::AppError,
};
use serde_json::{json, Value};
@@ -21,7 +18,10 @@ fn find_window(
pid: i32,
adapter: &dyn PlatformAdapter,
) -> Result<crate::node::WindowInfo, AppError> {
- let filter = crate::adapter::WindowFilter { focused_only: false, app: None };
+ let filter = crate::adapter::WindowFilter {
+ focused_only: false,
+ app: None,
+ };
let windows = adapter.list_windows(&filter)?;
windows
.into_iter()
diff --git a/crates/core/src/commands/mod.rs b/crates/core/src/commands/mod.rs
index e79a4dddc..922e55919 100644
--- a/crates/core/src/commands/mod.rs
+++ b/crates/core/src/commands/mod.rs
@@ -1,10 +1,10 @@
pub mod batch;
pub mod check;
pub mod clear;
+pub mod click;
pub mod clipboard_clear;
pub mod clipboard_get;
pub mod clipboard_set;
-pub mod click;
pub mod close_app;
pub mod collapse;
pub mod double_click;
diff --git a/crates/core/src/commands/mouse_click.rs b/crates/core/src/commands/mouse_click.rs
index 9cdcbbdf6..f4a6b14d6 100644
--- a/crates/core/src/commands/mouse_click.rs
+++ b/crates/core/src/commands/mouse_click.rs
@@ -15,7 +15,10 @@ pub struct MouseClickArgs {
pub fn execute(args: MouseClickArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
adapter.mouse_event(MouseEvent {
kind: MouseEventKind::Click { count: args.count },
- point: Point { x: args.x, y: args.y },
+ point: Point {
+ x: args.x,
+ y: args.y,
+ },
button: args.button,
})?;
Ok(json!({ "clicked": true, "x": args.x, "y": args.y, "count": args.count }))
diff --git a/crates/core/src/commands/mouse_down.rs b/crates/core/src/commands/mouse_down.rs
index bdabdeb8f..68a6d9892 100644
--- a/crates/core/src/commands/mouse_down.rs
+++ b/crates/core/src/commands/mouse_down.rs
@@ -14,7 +14,10 @@ pub struct MouseDownArgs {
pub fn execute(args: MouseDownArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
adapter.mouse_event(MouseEvent {
kind: MouseEventKind::Down,
- point: Point { x: args.x, y: args.y },
+ point: Point {
+ x: args.x,
+ y: args.y,
+ },
button: args.button,
})?;
Ok(json!({ "pressed": true, "x": args.x, "y": args.y }))
diff --git a/crates/core/src/commands/mouse_move.rs b/crates/core/src/commands/mouse_move.rs
index 37b1b15f3..9da3c78fa 100644
--- a/crates/core/src/commands/mouse_move.rs
+++ b/crates/core/src/commands/mouse_move.rs
@@ -13,7 +13,10 @@ pub struct MouseMoveArgs {
pub fn execute(args: MouseMoveArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
adapter.mouse_event(MouseEvent {
kind: MouseEventKind::Move,
- point: Point { x: args.x, y: args.y },
+ point: Point {
+ x: args.x,
+ y: args.y,
+ },
button: MouseButton::Left,
})?;
Ok(json!({ "moved": true, "x": args.x, "y": args.y }))
diff --git a/crates/core/src/commands/mouse_up.rs b/crates/core/src/commands/mouse_up.rs
index 5a054d93e..bcba54291 100644
--- a/crates/core/src/commands/mouse_up.rs
+++ b/crates/core/src/commands/mouse_up.rs
@@ -14,7 +14,10 @@ pub struct MouseUpArgs {
pub fn execute(args: MouseUpArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
adapter.mouse_event(MouseEvent {
kind: MouseEventKind::Up,
- point: Point { x: args.x, y: args.y },
+ point: Point {
+ x: args.x,
+ y: args.y,
+ },
button: args.button,
})?;
Ok(json!({ "released": true, "x": args.x, "y": args.y }))
diff --git a/crates/core/src/commands/move_window.rs b/crates/core/src/commands/move_window.rs
index 7dc5f042d..ec6d1fdcf 100644
--- a/crates/core/src/commands/move_window.rs
+++ b/crates/core/src/commands/move_window.rs
@@ -1,8 +1,5 @@
use crate::{
- action::WindowOp,
- adapter::PlatformAdapter,
- commands::helpers::resolve_app_pid,
- error::AppError,
+ action::WindowOp, adapter::PlatformAdapter, commands::helpers::resolve_app_pid, error::AppError,
};
use serde_json::{json, Value};
@@ -15,7 +12,13 @@ pub struct MoveWindowArgs {
pub fn execute(args: MoveWindowArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
let pid = resolve_app_pid(args.app.as_deref(), adapter)?;
let win = find_window(pid, adapter)?;
- adapter.window_op(&win, WindowOp::Move { x: args.x, y: args.y })?;
+ adapter.window_op(
+ &win,
+ WindowOp::Move {
+ x: args.x,
+ y: args.y,
+ },
+ )?;
Ok(json!({ "moved": true, "x": args.x, "y": args.y }))
}
@@ -23,7 +26,10 @@ fn find_window(
pid: i32,
adapter: &dyn PlatformAdapter,
) -> Result<crate::node::WindowInfo, AppError> {
- let filter = crate::adapter::WindowFilter { focused_only: false, app: None };
+ let filter = crate::adapter::WindowFilter {
+ focused_only: false,
+ app: None,
+ };
let windows = adapter.list_windows(&filter)?;
windows
.into_iter()
diff --git a/crates/core/src/commands/permissions.rs b/crates/core/src/commands/permissions.rs
index 81a3f870a..8b2c06c39 100644
--- a/crates/core/src/commands/permissions.rs
+++ b/crates/core/src/commands/permissions.rs
@@ -1,4 +1,7 @@
-use crate::{adapter::{PermissionStatus, PlatformAdapter}, error::AppError};
+use crate::{
+ adapter::{PermissionStatus, PlatformAdapter},
+ error::AppError,
+};
use serde_json::{json, Value};
pub struct PermissionsArgs {
diff --git a/crates/core/src/commands/resize_window.rs b/crates/core/src/commands/resize_window.rs
index f0d1177ee..343ce3ad7 100644
--- a/crates/core/src/commands/resize_window.rs
+++ b/crates/core/src/commands/resize_window.rs
@@ -1,8 +1,5 @@
use crate::{
- action::WindowOp,
- adapter::PlatformAdapter,
- commands::helpers::resolve_app_pid,
- error::AppError,
+ action::WindowOp, adapter::PlatformAdapter, commands::helpers::resolve_app_pid, error::AppError,
};
use serde_json::{json, Value};
@@ -15,7 +12,13 @@ pub struct ResizeWindowArgs {
pub fn execute(args: ResizeWindowArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
let pid = resolve_app_pid(args.app.as_deref(), adapter)?;
let win = find_window(pid, adapter)?;
- adapter.window_op(&win, WindowOp::Resize { width: args.width, height: args.height })?;
+ adapter.window_op(
+ &win,
+ WindowOp::Resize {
+ width: args.width,
+ height: args.height,
+ },
+ )?;
Ok(json!({ "resized": true, "width": args.width, "height": args.height }))
}
@@ -23,7 +26,10 @@ fn find_window(
pid: i32,
adapter: &dyn PlatformAdapter,
) -> Result<crate::node::WindowInfo, AppError> {
- let filter = crate::adapter::WindowFilter { focused_only: false, app: None };
+ let filter = crate::adapter::WindowFilter {
+ focused_only: false,
+ app: None,
+ };
let windows = adapter.list_windows(&filter)?;
windows
.into_iter()
diff --git a/crates/core/src/commands/restore.rs b/crates/core/src/commands/restore.rs
index dc14ffa96..5fee55086 100644
--- a/crates/core/src/commands/restore.rs
+++ b/crates/core/src/commands/restore.rs
@@ -1,8 +1,5 @@
use crate::{
- action::WindowOp,
- adapter::PlatformAdapter,
- commands::helpers::resolve_app_pid,
- error::AppError,
+ action::WindowOp, adapter::PlatformAdapter, commands::helpers::resolve_app_pid, error::AppError,
};
use serde_json::{json, Value};
@@ -21,7 +18,10 @@ fn find_window(
pid: i32,
adapter: &dyn PlatformAdapter,
) -> Result<crate::node::WindowInfo, AppError> {
- let filter = crate::adapter::WindowFilter { focused_only: false, app: None };
+ let filter = crate::adapter::WindowFilter {
+ focused_only: false,
+ app: None,
+ };
let windows = adapter.list_windows(&filter)?;
windows
.into_iter()
diff --git a/crates/core/src/commands/right_click.rs b/crates/core/src/commands/right_click.rs
index bdc0fc897..1c7fc48ed 100644
--- a/crates/core/src/commands/right_click.rs
+++ b/crates/core/src/commands/right_click.rs
@@ -1,8 +1,5 @@
use crate::{
- action::Action,
- adapter::PlatformAdapter,
- commands::helpers::resolve_ref,
- error::AppError,
+ action::Action, adapter::PlatformAdapter, commands::helpers::resolve_ref, error::AppError,
};
use serde_json::Value;
diff --git a/crates/core/src/commands/screenshot.rs b/crates/core/src/commands/screenshot.rs
index f163bff11..b1320c9cc 100644
--- a/crates/core/src/commands/screenshot.rs
+++ b/crates/core/src/commands/screenshot.rs
@@ -35,7 +35,10 @@ fn resolve_target(
adapter: &dyn PlatformAdapter,
) -> Result<ScreenshotTarget, AppError> {
if let Some(window_id) = &args.window_id {
- let filter = WindowFilter { focused_only: false, app: args.app.clone() };
+ let filter = WindowFilter {
+ focused_only: false,
+ app: args.app.clone(),
+ };
let windows = adapter.list_windows(&filter)?;
let win = windows
.into_iter()
@@ -45,7 +48,10 @@ fn resolve_target(
}
if let Some(app_name) = &args.app {
- let filter = WindowFilter { focused_only: false, app: Some(app_name.clone()) };
+ let filter = WindowFilter {
+ focused_only: false,
+ app: Some(app_name.clone()),
+ };
let windows = adapter.list_windows(&filter)?;
let win = windows.into_iter().next().ok_or_else(|| {
AppError::invalid_input(format!("No windows found for app '{app_name}'"))
diff --git a/crates/core/src/commands/scroll_to.rs b/crates/core/src/commands/scroll_to.rs
index 33e7fcc76..a40104854 100644
--- a/crates/core/src/commands/scroll_to.rs
+++ b/crates/core/src/commands/scroll_to.rs
@@ -1,8 +1,5 @@
use crate::{
- action::Action,
- adapter::PlatformAdapter,
- commands::helpers::resolve_ref,
- error::AppError,
+ action::Action, adapter::PlatformAdapter, commands::helpers::resolve_ref, error::AppError,
};
use serde_json::Value;
diff --git a/crates/core/src/commands/select.rs b/crates/core/src/commands/select.rs
index c72fa2d88..c52bf6f65 100644
--- a/crates/core/src/commands/select.rs
+++ b/crates/core/src/commands/select.rs
@@ -1,8 +1,5 @@
use crate::{
- action::Action,
- adapter::PlatformAdapter,
- commands::helpers::resolve_ref,
- error::AppError,
+ action::Action, adapter::PlatformAdapter, commands::helpers::resolve_ref, error::AppError,
};
use serde_json::Value;
diff --git a/crates/core/src/commands/set_value.rs b/crates/core/src/commands/set_value.rs
index a1c13a8ab..a45efcb34 100644
--- a/crates/core/src/commands/set_value.rs
+++ b/crates/core/src/commands/set_value.rs
@@ -1,8 +1,5 @@
use crate::{
- action::Action,
- adapter::PlatformAdapter,
- commands::helpers::resolve_ref,
- error::AppError,
+ action::Action, adapter::PlatformAdapter, commands::helpers::resolve_ref, error::AppError,
};
use serde_json::Value;
diff --git a/crates/core/src/commands/status.rs b/crates/core/src/commands/status.rs
index 9fc2af5b9..dc434c6e4 100644
--- a/crates/core/src/commands/status.rs
+++ b/crates/core/src/commands/status.rs
@@ -1,4 +1,8 @@
-use crate::{adapter::{PermissionStatus, PlatformAdapter}, error::AppError, refs::RefMap};
+use crate::{
+ adapter::{PermissionStatus, PlatformAdapter},
+ error::AppError,
+ refs::RefMap,
+};
use serde_json::{json, Value};
pub fn execute(adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
diff --git a/crates/core/src/commands/triple_click.rs b/crates/core/src/commands/triple_click.rs
index 5bdd3be3e..55e2f7ac3 100644
--- a/crates/core/src/commands/triple_click.rs
+++ b/crates/core/src/commands/triple_click.rs
@@ -1,8 +1,5 @@
use crate::{
- action::Action,
- adapter::PlatformAdapter,
- commands::helpers::resolve_ref,
- error::AppError,
+ action::Action, adapter::PlatformAdapter, commands::helpers::resolve_ref, error::AppError,
};
use serde_json::Value;
diff --git a/crates/core/src/commands/type_text.rs b/crates/core/src/commands/type_text.rs
index 9a0ee424d..f06974c98 100644
--- a/crates/core/src/commands/type_text.rs
+++ b/crates/core/src/commands/type_text.rs
@@ -1,8 +1,5 @@
use crate::{
- action::Action,
- adapter::PlatformAdapter,
- commands::helpers::resolve_ref,
- error::AppError,
+ action::Action, adapter::PlatformAdapter, commands::helpers::resolve_ref, error::AppError,
};
use serde_json::Value;
diff --git a/crates/core/src/commands/uncheck.rs b/crates/core/src/commands/uncheck.rs
index 17151bb87..399e8d5fa 100644
--- a/crates/core/src/commands/uncheck.rs
+++ b/crates/core/src/commands/uncheck.rs
@@ -1,8 +1,5 @@
use crate::{
- action::Action,
- adapter::PlatformAdapter,
- commands::helpers::resolve_ref,
- error::AppError,
+ action::Action, adapter::PlatformAdapter, commands::helpers::resolve_ref, error::AppError,
};
use serde_json::Value;
diff --git a/crates/core/src/commands/wait.rs b/crates/core/src/commands/wait.rs
index c187502c3..1f9598618 100644
--- a/crates/core/src/commands/wait.rs
+++ b/crates/core/src/commands/wait.rs
@@ -29,7 +29,9 @@ pub fn execute(args: WaitArgs, adapter: &dyn PlatformAdapter) -> Result<Value, A
if args.menu || args.menu_closed {
let pid = resolve_app_pid(args.app.as_deref(), adapter)?;
let start = Instant::now();
- adapter.wait_for_menu(pid, args.menu, args.timeout_ms).map_err(AppError::Adapter)?;
+ adapter
+ .wait_for_menu(pid, args.menu, args.timeout_ms)
+ .map_err(AppError::Adapter)?;
let elapsed = start.elapsed().as_millis();
return Ok(json!({ "found": true, "elapsed_ms": elapsed }));
}
@@ -71,9 +73,9 @@ fn wait_for_element(
}
if start.elapsed() >= timeout {
- return Err(AppError::Adapter(crate::error::AdapterError::timeout(format!(
- "Element {ref_id} not found within {timeout_ms}ms"
- ))));
+ return Err(AppError::Adapter(crate::error::AdapterError::timeout(
+ format!("Element {ref_id} not found within {timeout_ms}ms"),
+ )));
}
std::thread::sleep(Duration::from_millis(100));
@@ -87,7 +89,10 @@ fn wait_for_window(
) -> Result<Value, AppError> {
let start = Instant::now();
let timeout = Duration::from_millis(timeout_ms);
- let filter = WindowFilter { focused_only: false, app: None };
+ let filter = WindowFilter {
+ focused_only: false,
+ app: None,
+ };
loop {
if let Ok(windows) = adapter.list_windows(&filter) {
@@ -98,9 +103,9 @@ fn wait_for_window(
}
if start.elapsed() >= timeout {
- return Err(AppError::Adapter(crate::error::AdapterError::timeout(format!(
- "Window with title '{title}' not found within {timeout_ms}ms"
- ))));
+ return Err(AppError::Adapter(crate::error::AdapterError::timeout(
+ format!("Window with title '{title}' not found within {timeout_ms}ms"),
+ )));
}
std::thread::sleep(Duration::from_millis(100));
@@ -133,9 +138,9 @@ fn wait_for_text(
}
if start.elapsed() >= timeout {
- return Err(AppError::Adapter(crate::error::AdapterError::timeout(format!(
- "Text '{text}' not found within {timeout_ms}ms"
- ))));
+ return Err(AppError::Adapter(crate::error::AdapterError::timeout(
+ format!("Text '{text}' not found within {timeout_ms}ms"),
+ )));
}
std::thread::sleep(Duration::from_millis(200));
@@ -148,12 +153,24 @@ struct TextMatch {
}
fn find_text_in_tree(node: &AccessibilityNode, text_lower: &str) -> Option<TextMatch> {
- let in_name = node.name.as_deref().is_some_and(|n| n.to_lowercase().contains(text_lower));
- let in_value = node.value.as_deref().is_some_and(|v| v.to_lowercase().contains(text_lower));
- let in_desc = node.description.as_deref().is_some_and(|d| d.to_lowercase().contains(text_lower));
+ let in_name = node
+ .name
+ .as_deref()
+ .is_some_and(|n| n.to_lowercase().contains(text_lower));
+ let in_value = node
+ .value
+ .as_deref()
+ .is_some_and(|v| v.to_lowercase().contains(text_lower));
+ let in_desc = node
+ .description
+ .as_deref()
+ .is_some_and(|d| d.to_lowercase().contains(text_lower));
if in_name || in_value || in_desc {
- return Some(TextMatch { ref_id: node.ref_id.clone(), role: node.role.clone() });
+ return Some(TextMatch {
+ ref_id: node.ref_id.clone(),
+ role: node.role.clone(),
+ });
}
for child in &node.children {
diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs
index 73eb49ecd..1aefc5200 100644
--- a/crates/core/src/error.rs
+++ b/crates/core/src/error.rs
@@ -72,8 +72,11 @@ impl AdapterError {
}
pub fn stale_ref(ref_id: &str) -> Self {
- Self::new(ErrorCode::StaleRef, format!("{ref_id} not found in current RefMap"))
- .with_suggestion("Run 'snapshot' to refresh, then retry with updated ref")
+ Self::new(
+ ErrorCode::StaleRef,
+ format!("{ref_id} not found in current RefMap"),
+ )
+ .with_suggestion("Run 'snapshot' to refresh, then retry with updated ref")
}
pub fn not_supported(method: &str) -> Self {
@@ -85,8 +88,11 @@ impl AdapterError {
}
pub fn element_not_found(ref_id: &str) -> Self {
- Self::new(ErrorCode::ElementNotFound, format!("Element {ref_id} could not be resolved"))
- .with_suggestion("Run 'snapshot' to get fresh refs")
+ Self::new(
+ ErrorCode::ElementNotFound,
+ format!("Element {ref_id} could not be resolved"),
+ )
+ .with_suggestion("Run 'snapshot' to get fresh refs")
}
pub fn timeout(msg: impl Into<String>) -> Self {
@@ -99,10 +105,13 @@ impl AdapterError {
}
pub fn permission_denied() -> Self {
- Self::new(ErrorCode::PermDenied, "Accessibility permission not granted")
- .with_suggestion(
- "Open System Settings > Privacy & Security > Accessibility and add your terminal",
- )
+ Self::new(
+ ErrorCode::PermDenied,
+ "Accessibility permission not granted",
+ )
+ .with_suggestion(
+ "Open System Settings > Privacy & Security > Accessibility and add your terminal",
+ )
}
}
diff --git a/crates/core/src/refs.rs b/crates/core/src/refs.rs
index 3fe0ca6ce..5f4da86e9 100644
--- a/crates/core/src/refs.rs
+++ b/crates/core/src/refs.rs
@@ -29,7 +29,10 @@ pub struct RefMap {
impl RefMap {
pub fn new() -> Self {
- Self { inner: HashMap::new(), counter: 0 }
+ Self {
+ inner: HashMap::new(),
+ counter: 0,
+ }
}
pub fn allocate(&mut self, entry: RefEntry) -> String {
@@ -60,7 +63,10 @@ impl RefMap {
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
- std::fs::DirBuilder::new().recursive(true).mode(0o700).create(dir)?;
+ std::fs::DirBuilder::new()
+ .recursive(true)
+ .mode(0o700)
+ .create(dir)?;
}
#[cfg(not(unix))]
std::fs::create_dir_all(dir)?;
@@ -111,8 +117,7 @@ impl Default for RefMap {
}
fn refmap_path() -> Result<PathBuf, AppError> {
- let home = home_dir()
- .ok_or_else(|| AppError::Internal("HOME directory not found".into()))?;
+ let home = home_dir().ok_or_else(|| AppError::Internal("HOME directory not found".into()))?;
Ok(home.join(".agent-desktop").join("last_refmap.json"))
}
diff --git a/crates/core/src/snapshot.rs b/crates/core/src/snapshot.rs
index a070fce7f..6d235df13 100644
--- a/crates/core/src/snapshot.rs
+++ b/crates/core/src/snapshot.rs
@@ -6,9 +6,22 @@ use crate::{
};
const INTERACTIVE_ROLES: &[&str] = &[
- "button", "textfield", "checkbox", "link", "menuitem", "tab", "slider",
- "combobox", "treeitem", "cell", "radiobutton", "incrementor",
- "menubutton", "switch", "colorwell", "dockitem",
+ "button",
+ "textfield",
+ "checkbox",
+ "link",
+ "menuitem",
+ "tab",
+ "slider",
+ "combobox",
+ "treeitem",
+ "cell",
+ "radiobutton",
+ "incrementor",
+ "menubutton",
+ "switch",
+ "colorwell",
+ "dockitem",
];
pub struct SnapshotResult {
@@ -43,7 +56,10 @@ pub fn build(
.find(|w| w.app.eq_ignore_ascii_case(app) && w.is_focused)
.or_else(|| {
adapter
- .list_windows(&WindowFilter { focused_only: false, app: Some(app.to_string()) })
+ .list_windows(&WindowFilter {
+ focused_only: false,
+ app: Some(app.to_string()),
+ })
.ok()
.and_then(|ws| ws.into_iter().next())
})
@@ -54,15 +70,12 @@ pub fn build(
))
})?
} else {
- windows
- .into_iter()
- .find(|w| w.is_focused)
- .ok_or_else(|| {
- AppError::Adapter(crate::error::AdapterError::new(
- crate::error::ErrorCode::WindowNotFound,
- "No focused window found. Use --app to specify an application.",
- ))
- })?
+ windows.into_iter().find(|w| w.is_focused).ok_or_else(|| {
+ AppError::Adapter(crate::error::AdapterError::new(
+ crate::error::ErrorCode::WindowNotFound,
+ "No focused window found. Use --app to specify an application.",
+ ))
+ })?
};
let raw_tree = adapter.get_tree(&window, opts)?;
@@ -77,7 +90,11 @@ pub fn build(
Some(window.app.as_str()),
);
- Ok(SnapshotResult { tree, refmap, window })
+ Ok(SnapshotResult {
+ tree,
+ refmap,
+ window,
+ })
}
pub fn run(
@@ -124,7 +141,14 @@ fn allocate_refs(
.children
.into_iter()
.filter_map(|child| {
- let child = allocate_refs(child, refmap, include_bounds, interactive_only, window_pid, source_app);
+ let child = allocate_refs(
+ child,
+ refmap,
+ include_bounds,
+ interactive_only,
+ window_pid,
+ source_app,
+ );
if interactive_only && child.ref_id.is_none() && child.children.is_empty() {
None
} else {
diff --git a/crates/macos/examples/ax_probe.rs b/crates/macos/examples/ax_probe.rs
index e3322b1c0..09f2d7dda 100644
--- a/crates/macos/examples/ax_probe.rs
+++ b/crates/macos/examples/ax_probe.rs
@@ -17,8 +17,18 @@ fn main() {
#[cfg(target_os = "macos")]
fn find_pid(name: &str) -> Option<i32> {
- let out = std::process::Command::new("pgrep").arg("-xi").arg(name).output().ok()?;
- String::from_utf8_lossy(&out.stdout).trim().lines().next()?.trim().parse().ok()
+ let out = std::process::Command::new("pgrep")
+ .arg("-xi")
+ .arg(name)
+ .output()
+ .ok()?;
+ String::from_utf8_lossy(&out.stdout)
+ .trim()
+ .lines()
+ .next()?
+ .trim()
+ .parse()
+ .ok()
}
#[cfg(target_os = "macos")]
@@ -31,18 +41,23 @@ fn probe_app(pid: i32) {
// ── 1. What attributes does the app element expose? ──────────────────────
println!("\n[1] App element attribute names:");
let attr_names = get_attribute_names(app);
- for n in &attr_names { println!(" {n}"); }
+ for n in &attr_names {
+ println!(" {n}");
+ }
// ── 2. Get windows the right way ─────────────────────────────────────────
println!("\n[2] Windows via kAXWindowsAttribute:");
let windows = get_ax_children(app, kAXWindowsAttribute);
println!(" count = {}", windows.len());
for (i, win) in windows.iter().enumerate() {
- let role = read_string(*win, kAXRoleAttribute);
+ let role = read_string(*win, kAXRoleAttribute);
let title = read_string(*win, kAXTitleAttribute);
- let pos = read_cgpoint(*win, kAXPositionAttribute);
- let size = read_cgsize(*win, kAXSizeAttribute);
- println!(" [{i}] role={:?} title={:?} pos={:?} size={:?}", role, title, pos, size);
+ let pos = read_cgpoint(*win, kAXPositionAttribute);
+ let size = read_cgsize(*win, kAXSizeAttribute);
+ println!(
+ " [{i}] role={:?} title={:?} pos={:?} size={:?}",
+ role, title, pos, size
+ );
// Children of this window
let children = get_ax_children(*win, kAXChildrenAttribute);
@@ -53,9 +68,12 @@ fn probe_app(pid: i32) {
let cd = read_string(*child, kAXDescriptionAttribute);
let cv = read_string(*child, kAXValueAttribute);
let cpos = read_cgpoint(*child, kAXPositionAttribute);
- let csz = read_cgsize(*child, kAXSizeAttribute);
+ let csz = read_cgsize(*child, kAXSizeAttribute);
- println!(" [{ci}] role={:?} title={:?} desc={:?} val={:?}", cr, ct, cd, cv);
+ println!(
+ " [{ci}] role={:?} title={:?} desc={:?} val={:?}",
+ cr, ct, cd, cv
+ );
println!(" pos={:?} size={:?}", cpos, csz);
// ── 3. Test kAXPressAction on each child ────────────────────────
@@ -67,17 +85,26 @@ fn probe_app(pid: i32) {
let cx = p.0 + s.0 / 2.0;
let cy = p.1 + s.1 / 2.0;
let cg_ok = cg_click(cx, cy);
- println!(" CGEvent click at ({:.0},{:.0}) → {}", cx, cy, if cg_ok { "OK" } else { "FAIL" });
+ println!(
+ " CGEvent click at ({:.0},{:.0}) → {}",
+ cx,
+ cy,
+ if cg_ok { "OK" } else { "FAIL" }
+ );
} else {
println!(" CGEvent click → no bounds available");
}
release_ax(*child);
}
- for child in children.iter().skip(8) { release_ax(*child); }
+ for child in children.iter().skip(8) {
+ release_ax(*child);
+ }
release_ax(*win);
- if i >= 1 { break; } // only first 2 windows
+ if i >= 1 {
+ break;
+ } // only first 2 windows
}
// ── 5. Multi-attribute fetch speed comparison ─────────────────────────────
@@ -98,34 +125,49 @@ fn probe_app(pid: i32) {
#[cfg(target_os = "macos")]
fn get_attribute_names(el: accessibility_sys::AXUIElementRef) -> Vec<String> {
use accessibility_sys::*;
- use core_foundation::{array::CFArray, base::CFTypeRef, string::CFString, base::TCFType};
+ use core_foundation::{array::CFArray, base::CFTypeRef, base::TCFType, string::CFString};
let mut out_ref: CFTypeRef = std::ptr::null_mut();
let err = unsafe { AXUIElementCopyAttributeNames(el, &mut out_ref as *mut _ as *mut _) };
- if err != kAXErrorSuccess || out_ref.is_null() { return vec![]; }
+ if err != kAXErrorSuccess || out_ref.is_null() {
+ return vec![];
+ }
let arr = unsafe { CFArray::<CFString>::wrap_under_create_rule(out_ref as _) };
arr.into_iter().map(|s| s.to_string()).collect()
}
/// Read an array-typed AX attribute, retaining each element so it stays alive.
#[cfg(target_os = "macos")]
-fn get_ax_children(el: accessibility_sys::AXUIElementRef, attr: &str) -> Vec<accessibility_sys::AXUIElementRef> {
+fn get_ax_children(
+ el: accessibility_sys::AXUIElementRef,
+ attr: &str,
+) -> Vec<accessibility_sys::AXUIElementRef> {
use accessibility_sys::*;
- use core_foundation::{array::CFArray, base::{CFRetain, CFType, CFTypeRef, TCFType}, string::CFString};
+ use core_foundation::{
+ array::CFArray,
+ base::{CFRetain, CFType, CFTypeRef, TCFType},
+ string::CFString,
+ };
let key = CFString::new(attr);
let mut val: CFTypeRef = std::ptr::null_mut();
let err = unsafe { AXUIElementCopyAttributeValue(el, key.as_concrete_TypeRef(), &mut val) };
- if err != kAXErrorSuccess || val.is_null() { return vec![]; }
+ if err != kAXErrorSuccess || val.is_null() {
+ return vec![];
+ }
let arr = unsafe { CFArray::<CFType>::wrap_under_create_rule(val as _) };
- arr.into_iter().filter_map(|item| {
- let ptr = item.as_concrete_TypeRef() as AXUIElementRef;
- if ptr.is_null() { return None; }
- // Retain so the element lives past CFArray dealloc
- unsafe { CFRetain(ptr as CFTypeRef) };
- Some(ptr)
- }).collect()
+ arr.into_iter()
+ .filter_map(|item| {
+ let ptr = item.as_concrete_TypeRef() as AXUIElementRef;
+ if ptr.is_null() {
+ return None;
+ }
+ // Retain so the element lives past CFArray dealloc
+ unsafe { CFRetain(ptr as CFTypeRef) };
+ Some(ptr)
+ })
+ .collect()
}
#[cfg(target_os = "macos")]
@@ -138,12 +180,17 @@ fn release_ax(el: accessibility_sys::AXUIElementRef) {
#[cfg(target_os = "macos")]
fn read_string(el: accessibility_sys::AXUIElementRef, attr: &str) -> Option<String> {
use accessibility_sys::*;
- use core_foundation::{base::{CFType, CFTypeRef, TCFType}, string::CFString};
+ use core_foundation::{
+ base::{CFType, CFTypeRef, TCFType},
+ string::CFString,
+ };
let key = CFString::new(attr);
let mut val: CFTypeRef = std::ptr::null_mut();
let err = unsafe { AXUIElementCopyAttributeValue(el, key.as_concrete_TypeRef(), &mut val) };
- if err != kAXErrorSuccess || val.is_null() { return None; }
+ if err != kAXErrorSuccess || val.is_null() {
+ return None;
+ }
let cf = unsafe { CFType::wrap_under_create_rule(val) };
cf.downcast::<CFString>().map(|s| s.to_string())
}
@@ -151,33 +198,63 @@ fn read_string(el: accessibility_sys::AXUIElementRef, attr: &str) -> Option<Stri
#[cfg(target_os = "macos")]
fn read_cgpoint(el: accessibility_sys::AXUIElementRef, attr: &str) -> Option<(f64, f64)> {
use accessibility_sys::*;
- use core_foundation::{base::{CFTypeRef, TCFType}, string::CFString};
+ use core_foundation::{
+ base::{CFTypeRef, TCFType},
+ string::CFString,
+ };
use core_graphics::geometry::CGPoint;
let key = CFString::new(attr);
let mut val: CFTypeRef = std::ptr::null_mut();
let err = unsafe { AXUIElementCopyAttributeValue(el, key.as_concrete_TypeRef(), &mut val) };
- if err != kAXErrorSuccess || val.is_null() { return None; }
+ if err != kAXErrorSuccess || val.is_null() {
+ return None;
+ }
let mut pt = CGPoint::new(0.0, 0.0);
- let ok = unsafe { AXValueGetValue(val as _, kAXValueTypeCGPoint, &mut pt as *mut _ as *mut std::ffi::c_void) };
+ let ok = unsafe {
+ AXValueGetValue(
+ val as _,
+ kAXValueTypeCGPoint,
+ &mut pt as *mut _ as *mut std::ffi::c_void,
+ )
+ };
unsafe { core_foundation::base::CFRelease(val) };
- if ok { Some((pt.x, pt.y)) } else { None }
+ if ok {
+ Some((pt.x, pt.y))
+ } else {
+ None
+ }
}
#[cfg(target_os = "macos")]
fn read_cgsize(el: accessibility_sys::AXUIElementRef, attr: &str) -> Option<(f64, f64)> {
use accessibility_sys::*;
- use core_foundation::{base::{CFTypeRef, TCFType}, string::CFString};
+ use core_foundation::{
+ base::{CFTypeRef, TCFType},
+ string::CFString,
+ };
use core_graphics::geometry::CGSize;
let key = CFString::new(attr);
let mut val: CFTypeRef = std::ptr::null_mut();
let err = unsafe { AXUIElementCopyAttributeValue(el, key.as_concrete_TypeRef(), &mut val) };
- if err != kAXErrorSuccess || val.is_null() { return None; }
+ if err != kAXErrorSuccess || val.is_null() {
+ return None;
+ }
let mut sz = CGSize::new(0.0, 0.0);
- let ok = unsafe { AXValueGetValue(val as _, kAXValueTypeCGSize, &mut sz as *mut _ as *mut std::ffi::c_void) };
+ let ok = unsafe {
+ AXValueGetValue(
+ val as _,
+ kAXValueTypeCGSize,
+ &mut sz as *mut _ as *mut std::ffi::c_void,
+ )
+ };
unsafe { core_foundation::base::CFRelease(val) };
- if ok { Some((sz.width, sz.height)) } else { None }
+ if ok {
+ Some((sz.width, sz.height))
+ } else {
+ None
+ }
}
#[cfg(target_os = "macos")]
@@ -195,12 +272,24 @@ fn cg_click(x: f64, y: f64) -> bool {
event_source::{CGEventSource, CGEventSourceStateID},
geometry::CGPoint,
};
- let src = match CGEventSource::new(CGEventSourceStateID::HIDSystemState) { Ok(s) => s, Err(_) => return false };
+ let src = match CGEventSource::new(CGEventSourceStateID::HIDSystemState) {
+ Ok(s) => s,
+ Err(_) => return false,
+ };
let pt = CGPoint::new(x, y);
- let down = CGEvent::new_mouse_event(src.clone(), CGEventType::LeftMouseDown, pt, CGMouseButton::Left);
- let up = CGEvent::new_mouse_event(src, CGEventType::LeftMouseUp, pt, CGMouseButton::Left);
+ let down = CGEvent::new_mouse_event(
+ src.clone(),
+ CGEventType::LeftMouseDown,
+ pt,
+ CGMouseButton::Left,
+ );
+ let up = CGEvent::new_mouse_event(src, CGEventType::LeftMouseUp, pt, CGMouseButton::Left);
match (down, up) {
- (Ok(d), Ok(u)) => { d.post(CGEventTapLocation::HID); u.post(CGEventTapLocation::HID); true }
+ (Ok(d), Ok(u)) => {
+ d.post(CGEventTapLocation::HID);
+ u.post(CGEventTapLocation::HID);
+ true
+ }
_ => false,
}
}
@@ -211,9 +300,15 @@ fn cg_scroll(x: f64, y: f64, dx: i32, dy: i32) -> bool {
event::{CGEvent, CGEventTapLocation, ScrollEventUnit},
event_source::{CGEventSource, CGEventSourceStateID},
};
- let src = match CGEventSource::new(CGEventSourceStateID::HIDSystemState) { Ok(s) => s, Err(_) => return false };
+ let src = match CGEventSource::new(CGEventSourceStateID::HIDSystemState) {
+ Ok(s) => s,
+ Err(_) => return false,
+ };
match CGEvent::new_scroll_event(src, ScrollEventUnit::LINE, 2, dy, dx, 0) {
- Ok(ev) => { ev.post(CGEventTapLocation::HID); true }
+ Ok(ev) => {
+ ev.post(CGEventTapLocation::HID);
+ true
+ }
Err(_) => false,
}
}
@@ -221,15 +316,29 @@ fn cg_scroll(x: f64, y: f64, dx: i32, dy: i32) -> bool {
#[cfg(target_os = "macos")]
fn speed_test(app: accessibility_sys::AXUIElementRef, pid: i32) {
use accessibility_sys::*;
- use core_foundation::{array::CFArray, base::{CFRelease, CFType, CFTypeRef, TCFType}, string::CFString};
+ use core_foundation::{
+ array::CFArray,
+ base::{CFRelease, CFType, CFTypeRef, TCFType},
+ string::CFString,
+ };
use std::time::Instant;
// Get a real window element to test on
let windows = get_ax_children(app, kAXWindowsAttribute);
- let el = if let Some(&w) = windows.first() { w } else { app };
+ let el = if let Some(&w) = windows.first() {
+ w
+ } else {
+ app
+ };
- let attrs = [kAXRoleAttribute, kAXTitleAttribute, kAXDescriptionAttribute,
- kAXValueAttribute, kAXEnabledAttribute, kAXFocusedAttribute];
+ let attrs = [
+ kAXRoleAttribute,
+ kAXTitleAttribute,
+ kAXDescriptionAttribute,
+ kAXValueAttribute,
+ kAXEnabledAttribute,
+ kAXFocusedAttribute,
+ ];
let cf_attrs: Vec<CFString> = attrs.iter().map(|a| CFString::new(a)).collect();
let cf_refs: Vec<_> = cf_attrs.iter().map(|s| s.as_concrete_TypeRef()).collect();
let names_arr = CFArray::from_copyable(&cf_refs);
@@ -238,24 +347,50 @@ fn speed_test(app: accessibility_sys::AXUIElementRef, pid: i32) {
let t = Instant::now();
for _ in 0..100 {
let mut res: CFTypeRef = std::ptr::null_mut();
- unsafe { AXUIElementCopyMultipleAttributeValues(el, names_arr.as_concrete_TypeRef(), 0, &mut res as *mut _ as *mut _) };
- if !res.is_null() { unsafe { CFRelease(res) }; }
+ unsafe {
+ AXUIElementCopyMultipleAttributeValues(
+ el,
+ names_arr.as_concrete_TypeRef(),
+ 0,
+ &mut res as *mut _ as *mut _,
+ )
+ };
+ if !res.is_null() {
+ unsafe { CFRelease(res) };
+ }
}
let multi = t.elapsed();
// Individual attrs
let t2 = Instant::now();
for _ in 0..100 {
- for attr in &attrs { let _ = read_string(el, attr); }
+ for attr in &attrs {
+ let _ = read_string(el, attr);
+ }
}
let single = t2.elapsed();
- println!(" 100x multi-attr: {:?} ({:?}/call)", multi, multi / 100);
- println!(" 100x individual: {:?} ({:?}/call)", single, single / 100);
- println!(" speedup: {:.1}x", single.as_nanos() as f64 / multi.as_nanos().max(1) as f64);
-
- for w in windows { release_ax(w); }
+ println!(
+ " 100x multi-attr: {:?} ({:?}/call)",
+ multi,
+ multi / 100
+ );
+ println!(
+ " 100x individual: {:?} ({:?}/call)",
+ single,
+ single / 100
+ );
+ println!(
+ " speedup: {:.1}x",
+ single.as_nanos() as f64 / multi.as_nanos().max(1) as f64
+ );
+
+ for w in windows {
+ release_ax(w);
+ }
}
#[cfg(not(target_os = "macos"))]
-fn main() { eprintln!("macOS only"); }
+fn main() {
+ eprintln!("macOS only");
+}
diff --git a/crates/macos/examples/axprobe.rs b/crates/macos/examples/axprobe.rs
index eb2036c24..278d5a1ee 100644
--- a/crates/macos/examples/axprobe.rs
+++ b/crates/macos/examples/axprobe.rs
@@ -24,7 +24,9 @@ fn run() {
url::CFURL,
};
- let app_name = std::env::args().nth(1).unwrap_or_else(|| "Finder".to_string());
+ let app_name = std::env::args()
+ .nth(1)
+ .unwrap_or_else(|| "Finder".to_string());
let pid = find_pid(&app_name).unwrap_or_else(|| {
eprintln!("App '{}' not running", app_name);
std::process::exit(1);
@@ -59,13 +61,15 @@ fn run() {
println!("\n Direct children: {}", children.len());
for (ci, &child) in children.iter().enumerate() {
- let role = fetch_repr(child, "AXRole");
- let subrole = fetch_repr(child, "AXSubrole");
- let title = fetch_repr(child, "AXTitle");
- let desc = fetch_repr(child, "AXDescription");
- let value = fetch_repr(child, "AXValue");
- println!("\n Child[{}] role={} subrole={} title={} desc={} value={}",
- ci, role, subrole, title, desc, value);
+ let role = fetch_repr(child, "AXRole");
+ let subrole = fetch_repr(child, "AXSubrole");
+ let title = fetch_repr(child, "AXTitle");
+ let desc = fetch_repr(child, "AXDescription");
+ let value = fetch_repr(child, "AXValue");
+ println!(
+ "\n Child[{}] role={} subrole={} title={} desc={} value={}",
+ ci, role, subrole, title, desc, value
+ );
dump_all_attrs(child, 6);
// Grandchildren
@@ -77,8 +81,10 @@ fn run() {
let t = fetch_repr(gc, "AXTitle");
let d = fetch_repr(gc, "AXDescription");
let v = fetch_repr(gc, "AXValue");
- println!(" GC[{}] role={} subrole={} title={} desc={} value={}",
- gci, r, s, t, d, v);
+ println!(
+ " GC[{}] role={} subrole={} title={} desc={} value={}",
+ gci, r, s, t, d, v
+ );
dump_all_attrs(gc, 8);
// Great-grandchildren (just roles/names)
@@ -88,8 +94,10 @@ fn run() {
let t2 = fetch_repr(el, "AXTitle");
let d2 = fetch_repr(el, "AXDescription");
let v2 = fetch_repr(el, "AXValue");
- println!(" GGC[{}] role={} title={} desc={} value={}",
- ggci, r2, t2, d2, v2);
+ println!(
+ " GGC[{}] role={} title={} desc={} value={}",
+ ggci, r2, t2, d2, v2
+ );
dump_all_attrs(el, 10);
for &gggel in copy_el_array(el, "AXChildren").iter().take(4) {
@@ -140,7 +148,10 @@ fn run() {
let t = fetch_repr(pos_el, "AXTitle");
let d = fetch_repr(pos_el, "AXDescription");
let v = fetch_repr(pos_el, "AXValue");
- println!(" ({},{}): role={} title={} desc={} value={}", x, y, r, t, d, v);
+ println!(
+ " ({},{}): role={} title={} desc={} value={}",
+ x, y, r, t, d, v
+ );
unsafe { CFRelease(pos_el as CFTypeRef) };
} else {
println!(" ({},{}): err={}", x, y, err);
@@ -178,7 +189,12 @@ fn find_pid(app_name: &str) -> Option<i32> {
.arg(app_name)
.output()
.ok()?;
- String::from_utf8_lossy(&out.stdout).lines().next()?.trim().parse().ok()
+ String::from_utf8_lossy(&out.stdout)
+ .lines()
+ .next()?
+ .trim()
+ .parse()
+ .ok()
}
#[cfg(target_os = "macos")]
@@ -239,9 +255,8 @@ fn fetch_repr(el: accessibility_sys::AXUIElementRef, attr: &str) -> String {
let cf_attr = CFString::new(attr);
let mut value: CFTypeRef = std::ptr::null_mut();
- let err = unsafe {
- AXUIElementCopyAttributeValue(el, cf_attr.as_concrete_TypeRef(), &mut value)
- };
+ let err =
+ unsafe { AXUIElementCopyAttributeValue(el, cf_attr.as_concrete_TypeRef(), &mut value) };
if err != 0 {
return format!("<err:{}>", err);
}
@@ -296,9 +311,8 @@ fn copy_el_array(
let cf_attr = CFString::new(attr);
let mut value: CFTypeRef = std::ptr::null_mut();
- let err = unsafe {
- AXUIElementCopyAttributeValue(el, cf_attr.as_concrete_TypeRef(), &mut value)
- };
+ let err =
+ unsafe { AXUIElementCopyAttributeValue(el, cf_attr.as_concrete_TypeRef(), &mut value) };
if err != 0 || value.is_null() {
return vec![];
}
@@ -339,7 +353,7 @@ fn copy_action_names(el: accessibility_sys::AXUIElementRef) -> Vec<String> {
#[cfg(target_os = "macos")]
fn test_multi_attr(el: accessibility_sys::AXUIElementRef) {
use accessibility_sys::{
- AXUIElementCopyMultipleAttributeValues, kAXCopyMultipleAttributeOptionStopOnError,
+ kAXCopyMultipleAttributeOptionStopOnError, AXUIElementCopyMultipleAttributeValues,
};
use core_foundation::{
array::CFArray,
@@ -350,13 +364,24 @@ fn test_multi_attr(el: accessibility_sys::AXUIElementRef) {
};
let test_attrs = [
- "AXRole", "AXSubrole", "AXTitle", "AXDescription", "AXValue",
- "AXEnabled", "AXFocused", "AXHelp", "AXPlaceholderValue",
+ "AXRole",
+ "AXSubrole",
+ "AXTitle",
+ "AXDescription",
+ "AXValue",
+ "AXEnabled",
+ "AXFocused",
+ "AXHelp",
+ "AXPlaceholderValue",
"AXRoleDescription",
];
for &options in &[0u32, kAXCopyMultipleAttributeOptionStopOnError] {
- let label = if options == 0 { "AllowPartial(0)" } else { "StopOnError(0x1)" };
+ let label = if options == 0 {
+ "AllowPartial(0)"
+ } else {
+ "StopOnError(0x1)"
+ };
println!(" options={}", label);
let cf_names: Vec<CFString> = test_attrs.iter().map(|a| CFString::new(a)).collect();
@@ -376,7 +401,11 @@ fn test_multi_attr(el: accessibility_sys::AXUIElementRef) {
if err == 0 && !result_ref.is_null() {
let arr = unsafe { CFArray::<CFType>::wrap_under_create_rule(result_ref as _) };
- println!(" result_count={} (requested {})", arr.len(), test_attrs.len());
+ println!(
+ " result_count={} (requested {})",
+ arr.len(),
+ test_attrs.len()
+ );
for (i, item) in arr.into_iter().enumerate() {
let name = test_attrs.get(i).unwrap_or(&"?");
let repr = if let Some(s) = item.downcast::<CFString>() {
diff --git a/crates/macos/examples/axprobe2.rs b/crates/macos/examples/axprobe2.rs
index 33b942f3e..231889540 100644
--- a/crates/macos/examples/axprobe2.rs
+++ b/crates/macos/examples/axprobe2.rs
@@ -30,7 +30,10 @@ fn run() {
let windows = copy_el_array(app_el, "AXWindows");
let win = match windows.first() {
Some(&w) => w,
- None => { eprintln!("No windows"); return; }
+ None => {
+ eprintln!("No windows");
+ return;
+ }
};
unsafe { AXUIElementSetMessagingTimeout(win, 5.0) };
@@ -54,7 +57,9 @@ fn run() {
for (i, &row) in rows.iter().enumerate().take(8) {
dump_element(row, i, 2);
}
- for &row in &rows { unsafe { CFRelease(row as CFTypeRef) }; }
+ for &row in &rows {
+ unsafe { CFRelease(row as CFTypeRef) };
+ }
unsafe { CFRelease(outline as CFTypeRef) };
} else {
println!("Could not find sidebar outline");
@@ -80,14 +85,22 @@ fn run() {
dump_all_attrs(col, 4);
let col_rows = copy_el_array(col, "AXRows");
let col_children = copy_el_array(col, "AXChildren");
- println!(" AXRows={} AXChildren={}", col_rows.len(), col_children.len());
+ println!(
+ " AXRows={} AXChildren={}",
+ col_rows.len(),
+ col_children.len()
+ );
// Probe first few rows
for (ri, &row) in col_rows.iter().enumerate().take(6) {
dump_element(row, ri, 6);
}
- for &row in &col_rows { unsafe { CFRelease(row as CFTypeRef) }; }
- for &child in &col_children { unsafe { CFRelease(child as CFTypeRef) }; }
+ for &row in &col_rows {
+ unsafe { CFRelease(row as CFTypeRef) };
+ }
+ for &child in &col_children {
+ unsafe { CFRelease(child as CFTypeRef) };
+ }
unsafe { CFRelease(col as CFTypeRef) };
}
@@ -114,13 +127,19 @@ fn run() {
for (s2i, &s2) in sc2.iter().enumerate().take(6) {
dump_element(s2, s2i, 10);
}
- for &s2 in &sc2 { unsafe { CFRelease(s2 as CFTypeRef) }; }
+ for &s2 in &sc2 {
+ unsafe { CFRelease(s2 as CFTypeRef) };
+ }
+ unsafe { CFRelease(sc as CFTypeRef) };
+ }
+ for &sc in &sc_children {
unsafe { CFRelease(sc as CFTypeRef) };
}
- for &sc in &sc_children { unsafe { CFRelease(sc as CFTypeRef) }; }
unsafe { CFRelease(gc as CFTypeRef) };
}
- for &gc in &gchildren { unsafe { CFRelease(gc as CFTypeRef) }; }
+ for &gc in &gchildren {
+ unsafe { CFRelease(gc as CFTypeRef) };
+ }
unsafe { CFRelease(child as CFTypeRef) };
}
@@ -141,12 +160,16 @@ fn run() {
println!("Testing on first sidebar AXRow:");
test_multi_attr_extended(row);
}
- for &row in &rows { unsafe { CFRelease(row as CFTypeRef) }; }
+ for &row in &rows {
+ unsafe { CFRelease(row as CFTypeRef) };
+ }
unsafe { CFRelease(outline as CFTypeRef) };
}
// Cleanup
- for &win2 in &windows { unsafe { CFRelease(win2 as CFTypeRef) }; }
+ for &win2 in &windows {
+ unsafe { CFRelease(win2 as CFTypeRef) };
+ }
unsafe { CFRelease(app_el as CFTypeRef) };
}
@@ -156,14 +179,16 @@ fn run() {
fn dump_element(el: accessibility_sys::AXUIElementRef, idx: usize, indent: usize) {
use core_foundation::base::{CFRelease, CFTypeRef};
let pad = " ".repeat(indent);
- let role = fetch_str(el, "AXRole");
- let sub = fetch_str(el, "AXSubrole");
+ let role = fetch_str(el, "AXRole");
+ let sub = fetch_str(el, "AXSubrole");
let title = fetch_str(el, "AXTitle");
- let desc = fetch_str(el, "AXDescription");
- let val = fetch_str(el, "AXValue");
- let help = fetch_str(el, "AXHelp");
- println!("{}[{}] role={} subrole={} title={} desc={} value={} help={}",
- pad, idx, role, sub, title, desc, val, help);
+ let desc = fetch_str(el, "AXDescription");
+ let val = fetch_str(el, "AXValue");
+ let help = fetch_str(el, "AXHelp");
+ println!(
+ "{}[{}] role={} subrole={} title={} desc={} value={} help={}",
+ pad, idx, role, sub, title, desc, val, help
+ );
dump_all_attrs(el, indent + 2);
let children = copy_el_array(el, "AXChildren");
@@ -172,7 +197,10 @@ fn dump_element(el: accessibility_sys::AXUIElementRef, idx: usize, indent: usize
let ct = fetch_str(child, "AXTitle");
let cd = fetch_str(child, "AXDescription");
let cv = fetch_str(child, "AXValue");
- println!("{} child[{}] role={} title={} desc={} value={}", pad, ci, cr, ct, cd, cv);
+ println!(
+ "{} child[{}] role={} title={} desc={} value={}",
+ pad, ci, cr, ct, cd, cv
+ );
dump_all_attrs(child, indent + 4);
let gchildren = copy_el_array(child, "AXChildren");
@@ -181,7 +209,10 @@ fn dump_element(el: accessibility_sys::AXUIElementRef, idx: usize, indent: usize
let gt = fetch_str(gc, "AXTitle");
let gd = fetch_str(gc, "AXDescription");
let gv = fetch_str(gc, "AXValue");
- println!("{} gc[{}] role={} title={} desc={} value={}", pad, gi, gr, gt, gd, gv);
+ println!(
+ "{} gc[{}] role={} title={} desc={} value={}",
+ pad, gi, gr, gt, gd, gv
+ );
dump_all_attrs(gc, indent + 6);
unsafe { CFRelease(gc as CFTypeRef) };
}
@@ -191,7 +222,9 @@ fn dump_element(el: accessibility_sys::AXUIElementRef, idx: usize, indent: usize
#[cfg(target_os = "macos")]
fn test_multi_attr_extended(el: accessibility_sys::AXUIElementRef) {
- use accessibility_sys::{AXUIElementCopyMultipleAttributeValues, AXUIElementCopyAttributeNames};
+ use accessibility_sys::{
+ AXUIElementCopyAttributeNames, AXUIElementCopyMultipleAttributeValues,
+ };
use core_foundation::{
array::CFArray,
base::{CFType, CFTypeRef, TCFType},
@@ -203,9 +236,12 @@ fn test_multi_attr_extended(el: accessibility_sys::AXUIElementRef) {
// First, get ALL attribute names for this element
let mut names_ref: core_foundation_sys::array::CFArrayRef = std::ptr::null_mut();
let err = unsafe { AXUIElementCopyAttributeNames(el, &mut names_ref) };
- if err != 0 || names_ref.is_null() { return; }
+ if err != 0 || names_ref.is_null() {
+ return;
+ }
let name_arr = unsafe { CFArray::<CFType>::wrap_under_create_rule(names_ref as _) };
- let all_names: Vec<String> = name_arr.into_iter()
+ let all_names: Vec<String> = name_arr
+ .into_iter()
.filter_map(|item| item.downcast::<CFString>().map(|s| s.to_string()))
.collect();
@@ -219,7 +255,9 @@ fn test_multi_attr_extended(el: accessibility_sys::AXUIElementRef) {
let mut result: CFTypeRef = std::ptr::null_mut();
let err2 = unsafe {
AXUIElementCopyMultipleAttributeValues(
- el, names_arr2.as_concrete_TypeRef(), 0,
+ el,
+ names_arr2.as_concrete_TypeRef(),
+ 0,
&mut result as *mut _ as *mut _,
)
};
@@ -246,8 +284,17 @@ fn test_multi_attr_extended(el: accessibility_sys::AXUIElementRef) {
#[cfg(target_os = "macos")]
fn find_pid(name: &str) -> Option<i32> {
- let out = std::process::Command::new("pgrep").arg("-x").arg(name).output().ok()?;
- String::from_utf8_lossy(&out.stdout).lines().next()?.trim().parse().ok()
+ let out = std::process::Command::new("pgrep")
+ .arg("-x")
+ .arg(name)
+ .output()
+ .ok()?;
+ String::from_utf8_lossy(&out.stdout)
+ .lines()
+ .next()?
+ .trim()
+ .parse()
+ .ok()
}
#[cfg(target_os = "macos")]
@@ -267,29 +314,45 @@ fn fetch_str(el: accessibility_sys::AXUIElementRef, attr: &str) -> String {
let cf_attr = CFString::new(attr);
let mut value: CFTypeRef = std::ptr::null_mut();
- let err = unsafe {
- AXUIElementCopyAttributeValue(el, cf_attr.as_concrete_TypeRef(), &mut value)
- };
- if err != 0 { return format!("<err:{}>", err); }
- if value.is_null() { return "<null>".to_string(); }
+ let err =
+ unsafe { AXUIElementCopyAttributeValue(el, cf_attr.as_concrete_TypeRef(), &mut value) };
+ if err != 0 {
+ return format!("<err:{}>", err);
+ }
+ if value.is_null() {
+ return "<null>".to_string();
+ }
let cf = unsafe { CFType::wrap_under_create_rule(value) };
- if let Some(s) = cf.downcast::<CFString>() { return format!("\"{}\"", s.to_string()); }
- if let Some(b) = cf.downcast::<CFBoolean>() { return format!("bool:{}", bool::from(b)); }
- if let Some(n) = cf.downcast::<CFNumber>() { return format!("num:{}", n.to_i64().unwrap_or(-1)); }
+ if let Some(s) = cf.downcast::<CFString>() {
+ return format!("\"{}\"", s.to_string());
+ }
+ if let Some(b) = cf.downcast::<CFBoolean>() {
+ return format!("bool:{}", bool::from(b));
+ }
+ if let Some(n) = cf.downcast::<CFNumber>() {
+ return format!("num:{}", n.to_i64().unwrap_or(-1));
+ }
format!("cftype:{}", cf.type_of())
}
#[cfg(target_os = "macos")]
fn dump_all_attrs(el: accessibility_sys::AXUIElementRef, indent: usize) {
use accessibility_sys::AXUIElementCopyAttributeNames;
- use core_foundation::{array::CFArray, base::{CFType, TCFType}, string::CFString};
+ use core_foundation::{
+ array::CFArray,
+ base::{CFType, TCFType},
+ string::CFString,
+ };
let pad = " ".repeat(indent);
let mut names_ref: core_foundation_sys::array::CFArrayRef = std::ptr::null_mut();
let err = unsafe { AXUIElementCopyAttributeNames(el, &mut names_ref) };
- if err != 0 || names_ref.is_null() { return; }
+ if err != 0 || names_ref.is_null() {
+ return;
+ }
let arr = unsafe { CFArray::<CFType>::wrap_under_create_rule(names_ref as _) };
- let names: Vec<String> = arr.into_iter()
+ let names: Vec<String> = arr
+ .into_iter()
.filter_map(|item| item.downcast::<CFString>().map(|s| s.to_string()))
.collect();
for name in &names {
@@ -312,16 +375,18 @@ fn copy_el_array(
let cf_attr = CFString::new(attr);
let mut value: CFTypeRef = std::ptr::null_mut();
- let err = unsafe {
- AXUIElementCopyAttributeValue(el, cf_attr.as_concrete_TypeRef(), &mut value)
- };
- if err != 0 || value.is_null() { return vec![]; }
+ let err =
+ unsafe { AXUIElementCopyAttributeValue(el, cf_attr.as_concrete_TypeRef(), &mut value) };
+ if err != 0 || value.is_null() {
+ return vec![];
+ }
let arr = unsafe { CFArray::<CFType>::wrap_under_create_rule(value as _) };
arr.into_iter()
.filter_map(|item| {
let ptr = item.as_concrete_TypeRef() as accessibility_sys::AXUIElementRef;
- if ptr.is_null() { None }
- else {
+ if ptr.is_null() {
+ None
+ } else {
unsafe { CFRetain(ptr as CFTypeRef) };
Some(ptr)
}
@@ -337,7 +402,9 @@ fn find_by_desc(
depth: u32,
) -> Option<accessibility_sys::AXUIElementRef> {
use core_foundation::base::{CFRetain, CFTypeRef};
- if depth > 8 { return None; }
+ if depth > 8 {
+ return None;
+ }
let d = fetch_str(el, "AXDescription");
if d == format!("\"{}\"", desc) {
unsafe { CFRetain(el as CFTypeRef) };
@@ -360,8 +427,10 @@ fn find_by_role(
role: &str,
depth: u32,
) -> Option<accessibility_sys::AXUIElementRef> {
- use core_foundation::base::{CFRetain, CFRelease, CFTypeRef};
- if depth > 8 { return None; }
+ use core_foundation::base::{CFRelease, CFRetain, CFTypeRef};
+ if depth > 8 {
+ return None;
+ }
let r = fetch_str(el, "AXRole");
if r == format!("\"{}\"", role) {
unsafe { CFRetain(el as CFTypeRef) };
diff --git a/crates/macos/src/action_extras.rs b/crates/macos/src/action_extras.rs
index 066cb9bfa..c90e211b1 100644
--- a/crates/macos/src/action_extras.rs
+++ b/crates/macos/src/action_extras.rs
@@ -126,9 +126,8 @@ pub(crate) fn ax_scroll(
if let Some(scroll_bar) = get_scroll_bar(target, bar_orientation) {
let ax_action = CFString::new(action_name);
for _ in 0..amount {
- let err = unsafe {
- AXUIElementPerformAction(scroll_bar.0, ax_action.as_concrete_TypeRef())
- };
+ let err =
+ unsafe { AXUIElementPerformAction(scroll_bar.0, ax_action.as_concrete_TypeRef()) };
if err != kAXErrorSuccess {
return Err(AdapterError::new(
ErrorCode::ActionFailed,
diff --git a/crates/macos/src/actions.rs b/crates/macos/src/actions.rs
index bd76f7bef..fdb3b4c68 100644
--- a/crates/macos/src/actions.rs
+++ b/crates/macos/src/actions.rs
@@ -27,7 +27,8 @@ mod imp {
Action::DoubleClick => {
let open_action = CFString::new("AXOpen");
- let err = unsafe { AXUIElementPerformAction(el.0, open_action.as_concrete_TypeRef()) };
+ let err =
+ unsafe { AXUIElementPerformAction(el.0, open_action.as_concrete_TypeRef()) };
if err != kAXErrorSuccess {
ax_press_or_fail(el, "double-click (first press)")?;
std::thread::sleep(std::time::Duration::from_millis(50));
@@ -37,7 +38,8 @@ mod imp {
Action::RightClick => {
let ax_action = CFString::new("AXShowMenu");
- let err = unsafe { AXUIElementPerformAction(el.0, ax_action.as_concrete_TypeRef()) };
+ let err =
+ unsafe { AXUIElementPerformAction(el.0, ax_action.as_concrete_TypeRef()) };
if err != kAXErrorSuccess {
return Err(AdapterError::new(
ErrorCode::ActionFailed,
@@ -50,8 +52,12 @@ mod imp {
Action::Toggle => {
let role = element_role(el);
let toggle_roles = [
- "checkbox", "switch", "radiobutton", "togglebutton",
- "menuitemcheckbox", "menuitemradio",
+ "checkbox",
+ "switch",
+ "radiobutton",
+ "togglebutton",
+ "menuitemcheckbox",
+ "menuitemradio",
];
if !toggle_roles.iter().any(|r| role.as_deref() == Some(*r)) {
return Err(AdapterError::new(
@@ -169,7 +175,8 @@ mod imp {
Action::ScrollTo => {
let ax_action = CFString::new("AXScrollToVisible");
- let err = unsafe { AXUIElementPerformAction(el.0, ax_action.as_concrete_TypeRef()) };
+ let err =
+ unsafe { AXUIElementPerformAction(el.0, ax_action.as_concrete_TypeRef()) };
if err != kAXErrorSuccess {
return Err(AdapterError::new(
ErrorCode::ActionFailed,
@@ -186,7 +193,10 @@ mod imp {
Action::KeyDown(_) | Action::KeyUp(_) | Action::Hover | Action::Drag(_) => {
return Err(AdapterError::new(
ErrorCode::ActionNotSupported,
- format!("{} requires adapter-level handling, not element action", label),
+ format!(
+ "{} requires adapter-level handling, not element action",
+ label
+ ),
));
}
@@ -214,11 +224,7 @@ mod imp {
let cf_attr = CFString::new(kAXValueAttribute);
let cf_val = CFString::new(val);
let err = unsafe {
- AXUIElementSetAttributeValue(
- el.0,
- cf_attr.as_concrete_TypeRef(),
- cf_val.as_CFTypeRef(),
- )
+ AXUIElementSetAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), cf_val.as_CFTypeRef())
};
if err != kAXErrorSuccess {
return Err(AdapterError::new(
@@ -255,7 +261,14 @@ mod imp {
fn check_uncheck(el: &AXElement, want_checked: bool) -> Result<(), AdapterError> {
let role = element_role(el);
- let valid_roles = ["checkbox", "switch", "radiobutton", "togglebutton", "menuitemcheckbox", "menuitemradio"];
+ let valid_roles = [
+ "checkbox",
+ "switch",
+ "radiobutton",
+ "togglebutton",
+ "menuitemcheckbox",
+ "menuitemradio",
+ ];
if !valid_roles.iter().any(|r| role.as_deref() == Some(*r)) {
return Err(AdapterError::new(
ErrorCode::ActionNotSupported,
diff --git a/crates/macos/src/adapter.rs b/crates/macos/src/adapter.rs
index 4a37f4baf..719544037 100644
--- a/crates/macos/src/adapter.rs
+++ b/crates/macos/src/adapter.rs
@@ -117,7 +117,10 @@ impl PlatformAdapter for MacOSAdapter {
}
fn focused_window(&self) -> Result<Option<WindowInfo>, AdapterError> {
- let filter = WindowFilter { focused_only: true, app: None };
+ let filter = WindowFilter {
+ focused_only: true,
+ app: None,
+ };
let windows = self.list_windows(&filter)?;
Ok(windows.into_iter().next())
}
@@ -125,10 +128,12 @@ impl PlatformAdapter for MacOSAdapter {
fn get_live_value(&self, handle: &NativeHandle) -> Result<Option<String>, AdapterError> {
#[cfg(target_os = "macos")]
{
- use accessibility_sys::kAXValueAttribute;
use crate::tree::AXElement;
+ use accessibility_sys::kAXValueAttribute;
use std::mem::ManuallyDrop;
- let el = ManuallyDrop::new(AXElement(handle.as_raw() as accessibility_sys::AXUIElementRef));
+ let el = ManuallyDrop::new(AXElement(
+ handle.as_raw() as accessibility_sys::AXUIElementRef
+ ));
Ok(crate::tree::copy_string_attr(&el, kAXValueAttribute))
}
#[cfg(not(target_os = "macos"))]
@@ -140,7 +145,9 @@ impl PlatformAdapter for MacOSAdapter {
{
use crate::tree::AXElement;
use std::mem::ManuallyDrop;
- let el = ManuallyDrop::new(AXElement(handle.as_raw() as accessibility_sys::AXUIElementRef));
+ let el = ManuallyDrop::new(AXElement(
+ handle.as_raw() as accessibility_sys::AXUIElementRef
+ ));
Ok(crate::tree::read_bounds(&el))
}
#[cfg(not(target_os = "macos"))]
@@ -168,16 +175,24 @@ impl PlatformAdapter for MacOSAdapter {
}
#[cfg(target_os = "macos")]
-fn execute_action_impl(handle: &NativeHandle, action: Action) -> Result<ActionResult, AdapterError> {
+fn execute_action_impl(
+ handle: &NativeHandle,
+ action: Action,
+) -> Result<ActionResult, AdapterError> {
use crate::tree::AXElement;
use std::mem::ManuallyDrop;
- let el = ManuallyDrop::new(AXElement(handle.as_raw() as accessibility_sys::AXUIElementRef));
+ let el = ManuallyDrop::new(AXElement(
+ handle.as_raw() as accessibility_sys::AXUIElementRef
+ ));
crate::actions::perform_action(&el, &action)
}
#[cfg(not(target_os = "macos"))]
-fn execute_action_impl(_handle: &NativeHandle, _action: Action) -> Result<ActionResult, AdapterError> {
+fn execute_action_impl(
+ _handle: &NativeHandle,
+ _action: Action,
+) -> Result<ActionResult, AdapterError> {
Err(AdapterError::not_supported("execute_action"))
}
@@ -204,7 +219,10 @@ fn find_element_recursive(
}
let ax_role = crate::tree::copy_string_attr(el, kAXRoleAttribute);
- let normalized = ax_role.as_deref().map(crate::roles::ax_role_to_str).unwrap_or("unknown");
+ let normalized = ax_role
+ .as_deref()
+ .map(crate::roles::ax_role_to_str)
+ .unwrap_or("unknown");
if normalized == entry.role {
let elem_name = crate::tree::resolve_element_name(el);
@@ -223,7 +241,11 @@ fn find_element_recursive(
return Err(AdapterError::element_not_found("element"));
}
- let child_attr = if ax_role.as_deref() == Some("AXBrowser") { "AXColumns" } else { "AXChildren" };
+ let child_attr = if ax_role.as_deref() == Some("AXBrowser") {
+ "AXColumns"
+ } else {
+ "AXChildren"
+ };
let children = crate::tree::copy_ax_array(el, child_attr)
.filter(|v| !v.is_empty())
.or_else(|| crate::tree::copy_ax_array(el, "AXContents").filter(|v| !v.is_empty()))
@@ -252,8 +274,8 @@ pub fn list_windows_impl(filter: &WindowFilter) -> Result<Vec<WindowInfo>, Adapt
use core_foundation_sys::dictionary::CFDictionaryGetValue;
use core_graphics::display::CGDisplay;
use core_graphics::window::{
- kCGWindowLayer, kCGWindowListOptionOnScreenOnly, kCGWindowName,
- kCGWindowOwnerName, kCGWindowOwnerPID,
+ kCGWindowLayer, kCGWindowListOptionOnScreenOnly, kCGWindowName, kCGWindowOwnerName,
+ kCGWindowOwnerPID,
};
use rustc_hash::FxHasher;
use std::ffi::c_void;
@@ -261,14 +283,22 @@ pub fn list_windows_impl(filter: &WindowFilter) -> Result<Vec<WindowInfo>, Adapt
unsafe fn dict_string(dict: *const c_void, key: *const c_void) -> Option<String> {
let val = CFDictionaryGetValue(dict as _, key);
- if val.is_null() { return None; }
- CFType::wrap_under_get_rule(val as _).downcast::<CFString>().map(|s| s.to_string())
+ if val.is_null() {
+ return None;
+ }
+ CFType::wrap_under_get_rule(val as _)
+ .downcast::<CFString>()
+ .map(|s| s.to_string())
}
unsafe fn dict_i64(dict: *const c_void, key: *const c_void) -> Option<i64> {
let val = CFDictionaryGetValue(dict as _, key);
- if val.is_null() { return None; }
- CFType::wrap_under_get_rule(val as _).downcast::<CFNumber>().and_then(|n| n.to_i64())
+ if val.is_null() {
+ return None;
+ }
+ CFType::wrap_under_get_rule(val as _)
+ .downcast::<CFNumber>()
+ .and_then(|n| n.to_i64())
}
let arr = match CGDisplay::window_list_info(kCGWindowListOptionOnScreenOnly, None) {
@@ -280,9 +310,13 @@ pub fn list_windows_impl(filter: &WindowFilter) -> Result<Vec<WindowInfo>, Adapt
let mut windows = Vec::new();
for raw in arr.get_all_values() {
- if raw.is_null() { continue; }
+ if raw.is_null() {
+ continue;
+ }
let layer = unsafe { dict_i64(raw, kCGWindowLayer as _) }.unwrap_or(99);
- if layer != 0 { continue; }
+ if layer != 0 {
+ continue;
+ }
let app_name = match unsafe { dict_string(raw, kCGWindowOwnerName as _) } {
Some(n) if !n.is_empty() => n,
@@ -342,30 +376,54 @@ fn list_apps_impl() -> Result<Vec<AppInfo>, AdapterError> {
let mut apps = Vec::new();
for raw in arr.get_all_values() {
- if raw.is_null() { continue; }
+ if raw.is_null() {
+ continue;
+ }
let layer = unsafe {
let v = CFDictionaryGetValue(raw as _, kCGWindowLayer as _);
- if v.is_null() { continue; }
- CFType::wrap_under_get_rule(v as _).downcast::<CFNumber>().and_then(|n| n.to_i64()).unwrap_or(99)
+ if v.is_null() {
+ continue;
+ }
+ CFType::wrap_under_get_rule(v as _)
+ .downcast::<CFNumber>()
+ .and_then(|n| n.to_i64())
+ .unwrap_or(99)
};
- if layer != 0 { continue; }
+ if layer != 0 {
+ continue;
+ }
let pid = unsafe {
let v = CFDictionaryGetValue(raw as _, kCGWindowOwnerPID as _);
- if v.is_null() { continue; }
- CFType::wrap_under_get_rule(v as _).downcast::<CFNumber>().and_then(|n| n.to_i64()).unwrap_or(0) as i32
+ if v.is_null() {
+ continue;
+ }
+ CFType::wrap_under_get_rule(v as _)
+ .downcast::<CFNumber>()
+ .and_then(|n| n.to_i64())
+ .unwrap_or(0) as i32
};
- if !seen_pids.insert(pid) { continue; }
+ if !seen_pids.insert(pid) {
+ continue;
+ }
let name = unsafe {
let v = CFDictionaryGetValue(raw as _, kCGWindowOwnerName as _);
- if v.is_null() { continue; }
- CFType::wrap_under_get_rule(v as _).downcast::<CFString>().map(|s| s.to_string())
+ if v.is_null() {
+ continue;
+ }
+ CFType::wrap_under_get_rule(v as _)
+ .downcast::<CFString>()
+ .map(|s| s.to_string())
};
if let Some(n) = name {
- apps.push(AppInfo { name: n, pid, bundle_id: None });
+ apps.push(AppInfo {
+ name: n,
+ pid,
+ bundle_id: None,
+ });
}
}
Ok(apps)
diff --git a/crates/macos/src/app_ops.rs b/crates/macos/src/app_ops.rs
index ddb09563f..8d6b18010 100644
--- a/crates/macos/src/app_ops.rs
+++ b/crates/macos/src/app_ops.rs
@@ -1,8 +1,4 @@
-use agent_desktop_core::{
- adapter::WindowFilter,
- error::AdapterError,
- node::WindowInfo,
-};
+use agent_desktop_core::{adapter::WindowFilter, error::AdapterError, node::WindowInfo};
#[cfg(target_os = "macos")]
pub fn focus_window_impl(win: &WindowInfo) -> Result<(), AdapterError> {
@@ -66,7 +62,10 @@ pub fn launch_app_impl(id: &str, timeout_ms: u64) -> Result<WindowInfo, AdapterE
));
}
- let filter = WindowFilter { focused_only: false, app: Some(id.to_string()) };
+ let filter = WindowFilter {
+ focused_only: false,
+ app: Some(id.to_string()),
+ };
if let Ok(wins) = list_windows_impl(&filter) {
if let Some(win) = wins.into_iter().next() {
return Ok(win);
@@ -86,7 +85,10 @@ pub fn launch_app_impl(id: &str, timeout_ms: u64) -> Result<WindowInfo, AdapterE
loop {
std::thread::sleep(poll_interval);
- let filter = WindowFilter { focused_only: false, app: Some(id.to_string()) };
+ let filter = WindowFilter {
+ focused_only: false,
+ app: Some(id.to_string()),
+ };
if let Ok(wins) = list_windows_impl(&filter) {
if let Some(win) = wins.into_iter().next() {
return Ok(win);
@@ -162,10 +164,7 @@ fn try_quit_via_menu_bar(app_el: &crate::tree::AXElement) -> bool {
if t.contains("Quit") || t.contains("quit") {
let press = CFString::new("AXPress");
let err = unsafe {
- AXUIElementPerformAction(
- item.0,
- press.as_concrete_TypeRef(),
- )
+ AXUIElementPerformAction(item.0, press.as_concrete_TypeRef())
};
return err == kAXErrorSuccess;
}
diff --git a/crates/macos/src/input.rs b/crates/macos/src/input.rs
index ea15b5eed..4f86c179d 100644
--- a/crates/macos/src/input.rs
+++ b/crates/macos/src/input.rs
@@ -12,7 +12,9 @@ mod imp {
let sys_wide = unsafe { AXUIElementCreateSystemWide() };
if sys_wide.is_null() {
- return Err(AdapterError::internal("Failed to create system-wide AX element"));
+ return Err(AdapterError::internal(
+ "Failed to create system-wide AX element",
+ ));
}
if !combo.modifiers.is_empty() {
@@ -54,7 +56,9 @@ mod imp {
pub fn synthesize_text(text: &str) -> Result<(), AdapterError> {
let sys_wide = unsafe { AXUIElementCreateSystemWide() };
if sys_wide.is_null() {
- return Err(AdapterError::internal("Failed to create system-wide AX element"));
+ return Err(AdapterError::internal(
+ "Failed to create system-wide AX element",
+ ));
}
for ch in text.chars() {
@@ -107,22 +111,68 @@ mod imp {
fn is_shifted_char(ch: char) -> bool {
matches!(
ch,
- '!' | '@' | '#' | '$' | '%' | '^' | '&' | '*' | '(' | ')' | '_' | '+' | '{' | '}'
- | '|' | ':' | '"' | '<' | '>' | '?' | '~'
+ '!' | '@'
+ | '#'
+ | '$'
+ | '%'
+ | '^'
+ | '&'
+ | '*'
+ | '('
+ | ')'
+ | '_'
+ | '+'
+ | '{'
+ | '}'
+ | '|'
+ | ':'
+ | '"'
+ | '<'
+ | '>'
+ | '?'
+ | '~'
)
}
fn char_to_keycode(ch: char) -> Option<u16> {
let lower = ch.to_ascii_lowercase();
Some(match lower {
- 'a' => 0, 'b' => 11, 'c' => 8, 'd' => 2, 'e' => 14, 'f' => 3,
- 'g' => 5, 'h' => 4, 'i' => 34, 'j' => 38, 'k' => 40, 'l' => 37,
- 'm' => 46, 'n' => 45, 'o' => 31, 'p' => 35, 'q' => 12, 'r' => 15,
- 's' => 1, 't' => 17, 'u' => 32, 'v' => 9, 'w' => 13, 'x' => 7,
- 'y' => 16, 'z' => 6,
- '0' | ')' => 29, '1' | '!' => 18, '2' | '@' => 19, '3' | '#' => 20,
- '4' | '$' => 21, '5' | '%' => 23, '6' | '^' => 22, '7' | '&' => 26,
- '8' | '*' => 28, '9' | '(' => 25,
+ 'a' => 0,
+ 'b' => 11,
+ 'c' => 8,
+ 'd' => 2,
+ 'e' => 14,
+ 'f' => 3,
+ 'g' => 5,
+ 'h' => 4,
+ 'i' => 34,
+ 'j' => 38,
+ 'k' => 40,
+ 'l' => 37,
+ 'm' => 46,
+ 'n' => 45,
+ 'o' => 31,
+ 'p' => 35,
+ 'q' => 12,
+ 'r' => 15,
+ 's' => 1,
+ 't' => 17,
+ 'u' => 32,
+ 'v' => 9,
+ 'w' => 13,
+ 'x' => 7,
+ 'y' => 16,
+ 'z' => 6,
+ '0' | ')' => 29,
+ '1' | '!' => 18,
+ '2' | '@' => 19,
+ '3' | '#' => 20,
+ '4' | '$' => 21,
+ '5' | '%' => 23,
+ '6' | '^' => 22,
+ '7' | '&' => 26,
+ '8' | '*' => 28,
+ '9' | '(' => 25,
' ' => 49,
'-' | '_' => 27,
'=' | '+' => 24,
@@ -142,13 +192,42 @@ mod imp {
fn key_name_to_code(key: &str) -> Result<u16, AdapterError> {
let code = match key {
- "a" => 0, "b" => 11, "c" => 8, "d" => 2, "e" => 14, "f" => 3,
- "g" => 5, "h" => 4, "i" => 34, "j" => 38, "k" => 40, "l" => 37,
- "m" => 46, "n" => 45, "o" => 31, "p" => 35, "q" => 12, "r" => 15,
- "s" => 1, "t" => 17, "u" => 32, "v" => 9, "w" => 13, "x" => 7,
- "y" => 16, "z" => 6,
- "0" => 29, "1" => 18, "2" => 19, "3" => 20, "4" => 21,
- "5" => 23, "6" => 22, "7" => 26, "8" => 28, "9" => 25,
+ "a" => 0,
+ "b" => 11,
+ "c" => 8,
+ "d" => 2,
+ "e" => 14,
+ "f" => 3,
+ "g" => 5,
+ "h" => 4,
+ "i" => 34,
+ "j" => 38,
+ "k" => 40,
+ "l" => 37,
+ "m" => 46,
+ "n" => 45,
+ "o" => 31,
+ "p" => 35,
+ "q" => 12,
+ "r" => 15,
+ "s" => 1,
+ "t" => 17,
+ "u" => 32,
+ "v" => 9,
+ "w" => 13,
+ "x" => 7,
+ "y" => 16,
+ "z" => 6,
+ "0" => 29,
+ "1" => 18,
+ "2" => 19,
+ "3" => 20,
+ "4" => 21,
+ "5" => 23,
+ "6" => 22,
+ "7" => 26,
+ "8" => 28,
+ "9" => 25,
"return" | "enter" => 36,
"escape" | "esc" => 53,
"tab" => 48,
@@ -159,10 +238,22 @@ mod imp {
"end" => 119,
"pageup" => 116,
"pagedown" => 121,
- "left" => 123, "right" => 124, "down" => 125, "up" => 126,
- "f1" => 122, "f2" => 120, "f3" => 99, "f4" => 118,
- "f5" => 96, "f6" => 97, "f7" => 98, "f8" => 100,
- "f9" => 101, "f10" => 109, "f11" => 103, "f12" => 111,
+ "left" => 123,
+ "right" => 124,
+ "down" => 125,
+ "up" => 126,
+ "f1" => 122,
+ "f2" => 120,
+ "f3" => 99,
+ "f4" => 118,
+ "f5" => 96,
+ "f6" => 97,
+ "f7" => 98,
+ "f8" => 100,
+ "f9" => 101,
+ "f10" => 109,
+ "f11" => 103,
+ "f12" => 111,
other => {
return Err(AdapterError::new(
agent_desktop_core::error::ErrorCode::InvalidArgs,
diff --git a/crates/macos/src/key_dispatch.rs b/crates/macos/src/key_dispatch.rs
index 38f627278..6c57fadc8 100644
--- a/crates/macos/src/key_dispatch.rs
+++ b/crates/macos/src/key_dispatch.rs
@@ -4,10 +4,7 @@ use agent_desktop_core::{
};
#[cfg(target_os = "macos")]
-use agent_desktop_core::{
- action::Modifier,
- adapter::WindowFilter,
-};
+use agent_desktop_core::{action::Modifier, adapter::WindowFilter};
#[cfg(target_os = "macos")]
pub fn press_for_app_impl(app_name: &str, combo: &KeyCombo) -> Result<ActionResult, AdapterError> {
@@ -116,23 +113,17 @@ fn try_menu_bar_shortcut(
for menu_group in &menu {
if let Some(items) = crate::tree::copy_ax_array(menu_group, "AXChildren") {
for item in &items {
- let cmd_char =
- crate::tree::copy_string_attr(item, "AXMenuItemCmdChar");
+ let cmd_char = crate::tree::copy_string_attr(item, "AXMenuItemCmdChar");
let cmd_mods = read_menu_item_modifiers(item);
if let Some(ch) = &cmd_char {
if ch.to_uppercase() == target_char && cmd_mods == target_mods {
let press = CFString::new("AXPress");
let err = unsafe {
- AXUIElementPerformAction(
- item.0,
- press.as_concrete_TypeRef(),
- )
+ AXUIElementPerformAction(item.0, press.as_concrete_TypeRef())
};
if err == kAXErrorSuccess {
- return Some(Ok(ActionResult::new(
- "press_key".to_string(),
- )));
+ return Some(Ok(ActionResult::new("press_key".to_string())));
}
}
}
@@ -151,9 +142,8 @@ fn read_menu_item_modifiers(el: &crate::tree::AXElement) -> u32 {
let attr = CFString::new("AXMenuItemCmdModifiers");
let mut value: core_foundation_sys::base::CFTypeRef = std::ptr::null_mut();
- let err = unsafe {
- AXUIElementCopyAttributeValue(el.0, attr.as_concrete_TypeRef(), &mut value)
- };
+ let err =
+ unsafe { AXUIElementCopyAttributeValue(el.0, attr.as_concrete_TypeRef(), &mut value) };
if err != kAXErrorSuccess || value.is_null() {
return 0;
}
@@ -235,13 +225,42 @@ fn format_combo(combo: &KeyCombo) -> String {
#[cfg(target_os = "macos")]
fn key_to_keycode(key: &str) -> Option<u16> {
Some(match key {
- "a" => 0, "b" => 11, "c" => 8, "d" => 2, "e" => 14, "f" => 3,
- "g" => 5, "h" => 4, "i" => 34, "j" => 38, "k" => 40, "l" => 37,
- "m" => 46, "n" => 45, "o" => 31, "p" => 35, "q" => 12, "r" => 15,
- "s" => 1, "t" => 17, "u" => 32, "v" => 9, "w" => 13, "x" => 7,
- "y" => 16, "z" => 6,
- "0" => 29, "1" => 18, "2" => 19, "3" => 20, "4" => 21,
- "5" => 23, "6" => 22, "7" => 26, "8" => 28, "9" => 25,
+ "a" => 0,
+ "b" => 11,
+ "c" => 8,
+ "d" => 2,
+ "e" => 14,
+ "f" => 3,
+ "g" => 5,
+ "h" => 4,
+ "i" => 34,
+ "j" => 38,
+ "k" => 40,
+ "l" => 37,
+ "m" => 46,
+ "n" => 45,
+ "o" => 31,
+ "p" => 35,
+ "q" => 12,
+ "r" => 15,
+ "s" => 1,
+ "t" => 17,
+ "u" => 32,
+ "v" => 9,
+ "w" => 13,
+ "x" => 7,
+ "y" => 16,
+ "z" => 6,
+ "0" => 29,
+ "1" => 18,
+ "2" => 19,
+ "3" => 20,
+ "4" => 21,
+ "5" => 23,
+ "6" => 22,
+ "7" => 26,
+ "8" => 28,
+ "9" => 25,
"return" | "enter" => 36,
"escape" | "esc" => 53,
"tab" => 48,
@@ -252,27 +271,39 @@ fn key_to_keycode(key: &str) -> Option<u16> {
"end" => 119,
"pageup" => 116,
"pagedown" => 121,
- "left" => 123, "right" => 124, "down" => 125, "up" => 126,
- "f1" => 122, "f2" => 120, "f3" => 99, "f4" => 118,
- "f5" => 96, "f6" => 97, "f7" => 98, "f8" => 100,
- "f9" => 101, "f10" => 109, "f11" => 103, "f12" => 111,
+ "left" => 123,
+ "right" => 124,
+ "down" => 125,
+ "up" => 126,
+ "f1" => 122,
+ "f2" => 120,
+ "f3" => 99,
+ "f4" => 118,
+ "f5" => 96,
+ "f6" => 97,
+ "f7" => 98,
+ "f8" => 100,
+ "f9" => 101,
+ "f10" => 109,
+ "f11" => 103,
+ "f12" => 111,
_ => return None,
})
}
#[cfg(target_os = "macos")]
pub(crate) fn find_pid_by_name(app_name: &str) -> Result<i32, AdapterError> {
- let filter = WindowFilter { focused_only: false, app: Some(app_name.to_string()) };
+ let filter = WindowFilter {
+ focused_only: false,
+ app: Some(app_name.to_string()),
+ };
let windows = crate::adapter::list_windows_impl(&filter)?;
- windows
- .first()
- .map(|w| w.pid)
- .ok_or_else(|| {
- AdapterError::new(
- agent_desktop_core::error::ErrorCode::AppNotFound,
- format!("App '{app_name}' not found"),
- )
- })
+ windows.first().map(|w| w.pid).ok_or_else(|| {
+ AdapterError::new(
+ agent_desktop_core::error::ErrorCode::AppNotFound,
+ format!("App '{app_name}' not found"),
+ )
+ })
}
#[cfg(not(target_os = "macos"))]
diff --git a/crates/macos/src/mouse.rs b/crates/macos/src/mouse.rs
index 94d25706f..5da45a355 100644
--- a/crates/macos/src/mouse.rs
+++ b/crates/macos/src/mouse.rs
@@ -37,7 +37,11 @@ mod imp {
let t = i as f64 / steps as f64;
let x = params.from.x + (params.to.x - params.from.x) * t;
let y = params.from.y + (params.to.y - params.from.y) * t;
- post_event(CGEventType::LeftMouseDragged, CGPoint::new(x, y), CGMouseButton::Left)?;
+ post_event(
+ CGEventType::LeftMouseDragged,
+ CGPoint::new(x, y),
+ CGMouseButton::Left,
+ )?;
std::thread::sleep(step_delay);
}
@@ -78,11 +82,7 @@ mod imp {
}
extern "C" {
- fn CGEventSetIntegerValueField(
- event: *const std::ffi::c_void,
- field: u32,
- value: i64,
- );
+ fn CGEventSetIntegerValueField(event: *const std::ffi::c_void, field: u32, value: i64);
}
fn create_event(
diff --git a/crates/macos/src/permissions.rs b/crates/macos/src/permissions.rs
index e7345525d..21b6870b1 100644
--- a/crates/macos/src/permissions.rs
+++ b/crates/macos/src/permissions.rs
@@ -6,10 +6,7 @@ mod imp {
kAXTrustedCheckOptionPrompt, AXIsProcessTrusted, AXIsProcessTrustedWithOptions,
};
use core_foundation::{
- base::TCFType,
- boolean::CFBoolean,
- dictionary::CFDictionary,
- string::CFString,
+ base::TCFType, boolean::CFBoolean, dictionary::CFDictionary, string::CFString,
};
pub fn is_trusted() -> bool {
@@ -20,8 +17,7 @@ mod imp {
unsafe {
let key = CFString::wrap_under_get_rule(kAXTrustedCheckOptionPrompt);
let val = CFBoolean::true_value();
- let dict =
- CFDictionary::from_CFType_pairs(&[(key.as_CFType(), val.as_CFType())]);
+ let dict = CFDictionary::from_CFType_pairs(&[(key.as_CFType(), val.as_CFType())]);
AXIsProcessTrustedWithOptions(dict.as_concrete_TypeRef())
}
}
diff --git a/crates/macos/src/roles.rs b/crates/macos/src/roles.rs
index 44540bc3e..a469d269a 100644
--- a/crates/macos/src/roles.rs
+++ b/crates/macos/src/roles.rs
@@ -1,54 +1,54 @@
pub fn ax_role_to_str(ax_role: &str) -> &'static str {
match ax_role {
- "AXApplication" => "application",
- "AXButton" => "button",
- "AXMenuButton" => "menubutton",
+ "AXApplication" => "application",
+ "AXButton" => "button",
+ "AXMenuButton" => "menubutton",
"AXTextField" | "AXTextArea" | "AXSearchField" => "textfield",
- "AXCheckBox" => "checkbox",
- "AXSwitch" | "AXToggle" => "switch",
- "AXLink" => "link",
- "AXMenuItem" | "AXMenuBarItem" => "menuitem",
- "AXRadioButton" => "radiobutton",
- "AXTab" | "AXTabGroup" => "tab",
- "AXSlider" | "AXValueIndicator" => "slider",
- "AXComboBox" | "AXPopUpButton" => "combobox",
- "AXOutlineRow" | "AXRow" => "treeitem",
- "AXCell" => "cell",
- "AXColumn" => "column",
- "AXWindow" => "window",
- "AXSheet" => "sheet",
- "AXDialog" => "dialog",
- "AXGroup" | "AXGenericElement" => "group",
- "AXToolbar" => "toolbar",
- "AXStaticText" => "statictext",
- "AXImage" => "image",
- "AXTable" => "table",
- "AXList" => "list",
- "AXOutline" => "outline",
- "AXScrollArea" | "AXScrollBar" => "scrollarea",
- "AXSplitter" | "AXSplitGroup" => "splitter",
- "AXMenu" | "AXMenuBar" => "menu",
- "AXIncrementor" | "AXStepper" => "incrementor",
- "AXDisclosureTriangle" => "disclosure",
- "AXProgressIndicator" | "AXBusyIndicator" => "progressbar",
- "AXColorWell" => "colorwell",
- "AXWebArea" => "webarea",
- "AXBrowser" => "browser",
- "AXGrid" => "grid",
- "AXHandle" => "handle",
- "AXPopover" => "popover",
- "AXDockItem" => "dockitem",
- "AXRuler" => "ruler",
- "AXRulerMarker" => "rulermarker",
- "AXTimeField" => "timefield",
- "AXDateField" => "datefield",
- "AXHelpTag" => "helptag",
- "AXMatte" => "matte",
- "AXDrawer" => "drawer",
- "AXLayoutArea" | "AXLayoutItem" => "layoutitem",
- "AXLevelIndicator" => "levelindicator",
- "AXRelevanceIndicator" => "relevanceindicator",
- _ => "unknown",
+ "AXCheckBox" => "checkbox",
+ "AXSwitch" | "AXToggle" => "switch",
+ "AXLink" => "link",
+ "AXMenuItem" | "AXMenuBarItem" => "menuitem",
+ "AXRadioButton" => "radiobutton",
+ "AXTab" | "AXTabGroup" => "tab",
+ "AXSlider" | "AXValueIndicator" => "slider",
+ "AXComboBox" | "AXPopUpButton" => "combobox",
+ "AXOutlineRow" | "AXRow" => "treeitem",
+ "AXCell" => "cell",
+ "AXColumn" => "column",
+ "AXWindow" => "window",
+ "AXSheet" => "sheet",
+ "AXDialog" => "dialog",
+ "AXGroup" | "AXGenericElement" => "group",
+ "AXToolbar" => "toolbar",
+ "AXStaticText" => "statictext",
+ "AXImage" => "image",
+ "AXTable" => "table",
+ "AXList" => "list",
+ "AXOutline" => "outline",
+ "AXScrollArea" | "AXScrollBar" => "scrollarea",
+ "AXSplitter" | "AXSplitGroup" => "splitter",
+ "AXMenu" | "AXMenuBar" => "menu",
+ "AXIncrementor" | "AXStepper" => "incrementor",
+ "AXDisclosureTriangle" => "disclosure",
+ "AXProgressIndicator" | "AXBusyIndicator" => "progressbar",
+ "AXColorWell" => "colorwell",
+ "AXWebArea" => "webarea",
+ "AXBrowser" => "browser",
+ "AXGrid" => "grid",
+ "AXHandle" => "handle",
+ "AXPopover" => "popover",
+ "AXDockItem" => "dockitem",
+ "AXRuler" => "ruler",
+ "AXRulerMarker" => "rulermarker",
+ "AXTimeField" => "timefield",
+ "AXDateField" => "datefield",
+ "AXHelpTag" => "helptag",
+ "AXMatte" => "matte",
+ "AXDrawer" => "drawer",
+ "AXLayoutArea" | "AXLayoutItem" => "layoutitem",
+ "AXLevelIndicator" => "levelindicator",
+ "AXRelevanceIndicator" => "relevanceindicator",
+ _ => "unknown",
}
}
diff --git a/crates/macos/src/screenshot.rs b/crates/macos/src/screenshot.rs
index c3eb6fa9d..c62ec7f70 100644
--- a/crates/macos/src/screenshot.rs
+++ b/crates/macos/src/screenshot.rs
@@ -54,7 +54,12 @@ mod imp {
.map_err(|e| AdapterError::internal(format!("read screenshot: {e}")))?;
let _ = std::fs::remove_file(path);
let (width, height) = png_dimensions(&data);
- Ok(ImageBuffer { data, format: ImageFormat::Png, width, height })
+ Ok(ImageBuffer {
+ data,
+ format: ImageFormat::Png,
+ width,
+ height,
+ })
}
fn png_dimensions(data: &[u8]) -> (u32, u32) {
@@ -92,7 +97,7 @@ mod imp {
for item in array.iter() {
let dict = unsafe {
CFDictionary::<CFString, CFType>::wrap_under_get_rule(
- item.as_concrete_TypeRef() as _,
+ item.as_concrete_TypeRef() as _
)
};
@@ -124,13 +129,11 @@ mod imp {
)
};
let w = bounds_dict.find(CFString::new("Width")).and_then(|v| {
- let n =
- unsafe { CFNumber::wrap_under_get_rule(v.as_concrete_TypeRef() as _) };
+ let n = unsafe { CFNumber::wrap_under_get_rule(v.as_concrete_TypeRef() as _) };
n.to_f64()
});
let h = bounds_dict.find(CFString::new("Height")).and_then(|v| {
- let n =
- unsafe { CFNumber::wrap_under_get_rule(v.as_concrete_TypeRef() as _) };
+ let n = unsafe { CFNumber::wrap_under_get_rule(v.as_concrete_TypeRef() as _) };
n.to_f64()
});
w.unwrap_or(0.0) * h.unwrap_or(0.0)
diff --git a/crates/macos/src/surfaces.rs b/crates/macos/src/surfaces.rs
index 394feaf0e..4c090ad28 100644
--- a/crates/macos/src/surfaces.rs
+++ b/crates/macos/src/surfaces.rs
@@ -47,9 +47,9 @@ mod imp {
fn open_menubar_menu(pid: i32) -> Option<AXElement> {
let app = element_for_pid(pid);
let app_children = copy_ax_array(&app, "AXChildren")?;
- let menubar = app_children.into_iter().find(|ch| {
- copy_string_attr(ch, "AXRole").as_deref() == Some("AXMenuBar")
- })?;
+ let menubar = app_children
+ .into_iter()
+ .find(|ch| copy_string_attr(ch, "AXRole").as_deref() == Some("AXMenuBar"))?;
let items = copy_ax_array(&menubar, "AXChildren")?;
for item in &items {
if copy_string_attr(item, "AXRole").as_deref() != Some("AXMenuBarItem") {
@@ -59,9 +59,9 @@ mod imp {
continue;
}
if let Some(children) = copy_ax_array(item, "AXChildren") {
- return children.into_iter().find(|ch| {
- copy_string_attr(ch, "AXRole").as_deref() == Some("AXMenu")
- });
+ return children
+ .into_iter()
+ .find(|ch| copy_string_attr(ch, "AXRole").as_deref() == Some("AXMenu"));
}
}
None
@@ -74,17 +74,18 @@ mod imp {
let app = element_for_pid(pid);
if let Some(focused) = copy_element_attr(&app, "AXFocusedUIElement") {
if let Some(children) = copy_ax_array(&focused, "AXChildren") {
- if let Some(menu) = children.into_iter().find(|ch| {
- copy_string_attr(ch, "AXRole").as_deref() == Some("AXMenu")
- }) {
+ if let Some(menu) = children
+ .into_iter()
+ .find(|ch| copy_string_attr(ch, "AXRole").as_deref() == Some("AXMenu"))
+ {
return Some(menu);
}
}
}
let children = copy_ax_array(&app, "AXChildren")?;
- children.into_iter().find(|ch| {
- copy_string_attr(ch, "AXRole").as_deref() == Some("AXMenu")
- })
+ children
+ .into_iter()
+ .find(|ch| copy_string_attr(ch, "AXRole").as_deref() == Some("AXMenu"))
}
pub fn menu_element_for_pid(pid: i32) -> Option<AXElement> {
@@ -98,9 +99,9 @@ mod imp {
fn first_child_with_subrole(pid: i32, subrole: &str) -> Option<AXElement> {
let win = focused_window_element(pid)?;
let children = copy_ax_array(&win, "AXChildren")?;
- children.into_iter().find(|child| {
- copy_string_attr(child, "AXSubrole").as_deref() == Some(subrole)
- })
+ children
+ .into_iter()
+ .find(|child| copy_string_attr(child, "AXSubrole").as_deref() == Some(subrole))
}
pub fn sheet_for_pid(pid: i32) -> Option<AXElement> {
@@ -134,7 +135,9 @@ mod imp {
Some("AXMenuBar") => {
if let Some(items) = copy_ax_array(ch, "AXChildren") {
for item in &items {
- if copy_string_attr(item, "AXRole").as_deref() != Some("AXMenuBarItem") {
+ if copy_string_attr(item, "AXRole").as_deref()
+ != Some("AXMenuBarItem")
+ {
continue;
}
if !copy_bool_attr(item, "AXSelected").unwrap_or(false) {
@@ -143,8 +146,11 @@ mod imp {
let title = copy_string_attr(item, "AXTitle");
if let Some(menu_children) = copy_ax_array(item, "AXChildren") {
for menu in &menu_children {
- if copy_string_attr(menu, "AXRole").as_deref() == Some("AXMenu") {
- let item_count = copy_ax_array(menu, "AXChildren").map(|v| v.len());
+ if copy_string_attr(menu, "AXRole").as_deref()
+ == Some("AXMenu")
+ {
+ let item_count =
+ copy_ax_array(menu, "AXChildren").map(|v| v.len());
surfaces.push(SurfaceInfo {
kind: "menu".into(),
title: title.clone(),
@@ -160,7 +166,11 @@ mod imp {
let title = copy_string_attr(ch, "AXTitle")
.or_else(|| copy_string_attr(ch, "AXDescription"));
let item_count = copy_ax_array(ch, "AXChildren").map(|v| v.len());
- surfaces.push(SurfaceInfo { kind: "context_menu".into(), title, item_count });
+ surfaces.push(SurfaceInfo {
+ kind: "context_menu".into(),
+ title,
+ item_count,
+ });
}
_ => {}
}
@@ -174,7 +184,11 @@ mod imp {
let title = copy_string_attr(ch, "AXTitle")
.or_else(|| copy_string_attr(ch, "AXDescription"));
let item_count = copy_ax_array(ch, "AXChildren").map(|v| v.len());
- surfaces.push(SurfaceInfo { kind: "context_menu".into(), title, item_count });
+ surfaces.push(SurfaceInfo {
+ kind: "context_menu".into(),
+ title,
+ item_count,
+ });
}
}
}
@@ -192,7 +206,11 @@ mod imp {
};
let title = copy_string_attr(child, "AXTitle")
.or_else(|| copy_string_attr(child, "AXDescription"));
- surfaces.push(SurfaceInfo { kind: kind.into(), title, item_count: None });
+ surfaces.push(SurfaceInfo {
+ kind: kind.into(),
+ title,
+ item_count: None,
+ });
}
}
}
@@ -205,13 +223,27 @@ mod imp {
mod imp {
use super::*;
- pub fn menu_element_for_pid(_pid: i32) -> Option<AXElement> { None }
- pub fn focused_surface_for_pid(_pid: i32) -> Option<AXElement> { None }
- pub fn sheet_for_pid(_pid: i32) -> Option<AXElement> { None }
- pub fn popover_for_pid(_pid: i32) -> Option<AXElement> { None }
- pub fn alert_for_pid(_pid: i32) -> Option<AXElement> { None }
- pub fn is_menu_open(_pid: i32) -> bool { false }
- pub fn list_surfaces_for_pid(_pid: i32) -> Vec<SurfaceInfo> { Vec::new() }
+ pub fn menu_element_for_pid(_pid: i32) -> Option<AXElement> {
+ None
+ }
+ pub fn focused_surface_for_pid(_pid: i32) -> Option<AXElement> {
+ None
+ }
+ pub fn sheet_for_pid(_pid: i32) -> Option<AXElement> {
+ None
+ }
+ pub fn popover_for_pid(_pid: i32) -> Option<AXElement> {
+ None
+ }
+ pub fn alert_for_pid(_pid: i32) -> Option<AXElement> {
+ None
+ }
+ pub fn is_menu_open(_pid: i32) -> bool {
+ false
+ }
+ pub fn list_surfaces_for_pid(_pid: i32) -> Vec<SurfaceInfo> {
+ Vec::new()
+ }
}
pub use imp::{
diff --git a/crates/macos/src/tree.rs b/crates/macos/src/tree.rs
index a4b7838a7..2d5e355b9 100644
--- a/crates/macos/src/tree.rs
+++ b/crates/macos/src/tree.rs
@@ -7,11 +7,11 @@ pub const ABSOLUTE_MAX_DEPTH: u8 = 50;
mod imp {
use super::*;
use accessibility_sys::{
- kAXChildrenAttribute, kAXContentsAttribute, kAXDescriptionAttribute,
- kAXEnabledAttribute, kAXErrorSuccess, kAXFocusedAttribute, kAXRoleAttribute,
- kAXTitleAttribute, kAXValueAttribute, kAXWindowsAttribute,
- AXUIElementCopyAttributeValue, AXUIElementCopyMultipleAttributeValues,
- AXUIElementCreateApplication, AXUIElementRef, AXUIElementSetMessagingTimeout,
+ kAXChildrenAttribute, kAXContentsAttribute, kAXDescriptionAttribute, kAXEnabledAttribute,
+ kAXErrorSuccess, kAXFocusedAttribute, kAXRoleAttribute, kAXTitleAttribute,
+ kAXValueAttribute, kAXWindowsAttribute, AXUIElementCopyAttributeValue,
+ AXUIElementCopyMultipleAttributeValues, AXUIElementCreateApplication, AXUIElementRef,
+ AXUIElementSetMessagingTimeout,
};
use core_foundation::{
array::CFArray,
@@ -62,7 +62,10 @@ mod imp {
}
for win in &windows {
let title = copy_string_attr(win, kAXTitleAttribute);
- if title.as_deref().is_some_and(|t| t.contains(win_title) || win_title.contains(t)) {
+ if title
+ .as_deref()
+ .is_some_and(|t| t.contains(win_title) || win_title.contains(t))
+ {
return win.clone();
}
}
@@ -78,7 +81,14 @@ mod imp {
/// Value handles CFString, CFBoolean, and CFNumber types.
fn fetch_node_attrs(
el: &AXElement,
- ) -> (Option<String>, Option<String>, Option<String>, Option<String>, bool, bool) {
+ ) -> (
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ bool,
+ bool,
+ ) {
let attr_names = [
kAXRoleAttribute,
kAXTitleAttribute,
@@ -102,39 +112,51 @@ mod imp {
};
if err != kAXErrorSuccess || result_ref.is_null() {
- let role = copy_string_attr(el, kAXRoleAttribute);
- let title = copy_string_attr(el, kAXTitleAttribute);
- let desc = copy_string_attr(el, kAXDescriptionAttribute);
- let val = copy_value_typed(el);
+ let role = copy_string_attr(el, kAXRoleAttribute);
+ let title = copy_string_attr(el, kAXTitleAttribute);
+ let desc = copy_string_attr(el, kAXDescriptionAttribute);
+ let val = copy_value_typed(el);
let enabled = copy_bool_attr(el, kAXEnabledAttribute).unwrap_or(true);
let focused = copy_bool_attr(el, kAXFocusedAttribute).unwrap_or(false);
return (role, title, desc, val, enabled, focused);
}
let arr = unsafe { CFArray::<CFType>::wrap_under_create_rule(result_ref as _) };
- let items: Vec<Option<String>> = arr.into_iter().enumerate().map(|(idx, item)| {
- if let Some(s) = item.downcast::<CFString>() {
- return Some(s.to_string());
- }
- match idx {
- 3 => {
- if let Some(b) = item.downcast::<CFBoolean>() { return Some(bool::from(b).to_string()); }
- if let Some(n) = item.downcast::<CFNumber>() {
- if let Some(i) = n.to_i64() { return Some(i.to_string()); }
- if let Some(f) = n.to_f64() { return Some(format!("{:.2}", f)); }
+ let items: Vec<Option<String>> = arr
+ .into_iter()
+ .enumerate()
+ .map(|(idx, item)| {
+ if let Some(s) = item.downcast::<CFString>() {
+ return Some(s.to_string());
+ }
+ match idx {
+ 3 => {
+ if let Some(b) = item.downcast::<CFBoolean>() {
+ return Some(bool::from(b).to_string());
+ }
+ if let Some(n) = item.downcast::<CFNumber>() {
+ if let Some(i) = n.to_i64() {
+ return Some(i.to_string());
+ }
+ if let Some(f) = n.to_f64() {
+ return Some(format!("{:.2}", f));
+ }
+ }
+ None
}
- None
+ 4 | 5 => item
+ .downcast::<CFBoolean>()
+ .map(|b| bool::from(b).to_string()),
+ _ => None,
}
- 4 | 5 => item.downcast::<CFBoolean>().map(|b| bool::from(b).to_string()),
- _ => None,
- }
- }).collect();
+ })
+ .collect();
let get = |i: usize| items.get(i).and_then(|v| v.clone());
- let role = get(0);
- let title = get(1);
- let desc = get(2);
- let val = get(3);
+ let role = get(0);
+ let title = get(1);
+ let desc = get(2);
+ let val = get(3);
let enabled = get(4).map(|s| s == "true").unwrap_or(true);
let focused = get(5).map(|s| s == "true").unwrap_or(false);
@@ -192,17 +214,27 @@ mod imp {
};
let mut states = Vec::new();
- if focused { states.push("focused".into()); }
- if !enabled { states.push("disabled".into()); }
+ if focused {
+ states.push("focused".into());
+ }
+ if !enabled {
+ states.push("disabled".into());
+ }
- let bounds = if include_bounds { read_bounds(el) } else { None };
+ let bounds = if include_bounds {
+ read_bounds(el)
+ } else {
+ None
+ };
let children_raw = copy_children(el, ax_role.as_deref()).unwrap_or_default();
let name = name.or_else(|| label_from_children(&children_raw));
let children = children_raw
.into_iter()
- .filter_map(|child| build_subtree(&child, depth + 1, max_depth, include_bounds, visited))
+ .filter_map(|child| {
+ build_subtree(&child, depth + 1, max_depth, include_bounds, visited)
+ })
.collect();
Some(AccessibilityNode {
@@ -229,12 +261,18 @@ mod imp {
for child in children.iter().take(5) {
match copy_string_attr(child, kAXRoleAttribute).as_deref() {
Some("AXStaticText") => {
- if let Some(s) = text_of(child) { return Some(s); }
+ if let Some(s) = text_of(child) {
+ return Some(s);
+ }
}
Some("AXCell") | Some("AXGroup") => {
for gc in copy_ax_array(child, kAXChildrenAttribute).unwrap_or_default() {
- if copy_string_attr(&gc, kAXRoleAttribute).as_deref() == Some("AXStaticText") {
- if let Some(s) = text_of(&gc) { return Some(s); }
+ if copy_string_attr(&gc, kAXRoleAttribute).as_deref()
+ == Some("AXStaticText")
+ {
+ if let Some(s) = text_of(&gc) {
+ return Some(s);
+ }
}
}
}
@@ -250,9 +288,15 @@ mod imp {
if ax_role == Some("AXBrowser") {
return copy_ax_array(el, "AXColumns");
}
- for attr in &[kAXChildrenAttribute, kAXContentsAttribute, "AXChildrenInNavigationOrder"] {
+ for attr in &[
+ kAXChildrenAttribute,
+ kAXContentsAttribute,
+ "AXChildrenInNavigationOrder",
+ ] {
if let Some(v) = copy_ax_array(el, attr) {
- if !v.is_empty() { return Some(v); }
+ if !v.is_empty() {
+ return Some(v);
+ }
}
}
None
@@ -278,13 +322,23 @@ mod imp {
let err = unsafe {
AXUIElementCopyAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), &mut val_ref)
};
- if err != kAXErrorSuccess || val_ref.is_null() { return None; }
+ if err != kAXErrorSuccess || val_ref.is_null() {
+ return None;
+ }
let cf = unsafe { CFType::wrap_under_create_rule(val_ref) };
- if let Some(s) = cf.downcast::<CFString>() { return Some(s.to_string()); }
- if let Some(b) = cf.downcast::<CFBoolean>() { return Some(bool::from(b).to_string()); }
+ if let Some(s) = cf.downcast::<CFString>() {
+ return Some(s.to_string());
+ }
+ if let Some(b) = cf.downcast::<CFBoolean>() {
+ return Some(bool::from(b).to_string());
+ }
if let Some(n) = cf.downcast::<CFNumber>() {
- if let Some(i) = n.to_i64() { return Some(i.to_string()); }
- if let Some(f) = n.to_f64() { return Some(format!("{:.2}", f)); }
+ if let Some(i) = n.to_i64() {
+ return Some(i.to_string());
+ }
+ if let Some(f) = n.to_f64() {
+ return Some(format!("{:.2}", f));
+ }
}
None
}
@@ -295,7 +349,9 @@ mod imp {
let err = unsafe {
AXUIElementCopyAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), &mut value)
};
- if err != kAXErrorSuccess || value.is_null() { return None; }
+ if err != kAXErrorSuccess || value.is_null() {
+ return None;
+ }
let cf_type = unsafe { CFType::wrap_under_create_rule(value) };
cf_type.downcast::<CFBoolean>().map(|b| b.into())
}
@@ -307,13 +363,17 @@ mod imp {
let err = unsafe {
AXUIElementCopyAttributeValue(el.0, cf_attr.as_concrete_TypeRef(), &mut value)
};
- if err != kAXErrorSuccess || value.is_null() { return None; }
+ if err != kAXErrorSuccess || value.is_null() {
+ return None;
+ }
let arr = unsafe { CFArray::<CFType>::wrap_under_create_rule(value as _) };
let children: Vec<AXElement> = arr
.into_iter()
.filter_map(|item| {
let ptr = item.as_concrete_TypeRef() as AXUIElementRef;
- if ptr.is_null() { return None; }
+ if ptr.is_null() {
+ return None;
+ }
unsafe { CFRetain(ptr as CFTypeRef) };
Some(AXElement(ptr))
})
@@ -336,8 +396,8 @@ mod imp {
pub fn read_bounds(el: &AXElement) -> Option<Rect> {
use accessibility_sys::{
- kAXPositionAttribute, kAXSizeAttribute, AXValueGetValue,
- kAXValueTypeCGPoint, kAXValueTypeCGSize,
+ kAXPositionAttribute, kAXSizeAttribute, kAXValueTypeCGPoint, kAXValueTypeCGSize,
+ AXValueGetValue,
};
use core_graphics::geometry::{CGPoint, CGSize};
use std::ffi::c_void;
@@ -347,30 +407,51 @@ mod imp {
let pos_ok = unsafe {
AXUIElementCopyAttributeValue(el.0, pos_cf.as_concrete_TypeRef(), &mut pos_ref)
};
- if pos_ok != kAXErrorSuccess || pos_ref.is_null() { return None; }
+ if pos_ok != kAXErrorSuccess || pos_ref.is_null() {
+ return None;
+ }
let mut point = CGPoint::new(0.0, 0.0);
let got_pos = unsafe {
- AXValueGetValue(pos_ref as _, kAXValueTypeCGPoint, &mut point as *mut _ as *mut c_void)
+ AXValueGetValue(
+ pos_ref as _,
+ kAXValueTypeCGPoint,
+ &mut point as *mut _ as *mut c_void,
+ )
};
unsafe { CFRelease(pos_ref) };
- if !got_pos { return None; }
+ if !got_pos {
+ return None;
+ }
let size_cf = CFString::new(kAXSizeAttribute);
let mut size_ref: CFTypeRef = std::ptr::null_mut();
let size_ok = unsafe {
AXUIElementCopyAttributeValue(el.0, size_cf.as_concrete_TypeRef(), &mut size_ref)
};
- if size_ok != kAXErrorSuccess || size_ref.is_null() { return None; }
+ if size_ok != kAXErrorSuccess || size_ref.is_null() {
+ return None;
+ }
let mut size = CGSize::new(0.0, 0.0);
let got_size = unsafe {
- AXValueGetValue(size_ref as _, kAXValueTypeCGSize, &mut size as *mut _ as *mut c_void)
+ AXValueGetValue(
+ size_ref as _,
+ kAXValueTypeCGSize,
+ &mut size as *mut _ as *mut c_void,
+ )
};
unsafe { CFRelease(size_ref) };
- if !got_size { return None; }
+ if !got_size {
+ return None;
+ }
- Some(Rect { x: point.x, y: point.y, width: size.width, height: size.height })
+ Some(Rect {
+ x: point.x,
+ y: point.y,
+ width: size.width,
+ height: size.height,
+ })
}
}
@@ -380,18 +461,46 @@ mod imp {
pub struct AXElement(pub(crate) *const std::ffi::c_void);
- impl Drop for AXElement { fn drop(&mut self) {} }
- impl Clone for AXElement { fn clone(&self) -> Self { AXElement(self.0) } }
+ impl Drop for AXElement {
+ fn drop(&mut self) {}
+ }
+ impl Clone for AXElement {
+ fn clone(&self) -> Self {
+ AXElement(self.0)
+ }
+ }
- pub fn element_for_pid(_pid: i32) -> AXElement { AXElement(std::ptr::null()) }
- pub fn window_element_for(_pid: i32, _win_title: &str) -> AXElement { AXElement(std::ptr::null()) }
- pub fn copy_ax_array(_el: &AXElement, _attr: &str) -> Option<Vec<AXElement>> { None }
- pub fn copy_string_attr(_el: &AXElement, _attr: &str) -> Option<String> { None }
- pub fn copy_element_attr(_el: &AXElement, _attr: &str) -> Option<AXElement> { None }
- pub fn read_bounds(_el: &AXElement) -> Option<agent_desktop_core::node::Rect> { None }
- pub fn resolve_element_name(_el: &AXElement) -> Option<String> { None }
+ pub fn element_for_pid(_pid: i32) -> AXElement {
+ AXElement(std::ptr::null())
+ }
+ pub fn window_element_for(_pid: i32, _win_title: &str) -> AXElement {
+ AXElement(std::ptr::null())
+ }
+ pub fn copy_ax_array(_el: &AXElement, _attr: &str) -> Option<Vec<AXElement>> {
+ None
+ }
+ pub fn copy_string_attr(_el: &AXElement, _attr: &str) -> Option<String> {
+ None
+ }
+ pub fn copy_element_attr(_el: &AXElement, _attr: &str) -> Option<AXElement> {
+ None
+ }
+ pub fn read_bounds(_el: &AXElement) -> Option<agent_desktop_core::node::Rect> {
+ None
+ }
+ pub fn resolve_element_name(_el: &AXElement) -> Option<String> {
+ None
+ }
- pub fn build_subtree(_el: &AXElement, _depth: u8, _max_depth: u8, _include_bounds: bool, _visited: &mut FxHashSet<usize>) -> Option<AccessibilityNode> { None }
+ pub fn build_subtree(
+ _el: &AXElement,
+ _depth: u8,
+ _max_depth: u8,
+ _include_bounds: bool,
+ _visited: &mut FxHashSet<usize>,
+ ) -> Option<AccessibilityNode> {
+ None
+ }
}
pub use imp::{
diff --git a/crates/macos/src/window_ops.rs b/crates/macos/src/window_ops.rs
index c688a16e8..174090e13 100644
--- a/crates/macos/src/window_ops.rs
+++ b/crates/macos/src/window_ops.rs
@@ -3,17 +3,12 @@ use agent_desktop_core::{action::WindowOp, error::AdapterError, node::WindowInfo
#[cfg(target_os = "macos")]
mod imp {
use super::*;
- use agent_desktop_core::error::ErrorCode;
use accessibility_sys::{
- kAXErrorSuccess, kAXPositionAttribute, kAXSizeAttribute,
- AXUIElementPerformAction, AXUIElementSetAttributeValue,
- kAXValueTypeCGPoint, kAXValueTypeCGSize,
- };
- use core_foundation::{
- base::TCFType,
- boolean::CFBoolean,
- string::CFString,
+ kAXErrorSuccess, kAXPositionAttribute, kAXSizeAttribute, kAXValueTypeCGPoint,
+ kAXValueTypeCGSize, AXUIElementPerformAction, AXUIElementSetAttributeValue,
};
+ use agent_desktop_core::error::ErrorCode;
+ use core_foundation::{base::TCFType, boolean::CFBoolean, string::CFString};
use core_graphics::geometry::{CGPoint, CGSize};
use std::ffi::c_void;
@@ -32,15 +27,10 @@ mod imp {
}
}
- fn set_size(
- el: &crate::tree::AXElement,
- width: f64,
- height: f64,
- ) -> Result<(), AdapterError> {
+ fn set_size(el: &crate::tree::AXElement, width: f64, height: f64) -> Result<(), AdapterError> {
let size = CGSize::new(width, height);
- let ax_value = unsafe {
- AXValueCreate(kAXValueTypeCGSize, &size as *const _ as *const c_void)
- };
+ let ax_value =
+ unsafe { AXValueCreate(kAXValueTypeCGSize, &size as *const _ as *const c_void) };
if ax_value.is_null() {
return Err(AdapterError::internal("Failed to create AXValue for size"));
}
@@ -58,17 +48,14 @@ mod imp {
Ok(())
}
- fn set_position(
- el: &crate::tree::AXElement,
- x: f64,
- y: f64,
- ) -> Result<(), AdapterError> {
+ fn set_position(el: &crate::tree::AXElement, x: f64, y: f64) -> Result<(), AdapterError> {
let point = CGPoint::new(x, y);
- let ax_value = unsafe {
- AXValueCreate(kAXValueTypeCGPoint, &point as *const _ as *const c_void)
- };
+ let ax_value =
+ unsafe { AXValueCreate(kAXValueTypeCGPoint, &point as *const _ as *const c_void) };
if ax_value.is_null() {
- return Err(AdapterError::internal("Failed to create AXValue for position"));
+ return Err(AdapterError::internal(
+ "Failed to create AXValue for position",
+ ));
}
let cf_attr = CFString::new(kAXPositionAttribute);
let err = unsafe {
@@ -84,10 +71,7 @@ mod imp {
Ok(())
}
- fn set_minimized(
- el: &crate::tree::AXElement,
- minimized: bool,
- ) -> Result<(), AdapterError> {
+ fn set_minimized(el: &crate::tree::AXElement, minimized: bool) -> Result<(), AdapterError> {
let cf_attr = CFString::new("AXMinimized");
let val = if minimized {
CFBoolean::true_value()
@@ -112,9 +96,7 @@ mod imp {
match zoom {
Some(btn) => {
let action = CFString::new("AXPress");
- let err = unsafe {
- AXUIElementPerformAction(btn.0, action.as_concrete_TypeRef())
- };
+ let err = unsafe { AXUIElementPerformAction(btn.0, action.as_concrete_TypeRef()) };
if err != kAXErrorSuccess {
return Err(AdapterError::new(
ErrorCode::ActionFailed,
diff --git a/docs/plans/2026-02-19-feat-agent-desktop-phase1-foundation-plan.md b/docs/plans/2026-02-19-feat-agent-desktop-phase1-foundation-plan.md
index 3c0e007ff..3b25fdea4 100644
--- a/docs/plans/2026-02-19-feat-agent-desktop-phase1-foundation-plan.md
+++ b/docs/plans/2026-02-19-feat-agent-desktop-phase1-foundation-plan.md
@@ -11,11 +11,19 @@ deepened: 2026-02-19
## Enhancement Summary
-**Deepened on:** 2026-02-19
-**Research agents used:** 10 (Architecture Strategist, Performance Oracle, Security Sentinel, Code Simplicity Reviewer, Agent-Native Reviewer, Pattern Recognition Specialist, Best Practices Researcher, Framework Docs Researcher, Spec Flow Analyzer, Agent-Native Architecture Skill)
+**Deepened on:** 2026-02-19 (round 1), 2026-02-19 (round 2 — code quality audit)
+**Research agents used:** 15 (Architecture Strategist, Performance Oracle, Security Sentinel, Code Simplicity Reviewer, Agent-Native Reviewer, Pattern Recognition Specialist, Best Practices Researcher, Framework Docs Researcher, Spec Flow Analyzer, Agent-Native Architecture Skill, Dead Code/LOC Auditor, Test-Before-Implement Researcher, Modular Architecture Researcher, Code Quality Reviewer, Architecture Extensibility Reviewer)
**Context7 queries:** clap 4 derive patterns, serde performance patterns
**Web research:** macOS AX FFI best practices, cargo-dist distribution, rmcp latest version, accessibility-sys alternatives, thiserror 2.0 changes
+### Round 2 Structural Findings (Fix During Implementation)
+
+- **Dead code:** `clipboard.rs` (zero callers), `batch::execute` stub (never called)
+- **LOC violation:** `tree.rs` at 403 lines — split into `ax_element.rs` / `ax_attrs.rs` / `ax_tree.rs`
+- **Dispatch duplication:** 187/397 lines in `dispatch.rs` are a near-verbatim parallel dispatch table — collapse to single code path via `Commands` enum deserialization
+- **Probe binaries:** `axprobe.rs` / `axprobe2.rs` in `src/bin/` compile on every build — move to `examples/` with `required-features = ["dev-tools"]`
+- **Bugs:** `wait.rs` silently discards RefMap load errors; `is_check.rs` reads stale state; `press.rs` undocumented null-handle convention
+
### Blockers (Fix Before Writing Code)
1. **Circular dependency in CommandRegistry** — `CommandRegistry::dispatch` references `crate::cli::Commands` from the binary crate, creating a circular dep (core ↔ binary). **Fix:** Drop `Command` trait and `CommandRegistry` entirely; dispatch via `match` in the binary crate.
@@ -941,7 +949,11 @@ Use `serde_json::to_writer(BufWriter::new(stdout.lock()), &data)` instead of `to
## macOS Adapter Implementation
-### `crates/macos/src/tree.rs` — Key patterns
+### `crates/macos/src/` — Tree module split
+
+`tree.rs` exceeds 400 LOC and is split into three files (see "Code Quality and Structural Refactors" section). The patterns below apply to the split files: `AXElement` and `element_for_pid` go in `ax_element.rs`, attribute helpers in `ax_attrs.rs`, traversal logic in `ax_tree.rs`.
+
+### `crates/macos/src/ax_element.rs` — Key patterns
```rust
use accessibility_sys::{
@@ -1495,15 +1507,15 @@ macos_large_tree_test - snapshot Xcode → completes under 2 seconds
### Weeks 3–4: macOS Tree Traversal
**Deliverables:**
-- `crates/macos/src/tree.rs`: `AXElement` newtype with `Drop`, `element_for_pid()`,
- `build_subtree()` with cycle detection via `HashSet<usize>`, depth limiting
-- `crates/macos/src/roles.rs`: AXRole string → unified role enum mapping
- (AXButton → "button", AXTextField → "textfield", etc.)
+- `crates/macos/src/ax_element.rs`: `AXElement` newtype with `Drop`, `Clone` (CFRetain), `element_for_pid()`, `window_element_for()`
+- `crates/macos/src/ax_attrs.rs`: `copy_string_attr`, `copy_ax_array`, `fetch_node_attrs`, `read_bounds`
+- `crates/macos/src/ax_tree.rs`: `build_subtree()` with cycle detection via `FxHashSet<usize>`, depth limiting, `resolve_element_name`
+- `crates/macos/src/roles.rs`: AXRole string → unified role enum mapping (AXButton → "button", AXTextField → "textfield", etc.)
- `crates/macos/src/permissions.rs`: `is_trusted()`, `request_trust()`
-- `crates/macos/src/adapter.rs`: `MacOSAdapter::get_tree()` and
- `MacOSAdapter::check_permissions()` implemented; all other methods stub
-- Unit tests: role mapping coverage, cycle detection (synthetic circular tree),
- permission mock
+- `crates/macos/src/adapter.rs`: `MacOSAdapter::get_tree()` and `MacOSAdapter::check_permissions()` implemented; all other methods stub
+- `crates/macos/examples/axprobe.rs`: probe binary moved from `src/bin/`, gated on `dev-tools` feature
+- Unit tests: role mapping coverage, cycle detection (synthetic circular tree), permission mock
+- Stage 1–3 probe validation completed for each AX attribute used before wiring into adapter
- Manual validation: `cargo run -- snapshot --app Finder` produces valid JSON
**Gotchas from research:**
@@ -1720,6 +1732,154 @@ From the Agent-Native Reviewer (score: 26/30, 4 structural gaps):
---
+## Code Quality and Structural Refactors
+
+These findings are not blockers for Phase 1 feature work, but must be resolved before the Phase 1 milestone is closed. Each has a clear fix and zero risk of behaviour change.
+
+### Dead Code to Remove
+
+**`crates/core/src/commands/clipboard.rs`** — 13 lines, exports `execute_get()` and `execute_set()` with zero callers anywhere in the workspace. The clipboard commands are implemented in the correct split files `clipboard_get.rs` and `clipboard_set.rs` (one command per file), which `dispatch.rs` calls directly. `clipboard.rs` is a leftover from before the split and should be deleted along with its `pub mod clipboard;` line in `mod.rs`.
+
+**`batch::execute` stub** — `crates/core/src/commands/batch.rs` exports an `execute()` function that returns `Ok(json!({"note": "..."}))`. It is never called; `dispatch.rs` handles batch routing inline. Delete the `execute` function body. Keep `BatchArgs`, `BatchCommand`, and `parse_commands` — they are live.
+
+### LOC Violations
+
+**`crates/macos/src/tree.rs` is at 403 lines** — exceeds the 400-line hard limit. Split into three files by single responsibility:
+
+| New file | Contents | Estimated LOC |
+|---|---|---|
+| `ax_element.rs` | `AXElement` newtype, `Drop`, `Clone` (with `CFRetain`), `element_for_pid`, `window_element_for` | ~55 |
+| `ax_attrs.rs` | `copy_string_attr`, `copy_value_typed`, `copy_bool_attr`, `copy_ax_array`, `read_bounds`, `fetch_node_attrs` | ~200 |
+| `ax_tree.rs` | `build_subtree`, `resolve_element_name`, `label_from_children`, `copy_children` | ~115 |
+
+**`crates/macos/src/lib.rs`** — update module declarations:
+```rust
+pub mod ax_element;
+pub mod ax_attrs;
+pub mod ax_tree;
+// Remove: pub mod tree;
+```
+
+Internal cross-file imports use `super::` paths:
+```rust
+// ax_tree.rs
+use super::ax_element::AXElement;
+use super::ax_attrs::{copy_string_attr, fetch_node_attrs};
+```
+
+**`src/dispatch.rs` is at 397 lines** — 3 lines under the limit but contains 187 lines of duplication (see below). Collapsing the duplication brings it to ~210 lines.
+
+### Dispatch Duplication
+
+`dispatch.rs` has two parallel dispatch tables:
+- Lines 16–169: `dispatch()` — type-safe `Commands` enum, 29 match arms
+- Lines 171–358: `dispatch_batch_command()` — string-keyed version, same 29 commands parsed differently
+
+**Fix:** Collapse `dispatch_batch_command()` by deserializing batch JSON into the `Commands` enum. Because `Commands` derives `Deserialize`, `serde_json::from_value(json!({"snapshot": {"app": "Finder"}}))` already works:
+
+```rust
+pub fn dispatch_batch_command(
+ name: &str,
+ args: serde_json::Value,
+ adapter: &dyn PlatformAdapter,
+) -> Result<serde_json::Value, AppError> {
+ let cmd: Commands = serde_json::from_value(serde_json::json!({ name: args }))
+ .map_err(|e| AppError::invalid_args(e.to_string()))?;
+ dispatch(cmd, adapter)
+}
+```
+
+This eliminates ~187 lines of duplication. `batch.rs`'s `parse_commands` routes `{"command": "snapshot", "args": {...}}` entries to `dispatch_batch_command("snapshot", args, adapter)` — one unified code path.
+
+### Probe Binary Reorganization
+
+`src/bin/axprobe.rs` and `src/bin/axprobe2.rs` are development probe binaries compiled on every `cargo build`. They should live in `examples/` and only compile when explicitly requested:
+
+```
+crates/macos/
+└── examples/
+ ├── axprobe.rs # moved from src/bin/axprobe.rs
+ ├── axprobe2.rs # moved from src/bin/axprobe2.rs
+ └── probe_utils.rs # extract shared helpers (find_pid, string readers, array readers)
+```
+
+In `crates/macos/Cargo.toml`:
+```toml
+[[example]]
+name = "axprobe"
+path = "examples/axprobe.rs"
+required-features = ["dev-tools"]
+
+[features]
+dev-tools = []
+```
+
+Run with: `cargo run -p agent-desktop-macos --example axprobe --features dev-tools`
+
+### Bugs to Fix Before Phase 1 Ships
+
+| File | Bug | Fix |
+|---|---|---|
+| `wait.rs` | `if let Ok(refmap) = RefMap::load()` silently discards load errors on every polling iteration | Propagate with `?` or emit `tracing::warn!` |
+| `is_check.rs` | States read from stale RefMap entry; `_handle` is resolved (liveness check) but then discarded | Add `///` doc-comment: "Returns state from last snapshot. Run `snapshot` first for live state." |
+| `press.rs` | `parts.last().unwrap()` — safe but proof depends on preceding `is_empty` guard being visible | Change to `parts.last().ok_or_else(|| AppError::invalid_args("empty key combo"))` |
+| `press.rs` | `NativeHandle::null()` passed for `PressKey` action — convention undocumented | Add `// SAFETY: PressKey synthesises a global CGEvent; no element handle is required.` |
+
+---
+
+## Test-Before-Implement Development Workflow
+
+Every new AX capability must be confirmed at the OS level before being wired into the adapter. This 4-stage process eliminates "wrote 100 lines then discovered the attribute doesn't exist" failures. Document this in `CLAUDE.md` under `## Development Workflow`.
+
+### Stage 1 — Accessibility Inspector
+
+Open `/Applications/Xcode.app/Contents/Applications/Accessibility Inspector.app`. Point at the target application. Confirm the AX attribute exists and has a non-null value. Note the exact attribute name string (e.g. `AXMenus`, `AXFocusedWindow`).
+
+### Stage 2 — JXA Probe (30-second sanity check)
+
+```bash
+osascript -l JavaScript -e '
+ var sys = Application("System Events");
+ var proc = sys.processes.whose({ name: "Finder" })[0];
+ // inspect proc.windows(), proc.menuBars() etc.
+ JSON.stringify(proc.windows[0].attributes.whose({ name: "AXRole" })[0].value())
+'
+```
+
+If this returns the expected value, proceed to Stage 3. If it errors or returns null, the attribute is not accessible via standard AX for this app/macOS version — stop and reassess.
+
+### Stage 3 — Rust Probe in examples/
+
+Add a probe function to `examples/axprobe.rs` that calls the candidate AX API directly and prints the result:
+
+```rust
+// examples/axprobe.rs
+fn probe_ax_menus(pid: i32) {
+ let app = ax_element::element_for_pid(pid);
+ let menus = ax_attrs::copy_ax_array(&app, "AXMenus");
+ println!("AXMenus count: {:?}", menus.map(|v| v.len()));
+}
+```
+
+Run: `cargo run -p agent-desktop-macos --example axprobe --features dev-tools -- --pid $(pgrep Finder)`
+
+Only proceed to Stage 4 when Stage 3 prints the expected value.
+
+### Stage 4 — Implement as `pub(crate)` + Unit Test
+
+1. Add the function to the appropriate `ax_*.rs` file with `pub(crate)` visibility
+2. Write a unit test (with MockAdapter or synthetic tree if real AX not available)
+3. Wire into `adapter.rs` / `adapter.get_tree()`
+
+### Why the Stages Matter
+
+- AX attribute availability varies by app (Electron apps expose nothing; native apps vary)
+- Some attributes exist but always return `kAXErrorNoValue` for certain element subtypes
+- Stage 2 costs 30 seconds; Stage 3 costs 5 minutes; Stage 4 costs hours — fail early
+- The probe files double as executable documentation of how each AX API was validated
+
+---
+
## References
- PRD v2.0: `agent_desktop_prd_v2.pdf`
diff --git a/src/batch_dispatch.rs b/src/batch_dispatch.rs
index c91c60bfd..9a0c83870 100644
--- a/src/batch_dispatch.rs
+++ b/src/batch_dispatch.rs
@@ -1,6 +1,6 @@
use agent_desktop_core::{
commands::{
- check, clear, clipboard_clear, clipboard_get, clipboard_set, click, close_app, collapse,
+ check, clear, click, clipboard_clear, clipboard_get, clipboard_set, close_app, collapse,
double_click, drag, expand, find, focus, focus_window, get, helpers, hover, is_check,
key_down, key_up, launch, list_apps, list_surfaces, list_windows, maximize, minimize,
mouse_click, mouse_down, mouse_move, mouse_up, move_window, permissions, press,
@@ -23,8 +23,9 @@ pub fn dispatch_batch_command(
}
fn req_str(v: &Value, key: &str) -> Result<String, AppError> {
- str_field(v, key)
- .ok_or_else(|| AppError::invalid_input(format!("Batch: missing required field '{key}'")))
+ str_field(v, key).ok_or_else(|| {
+ AppError::invalid_input(format!("Batch: missing required field '{key}'"))
+ })
}
match command {
@@ -32,10 +33,23 @@ pub fn dispatch_batch_command(
snapshot::SnapshotArgs {
app: str_field(&args, "app"),
window_id: str_field(&args, "window_id"),
- max_depth: args.get("max_depth").and_then(|v| v.as_u64()).map(|v| v as u8).unwrap_or(10),
- include_bounds: args.get("include_bounds").and_then(|v| v.as_bool()).unwrap_or(false),
- interactive_only: args.get("interactive_only").and_then(|v| v.as_bool()).unwrap_or(false),
- compact: args.get("compact").and_then(|v| v.as_bool()).unwrap_or(false),
+ max_depth: args
+ .get("max_depth")
+ .and_then(|v| v.as_u64())
+ .map(|v| v as u8)
+ .unwrap_or(10),
+ include_bounds: args
+ .get("include_bounds")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false),
+ interactive_only: args
+ .get("interactive_only")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false),
+ compact: args
+ .get("compact")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false),
surface: parse_batch_surface(args.get("surface").and_then(|v| v.as_str())),
},
adapter,
@@ -69,7 +83,9 @@ pub fn dispatch_batch_command(
get::GetArgs {
ref_id: req_str(&args, "ref_id")?,
property: crate::dispatch::parse_get_property(
- args.get("property").and_then(|v| v.as_str()).unwrap_or("text"),
+ args.get("property")
+ .and_then(|v| v.as_str())
+ .unwrap_or("text"),
)?,
},
adapter,
@@ -79,46 +95,84 @@ pub fn dispatch_batch_command(
is_check::IsArgs {
ref_id: req_str(&args, "ref_id")?,
property: crate::dispatch::parse_is_property(
- args.get("property").and_then(|v| v.as_str()).unwrap_or("visible"),
+ args.get("property")
+ .and_then(|v| v.as_str())
+ .unwrap_or("visible"),
)?,
},
adapter,
),
- "click" => click::execute(click::ClickArgs { ref_id: req_str(&args, "ref_id")? }, adapter),
+ "click" => click::execute(
+ click::ClickArgs {
+ ref_id: req_str(&args, "ref_id")?,
+ },
+ adapter,
+ ),
"double-click" => double_click::execute(
- double_click::DoubleClickArgs { ref_id: req_str(&args, "ref_id")? },
+ double_click::DoubleClickArgs {
+ ref_id: req_str(&args, "ref_id")?,
+ },
adapter,
),
"triple-click" => triple_click::execute(
- triple_click::TripleClickArgs { ref_id: req_str(&args, "ref_id")? },
+ triple_click::TripleClickArgs {
+ ref_id: req_str(&args, "ref_id")?,
+ },
adapter,
),
"right-click" => right_click::execute(
- right_click::RightClickArgs { ref_id: req_str(&args, "ref_id")? },
+ right_click::RightClickArgs {
+ ref_id: req_str(&args, "ref_id")?,
+ },
+ adapter,
+ ),
+ "focus" => focus::execute(
+ helpers::RefArgs {
+ ref_id: req_str(&args, "ref_id")?,
+ },
+ adapter,
+ ),
+ "toggle" => toggle::execute(
+ helpers::RefArgs {
+ ref_id: req_str(&args, "ref_id")?,
+ },
+ adapter,
+ ),
+ "check" => check::execute(
+ check::CheckArgs {
+ ref_id: req_str(&args, "ref_id")?,
+ },
+ adapter,
+ ),
+ "uncheck" => uncheck::execute(
+ uncheck::UncheckArgs {
+ ref_id: req_str(&args, "ref_id")?,
+ },
+ adapter,
+ ),
+ "expand" => expand::execute(
+ helpers::RefArgs {
+ ref_id: req_str(&args, "ref_id")?,
+ },
+ adapter,
+ ),
+ "collapse" => collapse::execute(
+ helpers::RefArgs {
+ ref_id: req_str(&args, "ref_id")?,
+ },
+ adapter,
+ ),
+ "clear" => clear::execute(
+ clear::ClearArgs {
+ ref_id: req_str(&args, "ref_id")?,
+ },
adapter,
),
- "focus" => focus::execute(helpers::RefArgs { ref_id: req_str(&args, "ref_id")? }, adapter),
- "toggle" => {
- toggle::execute(helpers::RefArgs { ref_id: req_str(&args, "ref_id")? }, adapter)
- }
- "check" => {
- check::execute(check::CheckArgs { ref_id: req_str(&args, "ref_id")? }, adapter)
- }
- "uncheck" => {
- uncheck::execute(uncheck::UncheckArgs { ref_id: req_str(&args, "ref_id")? }, adapter)
- }
- "expand" => {
- expand::execute(helpers::RefArgs { ref_id: req_str(&args, "ref_id")? }, adapter)
- }
- "collapse" => {
- collapse::execute(helpers::RefArgs { ref_id: req_str(&args, "ref_id")? }, adapter)
- }
- "clear" => {
- clear::execute(clear::ClearArgs { ref_id: req_str(&args, "ref_id")? }, adapter)
- }
"scroll-to" => scroll_to::execute(
- scroll_to::ScrollToArgs { ref_id: req_str(&args, "ref_id")? },
+ scroll_to::ScrollToArgs {
+ ref_id: req_str(&args, "ref_id")?,
+ },
adapter,
),
@@ -150,32 +204,43 @@ pub fn dispatch_batch_command(
scroll::ScrollArgs {
ref_id: req_str(&args, "ref_id")?,
direction: parse_direction(
- args.get("direction").and_then(|v| v.as_str()).unwrap_or("down"),
+ args.get("direction")
+ .and_then(|v| v.as_str())
+ .unwrap_or("down"),
)?,
- amount: args.get("amount").and_then(|v| v.as_u64()).map(|v| v as u32).unwrap_or(3),
+ amount: args
+ .get("amount")
+ .and_then(|v| v.as_u64())
+ .map(|v| v as u32)
+ .unwrap_or(3),
},
adapter,
),
"press" => press::execute(
- press::PressArgs { combo: req_str(&args, "combo")?, app: str_field(&args, "app") },
+ press::PressArgs {
+ combo: req_str(&args, "combo")?,
+ app: str_field(&args, "app"),
+ },
adapter,
),
"key-down" => key_down::execute(
- key_down::KeyDownArgs { combo: req_str(&args, "combo")? },
+ key_down::KeyDownArgs {
+ combo: req_str(&args, "combo")?,
+ },
adapter,
),
"key-up" => key_up::execute(
- key_up::KeyUpArgs { combo: req_str(&args, "combo")? },
+ key_up::KeyUpArgs {
+ combo: req_str(&args, "combo")?,
+ },
adapter,
),
"hover" => {
- let xy = str_field(&args, "xy")
- .map(|s| parse_xy(&s))
- .transpose()?;
+ let xy = str_field(&args, "xy").map(|s| parse_xy(&s)).transpose()?;
hover::execute(
hover::HoverArgs {
ref_id: str_field(&args, "ref_id"),
@@ -214,7 +279,10 @@ pub fn dispatch_batch_command(
"mouse-click" => {
let xy = req_str(&args, "xy")?;
let (x, y) = parse_xy(&xy)?;
- let button = args.get("button").and_then(|v| v.as_str()).unwrap_or("left");
+ let button = args
+ .get("button")
+ .and_then(|v| v.as_str())
+ .unwrap_or("left");
mouse_click::execute(
mouse_click::MouseClickArgs {
x,
@@ -229,9 +297,16 @@ pub fn dispatch_batch_command(
"mouse-down" => {
let xy = req_str(&args, "xy")?;
let (x, y) = parse_xy(&xy)?;
- let button = args.get("button").and_then(|v| v.as_str()).unwrap_or("left");
+ let button = args
+ .get("button")
+ .and_then(|v| v.as_str())
+ .unwrap_or("left");
mouse_down::execute(
- mouse_down::MouseDownArgs { x, y, button: parse_mouse_button(button)? },
+ mouse_down::MouseDownArgs {
+ x,
+ y,
+ button: parse_mouse_button(button)?,
+ },
adapter,
)
}
@@ -239,9 +314,16 @@ pub fn dispatch_batch_command(
"mouse-up" => {
let xy = req_str(&args, "xy")?;
let (x, y) = parse_xy(&xy)?;
- let button = args.get("button").and_then(|v| v.as_str()).unwrap_or("left");
+ let button = args
+ .get("button")
+ .and_then(|v| v.as_str())
+ .unwrap_or("left");
mouse_up::execute(
- mouse_up::MouseUpArgs { x, y, button: parse_mouse_button(button)? },
+ mouse_up::MouseUpArgs {
+ x,
+ y,
+ button: parse_mouse_button(button)?,
+ },
adapter,
)
}
@@ -249,7 +331,10 @@ pub fn dispatch_batch_command(
"launch" => launch::execute(
launch::LaunchArgs {
app: req_str(&args, "app")?,
- timeout_ms: args.get("timeout").and_then(|v| v.as_u64()).unwrap_or(30000),
+ timeout_ms: args
+ .get("timeout")
+ .and_then(|v| v.as_u64())
+ .unwrap_or(30000),
},
adapter,
),
@@ -262,9 +347,12 @@ pub fn dispatch_batch_command(
adapter,
),
- "list-windows" => {
- list_windows::execute(list_windows::ListWindowsArgs { app: str_field(&args, "app") }, adapter)
- }
+ "list-windows" => list_windows::execute(
+ list_windows::ListWindowsArgs {
+ app: str_field(&args, "app"),
+ },
+ adapter,
+ ),
"list-apps" => list_apps::execute(adapter),
@@ -296,17 +384,23 @@ pub fn dispatch_batch_command(
),
"minimize" => minimize::execute(
- minimize::MinimizeArgs { app: str_field(&args, "app") },
+ minimize::MinimizeArgs {
+ app: str_field(&args, "app"),
+ },
adapter,
),
"maximize" => maximize::execute(
- maximize::MaximizeArgs { app: str_field(&args, "app") },
+ maximize::MaximizeArgs {
+ app: str_field(&args, "app"),
+ },
adapter,
),
"restore" => restore::execute(
- restore::RestoreArgs { app: str_field(&args, "app") },
+ restore::RestoreArgs {
+ app: str_field(&args, "app"),
+ },
adapter,
),
@@ -320,16 +414,24 @@ pub fn dispatch_batch_command(
element: str_field(&args, "element"),
window: str_field(&args, "window"),
text: str_field(&args, "text"),
- timeout_ms: args.get("timeout_ms").and_then(|v| v.as_u64()).unwrap_or(30000),
+ timeout_ms: args
+ .get("timeout_ms")
+ .and_then(|v| v.as_u64())
+ .unwrap_or(30000),
menu: args.get("menu").and_then(|v| v.as_bool()).unwrap_or(false),
- menu_closed: args.get("menu_closed").and_then(|v| v.as_bool()).unwrap_or(false),
+ menu_closed: args
+ .get("menu_closed")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false),
app: str_field(&args, "app"),
},
adapter,
),
"list-surfaces" => list_surfaces::execute(
- list_surfaces::ListSurfacesArgs { app: str_field(&args, "app") },
+ list_surfaces::ListSurfacesArgs {
+ app: str_field(&args, "app"),
+ },
adapter,
),
@@ -337,7 +439,10 @@ pub fn dispatch_batch_command(
"permissions" => permissions::execute(
permissions::PermissionsArgs {
- request: args.get("request").and_then(|v| v.as_bool()).unwrap_or(false),
+ request: args
+ .get("request")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false),
},
adapter,
),
@@ -355,11 +460,11 @@ pub fn dispatch_batch_command(
fn parse_batch_surface(s: Option<&str>) -> agent_desktop_core::adapter::SnapshotSurface {
use agent_desktop_core::adapter::SnapshotSurface;
match s {
- Some("menu") => SnapshotSurface::Menu,
- Some("sheet") => SnapshotSurface::Sheet,
+ Some("menu") => SnapshotSurface::Menu,
+ Some("sheet") => SnapshotSurface::Sheet,
Some("popover") => SnapshotSurface::Popover,
- Some("alert") => SnapshotSurface::Alert,
+ Some("alert") => SnapshotSurface::Alert,
Some("focused") => SnapshotSurface::Focused,
- _ => SnapshotSurface::Window,
+ _ => SnapshotSurface::Window,
}
}
diff --git a/src/cli.rs b/src/cli.rs
index 5eb82fc0c..0e6e4a431 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -105,7 +105,12 @@ EXAMPLES
agent-desktop batch '[{\"command\":\"click\",\"args\":{\"ref_id\":\"@e1\"}}]'"
)]
pub struct Cli {
- #[arg(long, short = 'v', global = true, help = "Enable debug logging to stderr")]
+ #[arg(
+ long,
+ short = 'v',
+ global = true,
+ help = "Enable debug logging to stderr"
+ )]
pub verbose: bool,
#[command(subcommand)]
diff --git a/src/cli_args.rs b/src/cli_args.rs
index 04b90954e..18ac13e87 100644
--- a/src/cli_args.rs
+++ b/src/cli_args.rs
@@ -15,7 +15,11 @@ pub enum Surface {
pub struct SnapshotArgs {
#[arg(long, help = "Filter to application by name")]
pub app: Option<String>,
- #[arg(long, name = "window-id", help = "Filter to window ID (from list-windows)")]
+ #[arg(
+ long,
+ name = "window-id",
+ help = "Filter to window ID (from list-windows)"
+ )]
pub window_id: Option<String>,
#[arg(long, default_value = "10", help = "Maximum tree depth")]
pub max_depth: u8,
@@ -33,7 +37,10 @@ pub struct SnapshotArgs {
pub struct FindArgs {
#[arg(long, help = "Filter to application by name")]
pub app: Option<String>,
- #[arg(long, help = "Match by accessibility role (button, textfield, checkbox ...)")]
+ #[arg(
+ long,
+ help = "Match by accessibility role (button, textfield, checkbox ...)"
+ )]
pub role: Option<String>,
#[arg(long, help = "Match by accessible name or label")]
pub name: Option<String>,
@@ -55,7 +62,11 @@ pub struct FindArgs {
pub struct ScreenshotArgs {
#[arg(long, help = "Filter to application by name")]
pub app: Option<String>,
- #[arg(long, name = "window-id", help = "Filter to window ID (from list-windows)")]
+ #[arg(
+ long,
+ name = "window-id",
+ help = "Filter to window ID (from list-windows)"
+ )]
pub window_id: Option<String>,
#[arg(value_name = "PATH", help = "Save to file instead of returning base64")]
pub output_path: Option<std::path::PathBuf>,
@@ -65,7 +76,11 @@ pub struct ScreenshotArgs {
pub struct GetArgs {
#[arg(value_name = "REF", help = "Element ref from snapshot (@e1, @e2 ...)")]
pub ref_id: String,
- #[arg(long, default_value = "text", help = "Property: text, value, title, bounds, role, states")]
+ #[arg(
+ long,
+ default_value = "text",
+ help = "Property: text, value, title, bounds, role, states"
+ )]
pub property: String,
}
@@ -73,7 +88,11 @@ pub struct GetArgs {
pub struct IsArgs {
#[arg(value_name = "REF", help = "Element ref from snapshot (@e1, @e2 ...)")]
pub ref_id: String,
- #[arg(long, default_value = "visible", help = "State: visible, enabled, checked, focused, expanded")]
+ #[arg(
+ long,
+ default_value = "visible",
+ help = "State: visible, enabled, checked, focused, expanded"
+ )]
pub property: String,
}
@@ -95,7 +114,11 @@ pub struct TypeArgs {
pub struct SetValueArgs {
#[arg(value_name = "REF", help = "Element ref from snapshot (@e1, @e2 ...)")]
pub ref_id: String,
- #[arg(value_name = "VALUE", allow_hyphen_values = true, help = "Value to set")]
+ #[arg(
+ value_name = "VALUE",
+ allow_hyphen_values = true,
+ help = "Value to set"
+ )]
pub value: String,
}
@@ -111,7 +134,11 @@ pub struct SelectArgs {
pub struct ScrollArgs {
#[arg(value_name = "REF", help = "Element ref from snapshot (@e1, @e2 ...)")]
pub ref_id: String,
- #[arg(long, default_value = "down", help = "Direction: up, down, left, right")]
+ #[arg(
+ long,
+ default_value = "down",
+ help = "Direction: up, down, left, right"
+ )]
pub direction: String,
#[arg(long, default_value = "3", help = "Number of scroll units")]
pub amount: u32,
@@ -119,7 +146,10 @@ pub struct ScrollArgs {
#[derive(Parser, Debug)]
pub struct PressArgs {
- #[arg(value_name = "COMBO", help = "Key combo: return, escape, cmd+c, shift+tab ...")]
+ #[arg(
+ value_name = "COMBO",
+ help = "Key combo: return, escape, cmd+c, shift+tab ..."
+ )]
pub combo: String,
#[arg(long, help = "Target application name (focuses app before pressing)")]
pub app: Option<String>,
@@ -127,7 +157,10 @@ pub struct PressArgs {
#[derive(Parser, Debug)]
pub struct KeyComboArgs {
- #[arg(value_name = "COMBO", help = "Key or modifier to hold/release: shift, cmd, ctrl ...")]
+ #[arg(
+ value_name = "COMBO",
+ help = "Key or modifier to hold/release: shift, cmd, ctrl ..."
+ )]
pub combo: String,
}
@@ -165,7 +198,11 @@ pub struct MouseMoveArgs {
pub struct MouseClickArgs {
#[arg(long, help = "Absolute coordinates as x,y")]
pub xy: String,
- #[arg(long, default_value = "left", help = "Mouse button: left, right, middle")]
+ #[arg(
+ long,
+ default_value = "left",
+ help = "Mouse button: left, right, middle"
+ )]
pub button: String,
#[arg(long, default_value = "1", help = "Number of clicks")]
pub count: u32,
@@ -175,7 +212,11 @@ pub struct MouseClickArgs {
pub struct MousePointArgs {
#[arg(long, help = "Absolute coordinates as x,y")]
pub xy: String,
- #[arg(long, default_value = "left", help = "Mouse button: left, right, middle")]
+ #[arg(
+ long,
+ default_value = "left",
+ help = "Mouse button: left, right, middle"
+ )]
pub button: String,
}
@@ -183,7 +224,11 @@ pub struct MousePointArgs {
pub struct LaunchArgs {
#[arg(value_name = "APP", help = "Application name or bundle ID")]
pub app: String,
- #[arg(long, default_value = "30000", help = "Max time in ms to wait for the window to appear")]
+ #[arg(
+ long,
+ default_value = "30000",
+ help = "Max time in ms to wait for the window to appear"
+ )]
pub timeout: u64,
}
@@ -251,9 +296,16 @@ pub struct WaitArgs {
pub element: Option<String>,
#[arg(long, help = "Block until a window with this title appears")]
pub window: Option<String>,
- #[arg(long, help = "Block until text appears in the app's accessibility tree")]
+ #[arg(
+ long,
+ help = "Block until text appears in the app's accessibility tree"
+ )]
pub text: Option<String>,
- #[arg(long, default_value = "30000", help = "Timeout in milliseconds for element/window/text waits")]
+ #[arg(
+ long,
+ default_value = "30000",
+ help = "Timeout in milliseconds for element/window/text waits"
+ )]
pub timeout: u64,
#[arg(long, help = "Block until a context menu is open")]
pub menu: bool,
diff --git a/src/dispatch.rs b/src/dispatch.rs
index f43148aea..ff65c3f8f 100644
--- a/src/dispatch.rs
+++ b/src/dispatch.rs
@@ -2,7 +2,7 @@ use agent_desktop_core::{
action::{Direction, MouseButton},
adapter::PlatformAdapter,
commands::{
- batch, check, clear, clipboard_clear, clipboard_get, clipboard_set, click, close_app,
+ batch, check, clear, click, clipboard_clear, clipboard_get, clipboard_set, close_app,
collapse, double_click, drag, expand, find, focus, focus_window, get, helpers, hover,
is_check, key_down, key_up, launch, list_apps, list_surfaces, list_windows, maximize,
minimize, mouse_click, mouse_down, mouse_move, mouse_up, move_window, permissions, press,
@@ -82,12 +82,18 @@ pub fn dispatch(cmd: Commands, adapter: &dyn PlatformAdapter) -> Result<Value, A
}
Commands::Type(a) => type_text::execute(
- type_text::TypeArgs { ref_id: a.ref_id, text: a.text },
+ type_text::TypeArgs {
+ ref_id: a.ref_id,
+ text: a.text,
+ },
adapter,
),
Commands::SetValue(a) => set_value::execute(
- set_value::SetValueArgs { ref_id: a.ref_id, value: a.value },
+ set_value::SetValueArgs {
+ ref_id: a.ref_id,
+ value: a.value,
+ },
adapter,
),
@@ -100,12 +106,13 @@ pub fn dispatch(cmd: Commands, adapter: &dyn PlatformAdapter) -> Result<Value, A
uncheck::execute(uncheck::UncheckArgs { ref_id: a.ref_id }, adapter)
}
Commands::Expand(a) => expand::execute(helpers::RefArgs { ref_id: a.ref_id }, adapter),
- Commands::Collapse(a) => {
- collapse::execute(helpers::RefArgs { ref_id: a.ref_id }, adapter)
- }
+ Commands::Collapse(a) => collapse::execute(helpers::RefArgs { ref_id: a.ref_id }, adapter),
Commands::Select(a) => select::execute(
- select::SelectArgs { ref_id: a.ref_id, value: a.value },
+ select::SelectArgs {
+ ref_id: a.ref_id,
+ value: a.value,
+ },
adapter,
),
@@ -122,9 +129,13 @@ pub fn dispatch(cmd: Commands, adapter: &dyn PlatformAdapter) -> Result<Value, A
scroll_to::execute(scroll_to::ScrollToArgs { ref_id: a.ref_id }, adapter)
}
- Commands::Press(a) => {
- press::execute(press::PressArgs { combo: a.combo, app: a.app }, adapter)
- }
+ Commands::Press(a) => press::execute(
+ press::PressArgs {
+ combo: a.combo,
+ app: a.app,
+ },
+ adapter,
+ ),
Commands::KeyDown(a) => {
key_down::execute(key_down::KeyDownArgs { combo: a.combo }, adapter)
@@ -173,7 +184,11 @@ pub fn dispatch(cmd: Commands, adapter: &dyn PlatformAdapter) -> Result<Value, A
Commands::MouseDown(a) => {
let (x, y) = parse_xy(&a.xy)?;
mouse_down::execute(
- mouse_down::MouseDownArgs { x, y, button: parse_mouse_button(&a.button)? },
+ mouse_down::MouseDownArgs {
+ x,
+ y,
+ button: parse_mouse_button(&a.button)?,
+ },
adapter,
)
}
@@ -181,17 +196,28 @@ pub fn dispatch(cmd: Commands, adapter: &dyn PlatformAdapter) -> Result<Value, A
Commands::MouseUp(a) => {
let (x, y) = parse_xy(&a.xy)?;
mouse_up::execute(
- mouse_up::MouseUpArgs { x, y, button: parse_mouse_button(&a.button)? },
+ mouse_up::MouseUpArgs {
+ x,
+ y,
+ button: parse_mouse_button(&a.button)?,
+ },
adapter,
)
}
- Commands::Launch(a) => {
- launch::execute(launch::LaunchArgs { app: a.app, timeout_ms: a.timeout }, adapter)
- }
+ Commands::Launch(a) => launch::execute(
+ launch::LaunchArgs {
+ app: a.app,
+ timeout_ms: a.timeout,
+ },
+ adapter,
+ ),
Commands::CloseApp(a) => close_app::execute(
- close_app::CloseAppArgs { app: a.app, force: a.force },
+ close_app::CloseAppArgs {
+ app: a.app,
+ force: a.force,
+ },
adapter,
),
@@ -201,10 +227,9 @@ pub fn dispatch(cmd: Commands, adapter: &dyn PlatformAdapter) -> Result<Value, A
Commands::ListApps => list_apps::execute(adapter),
- Commands::ListSurfaces(a) => list_surfaces::execute(
- list_surfaces::ListSurfacesArgs { app: a.app },
- adapter,
- ),
+ Commands::ListSurfaces(a) => {
+ list_surfaces::execute(list_surfaces::ListSurfacesArgs { app: a.app }, adapter)
+ }
Commands::FocusWindow(a) => focus_window::execute(
focus_window::FocusWindowArgs {
@@ -216,26 +241,28 @@ pub fn dispatch(cmd: Commands, adapter: &dyn PlatformAdapter) -> Result<Value, A
),
Commands::ResizeWindow(a) => resize_window::execute(
- resize_window::ResizeWindowArgs { app: a.app, width: a.width, height: a.height },
+ resize_window::ResizeWindowArgs {
+ app: a.app,
+ width: a.width,
+ height: a.height,
+ },
adapter,
),
Commands::MoveWindow(a) => move_window::execute(
- move_window::MoveWindowArgs { app: a.app, x: a.x, y: a.y },
+ move_window::MoveWindowArgs {
+ app: a.app,
+ x: a.x,
+ y: a.y,
+ },
adapter,
),
- Commands::Minimize(a) => {
- minimize::execute(minimize::MinimizeArgs { app: a.app }, adapter)
- }
+ Commands::Minimize(a) => minimize::execute(minimize::MinimizeArgs { app: a.app }, adapter),
- Commands::Maximize(a) => {
- maximize::execute(maximize::MaximizeArgs { app: a.app }, adapter)
- }
+ Commands::Maximize(a) => maximize::execute(maximize::MaximizeArgs { app: a.app }, adapter),
- Commands::Restore(a) => {
- restore::execute(restore::RestoreArgs { app: a.app }, adapter)
- }
+ Commands::Restore(a) => restore::execute(restore::RestoreArgs { app: a.app }, adapter),
Commands::ClipboardGet => clipboard_get::execute(adapter),
Commands::ClipboardSet(a) => clipboard_set::execute(a.text, adapter),
@@ -257,10 +284,9 @@ pub fn dispatch(cmd: Commands, adapter: &dyn PlatformAdapter) -> Result<Value, A
Commands::Status => status::execute(adapter),
- Commands::Permissions(a) => permissions::execute(
- permissions::PermissionsArgs { request: a.request },
- adapter,
- ),
+ Commands::Permissions(a) => {
+ permissions::execute(permissions::PermissionsArgs { request: a.request }, adapter)
+ }
Commands::Version(a) => version::execute(version::VersionArgs { json: a.json }),
@@ -346,12 +372,14 @@ pub(crate) fn parse_xy(s: &str) -> Result<(f64, f64), AppError> {
"Invalid coordinates '{s}'. Expected format: x,y (e.g., 500,300)"
)));
}
- let x: f64 = parts[0].trim().parse().map_err(|_| {
- AppError::invalid_input(format!("Invalid x coordinate: '{}'", parts[0]))
- })?;
- let y: f64 = parts[1].trim().parse().map_err(|_| {
- AppError::invalid_input(format!("Invalid y coordinate: '{}'", parts[1]))
- })?;
+ let x: f64 = parts[0]
+ .trim()
+ .parse()
+ .map_err(|_| AppError::invalid_input(format!("Invalid x coordinate: '{}'", parts[0])))?;
+ let y: f64 = parts[1]
+ .trim()
+ .parse()
+ .map_err(|_| AppError::invalid_input(format!("Invalid y coordinate: '{}'", parts[1])))?;
Ok((x, y))
}
@@ -363,14 +391,14 @@ fn parse_xy_opt(s: Option<&str>) -> Result<Option<(f64, f64)>, AppError> {
}
fn cli_surface_to_core(s: &crate::cli::Surface) -> agent_desktop_core::adapter::SnapshotSurface {
- use agent_desktop_core::adapter::SnapshotSurface;
use crate::cli::Surface;
+ use agent_desktop_core::adapter::SnapshotSurface;
match s {
- Surface::Window => SnapshotSurface::Window,
+ Surface::Window => SnapshotSurface::Window,
Surface::Focused => SnapshotSurface::Focused,
- Surface::Menu => SnapshotSurface::Menu,
- Surface::Sheet => SnapshotSurface::Sheet,
+ Surface::Menu => SnapshotSurface::Menu,
+ Surface::Sheet => SnapshotSurface::Sheet,
Surface::Popover => SnapshotSurface::Popover,
- Surface::Alert => SnapshotSurface::Alert,
+ Surface::Alert => SnapshotSurface::Alert,
}
}
diff --git a/src/main.rs b/src/main.rs
index 77311af00..e0543a894 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -45,10 +45,9 @@ fn main() {
match &cmd {
Commands::Version(a) => {
- let result =
- agent_desktop_core::commands::version::execute(
- agent_desktop_core::commands::version::VersionArgs { json: a.json },
- );
+ let result = agent_desktop_core::commands::version::execute(
+ agent_desktop_core::commands::version::VersionArgs { json: a.json },
+ );
finish(cmd_name, result);
return;
}
diff --git a/tests/agentic_test_notes.md b/tests/agentic_test_notes.md
new file mode 100644
index 000000000..46886ff0f
--- /dev/null
+++ b/tests/agentic_test_notes.md
@@ -0,0 +1,305 @@
+# Agent-Desktop Agentic Test Run
+## Date: 2026-02-19
+
+## Task: Multi-step desktop automation (TextEdit + Calculator)
+
+---
+
+## Command Results
+
+### Phase 1: Environment Assessment
+
+#### 1. `status`
+- Result: OK — returns permissions, platform, ref_count, version
+- Issues: NONE
+
+#### 2. `permissions`
+- Result: OK — `{"granted":true}`
+- Issues: NONE
+
+#### 3. `list-apps`
+- Result: OK — returned 8 apps with name + pid
+- Issues:
+ - **BUG (minor):** `data` is a bare array, not `{"apps":[...]}`. Inconsistent with other commands that nest under a named key. An agent parsing `d["data"]["apps"]` gets a TypeError. Should be `{"apps": [...]}`.
+ - **MISSING:** `bundle_id` is always `null`. Should be populated (e.g. `com.apple.TextEdit`) — agents need this for reliable app identification since display names can vary by locale.
+
+### Phase 2: App Launch & Window Management
+
+#### 4. `launch Calculator`
+- Result: FAILED — `"App 'Calculator' launched but no window found"`
+- Issues:
+ - **BUG:** The app did launch successfully and had a window 2 seconds later. `launch` doesn't wait long enough for the window to appear. Should poll for window with a configurable timeout (default ~5s) before declaring failure.
+ - The app DID get launched — the error is misleading. Should differentiate "failed to launch" from "launched but window not yet visible."
+
+#### 5. `list-windows --app TextEdit`
+- Result: OK — correct window info with id, title, pid, is_focused
+- Issues: NONE
+
+#### 6. `focus-window --app TextEdit`
+- Result: OK — focused and returned window info
+- Issues: NONE
+
+### Phase 3: Observation — Understanding the UI
+
+#### 7. `snapshot --app TextEdit --interactive-only --compact`
+- Result: OK — 12 refs, clean tree with roles and names
+- Issues: NONE — interactive-only and compact flags work well together
+
+#### 8. `find --app TextEdit --role button`
+- Result: OK — found 3 buttons with ref, role, path
+- Issues:
+ - **IMPROVEMENT:** Buttons @e9, @e10, @e11 have `"name": null`. These are the Bold/Italic/Underline toolbar buttons. The `find` output gives no way to distinguish them without snapshotting. Should fall back to showing `description` or `title` when `name` is null.
+
+#### 9. `find --app TextEdit --role textfield`
+- Result: OK — found @e1 with path `["window:Untitled.rtf","scrollarea"]`
+- Issues: NONE
+
+### Phase 4: Interaction — Writing Content
+
+#### 10. `click @e1`
+- Result: OK
+- Issues: NONE
+
+#### 11. `type @e1 "multi-line text"`
+- Result: OK — multi-line text with newlines typed correctly
+- Issues: NONE — handles newlines in quoted strings well
+
+#### 12. `get @e1 --property text`
+- Result: OK — returned full typed text with preserved newlines
+- Issues: NONE
+
+### Phase 5: Text Selection & Clipboard
+
+#### 13. `press --app TextEdit "cmd+a"`
+- Result: OK
+- Issues: NONE
+
+#### 14. `press --app TextEdit "cmd+c"`
+- Result: OK
+- Issues: NONE
+
+#### 15. `clipboard-get`
+- Result: OK — clipboard had the full document text
+- Issues: NONE
+
+#### 16. `clipboard-set "new text"`
+- Result: OK
+- Issues: NONE
+
+#### 17. `clipboard-get` (after set)
+- Result: OK — verified clipboard-set worked
+- Issues: NONE
+
+### Phase 6: Advanced Interactions
+
+#### 18. `set-value @e1 "replacement"`
+- Result: OK — text replaced directly
+- Issues: NONE
+
+#### 19. `get @e1 --property value`
+- Result: OK — confirmed set-value text
+- Issues: NONE — `text` and `value` both return the textfield content (consistent)
+
+#### 20. `double-click @e1`
+- Result: OK
+- Issues: NONE (visually selected a word)
+
+#### 21. `right-click @e1`
+- Result: OK — context menu opened
+- Issues: NONE
+
+#### 22. `wait --menu --app TextEdit`
+- Result: OK — `{"elapsed_ms":25,"found":true}`
+- Issues: NONE
+
+#### 23. `list-surfaces --app TextEdit` (with menu open)
+- Result: OK — detected `context_menu` with 31 items
+- Issues: NONE
+
+#### 24. `snapshot --surface menu --app TextEdit`
+- Result: OK — full context menu tree with 31 menu items
+- Issues: NONE
+
+#### 25. `press "escape"`
+- Result: OK — dismissed context menu
+- Issues:
+ - **BUG (moderate):** After pressing escape, the NEXT `snapshot --app TextEdit` (default surface=window) still included the 31 context menu refs mixed in with the window refs (e.g. @e2-@e32 were menuitems). The menu refs only disappeared on a subsequent snapshot. Likely a timing issue — the menu hasn't fully closed in the AX tree when the snapshot happens immediately. Should either: (a) poll until the menu is gone, or (b) filter out menu items from window-surface snapshots.
+
+### Phase 7: Scroll
+
+#### 26. `scroll @e1 --direction down --amount 3`
+- Result: OK
+- Issues: NONE — no way to verify scroll position changed (no scroll offset in get properties)
+
+#### 27. `scroll @e1 --direction up --amount 3`
+- Result: OK
+- Issues: NONE
+
+### Phase 8: Screenshot & State Queries
+
+#### 28. `screenshot --app TextEdit /tmp/agentic_test.png`
+- Result: OK — 96KB PNG captured correctly
+- Issues: NONE
+
+#### 29. `is @e1 --property visible`
+- Result: OK — `true`
+- Issues: NONE
+
+#### 30. `is @e1 --property enabled`
+- Result: OK — `true`
+- Issues: NONE
+
+#### 31. `is @e1 --property focused`
+- Result: OK — `true`
+- Issues: NONE
+
+#### 32. `is @e1 --property checked`
+- Result: OK — `false` (textfield isn't checkable)
+- Issues:
+ - **IMPROVEMENT:** Returns `false` instead of something like `"not_applicable"`. An agent can't tell if the element is unchecked vs. not-a-checkbox. This could cause logic errors (e.g., agent thinks a checkbox is unchecked when it's actually a button).
+
+#### 33. `is @e1 --property expanded`
+- Result: OK — `false`
+- Issues: Same as checked — `false` vs "not applicable" ambiguity.
+
+#### 34. `get @e1 --property role`
+- Result: OK — `"textfield"`
+- Issues: NONE
+
+#### 35. `get @e1 --property bounds`
+- Result: OK structurally — `"value": null`
+- Issues:
+ - **BUG:** Bounds returns `null` for @e1 even though the element clearly has screen position. Need to use `--include-bounds` in snapshot to see bounds. The `get` command should return bounds independently without requiring a snapshot flag.
+
+#### 36. `get @e1 --property states`
+- Result: OK — `["focused"]`
+- Issues: NONE
+
+#### 37. `get @e1 --property title`
+- Result: OK — `null` (textfield has no title attribute)
+- Issues: NONE
+
+### Phase 9: Expand / Collapse / Toggle / Select
+
+#### 38. `expand @e4` (combobox)
+- Result: FAILED — `ACTION_FAILED` (err=-25205)
+- Issues:
+ - **BUG:** macOS comboboxes don't support AXExpand. The error message is raw AX error code with no suggestion. Should detect that expand isn't in the element's supported actions and return `ACTION_NOT_SUPPORTED` with suggestion: "This element doesn't support expand. Try 'click' to open it instead."
+
+#### 39. `collapse @e4` (combobox)
+- Result: FAILED — same as expand
+- Issues: Same as above — should return `ACTION_NOT_SUPPORTED`.
+
+#### 40. `toggle @e1` (textfield)
+- Result: OK (returned success)
+- Issues:
+ - **BUG:** `toggle` returned `ok:true` on a textfield which doesn't support toggling. No visible effect occurred. Should either fail with `ACTION_NOT_SUPPORTED` or check supported actions before attempting.
+
+#### 41. `select @e4 "Courier"` (combobox)
+- Result: OK structurally (returned success)
+- Issues:
+ - **BUG:** `select` returned `ok:true` but the combobox value remained "Helvetica" — the font did NOT change. The command silently succeeded without actually performing the selection. Should verify the value changed, or at minimum, not return success if the AX select action wasn't available.
+
+### Phase 10: Calculator (Cross-App Test)
+
+#### 42. `snapshot --app Calculator --interactive-only --compact`
+- Result: OK — 53 refs, all buttons properly named ("7", "8", "Add", "Equals", etc.)
+- Issues: NONE — excellent button labeling from macOS AX
+
+#### 43. Clicking buttons: `@e27 @e39 @e20 @e18 @e50` (43 × 8 =)
+- Result: OK — all 5 clicks registered, screenshot confirmed display showed 344
+- Issues:
+ - **MISSING:** Calculator display value is NOT in the accessibility tree. An agent cannot read the calculation result programmatically — must use screenshot + OCR. The display is likely a custom-rendered view with no AX value. This is a macOS/Apple limitation, not an agent-desktop bug, but worth documenting.
+
+### Phase 11: Close App
+
+#### 44. `close-app Calculator`
+- Result: Reported `ok:true` but app was still running
+- Issues:
+ - **BUG:** `close-app` reported success but Calculator was still listed in `list-windows` even after 1 second. Only `close-app --force` actually killed it. The non-force variant either isn't sending the right signal or isn't waiting for confirmation. Should either: (a) verify the app actually quit before returning success, or (b) return a different status like `"requested":true` if it can't confirm termination.
+
+### Phase 12: Error Handling
+
+#### 45. `click @e999`
+- Result: OK — `STALE_REF` with helpful suggestion
+- Issues: NONE — good error UX
+
+#### 46. `snapshot --app NonExistentApp`
+- Result: OK — `APP_NOT_FOUND`
+- Issues: NONE
+
+#### 47. `wait --element @e999 --timeout 1500`
+- Result: OK — `TIMEOUT` with suggestion
+- Issues: NONE
+
+#### 48. `wait --window "NonExistent" --app TextEdit --timeout 1500`
+- Result: OK — `TIMEOUT`
+- Issues: NONE
+
+#### 49. `batch [...] --stop-on-error`
+- Result: OK — stopped correctly after failing command, didn't execute remaining
+- Issues: NONE
+
+### Phase 13: Help / UX
+
+#### 50. `--help` (top-level)
+- Result: OK — shows all commands with categories
+- Issues:
+ - **IMPROVEMENT:** Subcommand descriptions are empty. Every `Commands:` line just shows the name with no description. Should have one-line descriptions (e.g., `snapshot Capture the accessibility tree of an application`).
+
+#### 51. `snapshot --help`
+- Result: OK — shows all options
+- Issues:
+ - **IMPROVEMENT:** No option descriptions. `--app`, `--max-depth`, `--compact` etc. have no help text. Should describe what each flag does.
+
+### Phase 14: Global Output Issues
+
+#### 52. Stderr duplication
+- Issues:
+ - **BUG:** Every error JSON is printed TWICE (both to stdout and stderr, or duplicated on one stream). Makes parsing harder — an agent doing `json.load(sys.stdin)` gets a parse error if stderr bleeds into stdout. Error should appear once on stdout (for machine parsing) and optionally on stderr (for human debugging with `--verbose`).
+
+---
+
+## Summary
+
+### Working Well (22/30 commands flawless)
+- `status`, `permissions`, `version` — solid
+- `snapshot` (all surface variants) — excellent, the core strength
+- `find` — works well for element discovery
+- `get` (text, value, role, states) — reliable
+- `is` (visible, enabled, focused) — works
+- `click`, `double-click`, `right-click` — all work
+- `type`, `set-value` — both work correctly including multi-line
+- `press` (with `--app` targeting) — keyboard automation solid
+- `clipboard-get`, `clipboard-set` — roundtrip perfect
+- `scroll` — works (hard to verify but no errors)
+- `wait` (all variants: ms, --element, --window, --menu) — timeouts & success both correct
+- `list-windows`, `focus-window` — reliable
+- `list-surfaces` — correctly detects menus
+- `screenshot` — clean captures
+- `batch` (with and without --stop-on-error) — correct behavior
+
+### Bugs Found (7)
+1. **`list-apps` data shape** — bare array instead of `{"apps":[...]}`
+2. **`launch` window detection** — doesn't wait long enough, reports failure when app launches fine
+3. **`close-app` (non-force)** — reports success but app keeps running
+4. **`expand`/`collapse` error code** — returns `ACTION_FAILED` instead of `ACTION_NOT_SUPPORTED`
+5. **`toggle` false success** — returns ok on elements that don't support toggle
+6. **`select` false success** — returns ok but value doesn't change
+7. **Stderr duplication** — all errors printed twice
+
+### Needs Improvement (5)
+1. **`get --property bounds`** returns null — should work independently of snapshot flags
+2. **`is` checked/expanded** — returns `false` instead of "not applicable" for irrelevant properties
+3. **`find` output** — buttons with null names are indistinguishable without secondary info
+4. **`--help` descriptions** — all subcommands and options lack description text
+5. **`list-apps` bundle_id** — always null, should be populated
+
+### Missing Features / Gaps (2)
+1. **Calculator display** — not accessible via AX tree (macOS limitation, not a bug)
+2. **Scroll position** — no way to query current scroll offset
+
+### Severity Ranking
+1. **P0 (breaks agent workflows):** stderr duplication (JSON parse failures), `select`/`toggle` false success (agent thinks action worked when it didn't)
+2. **P1 (degrades reliability):** `launch` window detection, `close-app` not actually closing, `expand`/`collapse` wrong error code
+3. **P2 (minor inconsistencies):** `list-apps` shape, `get bounds` null, `is` false vs N/A, help text missing, bundle_id null