Skip to content

Computer use CLI for AI agents

feat: smart AX-first click chain + macOS crate restructure

Lahfir4616c8f65f97
diff --git a/README.md b/README.md
index e1c4078ee..31e58dfe2 100644
--- a/README.md
+++ b/README.md
@@ -1,37 +1,42 @@
# agent-desktop
-**Desktop automation for AI agents.** A fast, cross-platform Rust CLI that gives AI agents structured access to every native application on macOS, Windows, and Linux through OS accessibility trees — no screen scraping, no image recognition, no fragile selectors.
+[![Build](https://github.com/lahfir/agent-desktop/actions/workflows/ci.yml/badge.svg)](https://github.com/lahfir/agent-desktop/actions)
+[![License: Apache-2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
+[![Platform: macOS](https://img.shields.io/badge/platform-macOS-lightgrey.svg)]()
+
+A cross-platform Rust CLI that gives AI agents structured access to native desktop applications through OS accessibility trees. It outputs JSON with ref-based element identifiers (`@e1`, `@e2`, ...) so agents can observe UI state, act on elements, and drive any application programmatically. **agent-desktop is not an AI agent** — it is the tool AI agents invoke.
+
+## Quick example
```bash
-agent-desktop snapshot -i
+# 1. Observe: get the accessibility tree with interactive element refs
+agent-desktop snapshot --app "TextEdit" -i
+
+# 2. Act: click a button by ref
agent-desktop click @e3
+
+# 3. Type into a text field
agent-desktop type @e5 "quarterly report"
-agent-desktop screenshot --app "Finder" report.png
-```
----
+# 4. Submit with a keyboard shortcut
+agent-desktop press cmd+return
-## How it works
+# 5. Re-observe after the UI changes
+agent-desktop snapshot -i
+```
-Every desktop OS exposes a machine-readable accessibility tree — the same tree that powers screen readers. `agent-desktop` wraps that API behind a clean CLI and outputs structured JSON. AI agents call the binary, read the JSON, and act on element references (`@e1`, `@e2`, …). The observation-action loop lives in the agent, not here.
+The observation-action loop lives in the calling agent, not here.
```
AI Agent
- │
- ├─ agent-desktop snapshot -i # observe: get tree + ref IDs
- │ └─ {"tree": {...}, "ref_count": 14}
- │
- ├─ agent-desktop click @e7 # act: by ref
- │ └─ {"ok": true, "data": {"action": "click"}}
- │
- └─ agent-desktop snapshot -i # re-observe after action
- └─ {"tree": {...}, "ref_count": 11}
+ |
+ +-- agent-desktop snapshot -i → {"tree": {...}, "ref_count": 14}
+ |
+ +-- agent-desktop click @e7 → {"ok": true, "data": {"action": "click"}}
+ |
+ +-- agent-desktop snapshot -i → {"tree": {...}, "ref_count": 11}
```
-**agent-desktop is not an AI agent.** It is the tool AI agents invoke.
-
----
-
## Installation
### Build from source
@@ -40,10 +45,9 @@ AI Agent
git clone https://github.com/lahfir/agent-desktop
cd agent-desktop
cargo build --release
-# Binary at: ./target/release/agent-desktop
```
-Move to your PATH:
+The binary is at `./target/release/agent-desktop`. Move it to your PATH:
```bash
mv target/release/agent-desktop /usr/local/bin/
@@ -51,117 +55,24 @@ mv target/release/agent-desktop /usr/local/bin/
### Requirements
-| Platform | Minimum Version | Accessibility API |
-|----------|----------------|-------------------|
-| macOS | 13.0+ | AXUIElement (AXAPI) |
-| Windows | 10+ | UIAutomation *(Phase 2)* |
-| Linux | Any (X11/Wayland) | AT-SPI *(Phase 2)* |
+- **Rust** 1.78+ (pinned via `rust-toolchain.toml`)
+- **macOS** 13.0+ (Phase 1 — the only supported platform today)
-### macOS permissions
+## Permissions
-The first time you run any command, macOS will prompt for Accessibility permission. You can also trigger it explicitly:
+macOS requires Accessibility permission for agent-desktop to read UI trees and perform actions.
```bash
-agent-desktop permissions --request
-```
-
-Or grant it manually: **System Settings → Privacy & Security → Accessibility → add your terminal**.
-
----
-
-## Quick start
-
-```bash
-# 1. Get the focused app's interactive elements with ref IDs
-agent-desktop snapshot -i
-
-# 2. Read what's on screen
-agent-desktop find --role button --name "Open"
-
-# 3. Click a button by ref
-agent-desktop click @e4
-
-# 4. Type into a text field
-agent-desktop type @e7 "Hello, world"
-
-# 5. Submit with keyboard
-agent-desktop press "cmd+return"
-```
-
----
-
-## The ref system
-
-`snapshot` assigns stable identifiers to every interactive element in depth-first order: `@e1`, `@e2`, `@e3`, etc. These refs are valid for subsequent action commands **until the next snapshot replaces them**.
-
-**Only interactive roles receive refs:**
-
-| Role | Role | Role |
-|------|------|------|
-| `button` | `textfield` | `checkbox` |
-| `link` | `menuitem` | `tab` |
-| `slider` | `combobox` | `treeitem` |
-| `cell` | `radiobutton` | `incrementor` |
-
-Static elements (labels, groups, containers) appear in the tree for context but have no `ref` and cannot be acted upon.
-
-The refmap is persisted at `~/.agent-desktop/last_refmap.json` (permissions: `0600`) and fully replaced on every snapshot. Action commands perform optimistic re-identification — if the element at a ref has changed since the snapshot, they return `STALE_REF`.
-
----
-
-## JSON output
-
-Every command produces the same envelope:
-
-```json
-{
- "version": "1.0",
- "ok": true,
- "command": "click",
- "data": { ... }
-}
-```
-
-Errors follow the same envelope with a structured error object:
+# Check current permission status
+agent-desktop permissions
-```json
-{
- "version": "1.0",
- "ok": false,
- "command": "click",
- "error": {
- "code": "STALE_REF",
- "message": "Element at @e7 no longer matches the last snapshot",
- "suggestion": "Run 'snapshot' to refresh refs, then retry"
- }
-}
+# Trigger the system permission dialog
+agent-desktop permissions --request
```
-### Error codes
+Or grant manually: **System Settings > Privacy & Security > Accessibility** and add your terminal application.
-| Code | Meaning |
-|------|---------|
-| `PERM_DENIED` | Accessibility permission not granted |
-| `ELEMENT_NOT_FOUND` | No element matched the given ref or query |
-| `APP_NOT_FOUND` | Application is not running or has no open windows |
-| `ACTION_FAILED` | The OS rejected the action |
-| `ACTION_NOT_SUPPORTED` | Element does not support the requested action |
-| `STALE_REF` | Ref is from a previous snapshot |
-| `WINDOW_NOT_FOUND` | No window matched the given ID or query |
-| `PLATFORM_NOT_SUPPORTED` | Command not implemented on this OS |
-| `TIMEOUT` | Wait condition expired |
-| `INVALID_ARGS` | Bad argument values |
-| `INTERNAL` | Unexpected internal error |
-
-### Exit codes
-
-| Code | Meaning |
-|------|---------|
-| `0` | Success |
-| `1` | Structured error (JSON on stdout) |
-| `2` | Argument parse error |
-
----
+If permission is missing, commands return a `PERM_DENIED` error with guidance.
## Commands
@@ -169,7 +80,7 @@ Errors follow the same envelope with a structured error object:
#### `snapshot`
-Capture the accessibility tree of a window and allocate ref IDs.
+Capture the accessibility tree of a window as structured JSON with `@eN` ref IDs.
```bash
agent-desktop snapshot [OPTIONS]
@@ -181,18 +92,14 @@ agent-desktop snapshot [OPTIONS]
| `--window-id <ID>` | — | Filter to a specific window |
| `--max-depth <N>` | `10` | Maximum tree traversal depth |
| `--include-bounds` | off | Include pixel bounds for every node |
-| `--interactive-only` / `-i` | off | Omit non-interactive elements from output |
-| `--compact` | off | Single-line JSON output |
+| `-i` / `--interactive-only` | off | Omit non-interactive elements from output |
+| `--compact` | off | Omit empty structural nodes |
+| `--surface <TYPE>` | `window` | Surface to snapshot: window, focused, menu, sheet, popover, alert |
```bash
-# Snapshot the frontmost window
-agent-desktop snapshot
-
-# Snapshot a specific app, interactive elements only
agent-desktop snapshot --app "TextEdit" -i
-
-# Include pixel coordinates for layout analysis
-agent-desktop snapshot --include-bounds
+agent-desktop snapshot --include-bounds --max-depth 15
+agent-desktop snapshot --surface menu --app "Finder"
```
<details>
@@ -228,82 +135,54 @@ agent-desktop snapshot --include-bounds
</details>
----
-
-#### `find`
+#### `screenshot`
-Search the accessibility tree for elements matching a query. Returns all matches across the app.
+Capture a PNG screenshot of a window.
```bash
-agent-desktop find [--app <NAME>] [--role <ROLE>] [--name <TEXT>] [--value <TEXT>]
+agent-desktop screenshot [--app <NAME>] [--window-id <ID>] [PATH]
```
```bash
-# Find all buttons
-agent-desktop find --role button
-
-# Find the Save button in TextEdit
-agent-desktop find --app "TextEdit" --role button --name "Save"
-
-# Find a text field containing specific text
-agent-desktop find --role textfield --value "search"
-```
-
-<details>
-<summary>Example output</summary>
-
-```json
-{
- "version": "1.0",
- "ok": true,
- "command": "find",
- "data": {
- "matches": [
- { "ref": "@e2", "role": "button", "name": "Save", "interactive": true },
- { "ref": null, "role": "group", "name": "Toolbar", "interactive": false }
- ]
- }
-}
+agent-desktop screenshot --app "Finder" ~/Desktop/finder.png
+agent-desktop screenshot # base64 PNG to stdout
```
-</details>
-
----
-
-#### `screenshot`
+#### `find`
-Capture a PNG screenshot of a window or application.
+Search the accessibility tree for elements matching a query.
```bash
-agent-desktop screenshot [--app <NAME>] [--window-id <ID>] [PATH]
+agent-desktop find [OPTIONS]
```
-```bash
-# Screenshot the frontmost window to stdout (base64 PNG)
-agent-desktop screenshot
+| Flag | Description |
+|------|-------------|
+| `--app <NAME>` | Filter to application |
+| `--role <ROLE>` | Match by role (button, textfield, checkbox ...) |
+| `--name <TEXT>` | Match by accessible name or label |
+| `--value <TEXT>` | Match by current value |
+| `--text <TEXT>` | Match by text in name, value, title, or description |
+| `--count` | Return match count only |
+| `--first` | Return first match only |
+| `--last` | Return last match only |
+| `--nth <N>` | Return Nth match (0-indexed) |
-# Screenshot a specific app to a file
-agent-desktop screenshot --app "Finder" ~/Desktop/finder.png
+```bash
+agent-desktop find --role button --name "Save"
+agent-desktop find --app "TextEdit" --text "hello" --first
+agent-desktop find --role textfield --count
```
----
-
#### `get`
-Read a property of a specific element by ref.
+Read a property of an element by ref.
```bash
-agent-desktop get <REF> [--property <PROP>]
+agent-desktop get <REF> --property <PROP>
```
-| Property | Description |
-|----------|-------------|
-| `text` | Display text / label |
-| `value` | Current value (text field content, slider position) |
-| `title` | Window or element title |
-| `bounds` | `{ x, y, width, height }` in screen coordinates |
-| `role` | Accessibility role string |
-| `states` | Array of active states |
+Properties: `text` (default), `value`, `title`, `bounds`, `role`, `states`.
```bash
agent-desktop get @e3 --property value
@@ -311,112 +190,83 @@ agent-desktop get @e1 --property bounds
agent-desktop get @e5 --property states
```
-<details>
-<summary>Example output</summary>
-
-```json
-{
- "version": "1.0",
- "ok": true,
- "command": "get",
- "data": { "property": "value", "value": "quarterly-report.pdf" }
-}
-```
-
-</details>
-
----
-
#### `is`
-Check a boolean property of an element.
+Check a boolean state of an element.
```bash
-agent-desktop is <REF> [--property <PROP>]
+agent-desktop is <REF> --property <PROP>
```
-| Property | Description |
-|----------|-------------|
-| `visible` | Element is visible on screen |
-| `enabled` | Element is interactive (not disabled) |
-| `checked` | Checkbox/toggle is checked |
-| `focused` | Element has keyboard focus |
-| `expanded` | Disclosure or tree item is expanded |
+Properties: `visible` (default), `enabled`, `checked`, `focused`, `expanded`.
```bash
agent-desktop is @e4 --property enabled
agent-desktop is @e6 --property checked
```
-<details>
-<summary>Example output</summary>
+#### `list-surfaces`
-```json
-{
- "version": "1.0",
- "ok": true,
- "command": "is",
- "data": { "property": "enabled", "result": true }
-}
-```
-
-</details>
+List accessibility surfaces for an application (window, menu, sheet, popover, alert).
----
+```bash
+agent-desktop list-surfaces [--app <NAME>]
+```
### Interaction
-#### `click` / `double-click` / `right-click`
+#### `click` / `double-click` / `triple-click` / `right-click`
```bash
agent-desktop click <REF>
agent-desktop double-click <REF>
-agent-desktop right-click <REF>
+agent-desktop triple-click <REF> # select line or paragraph
+agent-desktop right-click <REF> # open context menu
```
----
-
#### `type`
-Type text into an element (simulates keyboard input, respects IME).
+Focus an element and type text (simulates keyboard input).
```bash
agent-desktop type <REF> <TEXT>
```
```bash
-agent-desktop type @e3 "your search query"
+agent-desktop type @e3 "[email protected]"
```
----
-
#### `set-value`
-Directly set the value of an element (faster than `type` for programmatic writes; bypasses key events).
+Set an element's value directly via the accessibility attribute (bypasses key events).
```bash
agent-desktop set-value <REF> <VALUE>
```
```bash
-agent-desktop set-value @e3 "2026-02-19"
+agent-desktop set-value @e3 "2026-02-20"
```
----
+#### `clear`
+
+Clear an element's value to an empty string.
+
+```bash
+agent-desktop clear <REF>
+```
#### `focus`
-Move keyboard focus to an element.
+Set keyboard focus on an element.
```bash
agent-desktop focus <REF>
```
----
-
#### `select`
-Select an option in a dropdown or combo box.
+Select an option in a list or dropdown.
```bash
agent-desktop select <REF> <VALUE>
@@ -426,18 +276,14 @@ agent-desktop select <REF> <VALUE>
agent-desktop select @e8 "Last 30 days"
```
----
-
-#### `toggle`
-
-Toggle a checkbox, switch, or toggle button.
+#### `toggle` / `check` / `uncheck`
```bash
-agent-desktop toggle <REF>
+agent-desktop toggle <REF> # flip checkbox or switch state
+agent-desktop check <REF> # set to checked (idempotent)
+agent-desktop uncheck <REF> # set to unchecked (idempotent)
```
----
-
#### `expand` / `collapse`
Expand or collapse a disclosure triangle, tree item, or accordion.
@@ -447,69 +293,92 @@ agent-desktop expand <REF>
agent-desktop collapse <REF>
```
----
-
-#### `scroll`
-
-Scroll an element in a direction.
+#### `scroll` / `scroll-to`
```bash
-agent-desktop scroll <REF> [--direction <DIR>] [--amount <N>]
+agent-desktop scroll <REF> [--direction up|down|left|right] [--amount <N>]
+agent-desktop scroll-to <REF> # scroll element into visible area
```
-| Flag | Default | Options |
-|------|---------|---------|
-| `--direction` | `down` | `up`, `down`, `left`, `right` |
-| `--amount` | `3` | Number of scroll units |
-
```bash
agent-desktop scroll @e2 --direction down --amount 5
+agent-desktop scroll-to @e14
```
----
-
### Keyboard
#### `press`
-Send a keyboard shortcut or key combination.
+Send a key combo. Modifiers: `cmd`, `ctrl`, `alt`, `shift`. Combine with `+`.
```bash
-agent-desktop press <COMBO>
+agent-desktop press <COMBO> [--app <NAME>]
```
-Modifiers: `cmd`, `ctrl`, `alt`/`opt`, `shift`, `fn`. Key names are lowercase. Combine with `+`.
+```bash
+agent-desktop press cmd+s
+agent-desktop press cmd+shift+z
+agent-desktop press escape
+agent-desktop press return
+agent-desktop press tab
+agent-desktop press cmd+c --app "TextEdit"
+```
+
+#### `key-down` / `key-up`
+
+Hold or release a key or modifier.
```bash
-agent-desktop press "cmd+s"
-agent-desktop press "cmd+shift+z"
-agent-desktop press "escape"
-agent-desktop press "return"
-agent-desktop press "tab"
+agent-desktop key-down shift
+agent-desktop key-up shift
```
----
+### Mouse
-### App & window management
+#### `hover`
-#### `launch`
+Move the cursor to an element or absolute coordinates.
-Launch an application by name or bundle ID.
+```bash
+agent-desktop hover <REF>
+agent-desktop hover --xy 500,300
+agent-desktop hover @e5 --duration 2000 # hold for 2s
+```
+
+#### `drag`
+
+Drag from one element or point to another.
```bash
-agent-desktop launch <APP> [--wait]
+agent-desktop drag --from @e1 --to @e5
+agent-desktop drag --from-xy 100,200 --to-xy 400,500 --duration 500
```
-| Flag | Description |
-|------|-------------|
-| `--wait` | Block until the app's main window is visible |
+#### `mouse-move` / `mouse-click` / `mouse-down` / `mouse-up`
+
+Low-level mouse operations at absolute screen coordinates.
```bash
-agent-desktop launch "TextEdit" --wait
-agent-desktop launch "com.apple.finder"
+agent-desktop mouse-move --xy 500,300
+agent-desktop mouse-click --xy 500,300 --button left --count 2
+agent-desktop mouse-down --xy 100,200 --button left
+agent-desktop mouse-up --xy 400,500 --button left
```
----
+### App & window management
+
+#### `launch`
+
+Launch an application by name or bundle ID and wait for its window.
+
+```bash
+agent-desktop launch <APP> [--timeout <MS>]
+```
+
+```bash
+agent-desktop launch "TextEdit"
+agent-desktop launch "com.apple.finder" --timeout 10000
+```
#### `close-app`
@@ -524,207 +393,104 @@ agent-desktop close-app "TextEdit"
agent-desktop close-app "TextEdit" --force # SIGKILL
```
----
-
#### `list-apps`
-List all running applications with accessibility trees.
+List all running GUI applications.
```bash
agent-desktop list-apps
```
-<details>
-<summary>Example output</summary>
-
-```json
-{
- "version": "1.0",
- "ok": true,
- "command": "list-apps",
- "data": {
- "apps": [
- { "name": "Finder", "pid": 391, "bundle_id": "com.apple.finder" },
- { "name": "TextEdit", "pid": 1204, "bundle_id": "com.apple.TextEdit" }
- ]
- }
-}
-```
-
-</details>
-
----
-
#### `list-windows`
-List windows for an application.
+List all visible windows.
```bash
agent-desktop list-windows [--app <NAME>]
```
-```bash
-agent-desktop list-windows --app "Finder"
-```
-
-<details>
-<summary>Example output</summary>
-
-```json
-{
- "version": "1.0",
- "ok": true,
- "command": "list-windows",
- "data": {
- "windows": [
- { "id": "w-4521", "title": "Documents", "app_name": "Finder", "pid": 391 }
- ]
- }
-}
-```
-
-</details>
-
----
-
#### `focus-window`
Bring a window to the foreground.
-```bash
-agent-desktop focus-window [--window-id <ID>] [--app <NAME>] [--title <TEXT>]
-```
-
```bash
agent-desktop focus-window --app "Finder" --title "Documents"
agent-desktop focus-window --window-id "w-4521"
```
----
-
-### Clipboard
-
-#### `clipboard-get`
-
-Read the current clipboard contents.
+#### `resize-window`
```bash
-agent-desktop clipboard-get
+agent-desktop resize-window --app "TextEdit" --width 800 --height 600
```
----
+#### `move-window`
-#### `clipboard-set`
+```bash
+agent-desktop move-window --app "TextEdit" --x 100 --y 50
+```
-Write text to the clipboard.
+#### `minimize` / `maximize` / `restore`
```bash
-agent-desktop clipboard-set <TEXT>
+agent-desktop minimize --app "TextEdit"
+agent-desktop maximize --app "TextEdit"
+agent-desktop restore --app "TextEdit"
```
+### Clipboard
+
```bash
-agent-desktop clipboard-set "copied text"
+agent-desktop clipboard-get # read plain-text clipboard
+agent-desktop clipboard-set "text" # write text to clipboard
+agent-desktop clipboard-clear # clear the clipboard
```
----
-
### Wait
-#### `wait`
-
-Block for a fixed duration or until a condition is met.
+Block for a duration or until a condition is met.
```bash
-agent-desktop wait [MS] [--element <REF>] [--window <TITLE>] [--timeout <MS>]
+agent-desktop wait [MS] [OPTIONS]
```
-| Form | Description |
+| Flag | Description |
|------|-------------|
-| `wait 2000` | Sleep for 2 seconds |
-| `wait --element @e3` | Block until the element at `@e3` is visible (polls) |
-| `wait --window "Save"` | Block until a window with this title appears |
+| `<MS>` | Sleep for N milliseconds |
+| `--element <REF>` | Block until element appears |
+| `--window <TITLE>` | Block until window appears |
+| `--text <TEXT>` | Block until text appears in the app's tree |
+| `--menu` | Block until a context menu is open |
+| `--menu-closed` | Block until a context menu is dismissed |
+| `--app <NAME>` | Scope wait to a specific application |
+| `--timeout <MS>` | Timeout (default 30000) |
```bash
-# Wait for a dialog to appear
-agent-desktop wait --window "Are you sure?" --timeout 10000
-
-# Wait for a loading spinner to disappear
-agent-desktop wait --element @e9 --timeout 15000
-
-# Fixed delay
agent-desktop wait 500
+agent-desktop wait --window "Save" --timeout 10000
+agent-desktop wait --element @e3 --timeout 5000
+agent-desktop wait --text "Loading complete" --app "Safari" --timeout 5000
+agent-desktop wait --menu --timeout 3000
```
----
-
### System
-#### `status`
-
-Report the runtime status of agent-desktop and its platform adapter.
-
-```bash
-agent-desktop status
-```
-
-<details>
-<summary>Example output</summary>
-
-```json
-{
- "version": "1.0",
- "ok": true,
- "command": "status",
- "data": {
- "platform": "macos",
- "accessibility": "granted",
- "version": "0.1.0"
- }
-}
-```
-
-</details>
-
----
-
-#### `permissions`
-
-Check or request Accessibility permissions.
-
-```bash
-agent-desktop permissions [--request]
-```
-
-```bash
-# Check current permission status
-agent-desktop permissions
-
-# Trigger the system permission dialog
-agent-desktop permissions --request
-```
-
----
-
-#### `version`
-
-Print the binary version.
-
```bash
-agent-desktop version [--json]
+agent-desktop status # adapter health, platform, permission state
+agent-desktop permissions # check accessibility permission
+agent-desktop permissions --request # trigger system dialog
+agent-desktop version # version string
+agent-desktop version --json # machine-readable version
```
----
-
### Batch
-Run multiple commands in a single invocation to reduce process-spawn overhead.
+Run multiple commands in a single invocation.
```bash
agent-desktop batch <JSON> [--stop-on-error]
```
-The `JSON` argument is an array of `{ "command": "...", "args": { ... } }` objects. Results are returned in order.
-
```bash
agent-desktop batch '[
{"command":"click", "args":{"ref_id":"@e2"}},
@@ -733,274 +499,142 @@ agent-desktop batch '[
]' --stop-on-error
```
-<details>
-<summary>Example output</summary>
+## JSON output format
+
+Every command produces a standard envelope:
```json
{
"version": "1.0",
"ok": true,
- "command": "batch",
- "data": {
- "results": [
- { "ok": true, "command": "click", "data": { "action": "click" } },
- { "ok": true, "command": "type", "data": { "action": "type" } },
- { "ok": false, "command": "press", "error": "STALE_REF: ..." }
- ]
- }
+ "command": "click",
+ "data": { "action": "click", "ref": "@e3" }
}
```
-</details>
-
----
-
-## Common agent patterns
+Errors include a machine-readable code and recovery hint:
-### Observe → identify → act
-
-```bash
-# Observe the current window
-TREE=$(agent-desktop snapshot -i)
-
-# Find the search field
-SEARCH=$(agent-desktop find --role textfield --name "Search")
-
-# Act on it
-agent-desktop click @e1
-agent-desktop type @e1 "quarterly report"
-agent-desktop press "return"
+```json
+{
+ "version": "1.0",
+ "ok": false,
+ "command": "click",
+ "error": {
+ "code": "STALE_REF",
+ "message": "Element at @e7 no longer matches the last snapshot",
+ "suggestion": "Run 'snapshot' to refresh refs, then retry"
+ }
+}
```
-### Handle stale refs
+### Error codes
-Refs become stale when the UI changes. The correct loop:
+| Code | Meaning |
+|------|---------|
+| `PERM_DENIED` | Accessibility permission not granted |
+| `ELEMENT_NOT_FOUND` | No element matched the ref or query |
+| `APP_NOT_FOUND` | Application not running or no windows |
+| `ACTION_FAILED` | The OS rejected the action |
+| `ACTION_NOT_SUPPORTED` | Element does not support this action |
+| `STALE_REF` | Ref is from a previous snapshot |
+| `WINDOW_NOT_FOUND` | No window matched the ID or query |
+| `PLATFORM_NOT_SUPPORTED` | Not implemented on this OS |
+| `TIMEOUT` | Wait condition expired |
+| `INVALID_ARGS` | Invalid argument values |
+| `INTERNAL` | Unexpected internal error |
-```
-snapshot → act → if STALE_REF → snapshot again → retry
-```
+### Exit codes
-### Wait for async UI
+| Code | Meaning |
+|------|---------|
+| `0` | Success |
+| `1` | Structured error (JSON on stdout) |
+| `2` | Argument parse error |
-```bash
-# Trigger an action
-agent-desktop click @e12
+## Ref system
-# Wait for the result dialog
-agent-desktop wait --window "Export complete" --timeout 30000
+`snapshot` assigns identifiers to every interactive element in depth-first order: `@e1`, `@e2`, `@e3`, etc. These refs are valid for action commands **until the next snapshot replaces them**.
-# Confirm
-agent-desktop click @e1 # OK button in the new snapshot
-```
+Only interactive roles receive refs:
-### Automated form fill
+| | | |
+|---|---|---|
+| `button` | `textfield` | `checkbox` |
+| `link` | `menuitem` | `tab` |
+| `slider` | `combobox` | `treeitem` |
+| `cell` | `radiobutton` | `incrementor` |
-```bash
-agent-desktop batch '[
- {"command":"focus", "args":{"ref_id":"@e1"}},
- {"command":"set-value", "args":{"ref_id":"@e1","value":"John Doe"}},
- {"command":"set-value", "args":{"ref_id":"@e2","value":"[email protected]"}},
- {"command":"select", "args":{"ref_id":"@e3","value":"Engineering"}},
- {"command":"click", "args":{"ref_id":"@e10"}}
-]'
-```
+Static elements (labels, groups, containers) appear in the tree for context but have no ref and cannot be acted upon.
----
+The refmap is stored at `~/.agent-desktop/last_refmap.json` (permissions `0600`) and fully replaced on every snapshot. Action commands perform optimistic re-identification — if the element has changed since the snapshot, they return `STALE_REF`.
-## Architecture
+Stale ref recovery pattern:
```
-agent-desktop/
-├── Cargo.toml # workspace (resolver = 2)
-├── src/ # binary crate (entry point)
-│ ├── main.rs # permission check, dispatch, JSON emit
-│ ├── cli.rs # clap derive structs (all 30 subcommands)
-│ └── dispatch.rs # match cmd → commands::execute()
-└── crates/
- ├── core/ # agent-desktop-core (platform-agnostic)
- │ └── src/
- │ ├── adapter.rs # PlatformAdapter trait
- │ ├── snapshot.rs # SnapshotEngine, RefAllocator
- │ ├── refs.rs # RefMap, RefEntry, @eN allocation
- │ ├── node.rs # AccessibilityNode, WindowInfo, Rect
- │ ├── action.rs # Action enum
- │ ├── error.rs # AppError, AdapterError, ErrorCode
- │ ├── output.rs # Response envelope
- │ └── commands/ # one file per CLI command
- ├── macos/ # agent-desktop-macos (Phase 1)
- │ └── src/
- │ ├── adapter.rs # MacOSAdapter: PlatformAdapter impl
- │ ├── tree.rs # AXUIElement tree traversal
- │ ├── actions.rs # CGEvent keyboard/mouse/scroll
- │ ├── app_ops.rs # launch, close, focus via AppleScript/pkill
- │ └── roles.rs # AXRole → unified role string
- ├── windows/ # agent-desktop-windows (Phase 2)
- └── linux/ # agent-desktop-linux (Phase 2)
-```
-
-### Dependency inversion
-
-`core` defines the `PlatformAdapter` trait. Platform crates implement it. **Core never imports platform crates.** The binary is the only wiring point:
-
-```rust
-fn build_adapter() -> impl PlatformAdapter {
- #[cfg(target_os = "macos")]
- { agent_desktop_macos::MacOSAdapter::new() }
- // ...
-}
-```
-
-This constraint is enforced in CI: `cargo tree -p agent-desktop-core` must contain no platform crate names.
-
-### PlatformAdapter trait
-
-```rust
-pub trait PlatformAdapter: Send + Sync {
- fn list_windows(&self, filter: &WindowFilter) -> Result<Vec<WindowInfo>, AdapterError>;
- fn list_apps(&self) -> Result<Vec<AppInfo>, AdapterError>;
- fn get_tree(&self, win: &WindowInfo, opts: &TreeOptions) -> Result<AccessibilityNode, AdapterError>;
- fn execute_action(&self, handle: &NativeHandle, action: Action) -> Result<ActionResult, AdapterError>;
- fn resolve_element(&self, entry: &RefEntry) -> Result<NativeHandle, AdapterError>;
- fn check_permissions(&self) -> PermissionStatus;
- fn focus_window(&self, win: &WindowInfo) -> Result<(), AdapterError>;
- fn launch_app(&self, id: &str, wait: bool) -> Result<WindowInfo, AdapterError>;
- fn close_app(&self, id: &str, force: bool) -> Result<(), AdapterError>;
- fn screenshot(&self, target: ScreenshotTarget) -> Result<ImageBuffer, AdapterError>;
- fn get_clipboard(&self) -> Result<String, AdapterError>;
- fn set_clipboard(&self, text: &str) -> Result<(), AdapterError>;
-}
+snapshot -> act -> if STALE_REF -> snapshot again -> retry
```
-All methods have default implementations returning `Err(AdapterError::not_supported())`, so platform stubs compile without implementing anything.
-
----
-
## Platform support
| Feature | macOS | Windows | Linux |
|---------|-------|---------|-------|
-| Snapshot / tree | ✅ Phase 1 | 🔜 Phase 2 | 🔜 Phase 2 |
-| Click / type / keyboard | ✅ Phase 1 | 🔜 Phase 2 | 🔜 Phase 2 |
-| Screenshot | ✅ Phase 1 | 🔜 Phase 2 | 🔜 Phase 2 |
-| Clipboard | ✅ Phase 1 | 🔜 Phase 2 | 🔜 Phase 2 |
-| App launch / close | ✅ Phase 1 | 🔜 Phase 2 | 🔜 Phase 2 |
-| MCP server mode | 🔜 Phase 3 | 🔜 Phase 3 | 🔜 Phase 3 |
-
-### macOS implementation
+| Accessibility tree | Phase 1 | Planned (Phase 2) | Planned (Phase 2) |
+| Click / type / keyboard | Phase 1 | Planned (Phase 2) | Planned (Phase 2) |
+| Mouse input | Phase 1 | Planned (Phase 2) | Planned (Phase 2) |
+| Screenshot | Phase 1 | Planned (Phase 2) | Planned (Phase 2) |
+| Clipboard | Phase 1 | Planned (Phase 2) | Planned (Phase 2) |
+| App launch / close | Phase 1 | Planned (Phase 2) | Planned (Phase 2) |
+| Window management | Phase 1 | Planned (Phase 2) | Planned (Phase 2) |
+| MCP server mode | Planned (Phase 3) | Planned (Phase 3) | Planned (Phase 3) |
-- **Tree**: `AXUIElementCopyAttributeValue` with cycle detection via visited-set
-- **Click/Type**: `AXUIElementPerformAction` + `CGEventCreateKeyboardEvent`
-- **Scroll**: `CGEvent::new_scroll_event` (highsierra feature)
-- **Screenshot**: `CGWindowListCreateImage`
-- **Clipboard**: `NSPasteboard.generalPasteboard` via Cocoa FFI
-- **App ops**: PID polling for launch, AppleScript for focus, `pkill -x` for close
+macOS implementation uses `AXUIElement` for tree traversal and actions, `CGEvent` for keyboard and mouse input, `CGWindowListCreateImage` for screenshots, and `NSPasteboard` for clipboard.
----
-
-## Performance
-
-### Snapshot tree: 6 s → 0.3 s
-
-The initial implementation fetched each AX attribute with a separate IPC call to the macOS Accessibility server — one call for role, one for title, one for description, one for value, one for enabled state, one for focused state. For a 2,000-node tree (e.g. Xcode), that is **~14,000 round-trips** across the process boundary, each stalling until the target application responds.
+## Architecture
-The fix was replacing six sequential `AXUIElementCopyAttributeValue` calls per node with a single `AXUIElementCopyMultipleAttributeValues` call that batches all attributes in one IPC message:
+The workspace follows strict dependency inversion. `agent-desktop-core` defines the `PlatformAdapter` trait and all shared types. Platform crates (`macos`, `windows`, `linux`) implement the trait. Core never imports platform crates — the binary crate is the only wiring point. This constraint is enforced in CI via `cargo tree`.
```
-Before: node × 7 calls = 14,000 IPC round-trips (Xcode)
-After: node × 1 call = 2,000 IPC round-trips (Xcode)
-```
-
-`AXUIElementCopyMultipleAttributeValues` is not exposed by the `accessibility-sys` crate and is declared manually:
-
-```rust
-extern "C" {
- fn AXUIElementCopyMultipleAttributeValues(
- element: AXUIElementRef,
- attributes: CFArrayRef,
- options: u32,
- values: *mut CFArrayRef,
- ) -> AXError;
-}
+agent-desktop/
+├── src/ # binary crate (entry point, CLI, dispatch)
+└── crates/
+ ├── core/ # platform-agnostic types, commands, engine
+ ├── macos/ # macOS adapter (Phase 1)
+ ├── windows/ # stub (Phase 2)
+ └── linux/ # stub (Phase 2)
```
-The implementation in `crates/macos/src/tree.rs` builds a `CFArray` of the six attribute name strings once per node and passes it to this call. The returned `CFArray` is then unpacked into `(role, title, description, value, enabled, focused)` with full type-safe downcasting for `CFString`, `CFBoolean`, and `CFNumber` values.
-
-### Measured benchmarks
-
-| Application | Nodes | IPC calls (before) | IPC calls (after) | Wall time (before) | Wall time (after) |
-|-------------|-------|--------------------|--------------------|---------------------|---------------------|
-| TextEdit (empty doc) | ~50 | ~350 | ~50 | 18–35 ms | 5–10 ms |
-| Finder Documents | ~100 | ~700 | ~100 | 35–70 ms | 10–20 ms |
-| System Settings | ~500 | ~3,500 | ~500 | 175–350 ms | 50–100 ms |
-| Xcode (depth 8) | ~1,500 | ~10,500 | ~1,500 | 525 ms – 1.05 s | 150–300 ms |
-| Xcode (depth 12, worst case) | ~2,000+ | ~14,000+ | ~2,000+ | ~6 s | ~0.3 s |
-
-The 6 s → 0.3 s figure is a 20× reduction observed on a large Xcode project tree with depth 12. The integration test CI gate asserts the Xcode snapshot completes in under 2 seconds at the default `--max-depth 10`.
-
-### Secondary optimisations
-
-**Cycle detection with `FxHashSet`**
-The visited-pointer set used during depth-first traversal switched from `std::collections::HashSet<usize>` to `rustc_hash::FxHashSet<usize>`. Because the keys are raw machine-word pointers (not user-controlled), the non-cryptographic FxHash is appropriate and benchmarks at roughly 2× the throughput of the default SipHash.
-
-**Streaming JSON serialisation**
-The snapshot output is written with `serde_json::to_writer(BufWriter::new(stdout.lock()), &response)` rather than `to_string()` followed by `println!`. This eliminates the intermediate heap allocation for the full JSON string, which matters for large trees (Xcode-scale output can exceed 200 KB).
-
-**Messaging timeout**
-`AXUIElementSetMessagingTimeout(element, 2.0)` is set on the application element immediately after creation. This caps how long a single IPC call can block when the target application is busy or hung, preventing the snapshot from stalling indefinitely.
-
----
-
-## Development
+## Contributing
### Build
```bash
-cargo build # debug build
+cargo build # debug
cargo build --release # optimized, stripped binary (<15MB)
```
### Test
```bash
-cargo test --workspace # all unit tests
+cargo test --workspace
cargo clippy --all-targets -- -D warnings
```
-### Add a command
-
-Adding a command touches exactly five files:
-
-1. **`crates/core/src/commands/{name}.rs`** — implement `execute(args, adapter)`
-2. **`crates/core/src/commands/mod.rs`** — register the module
-3. **`src/cli.rs`** — add a subcommand variant and arg struct
-4. **`src/dispatch.rs`** — add a match arm
-5. **`crates/core/src/action.rs`** — add an `Action` variant if a new native action is needed
-
-No existing files change beyond these registration points.
-
-### Coding standards
-
-- **400 LOC hard limit** per file — split by responsibility when approaching
-- **No inline comments** — names must be self-documenting; `///` doc-comments on public items only when necessary
-- **Zero `unwrap()`** in non-test code — propagate with `?` or match explicitly
-- **One command per file**, one domain type per file
-- **Explicit `pub` boundaries** — only `lib.rs` re-exports; internal modules use `pub(crate)`
-
----
-
-## Roadmap
+### Adding a command
-| Phase | Status | Scope |
-|-------|--------|-------|
-| Phase 1 | ✅ Complete | macOS adapter, 30 commands, core engine |
-| Phase 2 | 🔜 Planned | Windows (UIAutomation), Linux (AT-SPI), 10+ new commands |
-| Phase 3 | 🔜 Planned | MCP server mode (`--mcp`), JSON Schema generation |
-| Phase 4 | 🔜 Planned | Daemon, sessions, enterprise quality gates |
+1. Create `crates/core/src/commands/{name}.rs` with an `execute()` function
+2. Register in `crates/core/src/commands/mod.rs`
+3. Add subcommand variant to `src/cli.rs`
+4. Add match arm in `src/dispatch.rs`
+5. If needed: add `Action` variant in `crates/core/src/action.rs`
+6. If needed: add adapter method to `PlatformAdapter` with default `not_supported()` impl
-Phases 2–4 add adapters, transports, and hardening. The core engine is not rebuilt.
+### Standards
----
+- 400 LOC hard limit per file
+- No inline comments — code must be self-documenting
+- Zero `unwrap()` in non-test code
+- One command per file, one domain type per file
## License
-Apache-2.0 — see [LICENSE](LICENSE).
+Apache-2.0
diff --git a/crates/macos/src/actions/activate.rs b/crates/macos/src/actions/activate.rs
new file mode 100644
index 000000000..a168b59f8
--- /dev/null
+++ b/crates/macos/src/actions/activate.rs
@@ -0,0 +1,274 @@
+use agent_desktop_core::{action::MouseButton, error::AdapterError};
+
+#[cfg(target_os = "macos")]
+mod imp {
+ use super::*;
+ use crate::tree::AXElement;
+ use accessibility_sys::{
+ kAXErrorSuccess, kAXFocusedAttribute, kAXRoleAttribute, AXUIElementCopyActionNames,
+ AXUIElementIsAttributeSettable, AXUIElementPerformAction, AXUIElementSetAttributeValue,
+ };
+ use core_foundation::{
+ array::CFArray,
+ base::{CFRetain, CFType, CFTypeRef, TCFType},
+ boolean::CFBoolean,
+ string::CFString,
+ };
+ use std::os::raw::c_uchar;
+
+ /// Attempts a 10-step AX-first activation chain before falling back to CGEvent.
+ pub fn smart_activate(el: &AXElement) -> Result<(), AdapterError> {
+ let actions = list_ax_actions(el);
+
+ if try_action_from_list(el, &actions, &["AXPress"]) {
+ return Ok(());
+ }
+ if try_action_from_list(el, &actions, &["AXConfirm"]) {
+ return Ok(());
+ }
+ if try_action_from_list(el, &actions, &["AXOpen"]) {
+ return Ok(());
+ }
+ if try_action_from_list(el, &actions, &["AXPick"]) {
+ return Ok(());
+ }
+
+ if try_set_selected(el) {
+ return Ok(());
+ }
+ if try_select_via_parent(el) {
+ return Ok(());
+ }
+ if try_focus_then_activate(el) {
+ return Ok(());
+ }
+ if try_child_activation(el) {
+ return Ok(());
+ }
+ if try_parent_activation(el) {
+ return Ok(());
+ }
+
+ crate::actions::dispatch::click_via_bounds(el, MouseButton::Left, 1)
+ }
+
+ /// AXOpen first, then two smart_activate calls with a gap, then CGEvent double-click.
+ pub fn smart_double_activate(el: &AXElement) -> Result<(), AdapterError> {
+ let actions = list_ax_actions(el);
+ if try_action_from_list(el, &actions, &["AXOpen"]) {
+ return Ok(());
+ }
+
+ let _ = smart_activate(el);
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ let _ = smart_activate(el);
+
+ crate::actions::dispatch::click_via_bounds(el, MouseButton::Left, 2)
+ }
+
+ /// AXShowMenu first, then CGEvent right-click.
+ pub fn smart_right_activate(el: &AXElement) -> Result<(), AdapterError> {
+ let actions = list_ax_actions(el);
+ if try_action_from_list(el, &actions, &["AXShowMenu"]) {
+ return Ok(());
+ }
+ crate::actions::dispatch::click_via_bounds(el, MouseButton::Right, 1)
+ }
+
+ /// Three smart_activate calls with gaps, then CGEvent triple-click.
+ pub fn smart_triple_activate(el: &AXElement) -> Result<(), AdapterError> {
+ for _ in 0..3 {
+ let _ = smart_activate(el);
+ std::thread::sleep(std::time::Duration::from_millis(30));
+ }
+ crate::actions::dispatch::click_via_bounds(el, MouseButton::Left, 3)
+ }
+
+ pub fn is_attr_settable_pub(el: &AXElement, attr: &str) -> bool {
+ is_attr_settable(el, attr)
+ }
+
+ fn list_ax_actions(el: &AXElement) -> Vec<String> {
+ let mut actions_ref: core_foundation_sys::array::CFArrayRef = std::ptr::null();
+ let err = unsafe { AXUIElementCopyActionNames(el.0, &mut actions_ref) };
+ if err != kAXErrorSuccess || actions_ref.is_null() {
+ return Vec::new();
+ }
+ let actions: CFArray<CFType> = unsafe { TCFType::wrap_under_create_rule(actions_ref) };
+ let mut result = Vec::new();
+ for i in 0..actions.len() {
+ if let Some(name) = actions.get(i).and_then(|v| v.downcast::<CFString>()) {
+ result.push(name.to_string());
+ }
+ }
+ result
+ }
+
+ fn is_attr_settable(el: &AXElement, attr: &str) -> bool {
+ let cf_attr = CFString::new(attr);
+ let mut settable: c_uchar = 0;
+ let err = unsafe {
+ AXUIElementIsAttributeSettable(el.0, cf_attr.as_concrete_TypeRef(), &mut settable)
+ };
+ err == kAXErrorSuccess && settable != 0
+ }
+
+ fn try_action_from_list(el: &AXElement, actions: &[String], targets: &[&str]) -> bool {
+ for target in targets {
+ if actions.iter().any(|a| a == target) {
+ let action = CFString::new(target);
+ let err = unsafe { AXUIElementPerformAction(el.0, action.as_concrete_TypeRef()) };
+ if err == kAXErrorSuccess {
+ return true;
+ }
+ }
+ }
+ false
+ }
+
+ fn try_set_selected(el: &AXElement) -> bool {
+ if !is_attr_settable(el, "AXSelected") {
+ return false;
+ }
+ let cf_attr = CFString::new("AXSelected");
+ let err = unsafe {
+ AXUIElementSetAttributeValue(
+ el.0,
+ cf_attr.as_concrete_TypeRef(),
+ CFBoolean::true_value().as_CFTypeRef(),
+ )
+ };
+ err == kAXErrorSuccess
+ }
+
+ fn try_select_via_parent(el: &AXElement) -> bool {
+ let parent = match crate::tree::copy_element_attr(el, "AXParent") {
+ Some(p) => p,
+ None => return false,
+ };
+ let parent_role = match crate::tree::copy_string_attr(&parent, kAXRoleAttribute) {
+ Some(r) => r,
+ None => return false,
+ };
+ if !matches!(parent_role.as_str(), "AXTable" | "AXOutline" | "AXList") {
+ return false;
+ }
+ if !is_attr_settable(&parent, "AXSelectedRows") {
+ return false;
+ }
+ unsafe { CFRetain(el.0 as CFTypeRef) };
+ let el_as_cftype = unsafe { CFType::wrap_under_create_rule(el.0 as CFTypeRef) };
+ let arr = CFArray::from_CFTypes(&[el_as_cftype]);
+ let cf_attr = CFString::new("AXSelectedRows");
+ let err = unsafe {
+ AXUIElementSetAttributeValue(
+ parent.0,
+ cf_attr.as_concrete_TypeRef(),
+ arr.as_CFTypeRef(),
+ )
+ };
+ err == kAXErrorSuccess
+ }
+
+ fn try_focus_then_activate(el: &AXElement) -> bool {
+ let cf_attr = CFString::new(kAXFocusedAttribute);
+ let err = unsafe {
+ AXUIElementSetAttributeValue(
+ el.0,
+ cf_attr.as_concrete_TypeRef(),
+ CFBoolean::true_value().as_CFTypeRef(),
+ )
+ };
+ if err != kAXErrorSuccess {
+ return false;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ let confirm = CFString::new("AXConfirm");
+ if unsafe { AXUIElementPerformAction(el.0, confirm.as_concrete_TypeRef()) }
+ == kAXErrorSuccess
+ {
+ return true;
+ }
+ let press = CFString::new("AXPress");
+ let err = unsafe { AXUIElementPerformAction(el.0, press.as_concrete_TypeRef()) };
+ err == kAXErrorSuccess
+ }
+
+ fn try_child_activation(el: &AXElement) -> bool {
+ let children = crate::tree::copy_ax_array(el, "AXChildren").unwrap_or_default();
+ for child in children.iter().take(3) {
+ let press = CFString::new("AXPress");
+ if unsafe { AXUIElementPerformAction(child.0, press.as_concrete_TypeRef()) }
+ == kAXErrorSuccess
+ {
+ return true;
+ }
+ let confirm = CFString::new("AXConfirm");
+ if unsafe { AXUIElementPerformAction(child.0, confirm.as_concrete_TypeRef()) }
+ == kAXErrorSuccess
+ {
+ return true;
+ }
+ }
+ false
+ }
+
+ fn try_parent_activation(el: &AXElement) -> bool {
+ if let Some(parent) = crate::tree::copy_element_attr(el, "AXParent") {
+ let press = CFString::new("AXPress");
+ if unsafe { AXUIElementPerformAction(parent.0, press.as_concrete_TypeRef()) }
+ == kAXErrorSuccess
+ {
+ return true;
+ }
+ let confirm = CFString::new("AXConfirm");
+ if unsafe { AXUIElementPerformAction(parent.0, confirm.as_concrete_TypeRef()) }
+ == kAXErrorSuccess
+ {
+ return true;
+ }
+ if let Some(grandparent) = crate::tree::copy_element_attr(&parent, "AXParent") {
+ let press = CFString::new("AXPress");
+ if unsafe { AXUIElementPerformAction(grandparent.0, press.as_concrete_TypeRef()) }
+ == kAXErrorSuccess
+ {
+ return true;
+ }
+ let confirm = CFString::new("AXConfirm");
+ if unsafe { AXUIElementPerformAction(grandparent.0, confirm.as_concrete_TypeRef()) }
+ == kAXErrorSuccess
+ {
+ return true;
+ }
+ }
+ }
+ false
+ }
+}
+
+#[cfg(not(target_os = "macos"))]
+mod imp {
+ use super::*;
+ use crate::tree::AXElement;
+
+ pub fn smart_activate(_el: &AXElement) -> Result<(), AdapterError> {
+ Err(AdapterError::not_supported("smart_activate"))
+ }
+ pub fn smart_double_activate(_el: &AXElement) -> Result<(), AdapterError> {
+ Err(AdapterError::not_supported("smart_double_activate"))
+ }
+ pub fn smart_right_activate(_el: &AXElement) -> Result<(), AdapterError> {
+ Err(AdapterError::not_supported("smart_right_activate"))
+ }
+ pub fn smart_triple_activate(_el: &AXElement) -> Result<(), AdapterError> {
+ Err(AdapterError::not_supported("smart_triple_activate"))
+ }
+ pub fn is_attr_settable_pub(_el: &AXElement, _attr: &str) -> bool {
+ false
+ }
+}
+
+pub(crate) use imp::{
+ is_attr_settable_pub, smart_activate, smart_double_activate, smart_right_activate,
+ smart_triple_activate,
+};
diff --git a/crates/macos/src/actions.rs b/crates/macos/src/actions/dispatch.rs
similarity index 73%
rename from crates/macos/src/actions.rs
rename to crates/macos/src/actions/dispatch.rs
index 7cb6b380b..3e22a862c 100644
--- a/crates/macos/src/actions.rs
+++ b/crates/macos/src/actions/dispatch.rs
@@ -18,13 +18,13 @@ mod imp {
string::CFString,
};
- fn try_ax_action(el: &AXElement, name: &str) -> bool {
+ pub fn try_ax_action(el: &AXElement, name: &str) -> bool {
let action = CFString::new(name);
let err = unsafe { AXUIElementPerformAction(el.0, action.as_concrete_TypeRef()) };
err == kAXErrorSuccess
}
- fn click_via_bounds(
+ pub fn click_via_bounds(
el: &AXElement,
button: MouseButton,
count: u32,
@@ -50,7 +50,7 @@ mod imp {
y = center.y,
"AX action failed, falling back to CGEvent click"
);
- crate::mouse::synthesize_mouse(MouseEvent {
+ crate::input::mouse::synthesize_mouse(MouseEvent {
kind: MouseEventKind::Click { count },
point: center,
button,
@@ -61,28 +61,15 @@ mod imp {
let label = action_label(action);
match action {
Action::Click => {
- if !try_ax_action(el, kAXPressAction) && !try_ax_action(el, "AXConfirm") {
- click_via_bounds(el, MouseButton::Left, 1)?;
- }
+ crate::actions::activate::smart_activate(el)?;
}
Action::DoubleClick => {
- if !try_ax_action(el, "AXOpen") {
- if try_ax_action(el, kAXPressAction) {
- std::thread::sleep(std::time::Duration::from_millis(50));
- if !try_ax_action(el, kAXPressAction) {
- click_via_bounds(el, MouseButton::Left, 2)?;
- }
- } else {
- click_via_bounds(el, MouseButton::Left, 2)?;
- }
- }
+ crate::actions::activate::smart_double_activate(el)?;
}
Action::RightClick => {
- if !try_ax_action(el, "AXShowMenu") {
- click_via_bounds(el, MouseButton::Right, 1)?;
- }
+ crate::actions::activate::smart_right_activate(el)?;
}
Action::Toggle => {
@@ -107,9 +94,7 @@ mod imp {
"Toggle works on checkboxes, switches, and radio buttons. Use 'click' for other elements.",
));
}
- if !try_ax_action(el, kAXPressAction) && !try_ax_action(el, "AXConfirm") {
- click_via_bounds(el, MouseButton::Left, 1)?;
- }
+ crate::actions::activate::smart_activate(el)?;
}
Action::SetValue(val) => {
@@ -142,57 +127,73 @@ mod imp {
CFBoolean::true_value().as_CFTypeRef(),
)
};
- crate::input::synthesize_text(text)?;
+ crate::input::keyboard::synthesize_text(text)?;
}
Action::PressKey(combo) => {
- crate::input::synthesize_key(combo)?;
+ crate::input::keyboard::synthesize_key(combo)?;
}
Action::Expand => {
- if !has_ax_action(el, "AXExpand") {
- return Err(AdapterError::new(
- ErrorCode::ActionNotSupported,
- "This element doesn't support expand",
- )
- .with_suggestion("Try 'click' to open it instead."));
- }
- let ax_action = CFString::new("AXExpand");
- let err =
- unsafe { AXUIElementPerformAction(el.0, ax_action.as_concrete_TypeRef()) };
- if err != kAXErrorSuccess {
- return Err(AdapterError::new(
- ErrorCode::ActionFailed,
- format!("AXExpand failed (err={err})"),
- ));
+ if !try_ax_action(el, "AXExpand") {
+ if crate::actions::activate::is_attr_settable_pub(el, "AXDisclosing") {
+ let cf_attr = CFString::new("AXDisclosing");
+ let err = unsafe {
+ AXUIElementSetAttributeValue(
+ el.0,
+ cf_attr.as_concrete_TypeRef(),
+ CFBoolean::true_value().as_CFTypeRef(),
+ )
+ };
+ if err != kAXErrorSuccess {
+ return Err(AdapterError::new(
+ ErrorCode::ActionFailed,
+ format!("AXDisclosing set to true failed (err={err})"),
+ ));
+ }
+ } else {
+ return Err(AdapterError::new(
+ ErrorCode::ActionNotSupported,
+ "AXExpand failed and AXDisclosing not settable",
+ )
+ .with_suggestion("Try 'click' to open it instead."));
+ }
}
}
Action::Collapse => {
- if !has_ax_action(el, "AXCollapse") {
- return Err(AdapterError::new(
- ErrorCode::ActionNotSupported,
- "This element doesn't support collapse",
- )
- .with_suggestion("Try 'click' to close it instead."));
- }
- let ax_action = CFString::new("AXCollapse");
- let err =
- unsafe { AXUIElementPerformAction(el.0, ax_action.as_concrete_TypeRef()) };
- if err != kAXErrorSuccess {
- return Err(AdapterError::new(
- ErrorCode::ActionFailed,
- format!("AXCollapse failed (err={err})"),
- ));
+ if !try_ax_action(el, "AXCollapse") {
+ if crate::actions::activate::is_attr_settable_pub(el, "AXDisclosing") {
+ let cf_attr = CFString::new("AXDisclosing");
+ let err = unsafe {
+ AXUIElementSetAttributeValue(
+ el.0,
+ cf_attr.as_concrete_TypeRef(),
+ CFBoolean::false_value().as_CFTypeRef(),
+ )
+ };
+ if err != kAXErrorSuccess {
+ return Err(AdapterError::new(
+ ErrorCode::ActionFailed,
+ format!("AXDisclosing set to false failed (err={err})"),
+ ));
+ }
+ } else {
+ return Err(AdapterError::new(
+ ErrorCode::ActionNotSupported,
+ "AXCollapse failed and AXDisclosing not settable",
+ )
+ .with_suggestion("Try 'click' to close it instead."));
+ }
}
}
Action::Select(value) => {
- crate::action_extras::select_value(el, value)?;
+ crate::actions::extras::select_value(el, value)?;
}
Action::Scroll(direction, amount) => {
- crate::action_extras::ax_scroll(el, direction, *amount)?;
+ crate::actions::extras::ax_scroll(el, direction, *amount)?;
}
Action::Check => {
@@ -204,19 +205,7 @@ mod imp {
}
Action::TripleClick => {
- if !try_ax_action(el, kAXPressAction) {
- click_via_bounds(el, MouseButton::Left, 3)?;
- } else {
- std::thread::sleep(std::time::Duration::from_millis(30));
- if !try_ax_action(el, kAXPressAction) {
- click_via_bounds(el, MouseButton::Left, 3)?;
- } else {
- std::thread::sleep(std::time::Duration::from_millis(30));
- if !try_ax_action(el, kAXPressAction) {
- click_via_bounds(el, MouseButton::Left, 3)?;
- }
- }
- }
+ crate::actions::activate::smart_triple_activate(el)?;
}
Action::ScrollTo => {
@@ -284,7 +273,7 @@ mod imp {
pub fn element_role(el: &AXElement) -> Option<String> {
use accessibility_sys::kAXRoleAttribute;
crate::tree::copy_string_attr(el, kAXRoleAttribute)
- .map(|r| crate::roles::ax_role_to_str(&r).to_string())
+ .map(|r| crate::tree::roles::ax_role_to_str(&r).to_string())
}
pub fn has_ax_action(el: &AXElement, action_name: &str) -> bool {
@@ -330,9 +319,7 @@ mod imp {
if is_checked == want_checked {
return Ok(());
}
- if !try_ax_action(el, kAXPressAction) {
- click_via_bounds(el, MouseButton::Left, 1)?;
- }
+ crate::actions::activate::smart_activate(el)?;
Ok(())
}
}
@@ -350,7 +337,9 @@ mod imp {
pub use imp::perform_action;
#[cfg(target_os = "macos")]
-pub(crate) use imp::{ax_press_or_fail, ax_set_value, element_role, has_ax_action};
+pub(crate) use imp::{
+ ax_press_or_fail, ax_set_value, click_via_bounds, element_role, has_ax_action,
+};
fn action_label(action: &Action) -> String {
match action {
diff --git a/crates/macos/src/action_extras.rs b/crates/macos/src/actions/extras.rs
similarity index 97%
rename from crates/macos/src/action_extras.rs
rename to crates/macos/src/actions/extras.rs
index c90e211b1..01cedc3c6 100644
--- a/crates/macos/src/action_extras.rs
+++ b/crates/macos/src/actions/extras.rs
@@ -6,7 +6,7 @@ use crate::tree::AXElement;
#[cfg(target_os = "macos")]
pub(crate) fn select_value(el: &AXElement, value: &str) -> Result<(), AdapterError> {
- use crate::actions::{ax_press_or_fail, ax_set_value, element_role};
+ use crate::actions::dispatch::{ax_press_or_fail, ax_set_value, element_role};
let role = element_role(el);
match role.as_deref() {
@@ -145,7 +145,7 @@ pub(crate) fn ax_scroll(
Direction::Left => "AXScrollLeftByPage",
};
- if crate::actions::has_ax_action(target, scroll_action_name) {
+ if crate::actions::dispatch::has_ax_action(target, scroll_action_name) {
let ax_action = CFString::new(scroll_action_name);
for _ in 0..amount {
unsafe { AXUIElementPerformAction(target.0, ax_action.as_concrete_TypeRef()) };
diff --git a/crates/macos/src/actions/mod.rs b/crates/macos/src/actions/mod.rs
new file mode 100644
index 000000000..c833cebe4
--- /dev/null
+++ b/crates/macos/src/actions/mod.rs
@@ -0,0 +1,5 @@
+pub mod activate;
+pub mod dispatch;
+pub mod extras;
+
+pub use dispatch::perform_action;
diff --git a/crates/macos/src/adapter.rs b/crates/macos/src/adapter.rs
index d77716627..c89457d96 100644
--- a/crates/macos/src/adapter.rs
+++ b/crates/macos/src/adapter.rs
@@ -26,7 +26,7 @@ impl Default for MacOSAdapter {
impl PlatformAdapter for MacOSAdapter {
fn check_permissions(&self) -> PermissionStatus {
- crate::permissions::check()
+ crate::system::permissions::check()
}
fn get_tree(
@@ -36,15 +36,15 @@ impl PlatformAdapter for MacOSAdapter {
) -> Result<AccessibilityNode, AdapterError> {
let el = match opts.surface {
SnapshotSurface::Window => crate::tree::window_element_for(win.pid, &win.title),
- SnapshotSurface::Focused => crate::surfaces::focused_surface_for_pid(win.pid)
+ SnapshotSurface::Focused => crate::tree::surfaces::focused_surface_for_pid(win.pid)
.ok_or_else(|| AdapterError::internal("No focused surface found"))?,
- SnapshotSurface::Menu => crate::surfaces::menu_element_for_pid(win.pid)
+ SnapshotSurface::Menu => crate::tree::surfaces::menu_element_for_pid(win.pid)
.ok_or_else(|| AdapterError::element_not_found("No open context menu"))?,
- SnapshotSurface::Sheet => crate::surfaces::sheet_for_pid(win.pid)
+ SnapshotSurface::Sheet => crate::tree::surfaces::sheet_for_pid(win.pid)
.ok_or_else(|| AdapterError::element_not_found("No open sheet"))?,
- SnapshotSurface::Popover => crate::surfaces::popover_for_pid(win.pid)
+ SnapshotSurface::Popover => crate::tree::surfaces::popover_for_pid(win.pid)
.ok_or_else(|| AdapterError::element_not_found("No visible popover"))?,
- SnapshotSurface::Alert => crate::surfaces::alert_for_pid(win.pid)
+ SnapshotSurface::Alert => crate::tree::surfaces::alert_for_pid(win.pid)
.ok_or_else(|| AdapterError::element_not_found("No open alert or dialog"))?,
};
let mut visited = FxHashSet::default();
@@ -61,7 +61,7 @@ impl PlatformAdapter for MacOSAdapter {
}
fn resolve_element(&self, entry: &RefEntry) -> Result<NativeHandle, AdapterError> {
- resolve_element_impl(entry)
+ crate::tree::resolve::resolve_element_impl(entry)
}
fn list_windows(&self, filter: &WindowFilter) -> Result<Vec<WindowInfo>, AdapterError> {
@@ -73,31 +73,31 @@ impl PlatformAdapter for MacOSAdapter {
}
fn focus_window(&self, win: &WindowInfo) -> Result<(), AdapterError> {
- crate::app_ops::focus_window_impl(win)
+ crate::system::app_ops::focus_window_impl(win)
}
fn launch_app(&self, id: &str, timeout_ms: u64) -> Result<WindowInfo, AdapterError> {
- crate::app_ops::launch_app_impl(id, timeout_ms)
+ crate::system::app_ops::launch_app_impl(id, timeout_ms)
}
fn close_app(&self, id: &str, force: bool) -> Result<(), AdapterError> {
- crate::app_ops::close_app_impl(id, force)
+ crate::system::app_ops::close_app_impl(id, force)
}
fn screenshot(&self, target: ScreenshotTarget) -> Result<ImageBuffer, AdapterError> {
match target {
- ScreenshotTarget::Window(pid) => crate::screenshot::capture_app(pid),
- ScreenshotTarget::Screen(idx) => crate::screenshot::capture_screen(idx),
- ScreenshotTarget::FullScreen => crate::screenshot::capture_screen(0),
+ ScreenshotTarget::Window(pid) => crate::system::screenshot::capture_app(pid),
+ ScreenshotTarget::Screen(idx) => crate::system::screenshot::capture_screen(idx),
+ ScreenshotTarget::FullScreen => crate::system::screenshot::capture_screen(0),
}
}
fn get_clipboard(&self) -> Result<String, AdapterError> {
- crate::clipboard::get()
+ crate::input::clipboard::get()
}
fn set_clipboard(&self, text: &str) -> Result<(), AdapterError> {
- crate::clipboard::set(text)
+ crate::input::clipboard::set(text)
}
fn press_key_for_app(
@@ -105,15 +105,15 @@ impl PlatformAdapter for MacOSAdapter {
app_name: &str,
combo: &agent_desktop_core::action::KeyCombo,
) -> Result<agent_desktop_core::action::ActionResult, AdapterError> {
- crate::key_dispatch::press_for_app_impl(app_name, combo)
+ crate::system::key_dispatch::press_for_app_impl(app_name, combo)
}
fn wait_for_menu(&self, pid: i32, open: bool, timeout_ms: u64) -> Result<(), AdapterError> {
- crate::wait::wait_for_menu(pid, open, timeout_ms)
+ crate::system::wait::wait_for_menu(pid, open, timeout_ms)
}
fn list_surfaces(&self, pid: i32) -> Result<Vec<SurfaceInfo>, AdapterError> {
- Ok(crate::surfaces::list_surfaces_for_pid(pid))
+ Ok(crate::tree::surfaces::list_surfaces_for_pid(pid))
}
fn focused_window(&self) -> Result<Option<WindowInfo>, AdapterError> {
@@ -158,19 +158,19 @@ impl PlatformAdapter for MacOSAdapter {
}
fn window_op(&self, win: &WindowInfo, op: WindowOp) -> Result<(), AdapterError> {
- crate::window_ops::execute(win, op)
+ crate::system::window_ops::execute(win, op)
}
fn mouse_event(&self, event: MouseEvent) -> Result<(), AdapterError> {
- crate::mouse::synthesize_mouse(event)
+ crate::input::mouse::synthesize_mouse(event)
}
fn drag(&self, params: DragParams) -> Result<(), AdapterError> {
- crate::mouse::synthesize_drag(params)
+ crate::input::mouse::synthesize_drag(params)
}
fn clear_clipboard(&self) -> Result<(), AdapterError> {
- crate::clipboard::clear()
+ crate::input::clipboard::clear()
}
}
@@ -196,80 +196,6 @@ fn execute_action_impl(
Err(AdapterError::not_supported("execute_action"))
}
-#[cfg(target_os = "macos")]
-fn resolve_element_impl(entry: &RefEntry) -> Result<NativeHandle, AdapterError> {
- let root = crate::tree::element_for_pid(entry.pid);
- let mut visited = FxHashSet::default();
- find_element_recursive(&root, entry, 0, 20, &mut visited)
-}
-
-#[cfg(target_os = "macos")]
-fn find_element_recursive(
- el: &crate::tree::AXElement,
- entry: &RefEntry,
- depth: u8,
- max_depth: u8,
- ancestors: &mut FxHashSet<usize>,
-) -> Result<NativeHandle, AdapterError> {
- use accessibility_sys::kAXRoleAttribute;
- use core_foundation::base::{CFRetain, CFTypeRef};
-
- let ptr_key = el.0 as usize;
- if !ancestors.insert(ptr_key) {
- return Err(AdapterError::element_not_found("element"));
- }
-
- 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");
-
- if normalized == entry.role {
- let elem_name = crate::tree::resolve_element_name(el);
- let name_match = match (&entry.name, &elem_name) {
- (Some(en), Some(nn)) => en == nn,
- (None, None) => true,
- _ => false,
- };
- if name_match {
- ancestors.remove(&ptr_key);
- unsafe { CFRetain(el.0 as CFTypeRef) };
- return Ok(NativeHandle::from_ptr(el.0 as *const _));
- }
- }
-
- if depth >= max_depth {
- ancestors.remove(&ptr_key);
- return Err(AdapterError::element_not_found("element"));
- }
-
- 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()))
- .unwrap_or_default();
-
- for child in &children {
- if let Ok(handle) = find_element_recursive(child, entry, depth + 1, max_depth, ancestors) {
- ancestors.remove(&ptr_key);
- return Ok(handle);
- }
- }
-
- ancestors.remove(&ptr_key);
- Err(AdapterError::element_not_found("element"))
-}
-
-#[cfg(not(target_os = "macos"))]
-fn resolve_element_impl(_entry: &RefEntry) -> Result<NativeHandle, AdapterError> {
- Err(AdapterError::not_supported("resolve_element"))
-}
-
pub fn list_windows_impl(filter: &WindowFilter) -> Result<Vec<WindowInfo>, AdapterError> {
#[cfg(target_os = "macos")]
{
diff --git a/crates/macos/src/clipboard.rs b/crates/macos/src/input/clipboard.rs
similarity index 100%
rename from crates/macos/src/clipboard.rs
rename to crates/macos/src/input/clipboard.rs
diff --git a/crates/macos/src/input.rs b/crates/macos/src/input/keyboard.rs
similarity index 100%
rename from crates/macos/src/input.rs
rename to crates/macos/src/input/keyboard.rs
diff --git a/crates/macos/src/input/mod.rs b/crates/macos/src/input/mod.rs
new file mode 100644
index 000000000..769ec85ca
--- /dev/null
+++ b/crates/macos/src/input/mod.rs
@@ -0,0 +1,3 @@
+pub mod clipboard;
+pub mod keyboard;
+pub mod mouse;
diff --git a/crates/macos/src/mouse.rs b/crates/macos/src/input/mouse.rs
similarity index 100%
rename from crates/macos/src/mouse.rs
rename to crates/macos/src/input/mouse.rs
diff --git a/crates/macos/src/lib.rs b/crates/macos/src/lib.rs
index c792c1f8f..86fd4ba66 100644
--- a/crates/macos/src/lib.rs
+++ b/crates/macos/src/lib.rs
@@ -1,17 +1,7 @@
-pub mod action_extras;
pub mod actions;
pub mod adapter;
-pub mod app_ops;
-pub mod clipboard;
pub mod input;
-pub mod key_dispatch;
-pub mod mouse;
-pub mod permissions;
-pub mod roles;
-pub mod screenshot;
-pub mod surfaces;
+pub mod system;
pub mod tree;
-pub mod wait;
-pub mod window_ops;
pub use adapter::MacOSAdapter;
diff --git a/crates/macos/src/app_ops.rs b/crates/macos/src/system/app_ops.rs
similarity index 98%
rename from crates/macos/src/app_ops.rs
rename to crates/macos/src/system/app_ops.rs
index 8d6b18010..1694e72e1 100644
--- a/crates/macos/src/app_ops.rs
+++ b/crates/macos/src/system/app_ops.rs
@@ -122,7 +122,7 @@ pub fn close_app_impl(id: &str, force: bool) -> Result<(), AdapterError> {
.output()
.map_err(|e| AdapterError::internal(format!("pkill failed: {e}")))?;
} else {
- let pid = crate::key_dispatch::find_pid_by_name(id)?;
+ let pid = crate::system::key_dispatch::find_pid_by_name(id)?;
let app_ax = crate::tree::element_for_pid(pid);
let closed = try_quit_via_menu_bar(&app_ax);
if !closed {
diff --git a/crates/macos/src/key_dispatch.rs b/crates/macos/src/system/key_dispatch.rs
similarity index 100%
rename from crates/macos/src/key_dispatch.rs
rename to crates/macos/src/system/key_dispatch.rs
diff --git a/crates/macos/src/system/mod.rs b/crates/macos/src/system/mod.rs
new file mode 100644
index 000000000..81662af13
--- /dev/null
+++ b/crates/macos/src/system/mod.rs
@@ -0,0 +1,6 @@
+pub mod app_ops;
+pub mod key_dispatch;
+pub mod permissions;
+pub mod screenshot;
+pub mod wait;
+pub mod window_ops;
diff --git a/crates/macos/src/permissions.rs b/crates/macos/src/system/permissions.rs
similarity index 100%
rename from crates/macos/src/permissions.rs
rename to crates/macos/src/system/permissions.rs
diff --git a/crates/macos/src/screenshot.rs b/crates/macos/src/system/screenshot.rs
similarity index 100%
rename from crates/macos/src/screenshot.rs
rename to crates/macos/src/system/screenshot.rs
diff --git a/crates/macos/src/wait.rs b/crates/macos/src/system/wait.rs
similarity index 96%
rename from crates/macos/src/wait.rs
rename to crates/macos/src/system/wait.rs
index 3d8f162f6..a60133f39 100644
--- a/crates/macos/src/wait.rs
+++ b/crates/macos/src/system/wait.rs
@@ -4,7 +4,7 @@ use std::time::{Duration, Instant};
#[cfg(target_os = "macos")]
mod imp {
use super::*;
- use crate::surfaces::is_menu_open;
+ use crate::tree::surfaces::is_menu_open;
pub fn wait_for_menu(pid: i32, open: bool, timeout_ms: u64) -> Result<(), AdapterError> {
let deadline = Instant::now() + Duration::from_millis(timeout_ms);
diff --git a/crates/macos/src/window_ops.rs b/crates/macos/src/system/window_ops.rs
similarity index 100%
rename from crates/macos/src/window_ops.rs
rename to crates/macos/src/system/window_ops.rs
diff --git a/crates/macos/src/tree/builder.rs b/crates/macos/src/tree/builder.rs
new file mode 100644
index 000000000..362d136e1
--- /dev/null
+++ b/crates/macos/src/tree/builder.rs
@@ -0,0 +1,184 @@
+use agent_desktop_core::node::AccessibilityNode;
+use rustc_hash::FxHashSet;
+
+use super::element::{
+ copy_ax_array, copy_string_attr, element_for_pid, fetch_node_attrs, read_bounds, AXElement,
+ ABSOLUTE_MAX_DEPTH,
+};
+
+#[cfg(target_os = "macos")]
+use accessibility_sys::{
+ kAXChildrenAttribute, kAXContentsAttribute, kAXRoleAttribute, kAXTitleAttribute,
+ kAXValueAttribute, kAXWindowsAttribute,
+};
+
+#[cfg(target_os = "macos")]
+pub fn window_element_for(pid: i32, win_title: &str) -> AXElement {
+ let app = element_for_pid(pid);
+
+ if let Some(windows) = copy_ax_array(&app, kAXWindowsAttribute) {
+ for win in &windows {
+ let title = copy_string_attr(win, kAXTitleAttribute);
+ if title.as_deref() == Some(win_title) {
+ return win.clone();
+ }
+ }
+ 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))
+ {
+ return win.clone();
+ }
+ }
+ if let Some(first) = windows.into_iter().next() {
+ return first;
+ }
+ }
+
+ app
+}
+
+#[cfg(target_os = "macos")]
+pub fn build_subtree(
+ el: &AXElement,
+ depth: u8,
+ max_depth: u8,
+ include_bounds: bool,
+ ancestors: &mut FxHashSet<usize>,
+) -> Option<AccessibilityNode> {
+ if depth > max_depth || depth >= ABSOLUTE_MAX_DEPTH {
+ return None;
+ }
+ let ptr_key = el.0 as usize;
+ if !ancestors.insert(ptr_key) {
+ return None;
+ }
+
+ let (ax_role, title, ax_desc, value, enabled, focused) = fetch_node_attrs(el);
+
+ let role = ax_role
+ .as_deref()
+ .map(crate::tree::roles::ax_role_to_str)
+ .unwrap_or("unknown")
+ .to_string();
+
+ let name = title.clone().or_else(|| ax_desc.clone());
+ let description = if title.is_some() { ax_desc } else { None };
+
+ let name = if name.is_none() && ax_role.as_deref() == Some("AXStaticText") {
+ value.clone().or(name)
+ } else {
+ name
+ };
+
+ let mut states = Vec::new();
+ if focused {
+ states.push("focused".into());
+ }
+ if !enabled {
+ states.push("disabled".into());
+ }
+
+ 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, ancestors))
+ .collect();
+
+ ancestors.remove(&ptr_key);
+
+ Some(AccessibilityNode {
+ ref_id: None,
+ role,
+ name,
+ value,
+ description,
+ states,
+ bounds,
+ children,
+ })
+}
+
+pub fn label_from_children(children: &[AXElement]) -> Option<String> {
+ #[cfg(target_os = "macos")]
+ {
+ fn text_of(el: &AXElement) -> Option<String> {
+ copy_string_attr(el, kAXValueAttribute)
+ .or_else(|| copy_string_attr(el, kAXTitleAttribute))
+ .filter(|s| !s.is_empty())
+ }
+
+ 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);
+ }
+ }
+ 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);
+ }
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ None
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ let _ = children;
+ None
+ }
+}
+
+#[cfg(target_os = "macos")]
+fn copy_children(el: &AXElement, ax_role: Option<&str>) -> Option<Vec<AXElement>> {
+ if ax_role == Some("AXBrowser") {
+ return copy_ax_array(el, "AXColumns");
+ }
+ for attr in &[
+ kAXChildrenAttribute,
+ kAXContentsAttribute,
+ "AXChildrenInNavigationOrder",
+ ] {
+ if let Some(v) = copy_ax_array(el, attr) {
+ if !v.is_empty() {
+ return Some(v);
+ }
+ }
+ }
+ None
+}
+
+#[cfg(not(target_os = "macos"))]
+pub fn window_element_for(_pid: i32, _win_title: &str) -> AXElement {
+ element_for_pid(0)
+}
+
+#[cfg(not(target_os = "macos"))]
+pub fn build_subtree(
+ _el: &AXElement,
+ _depth: u8,
+ _max_depth: u8,
+ _include_bounds: bool,
+ _visited: &mut FxHashSet<usize>,
+) -> Option<AccessibilityNode> {
+ None
+}
diff --git a/crates/macos/src/tree.rs b/crates/macos/src/tree/element.rs
similarity index 62%
rename from crates/macos/src/tree.rs
rename to crates/macos/src/tree/element.rs
index 66634588b..54e79c383 100644
--- a/crates/macos/src/tree.rs
+++ b/crates/macos/src/tree/element.rs
@@ -1,5 +1,4 @@
-use agent_desktop_core::node::{AccessibilityNode, Rect};
-use rustc_hash::FxHashSet;
+use agent_desktop_core::node::Rect;
pub const ABSOLUTE_MAX_DEPTH: u8 = 50;
@@ -7,11 +6,10 @@ 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, kAXDescriptionAttribute, kAXEnabledAttribute, kAXErrorSuccess,
+ kAXFocusedAttribute, kAXRoleAttribute, kAXTitleAttribute, kAXValueAttribute,
+ AXUIElementCopyAttributeValue, AXUIElementCopyMultipleAttributeValues,
+ AXUIElementCreateApplication, AXUIElementRef, AXUIElementSetMessagingTimeout,
};
use core_foundation::{
array::CFArray,
@@ -48,38 +46,7 @@ mod imp {
el
}
- /// Find the AXWindow element whose title matches `win_title`.
- /// Falls back to the first window, then to the app element if no windows.
- pub fn window_element_for(pid: i32, win_title: &str) -> AXElement {
- let app = element_for_pid(pid);
-
- if let Some(windows) = copy_ax_array(&app, kAXWindowsAttribute) {
- for win in &windows {
- let title = copy_string_attr(win, kAXTitleAttribute);
- if title.as_deref() == Some(win_title) {
- return win.clone();
- }
- }
- 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))
- {
- return win.clone();
- }
- }
- if let Some(first) = windows.into_iter().next() {
- return first;
- }
- }
-
- app
- }
-
- /// Batch-fetch six most-used attributes. Returns (role, title, desc, value, enabled, focused).
- /// Value handles CFString, CFBoolean, and CFNumber types.
- fn fetch_node_attrs(
+ pub fn fetch_node_attrs(
el: &AXElement,
) -> (
Option<String>,
@@ -163,7 +130,6 @@ mod imp {
(role, title, desc, val, enabled, focused)
}
- /// Compute the effective display name for any element, mirroring `build_subtree` name resolution.
pub fn resolve_element_name(el: &AXElement) -> Option<String> {
let ax_role = copy_string_attr(el, kAXRoleAttribute);
let title = copy_string_attr(el, kAXTitleAttribute);
@@ -178,133 +144,10 @@ mod imp {
name.or_else(|| {
let children = copy_ax_array(el, kAXChildrenAttribute).unwrap_or_default();
- label_from_children(&children)
+ super::super::builder::label_from_children(&children)
})
}
- pub fn build_subtree(
- el: &AXElement,
- depth: u8,
- max_depth: u8,
- include_bounds: bool,
- ancestors: &mut FxHashSet<usize>,
- ) -> Option<AccessibilityNode> {
- if depth > max_depth || depth >= ABSOLUTE_MAX_DEPTH {
- return None;
- }
- let ptr_key = el.0 as usize;
- if !ancestors.insert(ptr_key) {
- return None;
- }
-
- let (ax_role, title, ax_desc, value, enabled, focused) = fetch_node_attrs(el);
-
- let role = ax_role
- .as_deref()
- .map(crate::roles::ax_role_to_str)
- .unwrap_or("unknown")
- .to_string();
-
- let name = title.clone().or_else(|| ax_desc.clone());
- let description = if title.is_some() { ax_desc } else { None };
-
- let name = if name.is_none() && ax_role.as_deref() == Some("AXStaticText") {
- value.clone().or(name)
- } else {
- name
- };
-
- let mut states = Vec::new();
- if focused {
- states.push("focused".into());
- }
- if !enabled {
- states.push("disabled".into());
- }
-
- 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, ancestors)
- })
- .collect();
-
- ancestors.remove(&ptr_key);
-
- Some(AccessibilityNode {
- ref_id: None,
- role,
- name,
- value,
- description,
- states,
- bounds,
- children,
- })
- }
-
- /// Scan immediate children (and one level deeper through AXCell) to find a text label.
- /// Resolves the common macOS pattern: AXRow → AXCell → AXStaticText.kAXValue = "label".
- fn label_from_children(children: &[AXElement]) -> Option<String> {
- fn text_of(el: &AXElement) -> Option<String> {
- copy_string_attr(el, kAXValueAttribute)
- .or_else(|| copy_string_attr(el, kAXTitleAttribute))
- .filter(|s| !s.is_empty())
- }
-
- 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);
- }
- }
- 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);
- }
- }
- }
- }
- _ => {}
- }
- }
- None
- }
-
- /// Read children using the appropriate attribute for this element's role.
- /// AXBrowser exposes its content via AXColumns, not AXChildren.
- fn copy_children(el: &AXElement, ax_role: Option<&str>) -> Option<Vec<AXElement>> {
- if ax_role == Some("AXBrowser") {
- return copy_ax_array(el, "AXColumns");
- }
- for attr in &[
- kAXChildrenAttribute,
- kAXContentsAttribute,
- "AXChildrenInNavigationOrder",
- ] {
- if let Some(v) = copy_ax_array(el, attr) {
- if !v.is_empty() {
- return Some(v);
- }
- }
- }
- None
- }
-
pub fn copy_string_attr(el: &AXElement, attr: &str) -> Option<String> {
let cf_attr = CFString::new(attr);
let mut value: CFTypeRef = std::ptr::null_mut();
@@ -318,7 +161,6 @@ mod imp {
cf_type.downcast::<CFString>().map(|s| s.to_string())
}
- /// Read kAXValueAttribute handling CFString, CFBoolean, and CFNumber.
fn copy_value_typed(el: &AXElement) -> Option<String> {
let cf_attr = CFString::new(kAXValueAttribute);
let mut val_ref: CFTypeRef = std::ptr::null_mut();
@@ -359,7 +201,6 @@ mod imp {
cf_type.downcast::<CFBoolean>().map(|b| b.into())
}
- /// Read an array-typed AX attribute, retaining each AXUIElement.
pub fn copy_ax_array(el: &AXElement, attr: &str) -> Option<Vec<AXElement>> {
let cf_attr = CFString::new(attr);
let mut value: CFTypeRef = std::ptr::null_mut();
@@ -476,9 +317,6 @@ mod imp {
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
}
@@ -488,25 +326,27 @@ mod imp {
pub fn copy_element_attr(_el: &AXElement, _attr: &str) -> Option<AXElement> {
None
}
- pub fn read_bounds(_el: &AXElement) -> Option<agent_desktop_core::node::Rect> {
+ pub fn read_bounds(_el: &AXElement) -> Option<Rect> {
None
}
pub fn resolve_element_name(_el: &AXElement) -> Option<String> {
None
}
-
- pub fn build_subtree(
+ pub fn fetch_node_attrs(
_el: &AXElement,
- _depth: u8,
- _max_depth: u8,
- _include_bounds: bool,
- _visited: &mut FxHashSet<usize>,
- ) -> Option<AccessibilityNode> {
- None
+ ) -> (
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ bool,
+ bool,
+ ) {
+ (None, None, None, None, true, false)
}
}
pub use imp::{
- build_subtree, copy_ax_array, copy_element_attr, copy_string_attr, element_for_pid,
- read_bounds, resolve_element_name, window_element_for, AXElement,
+ copy_ax_array, copy_element_attr, copy_string_attr, element_for_pid, fetch_node_attrs,
+ read_bounds, resolve_element_name, AXElement,
};
diff --git a/crates/macos/src/tree/mod.rs b/crates/macos/src/tree/mod.rs
new file mode 100644
index 000000000..c1daf454f
--- /dev/null
+++ b/crates/macos/src/tree/mod.rs
@@ -0,0 +1,17 @@
+pub mod builder;
+pub mod element;
+pub mod resolve;
+pub mod roles;
+pub mod surfaces;
+
+pub use builder::{build_subtree, window_element_for};
+pub use element::{
+ copy_ax_array, copy_element_attr, copy_string_attr, element_for_pid, read_bounds,
+ resolve_element_name, AXElement, ABSOLUTE_MAX_DEPTH,
+};
+pub use resolve::{find_element_recursive, resolve_element_impl};
+pub use roles::{ax_role_to_str, is_interactive_role};
+pub use surfaces::{
+ alert_for_pid, focused_surface_for_pid, is_menu_open, list_surfaces_for_pid,
+ menu_element_for_pid, popover_for_pid, sheet_for_pid,
+};
diff --git a/crates/macos/src/tree/resolve.rs b/crates/macos/src/tree/resolve.rs
new file mode 100644
index 000000000..ffc1f62fe
--- /dev/null
+++ b/crates/macos/src/tree/resolve.rs
@@ -0,0 +1,91 @@
+use agent_desktop_core::{adapter::NativeHandle, error::AdapterError, refs::RefEntry};
+use rustc_hash::FxHashSet;
+
+use super::element::{
+ copy_ax_array, copy_string_attr, element_for_pid, resolve_element_name, AXElement,
+};
+
+#[cfg(target_os = "macos")]
+pub fn resolve_element_impl(entry: &RefEntry) -> Result<NativeHandle, AdapterError> {
+ let root = element_for_pid(entry.pid);
+ let mut visited = FxHashSet::default();
+ find_element_recursive(&root, entry, 0, 20, &mut visited)
+}
+
+#[cfg(target_os = "macos")]
+pub fn find_element_recursive(
+ el: &AXElement,
+ entry: &RefEntry,
+ depth: u8,
+ max_depth: u8,
+ ancestors: &mut FxHashSet<usize>,
+) -> Result<NativeHandle, AdapterError> {
+ use accessibility_sys::kAXRoleAttribute;
+ use core_foundation::base::{CFRetain, CFTypeRef};
+
+ let ptr_key = el.0 as usize;
+ if !ancestors.insert(ptr_key) {
+ return Err(AdapterError::element_not_found("element"));
+ }
+
+ let ax_role = copy_string_attr(el, kAXRoleAttribute);
+ let normalized = ax_role
+ .as_deref()
+ .map(crate::tree::roles::ax_role_to_str)
+ .unwrap_or("unknown");
+
+ if normalized == entry.role {
+ let elem_name = resolve_element_name(el);
+ let name_match = match (&entry.name, &elem_name) {
+ (Some(en), Some(nn)) => en == nn,
+ (None, None) => true,
+ _ => false,
+ };
+ if name_match {
+ ancestors.remove(&ptr_key);
+ unsafe { CFRetain(el.0 as CFTypeRef) };
+ return Ok(NativeHandle::from_ptr(el.0 as *const _));
+ }
+ }
+
+ if depth >= max_depth {
+ ancestors.remove(&ptr_key);
+ return Err(AdapterError::element_not_found("element"));
+ }
+
+ let child_attr = if ax_role.as_deref() == Some("AXBrowser") {
+ "AXColumns"
+ } else {
+ "AXChildren"
+ };
+ let children = copy_ax_array(el, child_attr)
+ .filter(|v| !v.is_empty())
+ .or_else(|| copy_ax_array(el, "AXContents").filter(|v| !v.is_empty()))
+ .unwrap_or_default();
+
+ for child in &children {
+ if let Ok(handle) = find_element_recursive(child, entry, depth + 1, max_depth, ancestors) {
+ ancestors.remove(&ptr_key);
+ return Ok(handle);
+ }
+ }
+
+ ancestors.remove(&ptr_key);
+ Err(AdapterError::element_not_found("element"))
+}
+
+#[cfg(not(target_os = "macos"))]
+pub fn resolve_element_impl(_entry: &RefEntry) -> Result<NativeHandle, AdapterError> {
+ Err(AdapterError::not_supported("resolve_element"))
+}
+
+#[cfg(not(target_os = "macos"))]
+pub fn find_element_recursive(
+ _el: &AXElement,
+ _entry: &RefEntry,
+ _depth: u8,
+ _max_depth: u8,
+ _ancestors: &mut FxHashSet<usize>,
+) -> Result<NativeHandle, AdapterError> {
+ Err(AdapterError::not_supported("find_element_recursive"))
+}
diff --git a/crates/macos/src/roles.rs b/crates/macos/src/tree/roles.rs
similarity index 100%
rename from crates/macos/src/roles.rs
rename to crates/macos/src/tree/roles.rs
diff --git a/crates/macos/src/surfaces.rs b/crates/macos/src/tree/surfaces.rs
similarity index 94%
rename from crates/macos/src/surfaces.rs
rename to crates/macos/src/tree/surfaces.rs
index 4c090ad28..988132a89 100644
--- a/crates/macos/src/surfaces.rs
+++ b/crates/macos/src/tree/surfaces.rs
@@ -1,4 +1,4 @@
-use crate::tree::{copy_ax_array, copy_string_attr, element_for_pid, AXElement};
+use super::element::{copy_ax_array, copy_string_attr, element_for_pid, AXElement};
use agent_desktop_core::node::SurfaceInfo;
#[cfg(target_os = "macos")]
@@ -41,9 +41,6 @@ mod imp {
copy_element_attr(&app, "AXFocusedWindow")
}
- /// Find an open menu bar menu by looking for AXMenuBarItem with AXSelected=true.
- /// This is the correct macOS mechanism — menus are always children of their bar item,
- /// not direct children of the application.
fn open_menubar_menu(pid: i32) -> Option<AXElement> {
let app = element_for_pid(pid);
let app_children = copy_ax_array(&app, "AXChildren")?;
@@ -67,9 +64,6 @@ mod imp {
None
}
- /// Find a right-click context menu. After AXShowMenu, the menu appears
- /// as a child of the focused element (the one that was right-clicked).
- /// Falls back to scanning direct app children for Electron-style apps.
fn context_menu_from_app(pid: i32) -> Option<AXElement> {
let app = element_for_pid(pid);
if let Some(focused) = copy_element_attr(&app, "AXFocusedUIElement") {