Skip to content

Computer use CLI for AI agents

feat: add structured verbose logging across all layers

Lahfirc7316e8b5160
diff --git a/crates/core/src/commands/helpers.rs b/crates/core/src/commands/helpers.rs
index 7cdd14d7f..a13e8a019 100644
--- a/crates/core/src/commands/helpers.rs
+++ b/crates/core/src/commands/helpers.rs
@@ -18,7 +18,15 @@ pub fn resolve_ref(
.get(ref_id)
.ok_or_else(|| AppError::stale_ref(ref_id))?
.clone();
+ tracing::debug!(
+ "resolve: {} -> pid={} role={} name={:?}",
+ ref_id,
+ entry.pid,
+ entry.role,
+ entry.name.as_deref().unwrap_or("(none)")
+ );
let handle = adapter.resolve_element(&entry)?;
+ tracing::debug!("resolve: {} resolved successfully", ref_id);
Ok((entry, handle))
}
diff --git a/crates/core/src/commands/snapshot.rs b/crates/core/src/commands/snapshot.rs
index a2331aa5f..6c4f06700 100644
--- a/crates/core/src/commands/snapshot.rs
+++ b/crates/core/src/commands/snapshot.rs
@@ -16,6 +16,14 @@ pub struct SnapshotArgs {
}
pub fn execute(args: SnapshotArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
+ tracing::debug!(
+ "tree: snapshot app={:?} window_id={:?} max_depth={} interactive_only={}",
+ args.app.as_deref().unwrap_or("(focused)"),
+ args.window_id.as_deref().unwrap_or("(auto)"),
+ args.max_depth,
+ args.interactive_only
+ );
+
let opts = crate::adapter::TreeOptions {
max_depth: args.max_depth,
include_bounds: args.include_bounds,
@@ -35,6 +43,13 @@ pub fn execute(args: SnapshotArgs, adapter: &dyn PlatformAdapter) -> Result<Valu
let tree = serde_json::to_value(&result.tree)?;
let win = &result.window;
+ tracing::debug!(
+ "tree: snapshot complete app={:?} window={:?} refs={}",
+ win.app,
+ win.title,
+ ref_count
+ );
+
Ok(json!({
"app": win.app,
"window": {
diff --git a/crates/macos/src/actions/chain.rs b/crates/macos/src/actions/chain.rs
index af064d4f6..843f29b7b 100644
--- a/crates/macos/src/actions/chain.rs
+++ b/crates/macos/src/actions/chain.rs
@@ -57,27 +57,48 @@ mod imp {
ctx: &ChainContext,
) -> Result<(), AdapterError> {
let deadline = Instant::now() + CHAIN_TIMEOUT;
+ let total = def.steps.len();
ax_helpers::set_messaging_timeout(el, 3.0);
if def.pre_scroll {
+ tracing::debug!("chain: pre-scroll AXScrollToVisible");
ax_helpers::ensure_visible(el);
}
- for step in def.steps {
+ for (i, step) in def.steps.iter().enumerate() {
if Instant::now() > deadline {
+ tracing::debug!("chain: timeout after {i}/{total} steps");
return Err(AdapterError::timeout("Chain execution exceeded 10s"));
}
+ let label = step_label(step);
if execute_step(el, caps, step, ctx) {
+ tracing::debug!("chain: [{}/{}] {} -> success", i + 1, total, label);
return Ok(());
}
+ tracing::debug!("chain: [{}/{}] {} -> skip", i + 1, total, label);
}
+ tracing::debug!("chain: all {total} steps exhausted");
Err(
AdapterError::new(ErrorCode::ActionFailed, "All chain steps exhausted")
.with_suggestion(def.suggestion),
)
}
+ fn step_label(step: &ChainStep) -> &'static str {
+ match step {
+ ChainStep::Action(name) => name,
+ ChainStep::SetBool { attr, .. } => attr,
+ ChainStep::SetDynamic { attr } => attr,
+ ChainStep::FocusThenAction(name) => name,
+ ChainStep::FocusThenConfirmOrPress => "FocusThenConfirmOrPress",
+ ChainStep::ChildActions { .. } => "ChildActions",
+ ChainStep::AncestorActions { .. } => "AncestorActions",
+ ChainStep::Custom { label, .. } => label,
+ ChainStep::CGClick { .. } => "CGClick",
+ }
+ }
+
fn execute_step(
el: &AXElement,
caps: &ElementCaps,
diff --git a/crates/macos/src/actions/dispatch.rs b/crates/macos/src/actions/dispatch.rs
index 20b3523aa..afa966fff 100644
--- a/crates/macos/src/actions/dispatch.rs
+++ b/crates/macos/src/actions/dispatch.rs
@@ -60,6 +60,7 @@ mod imp {
pub fn perform_action(el: &AXElement, action: &Action) -> Result<ActionResult, AdapterError> {
let label = action_label(action);
+ tracing::debug!("action: perform {label}");
match action {
Action::Click => {
let caps = discovery::discover(el);
diff --git a/crates/macos/src/input/clipboard.rs b/crates/macos/src/input/clipboard.rs
index 2f0d1d409..a1805f260 100644
--- a/crates/macos/src/input/clipboard.rs
+++ b/crates/macos/src/input/clipboard.rs
@@ -35,6 +35,7 @@ mod imp {
}
pub fn get() -> Result<String, AdapterError> {
+ tracing::debug!("clipboard: get");
unsafe {
let pb = pasteboard()?;
let sel = sel_registerName(c"stringForType:".as_ptr());
@@ -42,16 +43,20 @@ mod imp {
std::mem::transmute(objc_msgSend as *const c_void);
let ns_string = send(pb, sel, NSPasteboardTypeString);
if ns_string.is_null() {
+ tracing::debug!("clipboard: get -> empty");
return Ok(String::new());
}
let cf_str = core_foundation::string::CFString::wrap_under_get_rule(
ns_string as core_foundation_sys::string::CFStringRef,
);
- Ok(cf_str.to_string())
+ let result = cf_str.to_string();
+ tracing::debug!("clipboard: get -> {} chars", result.len());
+ Ok(result)
}
}
pub fn set(text: &str) -> Result<(), AdapterError> {
+ tracing::debug!("clipboard: set {} chars", text.len());
unsafe {
let pb = pasteboard()?;
let clear_sel = sel_registerName(c"clearContents".as_ptr());
@@ -75,6 +80,7 @@ mod imp {
}
pub fn clear() -> Result<(), AdapterError> {
+ tracing::debug!("clipboard: clear");
unsafe {
let pb = pasteboard()?;
let sel = sel_registerName(c"clearContents".as_ptr());
diff --git a/crates/macos/src/input/keyboard.rs b/crates/macos/src/input/keyboard.rs
index ada320ca2..afde81a8e 100644
--- a/crates/macos/src/input/keyboard.rs
+++ b/crates/macos/src/input/keyboard.rs
@@ -8,6 +8,23 @@ mod imp {
};
pub fn synthesize_key(combo: &KeyCombo) -> Result<(), AdapterError> {
+ tracing::debug!(
+ "keyboard: synthesize_key {}{}",
+ if combo.modifiers.is_empty() {
+ String::new()
+ } else {
+ format!(
+ "{}+",
+ combo
+ .modifiers
+ .iter()
+ .map(|m| format!("{m:?}"))
+ .collect::<Vec<_>>()
+ .join("+")
+ )
+ },
+ combo.key
+ );
let key_code = key_name_to_code(&combo.key)?;
let sys_wide = unsafe { AXUIElementCreateSystemWide() };
@@ -54,6 +71,7 @@ mod imp {
}
pub fn synthesize_text(text: &str) -> Result<(), AdapterError> {
+ tracing::debug!("keyboard: synthesize_text {} chars", text.len());
let sys_wide = unsafe { AXUIElementCreateSystemWide() };
if sys_wide.is_null() {
return Err(AdapterError::internal(
diff --git a/crates/macos/src/input/mouse.rs b/crates/macos/src/input/mouse.rs
index 658fb0bea..0a26d0a39 100644
--- a/crates/macos/src/input/mouse.rs
+++ b/crates/macos/src/input/mouse.rs
@@ -11,6 +11,13 @@ mod imp {
use core_graphics::geometry::CGPoint;
pub fn synthesize_mouse(event: MouseEvent) -> Result<(), AdapterError> {
+ tracing::debug!(
+ "mouse: {:?} {:?} at ({:.0}, {:.0})",
+ event.kind,
+ event.button,
+ event.point.x,
+ event.point.y
+ );
let point = CGPoint::new(event.point.x, event.point.y);
let cg_button = to_cg_button(&event.button);
match event.kind {
@@ -24,6 +31,14 @@ mod imp {
}
pub fn synthesize_drag(params: DragParams) -> Result<(), AdapterError> {
+ tracing::debug!(
+ "mouse: drag ({:.0},{:.0}) -> ({:.0},{:.0}) duration={}ms",
+ params.from.x,
+ params.from.y,
+ params.to.x,
+ params.to.y,
+ params.duration_ms.unwrap_or(300)
+ );
let from = CGPoint::new(params.from.x, params.from.y);
let to = CGPoint::new(params.to.x, params.to.y);
let duration_ms = params.duration_ms.unwrap_or(300);
@@ -131,6 +146,7 @@ mod imp {
}
pub fn synthesize_scroll_at(x: f64, y: f64, dy: i32, dx: i32) -> Result<(), AdapterError> {
+ tracing::debug!("mouse: scroll at ({x:.0},{y:.0}) dy={dy} dx={dx}");
use core_graphics::geometry::CGPoint;
extern "C" {
diff --git a/crates/macos/src/system/app_ops.rs b/crates/macos/src/system/app_ops.rs
index 58c801865..2bee50e5d 100644
--- a/crates/macos/src/system/app_ops.rs
+++ b/crates/macos/src/system/app_ops.rs
@@ -13,6 +13,7 @@ pub fn pid_from_element(el: &crate::tree::AXElement) -> Option<i32> {
#[cfg(target_os = "macos")]
pub fn ensure_app_focused(pid: i32) -> Result<(), AdapterError> {
+ tracing::debug!("system: ensure_app_focused pid={pid}");
use accessibility_sys::{kAXErrorSuccess, AXUIElementSetAttributeValue};
use core_foundation::{base::TCFType, boolean::CFBoolean, string::CFString};
@@ -36,6 +37,11 @@ pub fn ensure_app_focused(pid: i32) -> Result<(), AdapterError> {
#[cfg(target_os = "macos")]
pub fn focus_window_impl(win: &WindowInfo) -> Result<(), AdapterError> {
+ tracing::debug!(
+ "system: focus_window app={:?} title={:?}",
+ win.app,
+ win.title
+ );
use accessibility_sys::{
kAXErrorSuccess, AXUIElementCreateApplication, AXUIElementPerformAction,
AXUIElementSetAttributeValue,
@@ -85,6 +91,7 @@ pub fn focus_window_impl(_win: &WindowInfo) -> Result<(), AdapterError> {
#[cfg(target_os = "macos")]
pub fn launch_app_impl(id: &str, timeout_ms: u64) -> Result<WindowInfo, AdapterError> {
+ tracing::debug!("system: launch app={id:?} timeout={timeout_ms}ms");
use crate::adapter::list_windows_impl;
use std::process::Command;
use std::time::{Duration, Instant};
@@ -149,6 +156,7 @@ pub fn launch_app_impl(_id: &str, _timeout_ms: u64) -> Result<WindowInfo, Adapte
#[cfg(target_os = "macos")]
pub fn close_app_impl(id: &str, force: bool) -> Result<(), AdapterError> {
+ tracing::debug!("system: close app={id:?} force={force}");
use std::process::Command;
if force {
Command::new("pkill")
diff --git a/crates/macos/src/system/key_dispatch.rs b/crates/macos/src/system/key_dispatch.rs
index 46fd1f20f..55717eb3a 100644
--- a/crates/macos/src/system/key_dispatch.rs
+++ b/crates/macos/src/system/key_dispatch.rs
@@ -11,6 +11,7 @@ pub fn press_for_app_impl(app_name: &str, combo: &KeyCombo) -> Result<ActionResu
use accessibility_sys::AXUIElementSetAttributeValue;
use core_foundation::{base::TCFType, boolean::CFBoolean, string::CFString};
+ tracing::debug!("system: press_for_app app={app_name:?} key={:?}", combo.key);
let pid = find_pid_by_name(app_name)?;
let app_el = crate::tree::element_for_pid(pid);
if app_el.0.is_null() {
diff --git a/crates/macos/src/system/screenshot.rs b/crates/macos/src/system/screenshot.rs
index c62ec7f70..fc4215e67 100644
--- a/crates/macos/src/system/screenshot.rs
+++ b/crates/macos/src/system/screenshot.rs
@@ -6,6 +6,7 @@ mod imp {
use std::process::Command;
pub fn capture_app(pid: i32) -> Result<ImageBuffer, AdapterError> {
+ tracing::debug!("system: screenshot app pid={pid}");
let temp = temp_path();
let cg_id = find_cg_window_id_for_pid(pid);
@@ -31,6 +32,7 @@ mod imp {
}
pub fn capture_screen(_idx: usize) -> Result<ImageBuffer, AdapterError> {
+ tracing::debug!("system: screenshot screen");
let temp = temp_path();
let status = Command::new("screencapture")
.args(["-x", "-t", "png"])
diff --git a/crates/macos/src/system/window_ops.rs b/crates/macos/src/system/window_ops.rs
index ddc63b9c2..5014e1805 100644
--- a/crates/macos/src/system/window_ops.rs
+++ b/crates/macos/src/system/window_ops.rs
@@ -17,6 +17,12 @@ mod imp {
}
pub fn execute(win: &WindowInfo, op: WindowOp) -> Result<(), AdapterError> {
+ tracing::debug!(
+ "system: window_op {:?} app={:?} title={:?}",
+ op,
+ win.app,
+ win.title
+ );
let win_el = crate::tree::window_element_for(win.pid, &win.title);
match op {
WindowOp::Resize { width, height } => set_size(&win_el, width, height),
diff --git a/crates/macos/src/tree/resolve.rs b/crates/macos/src/tree/resolve.rs
index ce78a57cb..dc4de06ea 100644
--- a/crates/macos/src/tree/resolve.rs
+++ b/crates/macos/src/tree/resolve.rs
@@ -7,21 +7,32 @@ use super::element::{
#[cfg(target_os = "macos")]
pub fn resolve_element_impl(entry: &RefEntry) -> Result<NativeHandle, AdapterError> {
+ tracing::debug!(
+ "resolve: searching pid={} role={} name={:?} bounds_hash={:?}",
+ entry.pid,
+ entry.role,
+ entry.name.as_deref().unwrap_or("(none)"),
+ entry.bounds_hash
+ );
let root = element_for_pid(entry.pid);
let mut visited = FxHashSet::default();
if let Ok(handle) = find_element_recursive(&root, entry, 0, 20, &mut visited) {
+ tracing::debug!("resolve: found exact match");
return Ok(handle);
}
if entry.bounds_hash.is_some() && entry.name.is_some() {
+ tracing::debug!("resolve: exact match failed, trying relaxed (name-only)");
let relaxed = RefEntry {
bounds_hash: None,
..entry.clone()
};
visited.clear();
if let Ok(handle) = find_element_recursive(&root, &relaxed, 0, 20, &mut visited) {
+ tracing::debug!("resolve: found via relaxed match (bounds changed)");
return Ok(handle);
}
}
+ tracing::debug!("resolve: element not found");
Err(AdapterError::new(
agent_desktop_core::error::ErrorCode::StaleRef,
format!(
diff --git a/src/dispatch.rs b/src/dispatch.rs
index 10fc0ccba..49d922286 100644
--- a/src/dispatch.rs
+++ b/src/dispatch.rs
@@ -16,6 +16,7 @@ use serde_json::Value;
use crate::cli::Commands;
pub fn dispatch(cmd: Commands, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {
+ tracing::debug!("dispatch: {}", command_name(&cmd));
match cmd {
Commands::Snapshot(a) => snapshot::execute(
snapshot::SnapshotArgs {
@@ -390,6 +391,60 @@ fn parse_xy_opt(s: Option<&str>) -> Result<Option<(f64, f64)>, AppError> {
}
}
+fn command_name(cmd: &Commands) -> &'static str {
+ match cmd {
+ Commands::Snapshot(_) => "snapshot",
+ Commands::Find(_) => "find",
+ Commands::Screenshot(_) => "screenshot",
+ Commands::Get(_) => "get",
+ Commands::Is(_) => "is",
+ Commands::Click(_) => "click",
+ Commands::DoubleClick(_) => "double-click",
+ Commands::TripleClick(_) => "triple-click",
+ Commands::RightClick(_) => "right-click",
+ Commands::Type(_) => "type",
+ Commands::SetValue(_) => "set-value",
+ Commands::Clear(_) => "clear",
+ Commands::Focus(_) => "focus",
+ Commands::Toggle(_) => "toggle",
+ Commands::Check(_) => "check",
+ Commands::Uncheck(_) => "uncheck",
+ Commands::Expand(_) => "expand",
+ Commands::Collapse(_) => "collapse",
+ Commands::Select(_) => "select",
+ Commands::Scroll(_) => "scroll",
+ Commands::ScrollTo(_) => "scroll-to",
+ Commands::Press(_) => "press",
+ Commands::KeyDown(_) => "key-down",
+ Commands::KeyUp(_) => "key-up",
+ Commands::Hover(_) => "hover",
+ Commands::Drag(_) => "drag",
+ Commands::MouseMove(_) => "mouse-move",
+ Commands::MouseClick(_) => "mouse-click",
+ Commands::MouseDown(_) => "mouse-down",
+ Commands::MouseUp(_) => "mouse-up",
+ Commands::Launch(_) => "launch",
+ Commands::CloseApp(_) => "close-app",
+ Commands::ListWindows(_) => "list-windows",
+ Commands::ListApps => "list-apps",
+ Commands::ListSurfaces(_) => "list-surfaces",
+ Commands::FocusWindow(_) => "focus-window",
+ Commands::ResizeWindow(_) => "resize-window",
+ Commands::MoveWindow(_) => "move-window",
+ Commands::Minimize(_) => "minimize",
+ Commands::Maximize(_) => "maximize",
+ Commands::Restore(_) => "restore",
+ Commands::ClipboardGet => "clipboard-get",
+ Commands::ClipboardSet(_) => "clipboard-set",
+ Commands::ClipboardClear => "clipboard-clear",
+ Commands::Wait(_) => "wait",
+ Commands::Status => "status",
+ Commands::Permissions(_) => "permissions",
+ Commands::Version(_) => "version",
+ Commands::Batch(_) => "batch",
+ }
+}
+
fn cli_surface_to_core(s: &crate::cli::Surface) -> agent_desktop_core::adapter::SnapshotSurface {
use crate::cli::Surface;
use agent_desktop_core::adapter::SnapshotSurface;